HomeRootView.swift 47 KB

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