HomeRootView.swift 41 KB

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