HomeRootView.swift 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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. currentGlucoseTarget: $state.currentGlucoseTarget,
  121. glucoseColorScheme: $state.glucoseColorScheme,
  122. glucose: state.latestTwoGlucoseValues
  123. ).scaleEffect(0.9)
  124. .onTapGesture {
  125. state.openCGM()
  126. }
  127. .onLongPressGesture {
  128. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  129. impactHeavy.impactOccurred()
  130. state.showModal(for: .snooze)
  131. }
  132. }
  133. var pumpView: some View {
  134. PumpView(
  135. reservoir: $state.reservoir,
  136. name: $state.pumpName,
  137. expiresAtDate: $state.pumpExpiresAtDate,
  138. timerDate: $state.timerDate,
  139. timeZone: $state.timeZone,
  140. pumpStatusHighlightMessage: $state.pumpStatusHighlightMessage,
  141. battery: $state.batteryFromPersistence
  142. ).onTapGesture {
  143. if state.pumpDisplayState == nil {
  144. // shows user confirmation dialog with pump model choices, then proceeds to setup
  145. showPumpSelection.toggle()
  146. } else {
  147. // sends user to pump settings
  148. state.setupPump.toggle()
  149. }
  150. }
  151. }
  152. var tempBasalString: String? {
  153. guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
  154. return nil
  155. }
  156. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  157. var manualBasalString = ""
  158. if let apsManager = state.apsManager, apsManager.isManualTempBasal {
  159. manualBasalString = NSLocalizedString(
  160. " - Manual Basal ⚠️",
  161. comment: "Manual Temp basal"
  162. )
  163. }
  164. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  165. }
  166. var overrideString: String? {
  167. guard let latestOverride = latestOverride.first else {
  168. return nil
  169. }
  170. let percent = latestOverride.percentage
  171. let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
  172. let unit = state.units
  173. var target = (latestOverride.target ?? 100) as Decimal
  174. target = unit == .mmolL ? target.asMmolL : target
  175. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  176. .rawValue
  177. if tempTargetString != nil {
  178. targetString = ""
  179. }
  180. let duration = latestOverride.duration ?? 0
  181. let addedMinutes = Int(truncating: duration)
  182. let date = latestOverride.date ?? Date()
  183. let newDuration = max(
  184. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  185. 0
  186. )
  187. let indefinite = latestOverride.indefinite
  188. var durationString = ""
  189. if !indefinite {
  190. if newDuration >= 1 {
  191. durationString =
  192. "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
  193. } else if newDuration > 0 {
  194. durationString =
  195. "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
  196. } else {
  197. /// Do not show the Override anymore
  198. Task {
  199. guard let objectID = self.latestOverride.first?.objectID else { return }
  200. await state.cancelOverride(withID: objectID)
  201. }
  202. }
  203. }
  204. let smbToggleString = latestOverride.smbIsOff ? " \u{20e0}" : ""
  205. let components = [percentString, targetString, durationString, smbToggleString].filter { !$0.isEmpty }
  206. return components.isEmpty ? nil : components.joined(separator: ", ")
  207. }
  208. var tempTargetString: String? {
  209. guard let tempTarget = state.tempTarget else {
  210. return nil
  211. }
  212. let target = tempTarget.targetBottom ?? 0
  213. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  214. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  215. .rawValue
  216. var string = ""
  217. if sliderTTpresets.first?.active ?? false {
  218. let hbt = sliderTTpresets.first?.hbt ?? 0
  219. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  220. }
  221. let percentString = state
  222. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  223. return tempTarget.displayName + " " + percentString
  224. }
  225. var infoPanel: some View {
  226. HStack(alignment: .center) {
  227. if state.pumpSuspended {
  228. Text("Pump suspended")
  229. .font(.system(size: 15, weight: .bold)).foregroundColor(.loopGray)
  230. .padding(.leading, 8)
  231. } else if let tempBasalString = tempBasalString {
  232. Text(tempBasalString)
  233. .font(.system(size: 15, weight: .bold))
  234. .foregroundColor(.insulin)
  235. .padding(.leading, 8)
  236. }
  237. if state.totalInsulinDisplayType == .totalInsulinInScope {
  238. Text(
  239. "TINS: \(state.calculateTINS())" +
  240. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  241. )
  242. .font(.system(size: 15, weight: .bold))
  243. .foregroundColor(.insulin)
  244. }
  245. if let tempTargetString = tempTargetString {
  246. Text(tempTargetString)
  247. .font(.caption)
  248. .foregroundColor(.secondary)
  249. }
  250. Spacer()
  251. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  252. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  253. }
  254. }
  255. .frame(maxWidth: .infinity, maxHeight: 30)
  256. }
  257. var timeInterval: some View {
  258. HStack(alignment: .center) {
  259. ForEach(timeButtons) { button in
  260. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  261. state.hours = button.hours
  262. }
  263. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  264. .frame(maxHeight: 30).padding(.horizontal, 8)
  265. .background(
  266. button.active ?
  267. // RGB(30, 60, 95)
  268. (
  269. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  270. Color.white
  271. ) :
  272. Color
  273. .clear
  274. )
  275. .cornerRadius(20)
  276. }
  277. Button(action: {
  278. state.isLegendPresented.toggle()
  279. }) {
  280. Image(systemName: "info")
  281. .foregroundColor(colorScheme == .dark ? Color.white : Color.black).opacity(0.9)
  282. .frame(width: 20, height: 20)
  283. .background(
  284. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  285. Color.white
  286. )
  287. .clipShape(Circle())
  288. }
  289. .padding([.top, .bottom])
  290. }
  291. .shadow(
  292. color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33),
  293. radius: colorScheme == .dark ? 5 : 3
  294. )
  295. .font(buttonFont)
  296. }
  297. @ViewBuilder func mainChart(geo: GeometryProxy) -> some View {
  298. ZStack {
  299. MainChartView(
  300. geo: geo,
  301. units: $state.units,
  302. hours: .constant(state.filteredHours),
  303. tempTargets: $state.tempTargets,
  304. highGlucose: $state.highGlucose,
  305. lowGlucose: $state.lowGlucose,
  306. currentGlucoseTarget: $state.currentGlucoseTarget,
  307. screenHours: $state.hours,
  308. glucoseColorScheme: $state.glucoseColorScheme,
  309. displayXgridLines: $state.displayXgridLines,
  310. displayYgridLines: $state.displayYgridLines,
  311. thresholdLines: $state.thresholdLines,
  312. state: state
  313. )
  314. }
  315. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: nil))
  316. }
  317. func highlightButtons() {
  318. for i in 0 ..< timeButtons.count {
  319. timeButtons[i].active = timeButtons[i].hours == state.hours
  320. }
  321. }
  322. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  323. VStack(alignment: .leading, spacing: 20) {
  324. /// Loop view at bottomLeading
  325. LoopView(
  326. closedLoop: $state.closedLoop,
  327. timerDate: $state.timerDate,
  328. isLooping: $state.isLooping,
  329. lastLoopDate: $state.lastLoopDate,
  330. manualTempBasal: $state.manualTempBasal,
  331. determination: state.determinationsFromPersistence
  332. ).onTapGesture {
  333. state.isStatusPopupPresented = true
  334. setStatusTitle()
  335. }.onLongPressGesture {
  336. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  337. impactHeavy.impactOccurred()
  338. state.runLoop()
  339. }
  340. /// eventualBG string at bottomTrailing
  341. if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
  342. let bg = eventualBG as Decimal
  343. HStack {
  344. Image(systemName: "arrow.right.circle")
  345. .font(.system(size: 16, weight: .bold))
  346. Text(
  347. numberFormatter.string(
  348. from: (
  349. state.units == .mmolL ? bg
  350. .asMmolL : bg
  351. ) as NSNumber
  352. )!
  353. )
  354. .font(.system(size: 16))
  355. }
  356. } else {
  357. HStack {
  358. Image(systemName: "arrow.right.circle")
  359. .font(.system(size: 16, weight: .bold))
  360. Text("--")
  361. .font(.system(size: 16))
  362. }
  363. }
  364. }
  365. }
  366. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  367. HStack {
  368. HStack {
  369. Image(systemName: "syringe.fill")
  370. .font(.system(size: 16))
  371. .foregroundColor(Color.insulin)
  372. Text(
  373. (
  374. numberFormatter
  375. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  376. ) +
  377. NSLocalizedString(" U", comment: "Insulin unit")
  378. )
  379. .font(.system(size: 16, weight: .bold, design: .rounded))
  380. }
  381. Spacer()
  382. HStack {
  383. Image(systemName: "fork.knife")
  384. .font(.system(size: 16))
  385. .foregroundColor(.loopYellow)
  386. Text(
  387. (
  388. numberFormatter
  389. .string(from: (state.enactedAndNonEnactedDeterminations.first?.cob ?? 0) as NSNumber) ?? "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) { _ in
  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) { _ in
  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: "Forecasts BG based on the amount of insulin still active in the body.",
  723. color: .insulin
  724. )
  725. DefinitionRow(
  726. term: "ZT (Zero-Temp)",
  727. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  728. color: .zt
  729. )
  730. DefinitionRow(
  731. term: "COB (Carbs on Board)",
  732. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  733. color: .loopYellow
  734. )
  735. DefinitionRow(
  736. term: "UAM (Unannounced Meal)",
  737. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  738. color: .uam
  739. )
  740. }
  741. .padding(.trailing, 10)
  742. .navigationBarTitle("Legend", displayMode: .inline)
  743. } else {
  744. List {
  745. DefinitionRow(
  746. term: "Cone of Uncertainty",
  747. 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.",
  748. color: Color.blue.opacity(0.5)
  749. )
  750. }
  751. .padding(.trailing, 10)
  752. .navigationBarTitle("Legend", displayMode: .inline)
  753. }
  754. Button { state.isLegendPresented.toggle() }
  755. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  756. .buttonStyle(.bordered)
  757. .padding(.top)
  758. }
  759. .padding()
  760. .presentationDetents(
  761. [.fraction(0.9), .large],
  762. selection: $state.legendSheetDetent
  763. )
  764. }
  765. }
  766. @State var settingsPath = NavigationPath()
  767. @ViewBuilder func tabBar() -> some View {
  768. ZStack(alignment: .bottom) {
  769. TabView(selection: $selectedTab) {
  770. let carbsRequiredBadge: String? = {
  771. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  772. state.showCarbsRequiredBadge
  773. else {
  774. return nil
  775. }
  776. let carbsRequiredDecimal = Decimal(carbsRequired)
  777. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  778. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  779. return (numberFormatter.string(from: numberAsNSNumber) ?? "") + " g"
  780. }
  781. return nil
  782. }()
  783. NavigationStack { mainView() }
  784. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  785. .badge(carbsRequiredBadge).tag(0)
  786. NavigationStack { DataTable.RootView(resolver: resolver) }
  787. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  788. Spacer()
  789. NavigationStack { OverrideConfig.RootView(resolver: resolver) }
  790. .tabItem {
  791. Label(
  792. "Adjustments",
  793. systemImage: "slider.horizontal.2.gobackward"
  794. ) }.tag(2)
  795. NavigationStack(path: self.$settingsPath) {
  796. Settings.RootView(resolver: resolver) }
  797. .tabItem { Label(
  798. "Settings",
  799. systemImage: "gear"
  800. ) }.tag(3)
  801. }
  802. .tint(Color.tabBar)
  803. Button(
  804. action: {
  805. state.showModal(for: .bolus) },
  806. label: {
  807. Image(systemName: "plus.circle.fill")
  808. .font(.system(size: 40))
  809. .foregroundStyle(Color.tabBar)
  810. .padding(.bottom, 1)
  811. .padding(.horizontal, 20)
  812. }
  813. )
  814. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  815. .onChange(of: selectedTab) { _ in
  816. print("current path is empty: \(settingsPath.isEmpty)")
  817. settingsPath = NavigationPath()
  818. }
  819. }
  820. var body: some View {
  821. ZStack(alignment: .center) {
  822. tabBar()
  823. if state.waitForSuggestion {
  824. CustomProgressView(text: "Updating IOB...")
  825. }
  826. }
  827. }
  828. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL: Bool) -> String {
  829. var updatedConclusion = reasonConclusion
  830. // Handle "minGuardBG x<y" pattern
  831. if let range = updatedConclusion.range(of: "minGuardBG\\s*-?\\d+<\\d+", options: .regularExpression) {
  832. let matchedString = updatedConclusion[range]
  833. let parts = matchedString.components(separatedBy: "<")
  834. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  835. let secondValue = Double(parts[1])
  836. {
  837. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  838. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  839. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  840. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  841. }
  842. }
  843. // Handle "Eventual BG x >= target" pattern
  844. if let range = updatedConclusion.range(of: "Eventual BG\\s*\\d+\\s*>?=\\s*\\d+", options: .regularExpression) {
  845. let matchedString = updatedConclusion[range]
  846. let parts = matchedString.components(separatedBy: " >= ")
  847. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  848. let secondValue = Double(parts[1])
  849. {
  850. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  851. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  852. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  853. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  854. }
  855. }
  856. return updatedConclusion.capitalizingFirstLetter()
  857. }
  858. private var popup: some View {
  859. VStack(alignment: .leading, spacing: 4) {
  860. Text(statusTitle).font(.headline).foregroundColor(.white)
  861. .padding(.bottom, 4)
  862. if let determination = state.determinationsFromPersistence.first {
  863. if determination.glucose == 400 {
  864. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  865. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  866. } else {
  867. let tags = !state.isSmoothingEnabled ? determination.reasonParts : determination
  868. .reasonParts + ["Smoothing: On"]
  869. TagCloudView(
  870. tags: tags,
  871. shouldParseToMmolL: state.units == .mmolL
  872. )
  873. .animation(.none, value: false)
  874. Text(
  875. self
  876. .parseReasonConclusion(
  877. determination.reasonConclusion,
  878. isMmolL: state.units == .mmolL
  879. )
  880. ).font(.caption).foregroundColor(.white)
  881. }
  882. } else {
  883. Text("No determination found").font(.body).foregroundColor(.white)
  884. }
  885. if let errorMessage = state.errorMessage, let date = state.errorDate {
  886. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  887. .foregroundColor(.white)
  888. .font(.headline)
  889. .padding(.bottom, 4)
  890. .padding(.top, 8)
  891. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  892. }
  893. }
  894. }
  895. private func setStatusTitle() {
  896. if let determination = state.determinationsFromPersistence.first {
  897. let dateFormatter = DateFormatter()
  898. dateFormatter.timeStyle = .short
  899. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  900. " " +
  901. dateFormatter
  902. .string(from: determination.deliverAt ?? Date())
  903. } else {
  904. statusTitle = "No Oref determination"
  905. return
  906. }
  907. }
  908. }
  909. }
  910. extension UIDevice {
  911. public enum DeviceSize: CGFloat {
  912. case smallDevice = 667 // Height for 4" iPhone SE
  913. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  914. }
  915. @usableFromInline static func adjustPadding(min: CGFloat? = nil, max: CGFloat? = nil) -> CGFloat? {
  916. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  917. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  918. return max
  919. } else {
  920. return min != nil ?
  921. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  922. }
  923. } else {
  924. return min
  925. }
  926. }
  927. }
  928. extension UIScreen {
  929. static var screenHeight: CGFloat {
  930. UIScreen.main.bounds.height
  931. }
  932. static var screenWidth: CGFloat {
  933. UIScreen.main.bounds.width
  934. }
  935. }