HomeRootView.swift 41 KB

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