HomeRootView.swift 48 KB

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