HomeRootView.swift 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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. @State var state = StateModel()
  10. @State var isStatusPopupPresented = false
  11. @State var showCancelAlert = false
  12. @State var showCancelConfirmDialog = false
  13. @State var isConfirmStopOverrideShown = false
  14. @State var isConfirmStopTempTargetShown = false
  15. @State var isMenuPresented = false
  16. @State var showTreatments = false
  17. @State var selectedTab: Int = 0
  18. @State private var statusTitle: String = ""
  19. @State var showPumpSelection: Bool = false
  20. struct Buttons: Identifiable {
  21. let label: String
  22. let number: String
  23. var active: Bool
  24. let hours: Int16
  25. var id: String { label }
  26. }
  27. @State var timeButtons: [Buttons] = [
  28. Buttons(label: "2 hours", number: "2", active: false, hours: 2),
  29. Buttons(label: "4 hours", number: "4", active: false, hours: 4),
  30. Buttons(label: "6 hours", number: "6", active: false, hours: 6),
  31. Buttons(label: "12 hours", number: "12", active: false, hours: 12),
  32. Buttons(label: "24 hours", number: "24", active: false, hours: 24)
  33. ]
  34. let buttonFont = Font.custom("TimeButtonFont", size: 14)
  35. @Environment(\.managedObjectContext) var moc
  36. @Environment(\.colorScheme) var colorScheme
  37. @FetchRequest(fetchRequest: OverrideStored.fetch(
  38. NSPredicate.lastActiveOverride,
  39. ascending: false,
  40. fetchLimit: 1
  41. )) var latestOverride: FetchedResults<OverrideStored>
  42. @FetchRequest(fetchRequest: TempTargetStored.fetch(
  43. NSPredicate.lastActiveTempTarget,
  44. ascending: false,
  45. fetchLimit: 1
  46. )) var latestTempTarget: FetchedResults<TempTargetStored>
  47. var bolusProgressFormatter: NumberFormatter {
  48. let formatter = NumberFormatter()
  49. formatter.numberStyle = .decimal
  50. formatter.minimum = 0
  51. formatter.maximumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  52. formatter.minimumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  53. formatter.allowsFloats = true
  54. formatter.roundingIncrement = Double(state.settingsManager.preferences.bolusIncrement) as NSNumber
  55. return formatter
  56. }
  57. private var numberFormatter: NumberFormatter {
  58. let formatter = NumberFormatter()
  59. formatter.numberStyle = .decimal
  60. formatter.maximumFractionDigits = 2
  61. return formatter
  62. }
  63. private var fetchedTargetFormatter: NumberFormatter {
  64. let formatter = NumberFormatter()
  65. formatter.numberStyle = .decimal
  66. if state.units == .mmolL {
  67. formatter.maximumFractionDigits = 1
  68. } else { formatter.maximumFractionDigits = 0 }
  69. return formatter
  70. }
  71. private var targetFormatter: NumberFormatter {
  72. let formatter = NumberFormatter()
  73. formatter.numberStyle = .decimal
  74. formatter.maximumFractionDigits = 1
  75. return formatter
  76. }
  77. private var tirFormatter: NumberFormatter {
  78. let formatter = NumberFormatter()
  79. formatter.numberStyle = .decimal
  80. formatter.maximumFractionDigits = 0
  81. return formatter
  82. }
  83. private var dateFormatter: DateFormatter {
  84. let dateFormatter = DateFormatter()
  85. dateFormatter.timeStyle = .short
  86. return dateFormatter
  87. }
  88. private var color: LinearGradient {
  89. colorScheme == .dark ? LinearGradient(
  90. gradient: Gradient(colors: [
  91. Color.bgDarkBlue,
  92. Color.bgDarkerDarkBlue
  93. ]),
  94. startPoint: .top,
  95. endPoint: .bottom
  96. )
  97. :
  98. LinearGradient(
  99. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  100. startPoint: .top,
  101. endPoint: .bottom
  102. )
  103. }
  104. private var historySFSymbol: String {
  105. if #available(iOS 17.0, *) {
  106. return "book.pages"
  107. } else {
  108. return "book"
  109. }
  110. }
  111. var glucoseView: some View {
  112. CurrentGlucoseView(
  113. timerDate: state.timerDate,
  114. units: state.units,
  115. alarm: state.alarm,
  116. lowGlucose: state.lowGlucose,
  117. highGlucose: state.highGlucose,
  118. cgmAvailable: state.cgmAvailable,
  119. currentGlucoseTarget: state.currentGlucoseTarget,
  120. glucoseColorScheme: state.glucoseColorScheme,
  121. glucose: state.latestTwoGlucoseValues
  122. ).scaleEffect(0.9)
  123. .onTapGesture {
  124. state.openCGM()
  125. }
  126. .onLongPressGesture {
  127. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  128. impactHeavy.impactOccurred()
  129. state.showModal(for: .snooze)
  130. }
  131. }
  132. var pumpView: some View {
  133. PumpView(
  134. reservoir: state.reservoir,
  135. name: state.pumpName,
  136. expiresAtDate: state.pumpExpiresAtDate,
  137. timerDate: state.timerDate,
  138. timeZone: state.timeZone,
  139. pumpStatusHighlightMessage: state.pumpStatusHighlightMessage,
  140. battery: state.batteryFromPersistence
  141. ).onTapGesture {
  142. if state.pumpDisplayState == nil {
  143. // shows user confirmation dialog with pump model choices, then proceeds to setup
  144. showPumpSelection.toggle()
  145. } else {
  146. // sends user to pump settings
  147. state.setupPump.toggle()
  148. }
  149. }
  150. }
  151. var tempBasalString: String? {
  152. guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
  153. return nil
  154. }
  155. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  156. var manualBasalString = ""
  157. if let apsManager = state.apsManager, apsManager.isManualTempBasal {
  158. manualBasalString = NSLocalizedString(
  159. " - Manual Basal ⚠️",
  160. comment: "Manual Temp basal"
  161. )
  162. }
  163. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  164. }
  165. var overrideString: String? {
  166. guard let latestOverride = latestOverride.first else {
  167. return nil
  168. }
  169. let percent = latestOverride.percentage
  170. let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
  171. let unit = state.units
  172. var target = (latestOverride.target ?? 100) as Decimal
  173. target = unit == .mmolL ? target.asMmolL : target
  174. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  175. .rawValue
  176. if tempTargetString != nil {
  177. targetString = ""
  178. }
  179. let duration = latestOverride.duration ?? 0
  180. let addedMinutes = Int(truncating: duration)
  181. let date = latestOverride.date ?? Date()
  182. let newDuration = max(
  183. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  184. 0
  185. )
  186. let indefinite = latestOverride.indefinite
  187. var durationString = ""
  188. if !indefinite {
  189. if newDuration >= 1 {
  190. durationString =
  191. "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
  192. } else if newDuration > 0 {
  193. durationString =
  194. "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
  195. } else {
  196. /// Do not show the Override anymore
  197. Task {
  198. guard let objectID = self.latestOverride.first?.objectID else { return }
  199. await state.cancelOverride(withID: objectID)
  200. }
  201. }
  202. }
  203. let smbToggleString = latestOverride.smbIsOff ? " \u{20e0}" : ""
  204. let components = [percentString, targetString, durationString, smbToggleString].filter { !$0.isEmpty }
  205. return components.isEmpty ? nil : components.joined(separator: ", ")
  206. }
  207. var tempTargetString: String? {
  208. guard let latestTempTarget = latestTempTarget.first else {
  209. return nil
  210. }
  211. let name = latestTempTarget.name
  212. let duration = latestTempTarget.duration
  213. let addedMinutes = Int(truncating: duration ?? 0)
  214. let date = latestTempTarget.date ?? Date()
  215. let newDuration = max(
  216. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  217. 0
  218. )
  219. var durationString = ""
  220. var target = (latestTempTarget.target ?? 100) as Decimal
  221. target = state.units == .mmolL ? target.asMmolL : target
  222. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: (target ?? 0) as NSNumber) ?? "") + " " +
  223. state.units
  224. .rawValue
  225. if newDuration >= 1 {
  226. durationString =
  227. "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
  228. } else if newDuration > 0 {
  229. durationString =
  230. "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
  231. } else {
  232. /// Do not show the Temp Target anymore
  233. Task {
  234. guard let objectID = self.latestTempTarget.first?.objectID else { return }
  235. await state.cancelTempTarget(withID: objectID)
  236. }
  237. }
  238. let components = [targetString, durationString].filter { !$0.isEmpty }
  239. return components.isEmpty ? nil : components.joined(separator: ", ")
  240. }
  241. var infoPanel: some View {
  242. HStack(alignment: .center) {
  243. if state.pumpSuspended {
  244. Text("Pump suspended")
  245. .font(.system(size: 15, weight: .bold)).foregroundColor(.loopGray)
  246. .padding(.leading, 8)
  247. } else if let tempBasalString = tempBasalString {
  248. Text(tempBasalString)
  249. .font(.system(size: 15, weight: .bold))
  250. .foregroundColor(.insulin)
  251. .padding(.leading, 8)
  252. }
  253. if state.totalInsulinDisplayType == .totalInsulinInScope {
  254. Text(
  255. "TINS: \(state.calculateTINS())" +
  256. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  257. )
  258. .font(.system(size: 15, weight: .bold))
  259. .foregroundColor(.insulin)
  260. }
  261. if let tempTargetString = tempTargetString {
  262. Text(tempTargetString)
  263. .font(.caption)
  264. .foregroundColor(.secondary)
  265. }
  266. Spacer()
  267. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  268. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  269. }
  270. }
  271. .frame(maxWidth: .infinity, maxHeight: 30)
  272. }
  273. var timeInterval: some View {
  274. HStack(alignment: .center) {
  275. ForEach(timeButtons) { button in
  276. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  277. state.hours = button.hours
  278. }
  279. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  280. .frame(maxHeight: 30).padding(.horizontal, 8)
  281. .background(
  282. button.active ?
  283. // RGB(30, 60, 95)
  284. (
  285. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  286. Color.white
  287. ) :
  288. Color
  289. .clear
  290. )
  291. .cornerRadius(20)
  292. }
  293. Button(action: {
  294. state.isLegendPresented.toggle()
  295. }) {
  296. Image(systemName: "info")
  297. .foregroundColor(colorScheme == .dark ? Color.white : Color.black).opacity(0.9)
  298. .frame(width: 20, height: 20)
  299. .background(
  300. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  301. Color.white
  302. )
  303. .clipShape(Circle())
  304. }
  305. .padding([.top, .bottom])
  306. }
  307. .shadow(
  308. color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33),
  309. radius: colorScheme == .dark ? 5 : 3
  310. )
  311. .font(buttonFont)
  312. }
  313. @ViewBuilder func mainChart(geo: GeometryProxy) -> some View {
  314. ZStack {
  315. MainChartView(
  316. geo: geo,
  317. units: state.units,
  318. hours: state.filteredHours,
  319. tempTargets: state.tempTargets,
  320. highGlucose: state.highGlucose,
  321. lowGlucose: state.lowGlucose,
  322. currentGlucoseTarget: state.currentGlucoseTarget,
  323. glucoseColorScheme: state.glucoseColorScheme,
  324. screenHours: state.hours,
  325. displayXgridLines: state.displayXgridLines,
  326. displayYgridLines: state.displayYgridLines,
  327. thresholdLines: state.thresholdLines,
  328. state: state
  329. )
  330. }
  331. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: nil))
  332. }
  333. func highlightButtons() {
  334. for i in 0 ..< timeButtons.count {
  335. timeButtons[i].active = timeButtons[i].hours == state.hours
  336. }
  337. }
  338. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  339. VStack(alignment: .leading, spacing: 20) {
  340. /// Loop view at bottomLeading
  341. LoopView(
  342. closedLoop: state.closedLoop,
  343. timerDate: state.timerDate,
  344. isLooping: state.isLooping,
  345. lastLoopDate: state.lastLoopDate,
  346. manualTempBasal: state.manualTempBasal,
  347. determination: state.determinationsFromPersistence
  348. ).onTapGesture {
  349. state.isStatusPopupPresented = true
  350. setStatusTitle()
  351. }.onLongPressGesture {
  352. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  353. impactHeavy.impactOccurred()
  354. state.runLoop()
  355. }
  356. /// eventualBG string at bottomTrailing
  357. if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
  358. let bg = eventualBG as Decimal
  359. HStack {
  360. Image(systemName: "arrow.right.circle")
  361. .font(.system(size: 16, weight: .bold))
  362. Text(
  363. numberFormatter.string(
  364. from: (
  365. state.units == .mmolL ? bg
  366. .asMmolL : bg
  367. ) as NSNumber
  368. )!
  369. )
  370. .font(.system(size: 16))
  371. }
  372. } else {
  373. HStack {
  374. Image(systemName: "arrow.right.circle")
  375. .font(.system(size: 16, weight: .bold))
  376. Text("--")
  377. .font(.system(size: 16))
  378. }
  379. }
  380. }
  381. }
  382. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  383. HStack {
  384. HStack {
  385. Image(systemName: "syringe.fill")
  386. .font(.system(size: 16))
  387. .foregroundColor(Color.insulin)
  388. Text(
  389. (
  390. numberFormatter
  391. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  392. ) +
  393. NSLocalizedString(" U", comment: "Insulin unit")
  394. )
  395. .font(.system(size: 16, weight: .bold, design: .rounded))
  396. }
  397. Spacer()
  398. HStack {
  399. Image(systemName: "fork.knife")
  400. .font(.system(size: 16))
  401. .foregroundColor(.loopYellow)
  402. Text(
  403. (
  404. numberFormatter.string(
  405. from: NSNumber(value: state.enactedAndNonEnactedDeterminations.first?.cob ?? 0)
  406. ) ?? "0"
  407. ) +
  408. NSLocalizedString(" g", comment: "gram of carbs")
  409. )
  410. .font(.system(size: 16, weight: .bold, design: .rounded))
  411. }
  412. Spacer()
  413. HStack {
  414. if state.pumpSuspended {
  415. Text("Pump suspended")
  416. .font(.system(size: 12, weight: .bold, design: .rounded)).foregroundColor(.loopGray)
  417. } else if let tempBasalString = tempBasalString {
  418. Image(systemName: "drop.circle")
  419. .font(.system(size: 16))
  420. .foregroundColor(.insulinTintColor)
  421. Text(tempBasalString)
  422. .font(.system(size: 16, weight: .bold, design: .rounded))
  423. } else {
  424. Image(systemName: "drop.circle")
  425. .font(.system(size: 16))
  426. .foregroundColor(.insulinTintColor)
  427. Text("No Data")
  428. .font(.system(size: 16, weight: .bold, design: .rounded))
  429. }
  430. }
  431. if state.totalInsulinDisplayType == .totalDailyDose {
  432. Spacer()
  433. Text(
  434. "TDD: " +
  435. (
  436. numberFormatter
  437. .string(from: (state.determinationsFromPersistence.first?.totalDailyDose ?? 0) as NSNumber) ??
  438. "0"
  439. ) +
  440. NSLocalizedString(" U", comment: "Insulin unit")
  441. )
  442. .font(.system(size: 16, weight: .bold, design: .rounded))
  443. } else {
  444. Spacer()
  445. HStack {
  446. Text(
  447. "TINS: \(state.roundedTotalBolus)" +
  448. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  449. )
  450. .font(.system(size: 16, weight: .bold, design: .rounded))
  451. .onChange(of: state.hours) { _ in
  452. state.roundedTotalBolus = state.calculateTINS()
  453. }
  454. .onAppear {
  455. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  456. state.roundedTotalBolus = state.calculateTINS()
  457. }
  458. }
  459. }
  460. }
  461. }.padding(.horizontal, 10)
  462. }
  463. @ViewBuilder func adjustmentsOverrideView(_ overrideString: String) -> some View {
  464. Group {
  465. Image(systemName: "clock.arrow.2.circlepath")
  466. .font(.system(size: 20))
  467. .foregroundStyle(Color.primary, Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569))
  468. VStack(alignment: .leading) {
  469. Text(latestOverride.first?.name ?? "Custom Override")
  470. .font(.subheadline)
  471. .frame(alignment: .leading)
  472. Text(overrideString)
  473. .font(.caption)
  474. }
  475. }
  476. }
  477. @ViewBuilder func adjustmentsTempTargetView(_ tempTargetString: String) -> some View {
  478. Group {
  479. Image(systemName: "target")
  480. .font(.system(size: 20))
  481. .foregroundStyle(Color.loopGreen)
  482. VStack(alignment: .leading) {
  483. Text(latestTempTarget.first?.name ?? "Temp Target")
  484. .font(.subheadline)
  485. Text(tempTargetString)
  486. .font(.caption)
  487. }
  488. }
  489. }
  490. @ViewBuilder func adjustmentsCancelView(_ cancelAction: @escaping () -> Void) -> some View {
  491. Image(systemName: "xmark.app")
  492. .font(.system(size: 24))
  493. .onTapGesture {
  494. cancelAction()
  495. }
  496. }
  497. @ViewBuilder func adjustmentsCancelTempTargetView() -> some View {
  498. Image(systemName: "xmark.app")
  499. .font(.system(size: 24))
  500. .confirmationDialog(
  501. "Stop the Temp Target \"\(latestTempTarget.first?.name ?? "")\"?",
  502. isPresented: $isConfirmStopTempTargetShown,
  503. titleVisibility: .visible
  504. ) {
  505. Button("Stop", role: .destructive) {
  506. Task {
  507. guard let objectID = latestTempTarget.first?.objectID else { return }
  508. await state.cancelTempTarget(withID: objectID)
  509. }
  510. }
  511. Button("Cancel", role: .cancel) {}
  512. }
  513. .padding(.trailing, 8)
  514. .onTapGesture {
  515. if !latestTempTarget.isEmpty {
  516. isConfirmStopTempTargetShown = true
  517. }
  518. }
  519. }
  520. @ViewBuilder func adjustmentsCancelOverrideView() -> some View {
  521. Image(systemName: "xmark.app")
  522. .font(.system(size: 24))
  523. .confirmationDialog(
  524. "Stop the Override \"\(latestOverride.first?.name ?? "")\"?",
  525. isPresented: $isConfirmStopOverrideShown,
  526. titleVisibility: .visible
  527. ) {
  528. Button("Stop", role: .destructive) {
  529. Task {
  530. guard let objectID = latestOverride.first?.objectID else { return }
  531. await state.cancelOverride(withID: objectID)
  532. }
  533. }
  534. Button("Cancel", role: .cancel) {}
  535. }
  536. .padding(.trailing, 8)
  537. .onTapGesture {
  538. if !latestOverride.isEmpty {
  539. isConfirmStopOverrideShown = true
  540. }
  541. }
  542. }
  543. @ViewBuilder func adjustmentView(geo: GeometryProxy) -> some View {
  544. ZStack {
  545. /// rectangle as background
  546. RoundedRectangle(cornerRadius: 15)
  547. .fill(
  548. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  549. .insulin
  550. .opacity(0.1)
  551. )
  552. .clipShape(RoundedRectangle(cornerRadius: 15))
  553. .frame(height: geo.size.height * 0.08)
  554. .shadow(
  555. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  556. Color.black.opacity(0.33),
  557. radius: 3
  558. )
  559. HStack {
  560. if let overrideString = overrideString, let tempTargetString = tempTargetString {
  561. HStack {
  562. adjustmentsOverrideView(overrideString)
  563. Spacer()
  564. Divider()
  565. .frame(height: geo.size.height * 0.05)
  566. .padding(.horizontal, 2)
  567. adjustmentsTempTargetView(tempTargetString)
  568. Spacer()
  569. adjustmentsCancelView({
  570. if !latestTempTarget.isEmpty, !latestOverride.isEmpty {
  571. showCancelConfirmDialog = true
  572. } else if !latestOverride.isEmpty {
  573. showCancelAlert = true
  574. } else if !latestTempTarget.isEmpty {
  575. showCancelAlert = true
  576. }
  577. })
  578. }
  579. } else if let overrideString = overrideString {
  580. adjustmentsOverrideView(overrideString)
  581. Spacer()
  582. adjustmentsCancelOverrideView()
  583. } else if let tempTargetString = tempTargetString {
  584. HStack {
  585. adjustmentsTempTargetView(tempTargetString)
  586. Spacer()
  587. adjustmentsCancelTempTargetView()
  588. }
  589. } else {
  590. VStack {
  591. Text("No Active Adjustment")
  592. .font(.subheadline)
  593. .frame(maxWidth: .infinity, alignment: .leading)
  594. Text("Profile at 100 %")
  595. .font(.caption)
  596. .frame(maxWidth: .infinity, alignment: .leading)
  597. }.padding(.leading, 10)
  598. Spacer()
  599. /// to ensure the same position....
  600. Image(systemName: "xmark.app")
  601. .font(.system(size: 25))
  602. // clear color for the icon
  603. .foregroundStyle(Color.clear)
  604. }
  605. }.padding(.horizontal, 10)
  606. .confirmationDialog("Adjustment to Cancel", isPresented: $showCancelConfirmDialog) {
  607. Button("Stop Override") {
  608. Task {
  609. guard let objectID = latestOverride.first?.objectID else { return }
  610. await state.cancelOverride(withID: objectID)
  611. }
  612. }
  613. Button("Stop Temp Target") {
  614. Task {
  615. guard let objectID = latestTempTarget.first?.objectID else { return }
  616. await state.cancelTempTarget(withID: objectID)
  617. }
  618. }
  619. } message: {
  620. Text("Select Adjustment")
  621. }
  622. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  623. }
  624. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  625. GeometryReader { geo in
  626. RoundedRectangle(cornerRadius: 15)
  627. .frame(height: 6)
  628. .foregroundColor(.clear)
  629. .background(
  630. LinearGradient(colors: [
  631. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  632. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  633. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  634. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  635. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  636. ], startPoint: .leading, endPoint: .trailing)
  637. .mask(alignment: .leading) {
  638. RoundedRectangle(cornerRadius: 15)
  639. .frame(width: geo.size.width * CGFloat(progress))
  640. }
  641. )
  642. }
  643. }
  644. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  645. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  646. /// - TRUE: show the pump bolus
  647. /// - FALSE: do not show a progress bar at all
  648. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  649. let bolusFraction = progress * (bolusTotal as Decimal)
  650. let bolusString =
  651. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  652. + " of " +
  653. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  654. + NSLocalizedString(" U", comment: "Insulin unit")
  655. ZStack {
  656. /// rectangle as background
  657. RoundedRectangle(cornerRadius: 15)
  658. .fill(
  659. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  660. .insulin
  661. .opacity(0.2)
  662. )
  663. .clipShape(RoundedRectangle(cornerRadius: 15))
  664. .frame(height: geo.size.height * 0.08)
  665. .shadow(
  666. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  667. Color.black.opacity(0.33),
  668. radius: 3
  669. )
  670. /// actual bolus view
  671. HStack {
  672. Image(systemName: "cross.vial.fill")
  673. .font(.system(size: 25))
  674. Spacer()
  675. VStack {
  676. Text("Bolusing")
  677. .font(.subheadline)
  678. .frame(maxWidth: .infinity, alignment: .leading)
  679. Text(bolusString)
  680. .font(.caption)
  681. .frame(maxWidth: .infinity, alignment: .leading)
  682. }.padding(.leading, 5)
  683. Spacer()
  684. Button {
  685. state.showProgressView()
  686. state.cancelBolus()
  687. } label: {
  688. Image(systemName: "xmark.app")
  689. .font(.system(size: 25))
  690. }
  691. }.padding(.horizontal, 10)
  692. .padding(.trailing, 8)
  693. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  694. .overlay(alignment: .bottom) {
  695. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 48)
  696. }.clipShape(RoundedRectangle(cornerRadius: 15))
  697. }
  698. }
  699. @ViewBuilder func mainView() -> some View {
  700. GeometryReader { geo in
  701. VStack(spacing: 0) {
  702. ZStack {
  703. /// glucose bobble
  704. glucoseView
  705. /// right panel with loop status and evBG
  706. HStack {
  707. Spacer()
  708. rightHeaderPanel(geo)
  709. }.padding(.trailing, 20)
  710. /// left panel with pump related info
  711. HStack {
  712. pumpView
  713. Spacer()
  714. }.padding(.leading, 20)
  715. }.padding(.top, 10)
  716. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  717. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  718. mainChart(geo: geo)
  719. timeInterval.padding(.top, UIDevice.adjustPadding(min: 0, max: 12))
  720. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 12))
  721. if let progress = state.bolusProgress {
  722. bolusView(geo: geo, progress).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  723. } else {
  724. adjustmentView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  725. }
  726. }
  727. .background(color)
  728. }
  729. .onChange(of: state.hours) { _ in
  730. highlightButtons()
  731. }
  732. .onAppear {
  733. configureView {
  734. highlightButtons()
  735. }
  736. }
  737. .navigationTitle("Home")
  738. .navigationBarHidden(true)
  739. .ignoresSafeArea(.keyboard)
  740. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  741. popup
  742. .padding()
  743. .background(
  744. RoundedRectangle(cornerRadius: 8, style: .continuous)
  745. .fill(colorScheme == .dark ? Color(
  746. "Chart"
  747. ) : Color(UIColor.darkGray))
  748. )
  749. .onTapGesture {
  750. state.isStatusPopupPresented = false
  751. }
  752. .gesture(
  753. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  754. .onEnded { value in
  755. if value.translation.height < 0 {
  756. state.isStatusPopupPresented = false
  757. }
  758. }
  759. )
  760. }
  761. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  762. Button("Medtronic") { state.addPump(.minimed) }
  763. Button("Omnipod Eros") { state.addPump(.omnipod) }
  764. Button("Omnipod Dash") { state.addPump(.omnipodBLE) }
  765. Button("Pump Simulator") { state.addPump(.simulator) }
  766. } message: { Text("Select Pump Model") }
  767. .sheet(isPresented: $state.setupPump) {
  768. if let pumpManager = state.provider.apsManager.pumpManager {
  769. PumpConfig.PumpSettingsView(
  770. pumpManager: pumpManager,
  771. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  772. completionDelegate: state,
  773. setupDelegate: state
  774. )
  775. } else {
  776. PumpConfig.PumpSetupView(
  777. pumpType: state.setupPumpType,
  778. pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  779. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  780. completionDelegate: state,
  781. setupDelegate: state
  782. )
  783. }
  784. }
  785. .sheet(isPresented: $state.isLegendPresented) {
  786. NavigationStack {
  787. Text(
  788. "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  789. )
  790. .font(.subheadline)
  791. .foregroundColor(.secondary)
  792. if state.forecastDisplayType == .lines {
  793. List {
  794. DefinitionRow(
  795. term: "IOB (Insulin on Board)",
  796. definition: "Forecasts BG based on the amount of insulin still active in the body.",
  797. color: .insulin
  798. )
  799. DefinitionRow(
  800. term: "ZT (Zero-Temp)",
  801. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  802. color: .zt
  803. )
  804. DefinitionRow(
  805. term: "COB (Carbs on Board)",
  806. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  807. color: .loopYellow
  808. )
  809. DefinitionRow(
  810. term: "UAM (Unannounced Meal)",
  811. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  812. color: .uam
  813. )
  814. }
  815. .padding(.trailing, 10)
  816. .navigationBarTitle("Legend", displayMode: .inline)
  817. } else {
  818. List {
  819. DefinitionRow(
  820. term: "Cone of Uncertainty",
  821. definition: "For simplicity reasons, oref's various forecast curves are displayed as a \"Cone of Uncertainty\" that depicts a possible, forecasted range of future glucose fluctuation based on the current data and the algothim's result.\n\nTo modify the forecast display type, go to Trio Settings > Features > User Interface > Forecast Display Type.",
  822. color: Color.blue.opacity(0.5)
  823. )
  824. }
  825. .padding(.trailing, 10)
  826. .navigationBarTitle("Legend", displayMode: .inline)
  827. }
  828. Button { state.isLegendPresented.toggle() }
  829. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  830. .buttonStyle(.bordered)
  831. .padding(.top)
  832. }
  833. .padding()
  834. .presentationDetents(
  835. [.fraction(0.9), .large],
  836. selection: $state.legendSheetDetent
  837. )
  838. }
  839. }
  840. @State var settingsPath = NavigationPath()
  841. @ViewBuilder func tabBar() -> some View {
  842. ZStack(alignment: .bottom) {
  843. TabView(selection: $selectedTab) {
  844. let carbsRequiredBadge: String? = {
  845. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  846. state.showCarbsRequiredBadge
  847. else {
  848. return nil
  849. }
  850. let carbsRequiredDecimal = Decimal(carbsRequired)
  851. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  852. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  853. return (numberFormatter.string(from: numberAsNSNumber) ?? "") + " g"
  854. }
  855. return nil
  856. }()
  857. NavigationStack { mainView() }
  858. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  859. .badge(carbsRequiredBadge).tag(0)
  860. NavigationStack { DataTable.RootView(resolver: resolver) }
  861. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  862. Spacer()
  863. NavigationStack { OverrideConfig.RootView(resolver: resolver) }
  864. .tabItem {
  865. Label(
  866. "Adjustments",
  867. systemImage: "slider.horizontal.2.gobackward"
  868. ) }.tag(2)
  869. NavigationStack(path: self.$settingsPath) {
  870. Settings.RootView(resolver: resolver) }
  871. .tabItem { Label(
  872. "Settings",
  873. systemImage: "gear"
  874. ) }.tag(3)
  875. }
  876. .tint(Color.tabBar)
  877. Button(
  878. action: {
  879. state.showModal(for: .bolus) },
  880. label: {
  881. Image(systemName: "plus.circle.fill")
  882. .font(.system(size: 40))
  883. .foregroundStyle(Color.tabBar)
  884. .padding(.bottom, 1)
  885. .padding(.horizontal, 20)
  886. }
  887. )
  888. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  889. .onChange(of: selectedTab) { _ in
  890. print("current path is empty: \(settingsPath.isEmpty)")
  891. settingsPath = NavigationPath()
  892. }
  893. }
  894. var body: some View {
  895. ZStack(alignment: .center) {
  896. tabBar()
  897. if state.waitForSuggestion {
  898. CustomProgressView(text: "Updating IOB...")
  899. }
  900. }
  901. }
  902. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL: Bool) -> String {
  903. var updatedConclusion = reasonConclusion
  904. // Handle "minGuardBG x<y" pattern
  905. if let range = updatedConclusion.range(of: "minGuardBG\\s*-?\\d+<\\d+", options: .regularExpression) {
  906. let matchedString = updatedConclusion[range]
  907. let parts = matchedString.components(separatedBy: "<")
  908. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  909. let secondValue = Double(parts[1])
  910. {
  911. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  912. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  913. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  914. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  915. }
  916. }
  917. // Handle "Eventual BG x >= target" pattern
  918. if let range = updatedConclusion.range(of: "Eventual BG\\s*\\d+\\s*>?=\\s*\\d+", options: .regularExpression) {
  919. let matchedString = updatedConclusion[range]
  920. let parts = matchedString.components(separatedBy: " >= ")
  921. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  922. let secondValue = Double(parts[1])
  923. {
  924. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  925. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  926. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  927. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  928. }
  929. }
  930. return updatedConclusion.capitalizingFirstLetter()
  931. }
  932. private var popup: some View {
  933. VStack(alignment: .leading, spacing: 4) {
  934. Text(statusTitle).font(.headline).foregroundColor(.white)
  935. .padding(.bottom, 4)
  936. if let determination = state.determinationsFromPersistence.first {
  937. if determination.glucose == 400 {
  938. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  939. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  940. } else {
  941. let tags = !state.isSmoothingEnabled ? determination.reasonParts : determination
  942. .reasonParts + ["Smoothing: On"]
  943. TagCloudView(
  944. tags: tags,
  945. shouldParseToMmolL: state.units == .mmolL
  946. )
  947. .animation(.none, value: false)
  948. Text(
  949. self
  950. .parseReasonConclusion(
  951. determination.reasonConclusion,
  952. isMmolL: state.units == .mmolL
  953. )
  954. ).font(.caption).foregroundColor(.white)
  955. }
  956. } else {
  957. Text("No determination found").font(.body).foregroundColor(.white)
  958. }
  959. if let errorMessage = state.errorMessage, let date = state.errorDate {
  960. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  961. .foregroundColor(.white)
  962. .font(.headline)
  963. .padding(.bottom, 4)
  964. .padding(.top, 8)
  965. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  966. }
  967. }
  968. }
  969. private func setStatusTitle() {
  970. if let determination = state.determinationsFromPersistence.first {
  971. let dateFormatter = DateFormatter()
  972. dateFormatter.timeStyle = .short
  973. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  974. " " +
  975. dateFormatter
  976. .string(from: determination.deliverAt ?? Date())
  977. } else {
  978. statusTitle = "No Oref determination"
  979. return
  980. }
  981. }
  982. }
  983. }
  984. extension UIDevice {
  985. public enum DeviceSize: CGFloat {
  986. case smallDevice = 667 // Height for 4" iPhone SE
  987. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  988. }
  989. @usableFromInline static func adjustPadding(min: CGFloat? = nil, max: CGFloat? = nil) -> CGFloat? {
  990. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  991. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  992. return max
  993. } else {
  994. return min != nil ?
  995. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  996. }
  997. } else {
  998. return min
  999. }
  1000. }
  1001. }
  1002. extension UIScreen {
  1003. static var screenHeight: CGFloat {
  1004. UIScreen.main.bounds.height
  1005. }
  1006. static var screenWidth: CGFloat {
  1007. UIScreen.main.bounds.width
  1008. }
  1009. }