HomeRootView.swift 49 KB

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