HomeRootView.swift 45 KB

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