HomeRootView.swift 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. manualGlucose: state.latestTwoManualGlucoseValues
  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. announcement: $state.announcement,
  302. hours: .constant(state.filteredHours),
  303. maxBasal: $state.maxBasal,
  304. autotunedBasalProfile: $state.autotunedBasalProfile,
  305. basalProfile: $state.basalProfile,
  306. tempTargets: $state.tempTargets,
  307. smooth: $state.smooth,
  308. highGlucose: $state.highGlucose,
  309. lowGlucose: $state.lowGlucose,
  310. screenHours: $state.hours,
  311. displayXgridLines: $state.displayXgridLines,
  312. displayYgridLines: $state.displayYgridLines,
  313. thresholdLines: $state.thresholdLines,
  314. state: state
  315. )
  316. }
  317. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: nil))
  318. }
  319. func highlightButtons() {
  320. for i in 0 ..< timeButtons.count {
  321. timeButtons[i].active = timeButtons[i].hours == state.hours
  322. }
  323. }
  324. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  325. VStack(alignment: .leading, spacing: 20) {
  326. /// Loop view at bottomLeading
  327. LoopView(
  328. closedLoop: $state.closedLoop,
  329. timerDate: $state.timerDate,
  330. isLooping: $state.isLooping,
  331. lastLoopDate: $state.lastLoopDate,
  332. manualTempBasal: $state.manualTempBasal,
  333. determination: state.determinationsFromPersistence
  334. ).onTapGesture {
  335. state.isStatusPopupPresented = true
  336. setStatusTitle()
  337. }.onLongPressGesture {
  338. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  339. impactHeavy.impactOccurred()
  340. state.runLoop()
  341. }
  342. /// eventualBG string at bottomTrailing
  343. if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
  344. let bg = eventualBG as Decimal
  345. HStack {
  346. Image(systemName: "arrow.right.circle")
  347. .font(.system(size: 16, weight: .bold))
  348. Text(
  349. numberFormatter.string(
  350. from: (
  351. state.units == .mmolL ? bg
  352. .asMmolL : bg
  353. ) as NSNumber
  354. )!
  355. )
  356. .font(.system(size: 16))
  357. }
  358. } else {
  359. HStack {
  360. Image(systemName: "arrow.right.circle")
  361. .font(.system(size: 16, weight: .bold))
  362. Text("--")
  363. .font(.system(size: 16))
  364. }
  365. }
  366. }
  367. }
  368. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  369. HStack {
  370. HStack {
  371. Image(systemName: "syringe.fill")
  372. .font(.system(size: 16))
  373. .foregroundColor(Color.insulin)
  374. Text(
  375. (
  376. numberFormatter
  377. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  378. ) +
  379. NSLocalizedString(" U", comment: "Insulin unit")
  380. )
  381. .font(.system(size: 16, weight: .bold, design: .rounded))
  382. }
  383. Spacer()
  384. HStack {
  385. Image(systemName: "fork.knife")
  386. .font(.system(size: 16))
  387. .foregroundColor(.loopYellow)
  388. Text(
  389. (
  390. numberFormatter
  391. .string(from: (state.enactedAndNonEnactedDeterminations.first?.cob ?? 0) as NSNumber) ?? "0"
  392. ) +
  393. NSLocalizedString(" g", comment: "gram of carbs")
  394. )
  395. .font(.system(size: 16, weight: .bold, design: .rounded))
  396. }
  397. Spacer()
  398. HStack {
  399. if state.pumpSuspended {
  400. Text("Pump suspended")
  401. .font(.system(size: 12, weight: .bold, design: .rounded)).foregroundColor(.loopGray)
  402. } else if let tempBasalString = tempBasalString {
  403. Image(systemName: "drop.circle")
  404. .font(.system(size: 16))
  405. .foregroundColor(.insulinTintColor)
  406. Text(tempBasalString)
  407. .font(.system(size: 16, weight: .bold, design: .rounded))
  408. } else {
  409. Image(systemName: "drop.circle")
  410. .font(.system(size: 16))
  411. .foregroundColor(.insulinTintColor)
  412. Text("No Data")
  413. .font(.system(size: 16, weight: .bold, design: .rounded))
  414. }
  415. }
  416. if state.totalInsulinDisplayType == .totalDailyDose {
  417. Spacer()
  418. Text(
  419. "TDD: " +
  420. (
  421. numberFormatter
  422. .string(from: (state.determinationsFromPersistence.first?.totalDailyDose ?? 0) as NSNumber) ??
  423. "0"
  424. ) +
  425. NSLocalizedString(" U", comment: "Insulin unit")
  426. )
  427. .font(.system(size: 16, weight: .bold, design: .rounded))
  428. } else {
  429. Spacer()
  430. HStack {
  431. Text(
  432. "TINS: \(state.roundedTotalBolus)" +
  433. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  434. )
  435. .font(.system(size: 16, weight: .bold, design: .rounded))
  436. .onChange(of: state.hours) { _ in
  437. state.roundedTotalBolus = state.calculateTINS()
  438. }
  439. .onAppear {
  440. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  441. state.roundedTotalBolus = state.calculateTINS()
  442. }
  443. }
  444. }
  445. }
  446. }.padding(.horizontal, 10)
  447. }
  448. @ViewBuilder func profileView(geo: GeometryProxy) -> some View {
  449. ZStack {
  450. /// rectangle as background
  451. RoundedRectangle(cornerRadius: 15)
  452. .fill(
  453. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  454. .opacity(0.1)
  455. )
  456. .clipShape(RoundedRectangle(cornerRadius: 15))
  457. .frame(height: geo.size.height * 0.08)
  458. .shadow(
  459. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  460. Color.black.opacity(0.33),
  461. radius: 3
  462. )
  463. HStack {
  464. /// actual profile view
  465. Image(systemName: "person.fill")
  466. .font(.system(size: 25))
  467. Spacer()
  468. if let overrideString = overrideString {
  469. VStack {
  470. Text(latestOverride.first?.name ?? "Custom Override")
  471. .font(.subheadline)
  472. .frame(maxWidth: .infinity, alignment: .leading)
  473. Text("\(overrideString)")
  474. .font(.caption)
  475. .frame(maxWidth: .infinity, alignment: .leading)
  476. }.padding(.leading, 5)
  477. Spacer()
  478. Image(systemName: "xmark.app")
  479. .font(.system(size: 25))
  480. } else {
  481. if tempTargetString == nil {
  482. VStack {
  483. Text("Normal Profile")
  484. .font(.subheadline)
  485. .frame(maxWidth: .infinity, alignment: .leading)
  486. Text("100 %")
  487. .font(.caption)
  488. .frame(maxWidth: .infinity, alignment: .leading)
  489. }.padding(.leading, 5)
  490. Spacer()
  491. /// to ensure the same position....
  492. Image(systemName: "xmark.app")
  493. .font(.system(size: 25))
  494. .foregroundStyle(Color.clear)
  495. }
  496. }
  497. }.padding(.horizontal, 10)
  498. .alert(
  499. "Return to Normal?", isPresented: $showCancelAlert,
  500. actions: {
  501. Button("No", role: .cancel) {}
  502. Button("Yes", role: .destructive) {
  503. Task {
  504. guard let objectID = latestOverride.first?.objectID else { return }
  505. await state.cancelOverride(withID: objectID)
  506. }
  507. }
  508. }, message: { Text("This will change settings back to your normal profile.") }
  509. )
  510. .padding(.trailing, 8)
  511. .onTapGesture {
  512. if !latestOverride.isEmpty {
  513. showCancelAlert = true
  514. }
  515. }
  516. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  517. .overlay {
  518. /// just show temp target if no profile is already active
  519. if overrideString == nil, let tempTargetString = tempTargetString {
  520. ZStack {
  521. /// rectangle as background
  522. RoundedRectangle(cornerRadius: 15)
  523. .fill(
  524. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  525. Color
  526. .insulin
  527. .opacity(0.2)
  528. )
  529. .clipShape(RoundedRectangle(cornerRadius: 15))
  530. .frame(height: UIScreen.main.bounds.height / 18)
  531. .shadow(
  532. color: colorScheme == .dark ? Color(
  533. red: 0.02745098039,
  534. green: 0.1098039216,
  535. blue: 0.1411764706
  536. ) :
  537. Color.black.opacity(0.33),
  538. radius: 3
  539. )
  540. HStack {
  541. Image(systemName: "person.fill")
  542. .font(.system(size: 25))
  543. Spacer()
  544. Text(tempTargetString)
  545. .font(.subheadline)
  546. Spacer()
  547. }.padding(.horizontal, 10)
  548. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  549. }
  550. }
  551. }
  552. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  553. GeometryReader { geo in
  554. RoundedRectangle(cornerRadius: 15)
  555. .frame(height: 6)
  556. .foregroundColor(.clear)
  557. .background(
  558. LinearGradient(colors: [
  559. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  560. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  561. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  562. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  563. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  564. ], startPoint: .leading, endPoint: .trailing)
  565. .mask(alignment: .leading) {
  566. RoundedRectangle(cornerRadius: 15)
  567. .frame(width: geo.size.width * CGFloat(progress))
  568. }
  569. )
  570. }
  571. }
  572. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  573. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  574. /// - TRUE: show the pump bolus
  575. /// - FALSE: do not show a progress bar at all
  576. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  577. let bolusFraction = progress * (bolusTotal as Decimal)
  578. let bolusString =
  579. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  580. + " of " +
  581. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  582. + NSLocalizedString(" U", comment: "Insulin unit")
  583. ZStack {
  584. /// rectangle as background
  585. RoundedRectangle(cornerRadius: 15)
  586. .fill(
  587. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  588. .insulin
  589. .opacity(0.2)
  590. )
  591. .clipShape(RoundedRectangle(cornerRadius: 15))
  592. .frame(height: geo.size.height * 0.08)
  593. .shadow(
  594. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  595. Color.black.opacity(0.33),
  596. radius: 3
  597. )
  598. /// actual bolus view
  599. HStack {
  600. Image(systemName: "cross.vial.fill")
  601. .font(.system(size: 25))
  602. Spacer()
  603. VStack {
  604. Text("Bolusing")
  605. .font(.subheadline)
  606. .frame(maxWidth: .infinity, alignment: .leading)
  607. Text(bolusString)
  608. .font(.caption)
  609. .frame(maxWidth: .infinity, alignment: .leading)
  610. }.padding(.leading, 5)
  611. Spacer()
  612. Button {
  613. state.showProgressView()
  614. state.cancelBolus()
  615. } label: {
  616. Image(systemName: "xmark.app")
  617. .font(.system(size: 25))
  618. }
  619. }.padding(.horizontal, 10)
  620. .padding(.trailing, 8)
  621. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  622. .overlay(alignment: .bottom) {
  623. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 48)
  624. }.clipShape(RoundedRectangle(cornerRadius: 15))
  625. }
  626. }
  627. @ViewBuilder func mainView() -> some View {
  628. GeometryReader { geo in
  629. VStack(spacing: 0) {
  630. ZStack {
  631. /// glucose bobble
  632. glucoseView
  633. /// right panel with loop status and evBG
  634. HStack {
  635. Spacer()
  636. rightHeaderPanel(geo)
  637. }.padding(.trailing, 20)
  638. /// left panel with pump related info
  639. HStack {
  640. pumpView
  641. Spacer()
  642. }.padding(.leading, 20)
  643. }.padding(.top, 10)
  644. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  645. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  646. mainChart(geo: geo)
  647. timeInterval.padding(.top, UIDevice.adjustPadding(min: 0, max: 12))
  648. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 12))
  649. if let progress = state.bolusProgress {
  650. bolusView(geo: geo, progress).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  651. } else {
  652. profileView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  653. }
  654. }
  655. .background(color)
  656. }
  657. .onChange(of: state.hours) { _ in
  658. highlightButtons()
  659. }
  660. .onAppear {
  661. configureView {
  662. highlightButtons()
  663. }
  664. }
  665. .navigationTitle("Home")
  666. .navigationBarHidden(true)
  667. .ignoresSafeArea(.keyboard)
  668. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  669. popup
  670. .padding()
  671. .background(
  672. RoundedRectangle(cornerRadius: 8, style: .continuous)
  673. .fill(colorScheme == .dark ? Color(
  674. "Chart"
  675. ) : Color(UIColor.darkGray))
  676. )
  677. .onTapGesture {
  678. state.isStatusPopupPresented = false
  679. }
  680. .gesture(
  681. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  682. .onEnded { value in
  683. if value.translation.height < 0 {
  684. state.isStatusPopupPresented = false
  685. }
  686. }
  687. )
  688. }
  689. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  690. Button("Medtronic") { state.addPump(.minimed) }
  691. Button("Omnipod Eros") { state.addPump(.omnipod) }
  692. Button("Omnipod Dash") { state.addPump(.omnipodBLE) }
  693. Button("Pump Simulator") { state.addPump(.simulator) }
  694. } message: { Text("Select Pump Model") }
  695. .sheet(isPresented: $state.setupPump) {
  696. if let pumpManager = state.provider.apsManager.pumpManager {
  697. PumpConfig.PumpSettingsView(
  698. pumpManager: pumpManager,
  699. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  700. completionDelegate: state,
  701. setupDelegate: state
  702. )
  703. } else {
  704. PumpConfig.PumpSetupView(
  705. pumpType: state.setupPumpType,
  706. pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  707. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  708. completionDelegate: state,
  709. setupDelegate: state
  710. )
  711. }
  712. }
  713. .sheet(isPresented: $state.isLegendPresented) {
  714. NavigationStack {
  715. Text(
  716. "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  717. )
  718. .font(.subheadline)
  719. .foregroundColor(.secondary)
  720. if state.forecastDisplayType == .lines {
  721. List {
  722. DefinitionRow(
  723. term: "IOB (Insulin on Board)",
  724. definition: "Forecasts BG based on the amount of insulin still active in the body.",
  725. color: .insulin
  726. )
  727. DefinitionRow(
  728. term: "ZT (Zero-Temp)",
  729. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  730. color: .zt
  731. )
  732. DefinitionRow(
  733. term: "COB (Carbs on Board)",
  734. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  735. color: .loopYellow
  736. )
  737. DefinitionRow(
  738. term: "UAM (Unannounced Meal)",
  739. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  740. color: .uam
  741. )
  742. }
  743. .padding(.trailing, 10)
  744. .navigationBarTitle("Legend", displayMode: .inline)
  745. } else {
  746. List {
  747. DefinitionRow(
  748. term: "Cone of Uncertainty",
  749. 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.",
  750. color: Color.blue.opacity(0.5)
  751. )
  752. }
  753. .padding(.trailing, 10)
  754. .navigationBarTitle("Legend", displayMode: .inline)
  755. }
  756. Button { state.isLegendPresented.toggle() }
  757. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  758. .buttonStyle(.bordered)
  759. .padding(.top)
  760. }
  761. .padding()
  762. .presentationDetents(
  763. [.fraction(0.9), .large],
  764. selection: $state.legendSheetDetent
  765. )
  766. }
  767. }
  768. @State var settingsPath = NavigationPath()
  769. @ViewBuilder func tabBar() -> some View {
  770. ZStack(alignment: .bottom) {
  771. TabView(selection: $selectedTab) {
  772. let carbsRequiredBadge: String? = {
  773. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  774. state.showCarbsRequiredBadge
  775. else {
  776. return nil
  777. }
  778. let carbsRequiredDecimal = Decimal(carbsRequired)
  779. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  780. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  781. return (numberFormatter.string(from: numberAsNSNumber) ?? "") + " g"
  782. }
  783. return nil
  784. }()
  785. NavigationStack { mainView() }
  786. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  787. .badge(carbsRequiredBadge).tag(0)
  788. NavigationStack { DataTable.RootView(resolver: resolver) }
  789. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  790. Spacer()
  791. NavigationStack { OverrideConfig.RootView(resolver: resolver) }
  792. .tabItem {
  793. Label(
  794. "Adjustments",
  795. systemImage: "slider.horizontal.2.gobackward"
  796. ) }.tag(2)
  797. NavigationStack(path: self.$settingsPath) {
  798. Settings.RootView(resolver: resolver) }
  799. .tabItem { Label(
  800. "Settings",
  801. systemImage: "gear"
  802. ) }.tag(3)
  803. }
  804. .tint(Color.tabBar)
  805. Button(
  806. action: {
  807. state.showModal(for: .bolus) },
  808. label: {
  809. Image(systemName: "plus.circle.fill")
  810. .font(.system(size: 40))
  811. .foregroundStyle(Color.tabBar)
  812. .padding(.bottom, 1)
  813. .padding(.horizontal, 20)
  814. }
  815. )
  816. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  817. .onChange(of: selectedTab) { _ in
  818. print("current path is empty: \(settingsPath.isEmpty)")
  819. settingsPath = NavigationPath()
  820. }
  821. }
  822. var body: some View {
  823. ZStack(alignment: .center) {
  824. tabBar()
  825. if state.waitForSuggestion {
  826. CustomProgressView(text: "Updating IOB...")
  827. }
  828. }
  829. }
  830. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL: Bool) -> String {
  831. var updatedConclusion = reasonConclusion
  832. // Handle "minGuardBG x<y" pattern
  833. if let range = updatedConclusion.range(of: "minGuardBG\\s*-?\\d+<\\d+", options: .regularExpression) {
  834. let matchedString = updatedConclusion[range]
  835. let parts = matchedString.components(separatedBy: "<")
  836. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  837. let secondValue = Double(parts[1])
  838. {
  839. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  840. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  841. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  842. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  843. }
  844. }
  845. // Handle "Eventual BG x >= target" pattern
  846. if let range = updatedConclusion.range(of: "Eventual BG\\s*\\d+\\s*>?=\\s*\\d+", options: .regularExpression) {
  847. let matchedString = updatedConclusion[range]
  848. let parts = matchedString.components(separatedBy: " >= ")
  849. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  850. let secondValue = Double(parts[1])
  851. {
  852. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  853. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  854. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  855. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  856. }
  857. }
  858. return updatedConclusion.capitalizingFirstLetter()
  859. }
  860. private var popup: some View {
  861. VStack(alignment: .leading, spacing: 4) {
  862. Text(statusTitle).font(.headline).foregroundColor(.white)
  863. .padding(.bottom, 4)
  864. if let determination = state.determinationsFromPersistence.first {
  865. if determination.glucose == 400 {
  866. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  867. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  868. } else {
  869. TagCloudView(tags: determination.reasonParts, shouldParseToMmolL: state.units == .mmolL)
  870. .animation(.none, value: false)
  871. Text(
  872. self
  873. .parseReasonConclusion(
  874. determination.reasonConclusion,
  875. isMmolL: state.units == .mmolL
  876. )
  877. ).font(.caption).foregroundColor(.white)
  878. }
  879. } else {
  880. Text("No determination found").font(.body).foregroundColor(.white)
  881. }
  882. if let errorMessage = state.errorMessage, let date = state.errorDate {
  883. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  884. .foregroundColor(.white)
  885. .font(.headline)
  886. .padding(.bottom, 4)
  887. .padding(.top, 8)
  888. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  889. }
  890. }
  891. }
  892. private func setStatusTitle() {
  893. if let determination = state.determinationsFromPersistence.first {
  894. let dateFormatter = DateFormatter()
  895. dateFormatter.timeStyle = .short
  896. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  897. " " +
  898. dateFormatter
  899. .string(from: determination.deliverAt ?? Date())
  900. } else {
  901. statusTitle = "No Oref determination"
  902. return
  903. }
  904. }
  905. }
  906. }
  907. extension UIDevice {
  908. public enum DeviceSize: CGFloat {
  909. case smallDevice = 667 // Height for 4" iPhone SE
  910. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  911. }
  912. @usableFromInline static func adjustPadding(min: CGFloat? = nil, max: CGFloat? = nil) -> CGFloat? {
  913. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  914. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  915. return max
  916. } else {
  917. return min != nil ?
  918. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  919. }
  920. } else {
  921. return min
  922. }
  923. }
  924. }
  925. extension UIScreen {
  926. static var screenHeight: CGFloat {
  927. UIScreen.main.bounds.height
  928. }
  929. static var screenWidth: CGFloat {
  930. UIScreen.main.bounds.width
  931. }
  932. }