HomeRootView.swift 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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. currentGlucoseTarget: $state.currentGlucoseTarget,
  332. screenHours: $state.hours,
  333. dynamicGlucoseColor: $state.dynamicGlucoseColor,
  334. displayXgridLines: $state.displayXgridLines,
  335. displayYgridLines: $state.displayYgridLines,
  336. thresholdLines: $state.thresholdLines,
  337. isTempTargetActive: $state.isTempTargetActive,
  338. state: state
  339. )
  340. }
  341. .padding(.bottom)
  342. }
  343. func highlightButtons() {
  344. for i in 0 ..< timeButtons.count {
  345. timeButtons[i].active = timeButtons[i].hours == state.hours
  346. }
  347. }
  348. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  349. VStack(alignment: .leading, spacing: 20) {
  350. /// Loop view at bottomLeading
  351. LoopView(
  352. closedLoop: $state.closedLoop,
  353. timerDate: $state.timerDate,
  354. isLooping: $state.isLooping,
  355. lastLoopDate: $state.lastLoopDate,
  356. manualTempBasal: $state.manualTempBasal,
  357. determination: state.determinationsFromPersistence
  358. ).onTapGesture {
  359. state.isStatusPopupPresented = true
  360. setStatusTitle()
  361. }.onLongPressGesture {
  362. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  363. impactHeavy.impactOccurred()
  364. state.runLoop()
  365. }
  366. /// eventualBG string at bottomTrailing
  367. if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
  368. let bg = eventualBG as Decimal
  369. HStack {
  370. Image(systemName: "arrow.right.circle")
  371. .font(.system(size: 16, weight: .bold))
  372. Text(
  373. numberFormatter.string(
  374. from: (
  375. state.units == .mmolL ? bg
  376. .asMmolL : bg
  377. ) as NSNumber
  378. )!
  379. )
  380. .font(.system(size: 16))
  381. }
  382. } else {
  383. HStack {
  384. Image(systemName: "arrow.right.circle")
  385. .font(.system(size: 16, weight: .bold))
  386. Text("--")
  387. .font(.system(size: 16))
  388. }
  389. }
  390. }
  391. }
  392. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  393. HStack {
  394. HStack {
  395. Image(systemName: "syringe.fill")
  396. .font(.system(size: 16))
  397. .foregroundColor(Color.insulin)
  398. Text(
  399. (
  400. numberFormatter
  401. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  402. ) +
  403. NSLocalizedString(" U", comment: "Insulin unit")
  404. )
  405. .font(.system(size: 16, weight: .bold, design: .rounded))
  406. }
  407. Spacer()
  408. HStack {
  409. Image(systemName: "fork.knife")
  410. .font(.system(size: 16))
  411. .foregroundColor(.loopYellow)
  412. Text(
  413. (
  414. numberFormatter
  415. .string(from: (state.enactedAndNonEnactedDeterminations.first?.cob ?? 0) as NSNumber) ?? "0"
  416. ) +
  417. NSLocalizedString(" g", comment: "gram of carbs")
  418. )
  419. .font(.system(size: 16, weight: .bold, design: .rounded))
  420. }
  421. Spacer()
  422. HStack {
  423. if state.pumpSuspended {
  424. Text("Pump suspended")
  425. .font(.system(size: 12, weight: .bold, design: .rounded)).foregroundColor(.loopGray)
  426. } else if let tempBasalString = tempBasalString {
  427. Image(systemName: "drop.circle")
  428. .font(.system(size: 16))
  429. .foregroundColor(.insulinTintColor)
  430. Text(tempBasalString)
  431. .font(.system(size: 16, weight: .bold, design: .rounded))
  432. } else {
  433. Image(systemName: "drop.circle")
  434. .font(.system(size: 16))
  435. .foregroundColor(.insulinTintColor)
  436. Text("No Data")
  437. .font(.system(size: 16, weight: .bold, design: .rounded))
  438. }
  439. }
  440. if !state.tins {
  441. Spacer()
  442. Text(
  443. "TDD: " +
  444. (
  445. numberFormatter
  446. .string(from: (state.determinationsFromPersistence.first?.totalDailyDose ?? 0) as NSNumber) ??
  447. "0"
  448. ) +
  449. NSLocalizedString(" U", comment: "Insulin unit")
  450. )
  451. .font(.system(size: 16, weight: .bold, design: .rounded))
  452. } else {
  453. Spacer()
  454. HStack {
  455. Text(
  456. "TINS: \(state.roundedTotalBolus)" +
  457. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  458. )
  459. .font(.system(size: 16, weight: .bold, design: .rounded))
  460. .onChange(of: state.hours) { _ in
  461. state.roundedTotalBolus = state.calculateTINS()
  462. }
  463. .onAppear {
  464. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  465. state.roundedTotalBolus = state.calculateTINS()
  466. }
  467. }
  468. }
  469. }
  470. }.padding(.horizontal, 10)
  471. }
  472. @ViewBuilder func profileView(geo: GeometryProxy) -> some View {
  473. ZStack {
  474. /// rectangle as background
  475. RoundedRectangle(cornerRadius: 15)
  476. .fill(
  477. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  478. .opacity(0.1)
  479. )
  480. .clipShape(RoundedRectangle(cornerRadius: 15))
  481. .frame(height: geo.size.height * 0.08)
  482. .shadow(
  483. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  484. Color.black.opacity(0.33),
  485. radius: 3
  486. )
  487. HStack {
  488. /// actual profile view
  489. Image(systemName: "person.fill")
  490. .font(.system(size: 25))
  491. Spacer()
  492. if let overrideString = overrideString {
  493. VStack {
  494. Text(latestOverride.first?.name ?? "Custom Override")
  495. .font(.subheadline)
  496. .frame(maxWidth: .infinity, alignment: .leading)
  497. Text("\(overrideString)")
  498. .font(.caption)
  499. .frame(maxWidth: .infinity, alignment: .leading)
  500. }.padding(.leading, 5)
  501. Spacer()
  502. Image(systemName: "xmark.app")
  503. .font(.system(size: 25))
  504. } else {
  505. if tempTargetString == nil {
  506. VStack {
  507. Text("Normal Profile")
  508. .font(.subheadline)
  509. .frame(maxWidth: .infinity, alignment: .leading)
  510. Text("100 %")
  511. .font(.caption)
  512. .frame(maxWidth: .infinity, alignment: .leading)
  513. }.padding(.leading, 5)
  514. Spacer()
  515. /// to ensure the same position....
  516. Image(systemName: "xmark.app")
  517. .font(.system(size: 25))
  518. .foregroundStyle(Color.clear)
  519. }
  520. }
  521. }.padding(.horizontal, 10)
  522. .alert(
  523. "Return to Normal?", isPresented: $showCancelAlert,
  524. actions: {
  525. Button("No", role: .cancel) {}
  526. Button("Yes", role: .destructive) {
  527. Task {
  528. guard let objectID = latestOverride.first?.objectID else { return }
  529. await state.cancelOverride(withID: objectID)
  530. }
  531. }
  532. }, message: { Text("This will change settings back to your normal profile.") }
  533. )
  534. .padding(.trailing, 8)
  535. .onTapGesture {
  536. if !latestOverride.isEmpty {
  537. showCancelAlert = true
  538. }
  539. }
  540. }.padding(.horizontal, 10).padding(.bottom, 10)
  541. .overlay {
  542. /// just show temp target if no profile is already active
  543. if overrideString == nil, let tempTargetString = tempTargetString {
  544. ZStack {
  545. /// rectangle as background
  546. RoundedRectangle(cornerRadius: 15)
  547. .fill(
  548. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  549. Color
  550. .insulin
  551. .opacity(0.2)
  552. )
  553. .clipShape(RoundedRectangle(cornerRadius: 15))
  554. .frame(height: UIScreen.main.bounds.height / 18)
  555. .shadow(
  556. color: colorScheme == .dark ? Color(
  557. red: 0.02745098039,
  558. green: 0.1098039216,
  559. blue: 0.1411764706
  560. ) :
  561. Color.black.opacity(0.33),
  562. radius: 3
  563. )
  564. HStack {
  565. Image(systemName: "person.fill")
  566. .font(.system(size: 25))
  567. Spacer()
  568. Text(tempTargetString)
  569. .font(.subheadline)
  570. Spacer()
  571. }.padding(.horizontal, 10)
  572. }.padding(.horizontal, 10).padding(.bottom, 10)
  573. }
  574. }
  575. }
  576. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  577. GeometryReader { geo in
  578. RoundedRectangle(cornerRadius: 15)
  579. .frame(height: 6)
  580. .foregroundColor(.clear)
  581. .background(
  582. LinearGradient(colors: [
  583. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  584. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  585. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  586. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  587. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  588. ], startPoint: .leading, endPoint: .trailing)
  589. .mask(alignment: .leading) {
  590. RoundedRectangle(cornerRadius: 15)
  591. .frame(width: geo.size.width * CGFloat(progress))
  592. }
  593. )
  594. }
  595. }
  596. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  597. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  598. /// - TRUE: show the pump bolus
  599. /// - FALSE: do not show a progress bar at all
  600. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  601. let bolusFraction = progress * (bolusTotal as Decimal)
  602. let bolusString =
  603. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  604. + " of " +
  605. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  606. + NSLocalizedString(" U", comment: "Insulin unit")
  607. ZStack {
  608. /// rectangle as background
  609. RoundedRectangle(cornerRadius: 15)
  610. .fill(
  611. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  612. .insulin
  613. .opacity(0.2)
  614. )
  615. .clipShape(RoundedRectangle(cornerRadius: 15))
  616. .frame(height: geo.size.height * 0.08)
  617. .shadow(
  618. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  619. Color.black.opacity(0.33),
  620. radius: 3
  621. )
  622. /// actual bolus view
  623. HStack {
  624. Image(systemName: "cross.vial.fill")
  625. .font(.system(size: 25))
  626. Spacer()
  627. VStack {
  628. Text("Bolusing")
  629. .font(.subheadline)
  630. .frame(maxWidth: .infinity, alignment: .leading)
  631. Text(bolusString)
  632. .font(.caption)
  633. .frame(maxWidth: .infinity, alignment: .leading)
  634. }.padding(.leading, 5)
  635. Spacer()
  636. Button {
  637. state.showProgressView()
  638. state.cancelBolus()
  639. } label: {
  640. Image(systemName: "xmark.app")
  641. .font(.system(size: 25))
  642. }
  643. }.padding(.horizontal, 10)
  644. .padding(.trailing, 8)
  645. }.padding(.horizontal, 10).padding(.bottom, 10)
  646. .overlay(alignment: .bottom) {
  647. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 48)
  648. }.clipShape(RoundedRectangle(cornerRadius: 15))
  649. }
  650. }
  651. @ViewBuilder func mainView() -> some View {
  652. GeometryReader { geo in
  653. VStack(spacing: 0) {
  654. ZStack {
  655. /// glucose bobble
  656. glucoseView
  657. /// right panel with loop status and evBG
  658. HStack {
  659. Spacer()
  660. rightHeaderPanel(geo)
  661. }.padding(.trailing, 20)
  662. /// left panel with pump related info
  663. HStack {
  664. pumpView
  665. Spacer()
  666. }.padding(.leading, 20)
  667. }.padding(.top, 10)
  668. mealPanel(geo).padding(.top, 30).padding(.bottom, 20)
  669. mainChart(geo: geo)
  670. timeInterval.padding(.top, 12).padding(.bottom, 12)
  671. if let progress = state.bolusProgress {
  672. bolusView(geo: geo, progress).padding(.bottom, 40)
  673. } else {
  674. profileView(geo: geo).padding(.bottom, 40)
  675. }
  676. }
  677. .background(color)
  678. }
  679. .onChange(of: state.hours) { _ in
  680. highlightButtons()
  681. }
  682. .onAppear {
  683. configureView {
  684. highlightButtons()
  685. }
  686. }
  687. .navigationTitle("Home")
  688. .navigationBarHidden(true)
  689. .ignoresSafeArea(.keyboard)
  690. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  691. popup
  692. .padding()
  693. .background(
  694. RoundedRectangle(cornerRadius: 8, style: .continuous)
  695. .fill(colorScheme == .dark ? Color(
  696. "Chart"
  697. ) : Color(UIColor.darkGray))
  698. )
  699. .onTapGesture {
  700. state.isStatusPopupPresented = false
  701. }
  702. .gesture(
  703. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  704. .onEnded { value in
  705. if value.translation.height < 0 {
  706. state.isStatusPopupPresented = false
  707. }
  708. }
  709. )
  710. }
  711. .sheet(isPresented: $state.isLegendPresented) {
  712. NavigationStack {
  713. Text(
  714. "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  715. )
  716. .font(.subheadline)
  717. .foregroundColor(.secondary)
  718. if state.settingsManager.settings.displayForecastsAsLines {
  719. List {
  720. DefinitionRow(
  721. term: "IOB (Insulin on Board)",
  722. definition: "Forecasts BG based on the amount of insulin still active in the body.",
  723. color: .insulin
  724. )
  725. DefinitionRow(
  726. term: "ZT (Zero-Temp)",
  727. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  728. color: .zt
  729. )
  730. DefinitionRow(
  731. term: "COB (Carbs on Board)",
  732. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  733. color: .loopYellow
  734. )
  735. DefinitionRow(
  736. term: "UAM (Unannounced Meal)",
  737. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  738. color: .uam
  739. )
  740. }
  741. .padding(.trailing, 10)
  742. .navigationBarTitle("Legend", displayMode: .inline)
  743. } else {
  744. List {
  745. DefinitionRow(
  746. term: "Cone of Uncertainty",
  747. 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.",
  748. color: Color.blue.opacity(0.5)
  749. )
  750. }
  751. .padding(.trailing, 10)
  752. .navigationBarTitle("Legend", displayMode: .inline)
  753. }
  754. Button { state.isLegendPresented.toggle() }
  755. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  756. .buttonStyle(.bordered)
  757. .padding(.top)
  758. }
  759. .padding()
  760. .presentationDetents(
  761. [.fraction(0.9), .large],
  762. selection: $state.legendSheetDetent
  763. )
  764. }
  765. }
  766. @State var settingsPath = NavigationPath()
  767. @ViewBuilder func tabBar() -> some View {
  768. ZStack(alignment: .bottom) {
  769. TabView(selection: $selectedTab) {
  770. let carbsRequiredBadge: String? = {
  771. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired else {
  772. return nil
  773. }
  774. let carbsRequiredDecimal = Decimal(carbsRequired)
  775. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  776. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  777. return (numberFormatter.string(from: numberAsNSNumber) ?? "") + " g"
  778. }
  779. return nil
  780. }()
  781. NavigationStack { mainView() }
  782. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  783. .badge(carbsRequiredBadge).tag(0)
  784. NavigationStack { DataTable.RootView(resolver: resolver) }
  785. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  786. Spacer()
  787. NavigationStack { OverrideConfig.RootView(resolver: resolver) }
  788. .tabItem {
  789. Label(
  790. "Adjustments",
  791. systemImage: "slider.horizontal.2.gobackward"
  792. ) }.tag(2)
  793. NavigationStack(path: self.$settingsPath) {
  794. Settings.RootView(resolver: resolver) }
  795. .tabItem { Label(
  796. "Settings",
  797. systemImage: "gear"
  798. ) }.tag(3)
  799. }
  800. .tint(Color.tabBar)
  801. Button(
  802. action: {
  803. state.showModal(for: .bolus) },
  804. label: {
  805. Image(systemName: "plus.circle.fill")
  806. .font(.system(size: 40))
  807. .foregroundStyle(Color.tabBar)
  808. .padding(.bottom, 1)
  809. .padding(.horizontal, 20)
  810. }
  811. )
  812. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  813. .onChange(of: selectedTab) { _ in
  814. print("current path is empty: \(settingsPath.isEmpty)")
  815. settingsPath = NavigationPath()
  816. }
  817. }
  818. var body: some View {
  819. ZStack(alignment: .center) {
  820. tabBar()
  821. if state.waitForSuggestion {
  822. CustomProgressView(text: "Updating IOB...")
  823. }
  824. }
  825. }
  826. private var popup: some View {
  827. VStack(alignment: .leading, spacing: 4) {
  828. Text(statusTitle).font(.headline).foregroundColor(.white)
  829. .padding(.bottom, 4)
  830. if let determination = state.determinationsFromPersistence.first {
  831. if determination.glucose == 400 {
  832. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  833. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  834. } else {
  835. TagCloudView(tags: determination.reasonParts).animation(.none, value: false)
  836. Text(determination.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  837. }
  838. } else {
  839. Text("No determination found").font(.body).foregroundColor(.white)
  840. }
  841. if let errorMessage = state.errorMessage, let date = state.errorDate {
  842. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  843. .foregroundColor(.white)
  844. .font(.headline)
  845. .padding(.bottom, 4)
  846. .padding(.top, 8)
  847. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  848. }
  849. }
  850. }
  851. private func setStatusTitle() {
  852. if let determination = state.determinationsFromPersistence.first {
  853. let dateFormatter = DateFormatter()
  854. dateFormatter.timeStyle = .short
  855. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  856. " " +
  857. dateFormatter
  858. .string(from: determination.deliverAt ?? Date())
  859. } else {
  860. statusTitle = "No Oref determination"
  861. return
  862. }
  863. }
  864. }
  865. }