HomeRootView.swift 50 KB

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