HomeRootView.swift 46 KB

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