HomeRootView.swift 50 KB

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