HomeRootView.swift 47 KB

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