HomeRootView.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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. @State private var statusTitle: String = ""
  16. struct Buttons: Identifiable {
  17. let label: String
  18. let number: String
  19. var active: Bool
  20. let hours: Int16
  21. var id: String { label }
  22. }
  23. @State var timeButtons: [Buttons] = [
  24. Buttons(label: "2 hours", number: "2", active: false, hours: 2),
  25. Buttons(label: "4 hours", number: "4", active: false, hours: 4),
  26. Buttons(label: "6 hours", number: "6", active: false, hours: 6),
  27. Buttons(label: "12 hours", number: "12", active: false, hours: 12),
  28. Buttons(label: "24 hours", number: "24", active: false, hours: 24)
  29. ]
  30. let buttonFont = Font.custom("TimeButtonFont", size: 14)
  31. @Environment(\.managedObjectContext) var moc
  32. @Environment(\.colorScheme) var colorScheme
  33. @FetchRequest(fetchRequest: OverrideStored.fetch(
  34. NSPredicate.lastActiveOverride,
  35. ascending: false,
  36. fetchLimit: 1
  37. )) var latestOverride: FetchedResults<OverrideStored>
  38. @FetchRequest(
  39. entity: TempTargets.entity(),
  40. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  41. ) var sliderTTpresets: FetchedResults<TempTargets>
  42. @FetchRequest(
  43. entity: TempTargetsSlider.entity(),
  44. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  45. ) var enactedSliderTT: FetchedResults<TempTargetsSlider>
  46. // TODO: end todo
  47. var bolusProgressFormatter: NumberFormatter {
  48. let formatter = NumberFormatter()
  49. formatter.numberStyle = .decimal
  50. formatter.minimum = 0
  51. formatter.maximumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  52. formatter.minimumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  53. formatter.allowsFloats = true
  54. formatter.roundingIncrement = Double(state.settingsManager.preferences.bolusIncrement) as NSNumber
  55. return formatter
  56. }
  57. private var numberFormatter: NumberFormatter {
  58. let formatter = NumberFormatter()
  59. formatter.numberStyle = .decimal
  60. formatter.maximumFractionDigits = 2
  61. return formatter
  62. }
  63. private var fetchedTargetFormatter: NumberFormatter {
  64. let formatter = NumberFormatter()
  65. formatter.numberStyle = .decimal
  66. if state.units == .mmolL {
  67. formatter.maximumFractionDigits = 1
  68. } else { formatter.maximumFractionDigits = 0 }
  69. return formatter
  70. }
  71. private var targetFormatter: NumberFormatter {
  72. let formatter = NumberFormatter()
  73. formatter.numberStyle = .decimal
  74. formatter.maximumFractionDigits = 1
  75. return formatter
  76. }
  77. private var tirFormatter: NumberFormatter {
  78. let formatter = NumberFormatter()
  79. formatter.numberStyle = .decimal
  80. formatter.maximumFractionDigits = 0
  81. return formatter
  82. }
  83. private var dateFormatter: DateFormatter {
  84. let dateFormatter = DateFormatter()
  85. dateFormatter.timeStyle = .short
  86. return dateFormatter
  87. }
  88. private var spriteScene: SKScene {
  89. let scene = SnowScene()
  90. scene.scaleMode = .resizeFill
  91. scene.backgroundColor = .clear
  92. return scene
  93. }
  94. private var color: LinearGradient {
  95. colorScheme == .dark ? LinearGradient(
  96. gradient: Gradient(colors: [
  97. Color.bgDarkBlue,
  98. Color.bgDarkerDarkBlue
  99. ]),
  100. startPoint: .top,
  101. endPoint: .bottom
  102. )
  103. :
  104. LinearGradient(
  105. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  106. startPoint: .top,
  107. endPoint: .bottom
  108. )
  109. }
  110. private var historySFSymbol: String {
  111. if #available(iOS 17.0, *) {
  112. return "book.pages"
  113. } else {
  114. return "book"
  115. }
  116. }
  117. var glucoseView: some View {
  118. CurrentGlucoseView(
  119. timerDate: $state.timerDate,
  120. units: $state.units,
  121. alarm: $state.alarm,
  122. lowGlucose: $state.lowGlucose,
  123. highGlucose: $state.highGlucose,
  124. cgmAvailable: $state.cgmAvailable,
  125. glucose: state.glucoseFromPersistence,
  126. manualGlucose: state.manualGlucoseFromPersistence
  127. ).scaleEffect(0.9)
  128. .onTapGesture {
  129. state.openCGM()
  130. }
  131. .onLongPressGesture {
  132. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  133. impactHeavy.impactOccurred()
  134. state.showModal(for: .snooze)
  135. }
  136. }
  137. var pumpView: some View {
  138. PumpView(
  139. reservoir: $state.reservoir,
  140. name: $state.pumpName,
  141. expiresAtDate: $state.pumpExpiresAtDate,
  142. timerDate: $state.timerDate,
  143. timeZone: $state.timeZone,
  144. pumpStatusHighlightMessage: $state.pumpStatusHighlightMessage,
  145. battery: $state.batteryFromPersistence
  146. ).onTapGesture {
  147. state.setupPump = true
  148. }
  149. }
  150. var tempBasalString: String? {
  151. guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
  152. return nil
  153. }
  154. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  155. var manualBasalString = ""
  156. if let apsManager = state.apsManager, apsManager.isManualTempBasal {
  157. manualBasalString = NSLocalizedString(
  158. " - Manual Basal ⚠️",
  159. comment: "Manual Temp basal"
  160. )
  161. }
  162. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  163. }
  164. var overrideString: String? {
  165. guard let latestOverride = latestOverride.first else {
  166. return nil
  167. }
  168. let percent = latestOverride.percentage
  169. let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
  170. let unit = state.units
  171. var target = (latestOverride.target ?? 100) as Decimal
  172. target = unit == .mmolL ? target.asMmolL : target
  173. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  174. .rawValue
  175. if tempTargetString != nil {
  176. targetString = ""
  177. }
  178. let duration = latestOverride.duration ?? 0
  179. let addedMinutes = Int(truncating: duration)
  180. let date = latestOverride.date ?? Date()
  181. let newDuration = max(
  182. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  183. 0
  184. )
  185. let indefinite = latestOverride.indefinite
  186. var durationString = ""
  187. if !indefinite {
  188. if newDuration >= 1 {
  189. durationString =
  190. "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
  191. } else if newDuration > 0 {
  192. durationString =
  193. "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
  194. } else {
  195. /// Do not show the Override anymore
  196. Task {
  197. guard let objectID = self.latestOverride.first?.objectID else { return }
  198. await state.cancelOverride(withID: objectID)
  199. }
  200. }
  201. }
  202. let smbToggleString = latestOverride.smbIsOff ? " \u{20e0}" : ""
  203. let components = [percentString, targetString, durationString, smbToggleString].filter { !$0.isEmpty }
  204. return components.isEmpty ? nil : components.joined(separator: ", ")
  205. }
  206. var tempTargetString: String? {
  207. guard let tempTarget = state.tempTarget else {
  208. return nil
  209. }
  210. let target = tempTarget.targetBottom ?? 0
  211. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  212. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  213. .rawValue
  214. var string = ""
  215. if sliderTTpresets.first?.active ?? false {
  216. let hbt = sliderTTpresets.first?.hbt ?? 0
  217. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  218. }
  219. let percentString = state
  220. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  221. return tempTarget.displayName + " " + percentString
  222. }
  223. var infoPanel: some View {
  224. HStack(alignment: .center) {
  225. if state.pumpSuspended {
  226. Text("Pump suspended")
  227. .font(.system(size: 15, weight: .bold)).foregroundColor(.loopGray)
  228. .padding(.leading, 8)
  229. } else if let tempBasalString = tempBasalString {
  230. Text(tempBasalString)
  231. .font(.system(size: 15, weight: .bold))
  232. .foregroundColor(.insulin)
  233. .padding(.leading, 8)
  234. }
  235. if state.totalInsulinDisplayType == .totalInsulinInScope {
  236. Text(
  237. "TINS: \(state.calculateTINS())" +
  238. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  239. )
  240. .font(.system(size: 15, weight: .bold))
  241. .foregroundColor(.insulin)
  242. }
  243. if let tempTargetString = tempTargetString {
  244. Text(tempTargetString)
  245. .font(.caption)
  246. .foregroundColor(.secondary)
  247. }
  248. Spacer()
  249. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  250. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  251. }
  252. }
  253. .frame(maxWidth: .infinity, maxHeight: 30)
  254. }
  255. var timeInterval: some View {
  256. HStack(alignment: .center) {
  257. ForEach(timeButtons) { button in
  258. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  259. state.hours = button.hours
  260. }
  261. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  262. .frame(maxHeight: 30).padding(.horizontal, 8)
  263. .background(
  264. button.active ?
  265. // RGB(30, 60, 95)
  266. (
  267. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  268. Color.white
  269. ) :
  270. Color
  271. .clear
  272. )
  273. .cornerRadius(20)
  274. }
  275. Button(action: {
  276. state.isLegendPresented.toggle()
  277. }) {
  278. Image(systemName: "info")
  279. .foregroundColor(colorScheme == .dark ? Color.white : Color.black).opacity(0.9)
  280. .frame(width: 20, height: 20)
  281. .background(
  282. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  283. Color.white
  284. )
  285. .clipShape(Circle())
  286. }
  287. .padding([.top, .bottom])
  288. }
  289. .shadow(
  290. color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33),
  291. radius: colorScheme == .dark ? 5 : 3
  292. )
  293. .font(buttonFont)
  294. }
  295. @ViewBuilder func mainChart(geo: GeometryProxy) -> some View {
  296. ZStack {
  297. MainChartView(
  298. geo: geo,
  299. units: $state.units,
  300. announcement: $state.announcement,
  301. hours: .constant(state.filteredHours),
  302. maxBasal: $state.maxBasal,
  303. autotunedBasalProfile: $state.autotunedBasalProfile,
  304. basalProfile: $state.basalProfile,
  305. tempTargets: $state.tempTargets,
  306. smooth: $state.smooth,
  307. highGlucose: $state.highGlucose,
  308. lowGlucose: $state.lowGlucose,
  309. screenHours: $state.hours,
  310. displayXgridLines: $state.displayXgridLines,
  311. displayYgridLines: $state.displayYgridLines,
  312. thresholdLines: $state.thresholdLines,
  313. isTempTargetActive: $state.isTempTargetActive,
  314. state: state
  315. )
  316. }
  317. .padding(.bottom)
  318. }
  319. func highlightButtons() {
  320. for i in 0 ..< timeButtons.count {
  321. timeButtons[i].active = timeButtons[i].hours == state.hours
  322. }
  323. }
  324. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  325. VStack(alignment: .leading, spacing: 20) {
  326. /// Loop view at bottomLeading
  327. LoopView(
  328. closedLoop: $state.closedLoop,
  329. timerDate: $state.timerDate,
  330. isLooping: $state.isLooping,
  331. lastLoopDate: $state.lastLoopDate,
  332. manualTempBasal: $state.manualTempBasal,
  333. determination: state.determinationsFromPersistence
  334. ).onTapGesture {
  335. state.isStatusPopupPresented = true
  336. setStatusTitle()
  337. }.onLongPressGesture {
  338. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  339. impactHeavy.impactOccurred()
  340. state.runLoop()
  341. }
  342. /// eventualBG string at bottomTrailing
  343. if let eventualBG = state.determinationsFromPersistence.first?.eventualBG {
  344. let bg = eventualBG as Decimal
  345. HStack {
  346. Image(systemName: "arrow.right.circle")
  347. .font(.system(size: 16, weight: .bold))
  348. Text(
  349. numberFormatter.string(
  350. from: (
  351. state.units == .mmolL ? bg
  352. .asMmolL : bg
  353. ) as NSNumber
  354. )!
  355. )
  356. .font(.system(size: 16))
  357. }
  358. } else {
  359. HStack {
  360. Image(systemName: "arrow.right.circle")
  361. .font(.system(size: 16, weight: .bold))
  362. Text("--")
  363. .font(.system(size: 16))
  364. }
  365. }
  366. }
  367. }
  368. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  369. HStack {
  370. HStack {
  371. Image(systemName: "syringe.fill")
  372. .font(.system(size: 16))
  373. .foregroundColor(Color.insulin)
  374. Text(
  375. (
  376. numberFormatter
  377. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  378. ) +
  379. NSLocalizedString(" U", comment: "Insulin unit")
  380. )
  381. .font(.system(size: 16, weight: .bold, design: .rounded))
  382. }
  383. Spacer()
  384. HStack {
  385. Image(systemName: "fork.knife")
  386. .font(.system(size: 16))
  387. .foregroundColor(.loopYellow)
  388. Text(
  389. (
  390. numberFormatter
  391. .string(from: (state.enactedAndNonEnactedDeterminations.first?.cob ?? 0) as NSNumber) ?? "0"
  392. ) +
  393. NSLocalizedString(" g", comment: "gram of carbs")
  394. )
  395. .font(.system(size: 16, weight: .bold, design: .rounded))
  396. }
  397. Spacer()
  398. HStack {
  399. if state.pumpSuspended {
  400. Text("Pump suspended")
  401. .font(.system(size: 12, weight: .bold, design: .rounded)).foregroundColor(.loopGray)
  402. } else if let tempBasalString = tempBasalString {
  403. Image(systemName: "drop.circle")
  404. .font(.system(size: 16))
  405. .foregroundColor(.insulinTintColor)
  406. Text(tempBasalString)
  407. .font(.system(size: 16, weight: .bold, design: .rounded))
  408. } else {
  409. Image(systemName: "drop.circle")
  410. .font(.system(size: 16))
  411. .foregroundColor(.insulinTintColor)
  412. Text("No Data")
  413. .font(.system(size: 16, weight: .bold, design: .rounded))
  414. }
  415. }
  416. if state.totalInsulinDisplayType == .totalDailyDose {
  417. Spacer()
  418. Text(
  419. "TDD: " +
  420. (
  421. numberFormatter
  422. .string(from: (state.determinationsFromPersistence.first?.totalDailyDose ?? 0) as NSNumber) ??
  423. "0"
  424. ) +
  425. NSLocalizedString(" U", comment: "Insulin unit")
  426. )
  427. .font(.system(size: 16, weight: .bold, design: .rounded))
  428. } else {
  429. Spacer()
  430. HStack {
  431. Text(
  432. "TINS: \(state.roundedTotalBolus)" +
  433. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  434. )
  435. .font(.system(size: 16, weight: .bold, design: .rounded))
  436. .onChange(of: state.hours) { _ in
  437. state.roundedTotalBolus = state.calculateTINS()
  438. }
  439. .onAppear {
  440. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  441. state.roundedTotalBolus = state.calculateTINS()
  442. }
  443. }
  444. }
  445. }
  446. }.padding(.horizontal, 10)
  447. }
  448. @ViewBuilder func profileView(geo: GeometryProxy) -> some View {
  449. ZStack {
  450. /// rectangle as background
  451. RoundedRectangle(cornerRadius: 15)
  452. .fill(
  453. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  454. .opacity(0.1)
  455. )
  456. .clipShape(RoundedRectangle(cornerRadius: 15))
  457. .frame(height: geo.size.height * 0.08)
  458. .shadow(
  459. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  460. Color.black.opacity(0.33),
  461. radius: 3
  462. )
  463. HStack {
  464. /// actual profile view
  465. Image(systemName: "person.fill")
  466. .font(.system(size: 25))
  467. Spacer()
  468. if let overrideString = overrideString {
  469. VStack {
  470. Text(latestOverride.first?.name ?? "Custom Override")
  471. .font(.subheadline)
  472. .frame(maxWidth: .infinity, alignment: .leading)
  473. Text("\(overrideString)")
  474. .font(.caption)
  475. .frame(maxWidth: .infinity, alignment: .leading)
  476. }.padding(.leading, 5)
  477. Spacer()
  478. Image(systemName: "xmark.app")
  479. .font(.system(size: 25))
  480. } else {
  481. if tempTargetString == nil {
  482. VStack {
  483. Text("Normal Profile")
  484. .font(.subheadline)
  485. .frame(maxWidth: .infinity, alignment: .leading)
  486. Text("100 %")
  487. .font(.caption)
  488. .frame(maxWidth: .infinity, alignment: .leading)
  489. }.padding(.leading, 5)
  490. Spacer()
  491. /// to ensure the same position....
  492. Image(systemName: "xmark.app")
  493. .font(.system(size: 25))
  494. .foregroundStyle(Color.clear)
  495. }
  496. }
  497. }.padding(.horizontal, 10)
  498. .alert(
  499. "Return to Normal?", isPresented: $showCancelAlert,
  500. actions: {
  501. Button("No", role: .cancel) {}
  502. Button("Yes", role: .destructive) {
  503. Task {
  504. guard let objectID = latestOverride.first?.objectID else { return }
  505. await state.cancelOverride(withID: objectID)
  506. }
  507. }
  508. }, message: { Text("This will change settings back to your normal profile.") }
  509. )
  510. .padding(.trailing, 8)
  511. .onTapGesture {
  512. if !latestOverride.isEmpty {
  513. showCancelAlert = true
  514. }
  515. }
  516. }.padding(.horizontal, 10).padding(.bottom, 10)
  517. .overlay {
  518. /// just show temp target if no profile is already active
  519. if overrideString == nil, let tempTargetString = tempTargetString {
  520. ZStack {
  521. /// rectangle as background
  522. RoundedRectangle(cornerRadius: 15)
  523. .fill(
  524. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  525. Color
  526. .insulin
  527. .opacity(0.2)
  528. )
  529. .clipShape(RoundedRectangle(cornerRadius: 15))
  530. .frame(height: UIScreen.main.bounds.height / 18)
  531. .shadow(
  532. color: colorScheme == .dark ? Color(
  533. red: 0.02745098039,
  534. green: 0.1098039216,
  535. blue: 0.1411764706
  536. ) :
  537. Color.black.opacity(0.33),
  538. radius: 3
  539. )
  540. HStack {
  541. Image(systemName: "person.fill")
  542. .font(.system(size: 25))
  543. Spacer()
  544. Text(tempTargetString)
  545. .font(.subheadline)
  546. Spacer()
  547. }.padding(.horizontal, 10)
  548. }.padding(.horizontal, 10).padding(.bottom, 10)
  549. }
  550. }
  551. }
  552. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  553. GeometryReader { geo in
  554. RoundedRectangle(cornerRadius: 15)
  555. .frame(height: 6)
  556. .foregroundColor(.clear)
  557. .background(
  558. LinearGradient(colors: [
  559. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  560. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  561. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  562. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  563. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  564. ], startPoint: .leading, endPoint: .trailing)
  565. .mask(alignment: .leading) {
  566. RoundedRectangle(cornerRadius: 15)
  567. .frame(width: geo.size.width * CGFloat(progress))
  568. }
  569. )
  570. }
  571. }
  572. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  573. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  574. /// - TRUE: show the pump bolus
  575. /// - FALSE: do not show a progress bar at all
  576. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  577. let bolusFraction = progress * (bolusTotal as Decimal)
  578. let bolusString =
  579. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  580. + " of " +
  581. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  582. + NSLocalizedString(" U", comment: "Insulin unit")
  583. ZStack {
  584. /// rectangle as background
  585. RoundedRectangle(cornerRadius: 15)
  586. .fill(
  587. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  588. .insulin
  589. .opacity(0.2)
  590. )
  591. .clipShape(RoundedRectangle(cornerRadius: 15))
  592. .frame(height: geo.size.height * 0.08)
  593. .shadow(
  594. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  595. Color.black.opacity(0.33),
  596. radius: 3
  597. )
  598. /// actual bolus view
  599. HStack {
  600. Image(systemName: "cross.vial.fill")
  601. .font(.system(size: 25))
  602. Spacer()
  603. VStack {
  604. Text("Bolusing")
  605. .font(.subheadline)
  606. .frame(maxWidth: .infinity, alignment: .leading)
  607. Text(bolusString)
  608. .font(.caption)
  609. .frame(maxWidth: .infinity, alignment: .leading)
  610. }.padding(.leading, 5)
  611. Spacer()
  612. Button {
  613. state.waitForSuggestion = true
  614. state.cancelBolus()
  615. } label: {
  616. Image(systemName: "xmark.app")
  617. .font(.system(size: 25))
  618. }
  619. }.padding(.horizontal, 10)
  620. .padding(.trailing, 8)
  621. }.padding(.horizontal, 10).padding(.bottom, 10)
  622. .overlay(alignment: .bottom) {
  623. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 48)
  624. }.clipShape(RoundedRectangle(cornerRadius: 15))
  625. }
  626. }
  627. @ViewBuilder func mainView() -> some View {
  628. GeometryReader { geo in
  629. VStack(spacing: 0) {
  630. ZStack {
  631. /// glucose bobble
  632. glucoseView
  633. /// right panel with loop status and evBG
  634. HStack {
  635. Spacer()
  636. rightHeaderPanel(geo)
  637. }.padding(.trailing, 20)
  638. /// left panel with pump related info
  639. HStack {
  640. pumpView
  641. Spacer()
  642. }.padding(.leading, 20)
  643. }.padding(.top, 10)
  644. mealPanel(geo).padding(.top, 30).padding(.bottom, 20)
  645. mainChart(geo: geo)
  646. timeInterval.padding(.top, 12).padding(.bottom, 12)
  647. if let progress = state.bolusProgress {
  648. bolusView(geo: geo, progress).padding(.bottom, 40)
  649. } else {
  650. profileView(geo: geo).padding(.bottom, 40)
  651. }
  652. }
  653. .background(color)
  654. }
  655. .onChange(of: state.hours) { _ in
  656. highlightButtons()
  657. }
  658. .onAppear {
  659. configureView {
  660. highlightButtons()
  661. }
  662. }
  663. .navigationTitle("Home")
  664. .navigationBarHidden(true)
  665. .ignoresSafeArea(.keyboard)
  666. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  667. popup
  668. .padding()
  669. .background(
  670. RoundedRectangle(cornerRadius: 8, style: .continuous)
  671. .fill(colorScheme == .dark ? Color(
  672. "Chart"
  673. ) : Color(UIColor.darkGray))
  674. )
  675. .onTapGesture {
  676. state.isStatusPopupPresented = false
  677. }
  678. .gesture(
  679. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  680. .onEnded { value in
  681. if value.translation.height < 0 {
  682. state.isStatusPopupPresented = false
  683. }
  684. }
  685. )
  686. }
  687. .sheet(isPresented: $state.isLegendPresented) {
  688. NavigationStack {
  689. Text(
  690. "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  691. )
  692. .font(.subheadline)
  693. .foregroundColor(.secondary)
  694. List {
  695. DefinitionRow(
  696. term: "IOB (Insulin on Board)",
  697. definition: "Forecasts BG based on the amount of insulin still active in the body.",
  698. color: .insulin
  699. )
  700. DefinitionRow(
  701. term: "ZT (Zero-Temp)",
  702. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  703. color: .zt
  704. )
  705. DefinitionRow(
  706. term: "COB (Carbs on Board)",
  707. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  708. color: .loopYellow
  709. )
  710. DefinitionRow(
  711. term: "UAM (Unannounced Meal)",
  712. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  713. color: .uam
  714. )
  715. }
  716. .padding(.trailing, 10)
  717. .navigationBarTitle("Legend", displayMode: .inline)
  718. Button { state.isLegendPresented.toggle() }
  719. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  720. .buttonStyle(.bordered)
  721. .padding(.top)
  722. }
  723. .padding()
  724. .presentationDetents(
  725. [.fraction(0.9), .large],
  726. selection: $state.legendSheetDetent
  727. )
  728. }
  729. }
  730. @State var settingsPath = NavigationPath()
  731. @ViewBuilder func tabBar() -> some View {
  732. ZStack(alignment: .bottom) {
  733. TabView(selection: $selectedTab) {
  734. let carbsRequiredBadge: String? = {
  735. guard let carbsRequired = state.determinationsFromPersistence.first?.carbsRequired as? Decimal,
  736. state.showCarbsRequiredBadge
  737. else { return nil }
  738. if carbsRequired > state.settingsManager.settings.carbsRequiredThreshold {
  739. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequired)
  740. let formattedNumber = numberFormatter.string(from: numberAsNSNumber) ?? ""
  741. return formattedNumber + " g"
  742. } else {
  743. return nil
  744. }
  745. }()
  746. NavigationStack { mainView() }
  747. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  748. .badge(carbsRequiredBadge).tag(0)
  749. NavigationStack { DataTable.RootView(resolver: resolver) }
  750. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  751. Spacer()
  752. NavigationStack { OverrideConfig.RootView(resolver: resolver) }
  753. .tabItem {
  754. Label(
  755. "Adjustments",
  756. systemImage: "slider.horizontal.2.gobackward"
  757. ) }.tag(2)
  758. NavigationStack(path: self.$settingsPath) {
  759. Settings.RootView(resolver: resolver) }
  760. .tabItem { Label(
  761. "Settings",
  762. systemImage: "gear"
  763. ) }.tag(3)
  764. }
  765. .tint(Color.tabBar)
  766. Button(
  767. action: {
  768. state.showModal(for: .bolus) },
  769. label: {
  770. Image(systemName: "plus.circle.fill")
  771. .font(.system(size: 40))
  772. .foregroundStyle(Color.tabBar)
  773. .padding(.bottom, 1)
  774. .padding(.horizontal, 20)
  775. }
  776. )
  777. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  778. .onChange(of: selectedTab) { _ in
  779. print("current path is empty: \(settingsPath.isEmpty)")
  780. settingsPath = NavigationPath()
  781. }
  782. }
  783. var body: some View {
  784. ZStack(alignment: .center) {
  785. tabBar()
  786. if state.waitForSuggestion {
  787. CustomProgressView(text: "Updating IOB...")
  788. }
  789. }
  790. }
  791. private var popup: some View {
  792. VStack(alignment: .leading, spacing: 4) {
  793. Text(statusTitle).font(.headline).foregroundColor(.white)
  794. .padding(.bottom, 4)
  795. if let determination = state.determinationsFromPersistence.first {
  796. if determination.glucose == 400 {
  797. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  798. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  799. } else {
  800. TagCloudView(tags: determination.reasonParts).animation(.none, value: false)
  801. Text(determination.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  802. }
  803. } else {
  804. Text("No determination found").font(.body).foregroundColor(.white)
  805. }
  806. if let errorMessage = state.errorMessage, let date = state.errorDate {
  807. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  808. .foregroundColor(.white)
  809. .font(.headline)
  810. .padding(.bottom, 4)
  811. .padding(.top, 8)
  812. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  813. }
  814. }
  815. }
  816. private func setStatusTitle() {
  817. if let determination = state.determinationsFromPersistence.first {
  818. let dateFormatter = DateFormatter()
  819. dateFormatter.timeStyle = .short
  820. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  821. " " +
  822. dateFormatter
  823. .string(from: determination.deliverAt ?? Date())
  824. } else {
  825. statusTitle = "No Oref determination"
  826. return
  827. }
  828. }
  829. }
  830. }