HomeRootView.swift 46 KB

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