HomeRootView.swift 40 KB

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