HomeRootView.swift 46 KB

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