HomeRootView.swift 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. import CoreData
  2. import SpriteKit
  3. import SwiftDate
  4. import SwiftUI
  5. import Swinject
  6. extension Home {
  7. struct RootView: BaseView {
  8. let resolver: Resolver
  9. @StateObject var state = StateModel()
  10. @State var isStatusPopupPresented = false
  11. @State var showCancelAlert = false
  12. @State var isMenuPresented = false
  13. @State var showTreatments = false
  14. @State var selectedTab: Int = 0
  15. struct Buttons: Identifiable {
  16. let label: String
  17. let number: String
  18. var active: Bool
  19. let hours: Int16
  20. var id: String { label }
  21. }
  22. @State var timeButtons: [Buttons] = [
  23. Buttons(label: "2 hours", number: "2", active: false, hours: 2),
  24. Buttons(label: "4 hours", number: "4", active: false, hours: 4),
  25. Buttons(label: "6 hours", number: "6", active: false, hours: 6),
  26. Buttons(label: "12 hours", number: "12", active: false, hours: 12),
  27. Buttons(label: "24 hours", number: "24", active: false, hours: 24)
  28. ]
  29. let buttonFont = Font.custom("TimeButtonFont", size: 14)
  30. @Environment(\.managedObjectContext) var moc
  31. @Environment(\.colorScheme) var colorScheme
  32. @FetchRequest(
  33. entity: Override.entity(),
  34. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  35. ) var fetchedPercent: FetchedResults<Override>
  36. @FetchRequest(
  37. entity: OverridePresets.entity(),
  38. sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(
  39. format: "name != %@", "" as String
  40. )
  41. ) var fetchedProfiles: FetchedResults<OverridePresets>
  42. @FetchRequest(
  43. entity: TempTargets.entity(),
  44. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  45. ) var sliderTTpresets: FetchedResults<TempTargets>
  46. @FetchRequest(
  47. entity: TempTargetsSlider.entity(),
  48. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  49. ) var enactedSliderTT: FetchedResults<TempTargetsSlider>
  50. var bolusProgressFormatter: NumberFormatter {
  51. let formatter = NumberFormatter()
  52. formatter.numberStyle = .decimal
  53. formatter.minimum = 0
  54. formatter.maximumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  55. formatter.minimumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  56. formatter.allowsFloats = true
  57. formatter.roundingIncrement = Double(state.settingsManager.preferences.bolusIncrement) as NSNumber
  58. return formatter
  59. }
  60. private var numberFormatter: NumberFormatter {
  61. let formatter = NumberFormatter()
  62. formatter.numberStyle = .decimal
  63. formatter.maximumFractionDigits = 2
  64. return formatter
  65. }
  66. private var fetchedTargetFormatter: NumberFormatter {
  67. let formatter = NumberFormatter()
  68. formatter.numberStyle = .decimal
  69. if state.units == .mmolL {
  70. formatter.maximumFractionDigits = 1
  71. } else { formatter.maximumFractionDigits = 0 }
  72. return formatter
  73. }
  74. private var targetFormatter: NumberFormatter {
  75. let formatter = NumberFormatter()
  76. formatter.numberStyle = .decimal
  77. formatter.maximumFractionDigits = 1
  78. return formatter
  79. }
  80. private var tirFormatter: NumberFormatter {
  81. let formatter = NumberFormatter()
  82. formatter.numberStyle = .decimal
  83. formatter.maximumFractionDigits = 0
  84. return formatter
  85. }
  86. private var dateFormatter: DateFormatter {
  87. let dateFormatter = DateFormatter()
  88. dateFormatter.timeStyle = .short
  89. return dateFormatter
  90. }
  91. private var spriteScene: SKScene {
  92. let scene = SnowScene()
  93. scene.scaleMode = .resizeFill
  94. scene.backgroundColor = .clear
  95. return scene
  96. }
  97. private var color: LinearGradient {
  98. colorScheme == .dark ? LinearGradient(
  99. gradient: Gradient(colors: [
  100. Color.bgDarkBlue,
  101. // Color.bgDarkBlue,
  102. Color.bgDarkerDarkBlue
  103. // Color.bgDarkBlue
  104. ]),
  105. startPoint: .top,
  106. endPoint: .bottom
  107. )
  108. :
  109. LinearGradient(
  110. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  111. startPoint: .top,
  112. endPoint: .bottom
  113. )
  114. }
  115. private var historySFSymbol: String {
  116. if #available(iOS 17.0, *) {
  117. return "book.pages"
  118. } else {
  119. return "book"
  120. }
  121. }
  122. var glucoseView: some View {
  123. CurrentGlucoseView(
  124. recentGlucose: $state.recentGlucose,
  125. timerDate: $state.timerDate,
  126. delta: $state.glucoseDelta,
  127. units: $state.units,
  128. alarm: $state.alarm,
  129. lowGlucose: $state.lowGlucose,
  130. highGlucose: $state.highGlucose
  131. ).scaleEffect(0.9)
  132. .onTapGesture {
  133. if state.alarm == nil {
  134. state.openCGM()
  135. } else {
  136. state.showModal(for: .snooze)
  137. }
  138. }
  139. .onLongPressGesture {
  140. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  141. impactHeavy.impactOccurred()
  142. if state.alarm == nil {
  143. state.showModal(for: .snooze)
  144. } else {
  145. state.openCGM()
  146. }
  147. }
  148. }
  149. var pumpView: some View {
  150. PumpView(
  151. reservoir: $state.reservoir,
  152. battery: $state.battery,
  153. name: $state.pumpName,
  154. expiresAtDate: $state.pumpExpiresAtDate,
  155. timerDate: $state.timerDate,
  156. timeZone: $state.timeZone,
  157. state: state
  158. ).onTapGesture {
  159. if state.pumpDisplayState != nil {
  160. state.setupPump = true
  161. }
  162. }
  163. }
  164. var tempBasalString: String? {
  165. guard let tempRate = state.tempRate else {
  166. return nil
  167. }
  168. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  169. var manualBasalString = ""
  170. if state.apsManager.isManualTempBasal {
  171. manualBasalString = NSLocalizedString(
  172. " - Manual Basal ⚠️",
  173. comment: "Manual Temp basal"
  174. )
  175. }
  176. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  177. }
  178. var tempTargetString: String? {
  179. guard let tempTarget = state.tempTarget else {
  180. return nil
  181. }
  182. let target = tempTarget.targetBottom ?? 0
  183. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  184. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  185. .rawValue
  186. var string = ""
  187. if sliderTTpresets.first?.active ?? false {
  188. let hbt = sliderTTpresets.first?.hbt ?? 0
  189. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  190. }
  191. let percentString = state
  192. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  193. return tempTarget.displayName + " " + percentString
  194. }
  195. var overrideString: String? {
  196. guard fetchedPercent.first?.enabled ?? false else {
  197. return nil
  198. }
  199. var percentString = "\((fetchedPercent.first?.percentage ?? 100).formatted(.number)) %"
  200. var target = (fetchedPercent.first?.target ?? 100) as Decimal
  201. let indefinite = (fetchedPercent.first?.indefinite ?? false)
  202. let unit = state.units.rawValue
  203. if state.units == .mmolL {
  204. target = target.asMmolL
  205. }
  206. var targetString = (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  207. if tempTargetString != nil || target == 0 { targetString = "" }
  208. percentString = percentString == "100 %" ? "" : percentString
  209. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  210. let addedMinutes = Int(duration)
  211. let date = fetchedPercent.first?.date ?? Date()
  212. var newDuration: Decimal = 0
  213. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() {
  214. newDuration = Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes)
  215. }
  216. var durationString = indefinite ?
  217. "" : newDuration >= 1 ?
  218. (newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " min") :
  219. (
  220. newDuration > 0 ? (
  221. (newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " s"
  222. ) :
  223. ""
  224. )
  225. let smbToggleString = (fetchedPercent.first?.smbIsOff ?? false) ? " \u{20e0}" : ""
  226. var comma1 = ", "
  227. var comma2 = comma1
  228. var comma3 = comma1
  229. if targetString == "" || percentString == "" { comma1 = "" }
  230. if durationString == "" { comma2 = "" }
  231. if smbToggleString == "" { comma3 = "" }
  232. if percentString == "", targetString == "" {
  233. comma1 = ""
  234. comma2 = ""
  235. }
  236. if percentString == "", targetString == "", smbToggleString == "" {
  237. durationString = ""
  238. comma1 = ""
  239. comma2 = ""
  240. comma3 = ""
  241. }
  242. if durationString == "" {
  243. comma2 = ""
  244. }
  245. if smbToggleString == "" {
  246. comma3 = ""
  247. }
  248. if durationString == "", !indefinite {
  249. return nil
  250. }
  251. return percentString + comma1 + targetString + comma2 + durationString + comma3 + smbToggleString
  252. }
  253. var infoPanel: some View {
  254. HStack(alignment: .center) {
  255. if state.pumpSuspended {
  256. Text("Pump suspended")
  257. .font(.system(size: 15, weight: .bold)).foregroundColor(.loopGray)
  258. .padding(.leading, 8)
  259. } else if let tempBasalString = tempBasalString {
  260. Text(tempBasalString)
  261. .font(.system(size: 15, weight: .bold))
  262. .foregroundColor(.insulin)
  263. .padding(.leading, 8)
  264. }
  265. if state.tins {
  266. Text(
  267. "TINS: \(state.calculateTINS())" +
  268. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  269. )
  270. .font(.system(size: 15, weight: .bold))
  271. .foregroundColor(.insulin)
  272. }
  273. if let tempTargetString = tempTargetString {
  274. Text(tempTargetString)
  275. .font(.caption)
  276. .foregroundColor(.secondary)
  277. }
  278. Spacer()
  279. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  280. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  281. }
  282. }
  283. .frame(maxWidth: .infinity, maxHeight: 30)
  284. }
  285. var timeInterval: some View {
  286. HStack(alignment: .center) {
  287. ForEach(timeButtons) { button in
  288. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  289. state.hours = button.hours
  290. }
  291. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  292. .frame(maxHeight: 30).padding(.horizontal, 8)
  293. .background(
  294. button.active ?
  295. // RGB(30, 60, 95)
  296. (
  297. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  298. Color.white
  299. ) :
  300. Color
  301. .clear
  302. )
  303. .cornerRadius(20)
  304. }
  305. }
  306. .shadow(
  307. color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33),
  308. radius: colorScheme == .dark ? 5 : 3
  309. )
  310. .font(buttonFont)
  311. }
  312. var mainChart: some View {
  313. ZStack {
  314. if state.animatedBackground {
  315. SpriteView(scene: spriteScene, options: [.allowsTransparency])
  316. .ignoresSafeArea()
  317. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  318. }
  319. MainChartView(
  320. glucose: $state.glucose,
  321. units: $state.units,
  322. eventualBG: $state.eventualBG,
  323. suggestion: $state.suggestion,
  324. tempBasals: $state.tempBasals,
  325. boluses: $state.boluses,
  326. suspensions: $state.suspensions,
  327. announcement: $state.announcement,
  328. hours: .constant(state.filteredHours),
  329. maxBasal: $state.maxBasal,
  330. autotunedBasalProfile: $state.autotunedBasalProfile,
  331. basalProfile: $state.basalProfile,
  332. tempTargets: $state.tempTargets,
  333. carbs: $state.carbs,
  334. smooth: $state.smooth,
  335. highGlucose: $state.highGlucose,
  336. lowGlucose: $state.lowGlucose,
  337. screenHours: $state.hours,
  338. displayXgridLines: $state.displayXgridLines,
  339. displayYgridLines: $state.displayYgridLines,
  340. thresholdLines: $state.thresholdLines,
  341. isTempTargetActive: $state.isTempTargetActive
  342. )
  343. }
  344. .padding(.bottom)
  345. }
  346. private func selectedProfile() -> (name: String, isOn: Bool) {
  347. var profileString = ""
  348. var display: Bool = false
  349. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  350. let indefinite = fetchedPercent.first?.indefinite ?? false
  351. let addedMinutes = Int(duration)
  352. let date = fetchedPercent.first?.date ?? Date()
  353. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() || indefinite {
  354. display.toggle()
  355. }
  356. if fetchedPercent.first?.enabled ?? false, !(fetchedPercent.first?.isPreset ?? false), display {
  357. profileString = NSLocalizedString("Custom Profile", comment: "Custom but unsaved Profile")
  358. } else if !(fetchedPercent.first?.enabled ?? false) || !display {
  359. profileString = NSLocalizedString("Normal Profile", comment: "Your normal Profile. Use a short string")
  360. } else {
  361. let id_ = fetchedPercent.first?.id ?? ""
  362. let profile = fetchedProfiles.filter({ $0.id == id_ }).first
  363. if profile != nil {
  364. profileString = profile?.name?.description ?? ""
  365. }
  366. }
  367. return (name: profileString, isOn: display)
  368. }
  369. func highlightButtons() {
  370. for i in 0 ..< timeButtons.count {
  371. timeButtons[i].active = timeButtons[i].hours == state.hours
  372. }
  373. }
  374. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  375. VStack(alignment: .leading, spacing: 20) {
  376. /// Loop view at bottomLeading
  377. LoopView(
  378. suggestion: $state.suggestion,
  379. enactedSuggestion: $state.enactedSuggestion,
  380. closedLoop: $state.closedLoop,
  381. timerDate: $state.timerDate,
  382. isLooping: $state.isLooping,
  383. lastLoopDate: $state.lastLoopDate,
  384. manualTempBasal: $state.manualTempBasal
  385. ).onTapGesture {
  386. state.isStatusPopupPresented = true
  387. }.onLongPressGesture {
  388. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  389. impactHeavy.impactOccurred()
  390. state.runLoop()
  391. }
  392. /// eventualBG string at bottomTrailing
  393. if let eventualBG = state.eventualBG {
  394. HStack {
  395. Image(systemName: "arrow.right.circle")
  396. .font(.system(size: 16, weight: .bold))
  397. Text(
  398. numberFormatter.string(
  399. from: (
  400. state.units == .mmolL ? eventualBG
  401. .asMmolL : Decimal(eventualBG)
  402. ) as NSNumber
  403. )!
  404. )
  405. .font(.system(size: 16))
  406. }
  407. }
  408. }
  409. }
  410. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  411. HStack {
  412. HStack {
  413. Image(systemName: "syringe.fill")
  414. .font(.system(size: 16))
  415. .foregroundColor(Color.insulin)
  416. Text(
  417. (numberFormatter.string(from: (state.suggestion?.iob ?? 0) as NSNumber) ?? "0") +
  418. NSLocalizedString(" U", comment: "Insulin unit")
  419. )
  420. .font(.system(size: 16, weight: .bold))
  421. }
  422. Spacer()
  423. HStack {
  424. Image(systemName: "fork.knife")
  425. .font(.system(size: 16))
  426. .foregroundColor(.loopYellow)
  427. Text(
  428. (numberFormatter.string(from: (state.suggestion?.cob ?? 0) as NSNumber) ?? "0") +
  429. NSLocalizedString(" g", comment: "gram of carbs")
  430. )
  431. .font(.system(size: 16, weight: .bold))
  432. }
  433. Spacer()
  434. HStack {
  435. if state.pumpSuspended {
  436. Text("Pump suspended")
  437. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGray)
  438. } else if let tempBasalString = tempBasalString {
  439. Image(systemName: "drop.circle")
  440. .font(.system(size: 16))
  441. .foregroundColor(.insulinTintColor)
  442. Text(tempBasalString)
  443. .font(.system(size: 16, weight: .bold))
  444. }
  445. }
  446. if !state.tins {
  447. Spacer()
  448. Text(
  449. "TDD: " + (numberFormatter.string(from: (state.suggestion?.tdd ?? 0) as NSNumber) ?? "0") +
  450. NSLocalizedString(" U", comment: "Insulin unit")
  451. )
  452. .font(.system(size: 16, weight: .bold))
  453. } else {
  454. Spacer()
  455. HStack {
  456. Text(
  457. "TINS: \(state.roundedTotalBolus)" +
  458. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  459. )
  460. .font(.system(size: 16, weight: .bold))
  461. .onChange(of: state.hours) { _ in
  462. state.roundedTotalBolus = state.calculateTINS()
  463. }
  464. .onAppear {
  465. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  466. state.roundedTotalBolus = state.calculateTINS()
  467. }
  468. }
  469. }
  470. }
  471. }.padding(.horizontal, 10)
  472. }
  473. @ViewBuilder func profileView(_: GeometryProxy) -> some View {
  474. ZStack {
  475. /// rectangle as background
  476. RoundedRectangle(cornerRadius: 15)
  477. .fill(
  478. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  479. .opacity(0.1)
  480. )
  481. .clipShape(RoundedRectangle(cornerRadius: 15))
  482. .frame(height: UIScreen.main.bounds.height / 18)
  483. .shadow(
  484. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  485. Color.black.opacity(0.33),
  486. radius: 3
  487. )
  488. HStack {
  489. /// actual profile view
  490. Image(systemName: "person.fill")
  491. .font(.system(size: 25))
  492. Spacer()
  493. if let overrideString = overrideString {
  494. VStack {
  495. Text(selectedProfile().name)
  496. .font(.subheadline)
  497. .frame(maxWidth: .infinity, alignment: .leading)
  498. Text(overrideString)
  499. .font(.caption)
  500. .frame(maxWidth: .infinity, alignment: .leading)
  501. }.padding(.leading, 5)
  502. Spacer()
  503. Image(systemName: "xmark.app")
  504. .font(.system(size: 25))
  505. } else {
  506. if tempTargetString == nil {
  507. VStack {
  508. Text(selectedProfile().name)
  509. .font(.subheadline)
  510. .frame(maxWidth: .infinity, alignment: .leading)
  511. Text("100 %")
  512. .font(.caption)
  513. .frame(maxWidth: .infinity, alignment: .leading)
  514. }.padding(.leading, 5)
  515. Spacer()
  516. /// to ensure the same position....
  517. Image(systemName: "xmark.app")
  518. .font(.system(size: 25))
  519. .foregroundStyle(Color.clear)
  520. }
  521. }
  522. }.padding(.horizontal, 10)
  523. .alert(
  524. "Return to Normal?", isPresented: $showCancelAlert,
  525. actions: {
  526. Button("No", role: .cancel) {}
  527. Button("Yes", role: .destructive) {
  528. state.cancelProfile()
  529. }
  530. }, message: { Text("This will change settings back to your normal profile.") }
  531. )
  532. .padding(.trailing, 8)
  533. .onTapGesture {
  534. if selectedProfile().name != "Normal Profile" {
  535. showCancelAlert = true
  536. }
  537. }
  538. }.padding(.horizontal, 10).padding(.bottom, 10)
  539. .overlay {
  540. /// just show temp target if no profile is already active
  541. if overrideString == nil, let tempTargetString = tempTargetString {
  542. ZStack {
  543. /// rectangle as background
  544. RoundedRectangle(cornerRadius: 15)
  545. .fill(
  546. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  547. Color
  548. .insulin
  549. .opacity(0.2)
  550. )
  551. .clipShape(RoundedRectangle(cornerRadius: 15))
  552. .frame(height: UIScreen.main.bounds.height / 18)
  553. .shadow(
  554. color: colorScheme == .dark ? Color(
  555. red: 0.02745098039,
  556. green: 0.1098039216,
  557. blue: 0.1411764706
  558. ) :
  559. Color.black.opacity(0.33),
  560. radius: 3
  561. )
  562. HStack {
  563. Image(systemName: "person.fill")
  564. .font(.system(size: 25))
  565. Spacer()
  566. Text(tempTargetString)
  567. .font(.subheadline)
  568. Spacer()
  569. }.padding(.horizontal, 10)
  570. }.padding(.horizontal, 10).padding(.bottom, 10)
  571. }
  572. }
  573. }
  574. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  575. GeometryReader { geo in
  576. RoundedRectangle(cornerRadius: 15)
  577. .frame(height: 6)
  578. .foregroundColor(.clear)
  579. .background(
  580. LinearGradient(colors: [
  581. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  582. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  583. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  584. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  585. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  586. ], startPoint: .leading, endPoint: .trailing)
  587. .mask(alignment: .leading) {
  588. RoundedRectangle(cornerRadius: 15)
  589. .frame(width: geo.size.width * CGFloat(progress))
  590. }
  591. )
  592. }
  593. }
  594. @ViewBuilder func bolusView(_: GeometryProxy, _ progress: Decimal) -> some View {
  595. let bolusTotal = state.boluses.last?.amount ?? 0
  596. let bolusFraction = progress * bolusTotal
  597. let bolusString =
  598. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  599. + " of " +
  600. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  601. + NSLocalizedString(" U", comment: "Insulin unit")
  602. ZStack {
  603. /// rectangle as background
  604. RoundedRectangle(cornerRadius: 15)
  605. .fill(
  606. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  607. .opacity(0.2)
  608. )
  609. .clipShape(RoundedRectangle(cornerRadius: 15))
  610. .frame(height: UIScreen.main.bounds.height / 18)
  611. .shadow(
  612. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  613. Color.black.opacity(0.33),
  614. radius: 3
  615. )
  616. /// actual bolus view
  617. HStack {
  618. Image(systemName: "cross.vial.fill")
  619. .font(.system(size: 25))
  620. Spacer()
  621. VStack {
  622. Text("Bolusing")
  623. .font(.subheadline)
  624. .frame(maxWidth: .infinity, alignment: .leading)
  625. Text(bolusString)
  626. .font(.caption)
  627. .frame(maxWidth: .infinity, alignment: .leading)
  628. }.padding(.leading, 5)
  629. Spacer()
  630. Button {
  631. state.cancelBolus()
  632. } label: {
  633. Image(systemName: "xmark.app")
  634. .font(.system(size: 25))
  635. }
  636. }.padding(.horizontal, 10)
  637. .padding(.trailing, 8)
  638. }.padding(.horizontal, 10).padding(.bottom, 10)
  639. .overlay(alignment: .bottom) {
  640. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 45)
  641. }.clipShape(RoundedRectangle(cornerRadius: 15))
  642. }
  643. // @ViewBuilder func menuSymbols(action: @escaping () -> Void, systemName: String) -> some View {
  644. // Button(
  645. // action: action,
  646. // label: {
  647. // HStack {
  648. // Image(systemName: systemName)
  649. // .font(.system(size: 21))
  650. // .foregroundStyle(colorScheme == .dark ? .white : .black)
  651. // }.padding(.top, 1)
  652. // }
  653. // )
  654. // }
  655. //
  656. // @ViewBuilder func menuElements(action: @escaping () -> Void, title: String) -> some View {
  657. // Button(
  658. // action: action,
  659. // label: {
  660. // HStack {
  661. // Text(title)
  662. // .font(.system(size: 19))
  663. // .foregroundStyle(colorScheme == .dark ? .white : .black)
  664. // Spacer()
  665. // Image(systemName: "arrow.right")
  666. // .font(.system(size: 21))
  667. // .foregroundStyle(colorScheme == .dark ? .white : .black)
  668. // }.padding(.top, 1)
  669. // }
  670. // )
  671. // }
  672. //
  673. // @ViewBuilder func sideMenuView() -> some View {
  674. // ZStack {
  675. // RoundedRectangle(cornerRadius: 8)
  676. // .fill(color)
  677. // .shadow(
  678. // color: Color.black.opacity(0.33),
  679. // radius: 3
  680. // )
  681. // .ignoresSafeArea(edges: .all)
  682. //
  683. // VStack(alignment: .leading) {
  684. // Button {
  685. // isMenuPresented.toggle()
  686. // } label: {
  687. // HStack {
  688. // Image(systemName: "arrow.left")
  689. // .font(.system(size: 30))
  690. // .foregroundStyle(colorScheme == .dark ? .white : .black)
  691. // Text("Menu")
  692. // .font(.system(size: 30)).fontWeight(.bold)
  693. // .foregroundStyle(colorScheme == .dark ? .white : .black)
  694. // }
  695. // }
  696. // .padding(.top, 60)
  697. //
  698. // HStack(spacing: 15) {
  699. // VStack(alignment: .leading, spacing: 25, content: {
  700. //// menuSymbols(action: { state.showModal(for: .statistics) }, systemName: "chart.bar.xaxis")
  701. //// .padding(.top, 20)
  702. //
  703. // menuSymbols(action: {
  704. // if state.pumpDisplayState != nil {
  705. // state.setupPump = true
  706. // }
  707. // }, systemName: "cross.vial.fill")
  708. //
  709. // menuSymbols(action: {
  710. // if state.alarm == nil {
  711. // state.openCGM()
  712. // } else {
  713. // state.showModal(for: .snooze)
  714. // }
  715. // }, systemName: "sensor.tag.radiowaves.forward.fill")
  716. //
  717. // menuSymbols(action: { state.showModal(for: .addTempTarget) }, systemName: "target")
  718. //
  719. // Spacer()
  720. // })
  721. // VStack(alignment: .leading, spacing: 25, content: {
  722. // menuElements(action: { state.showModal(for: .statistics) }, title: "Statistics")
  723. // .padding(.top, 20)
  724. //
  725. // menuElements(action: {
  726. // if state.pumpDisplayState != nil {
  727. // state.setupPump = true
  728. // }
  729. // }, title: "Pump Settings")
  730. //
  731. // menuElements(action: {
  732. // if state.alarm == nil {
  733. // state.openCGM()
  734. // } else {
  735. // state.showModal(for: .snooze)
  736. // }
  737. // }, title: "CGM")
  738. //
  739. // menuElements(action: { state.showModal(for: .addTempTarget) }, title: "Temp targets")
  740. //
  741. // Spacer()
  742. // })
  743. // }
  744. // }.padding(.horizontal, 25)
  745. // }
  746. // .frame(width: UIScreen.main.bounds.width / 1.2, height: UIScreen.main.bounds.height - 20)
  747. // }
  748. @ViewBuilder func mainView() -> some View {
  749. GeometryReader { geo in
  750. VStack(spacing: 0) {
  751. Spacer()
  752. .frame(height: UIScreen.main.bounds.height / 16)
  753. ZStack {
  754. /// glucose bobble
  755. glucoseView
  756. /// right panel with loop status and evBG
  757. HStack {
  758. Spacer()
  759. rightHeaderPanel(geo)
  760. }.padding(.trailing, 20)
  761. /// left panel with pump related info
  762. HStack {
  763. pumpView
  764. Spacer()
  765. }.padding(.leading, 20)
  766. }.padding(.top, 10)
  767. mealPanel(geo).padding(.top, 30).padding(.bottom, 20)
  768. RoundedRectangle(cornerRadius: 15)
  769. .fill(Color("Chart"))
  770. .overlay(mainChart)
  771. .clipShape(RoundedRectangle(cornerRadius: 15))
  772. .shadow(
  773. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  774. Color.black.opacity(0.33),
  775. radius: 3
  776. )
  777. .padding(.horizontal, 10)
  778. .frame(maxHeight: UIScreen.main.bounds.height / 2.2)
  779. timeInterval.padding(.top, 15).padding(.bottom, 20)
  780. if let progress = state.bolusProgress {
  781. bolusView(geo, progress).padding(.bottom, 25)
  782. } else {
  783. profileView(geo).padding(.bottom, 25)
  784. }
  785. }
  786. .background(color)
  787. .edgesIgnoringSafeArea(.all)
  788. }
  789. .onChange(of: state.hours) { _ in
  790. highlightButtons()
  791. }
  792. .onAppear {
  793. configureView {
  794. highlightButtons()
  795. }
  796. }
  797. .navigationTitle("Home")
  798. .navigationBarHidden(true)
  799. .ignoresSafeArea(.keyboard)
  800. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  801. popup
  802. .padding()
  803. .background(
  804. RoundedRectangle(cornerRadius: 8, style: .continuous)
  805. .fill(colorScheme == .dark ? Color(
  806. "Chart"
  807. ) : Color(UIColor.darkGray))
  808. )
  809. .onTapGesture {
  810. state.isStatusPopupPresented = false
  811. }
  812. .gesture(
  813. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  814. .onEnded { value in
  815. if value.translation.height < 0 {
  816. state.isStatusPopupPresented = false
  817. }
  818. }
  819. )
  820. }
  821. }
  822. @ViewBuilder func tabBarButton(index: Int, systemName: String, label: String) -> some View {
  823. Button(action: {
  824. selectedTab = index
  825. }) {
  826. ZStack(alignment: .bottom, content: {
  827. VStack {
  828. Image(systemName: systemName)
  829. .font(.system(size: 22))
  830. .foregroundStyle(selectedTab == index ? Color(.label) : Color.gray)
  831. Text(label)
  832. .font(.caption2)
  833. .foregroundStyle(selectedTab == index ? Color(.label) : Color.gray)
  834. .padding(.top, 1)
  835. }
  836. if selectedTab == index {
  837. Capsule()
  838. .frame(width: 25, height: 5)
  839. .foregroundStyle(Color(.label))
  840. .offset(y: 10)
  841. }
  842. })
  843. }
  844. }
  845. @ViewBuilder func customTabBar() -> some View {
  846. VStack {
  847. ZStack {
  848. switch selectedTab {
  849. case 0:
  850. mainView()
  851. case 1:
  852. NavigationStack { DataTable.RootView(resolver: resolver) }
  853. case 2:
  854. NavigationStack { OverrideProfilesConfig.RootView(resolver: resolver) }
  855. case 3:
  856. NavigationStack { Settings.RootView(resolver: resolver) }
  857. default:
  858. mainView()
  859. }
  860. }
  861. HStack {
  862. tabBarButton(
  863. index: 0,
  864. systemName: selectedTab == 0 ? "house.fill" : "house",
  865. label: "Home"
  866. )
  867. Spacer()
  868. tabBarButton(index: 1, systemName: historySFSymbol, label: "History")
  869. Spacer()
  870. Button(action: {
  871. state.showModal(for: .bolus(waitForSuggestion: false, fetch: false))
  872. }) {
  873. Image(systemName: "plus.circle.fill")
  874. .font(.system(size: 45))
  875. .foregroundStyle(Color.tabBar)
  876. .padding(.bottom, 2)
  877. }
  878. Spacer()
  879. tabBarButton(
  880. index: 2,
  881. systemName: selectedTab == 2 ? "person.fill" : "person",
  882. label: "Profile"
  883. )
  884. Spacer()
  885. tabBarButton(index: 3, systemName: "text.justify", label: "Menu")
  886. }
  887. .padding(.horizontal, 20)
  888. }.blur(radius: isMenuPresented ? 5 : 0)
  889. }
  890. @ViewBuilder func tabBar() -> some View {
  891. ZStack(alignment: .bottom) {
  892. TabView {
  893. mainView()
  894. .tabItem { Label("Home", systemImage: "house") }
  895. NavigationStack { DataTable.RootView(resolver: resolver) }
  896. .tabItem { Label("History", systemImage: historySFSymbol) }
  897. Spacer()
  898. NavigationStack { OverrideProfilesConfig.RootView(resolver: resolver) }
  899. .tabItem {
  900. Label(
  901. "Profile",
  902. systemImage: state.isTempTargetActive || overrideString != nil ? "person.fill" : "person"
  903. ) }
  904. NavigationStack { Settings.RootView(resolver: resolver) }
  905. .tabItem {
  906. Label(
  907. "Settings",
  908. systemImage: "gear"
  909. ) }
  910. }
  911. .tint(Color.tabBar)
  912. Button(
  913. action: {
  914. state.showModal(for: .bolus(waitForSuggestion: false, fetch: false)) },
  915. label: {
  916. Image(systemName: "plus.circle.fill")
  917. .font(.system(size: 45))
  918. .foregroundStyle(Color.tabBar)
  919. .padding(.bottom, 1)
  920. }
  921. )
  922. }.ignoresSafeArea(.keyboard, edges: .bottom)
  923. }
  924. var body: some View {
  925. // customTabBar()
  926. tabBar()
  927. }
  928. private var popup: some View {
  929. VStack(alignment: .leading, spacing: 4) {
  930. Text(state.statusTitle).font(.headline).foregroundColor(.white)
  931. .padding(.bottom, 4)
  932. if let suggestion = state.suggestion {
  933. TagCloudView(tags: suggestion.reasonParts).animation(.none, value: false)
  934. Text(suggestion.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  935. } else {
  936. Text("No sugestion found").font(.body).foregroundColor(.white)
  937. }
  938. if let errorMessage = state.errorMessage, let date = state.errorDate {
  939. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  940. .foregroundColor(.white)
  941. .font(.headline)
  942. .padding(.bottom, 4)
  943. .padding(.top, 8)
  944. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  945. } else if let suggestion = state.suggestion, (suggestion.bg ?? 100) == 400 {
  946. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  947. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  948. }
  949. }
  950. }
  951. }
  952. }