HomeRootView.swift 41 KB

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