HomeRootView.swift 47 KB

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