HomeRootView.swift 48 KB

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