HomeRootView.swift 40 KB

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