HomeRootView.swift 50 KB

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