HomeRootView.swift 42 KB

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