HomeRootView.swift 47 KB

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