HomeRootView.swift 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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 spriteScene: SKScene {
  90. let scene = SnowScene()
  91. scene.scaleMode = .resizeFill
  92. scene.backgroundColor = .clear
  93. return scene
  94. }
  95. private var color: LinearGradient {
  96. colorScheme == .dark ? LinearGradient(
  97. gradient: Gradient(colors: [
  98. Color.bgDarkBlue,
  99. Color.bgDarkerDarkBlue
  100. ]),
  101. startPoint: .top,
  102. endPoint: .bottom
  103. )
  104. :
  105. LinearGradient(
  106. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  107. startPoint: .top,
  108. endPoint: .bottom
  109. )
  110. }
  111. private var historySFSymbol: String {
  112. if #available(iOS 17.0, *) {
  113. return "book.pages"
  114. } else {
  115. return "book"
  116. }
  117. }
  118. var glucoseView: some View {
  119. CurrentGlucoseView(
  120. timerDate: $state.timerDate,
  121. units: $state.units,
  122. alarm: $state.alarm,
  123. lowGlucose: $state.lowGlucose,
  124. highGlucose: $state.highGlucose,
  125. cgmAvailable: $state.cgmAvailable,
  126. glucose: state.glucoseFromPersistence,
  127. manualGlucose: state.manualGlucoseFromPersistence
  128. ).scaleEffect(0.9)
  129. .onTapGesture {
  130. state.openCGM()
  131. }
  132. .onLongPressGesture {
  133. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  134. impactHeavy.impactOccurred()
  135. state.showModal(for: .snooze)
  136. }
  137. }
  138. var pumpView: some View {
  139. PumpView(
  140. reservoir: $state.reservoir,
  141. name: $state.pumpName,
  142. expiresAtDate: $state.pumpExpiresAtDate,
  143. timerDate: $state.timerDate,
  144. timeZone: $state.timeZone,
  145. pumpStatusHighlightMessage: $state.pumpStatusHighlightMessage,
  146. battery: $state.batteryFromPersistence
  147. ).onTapGesture {
  148. if state.pumpDisplayState == nil {
  149. // shows user confirmation dialog with pump model choices, then proceeds to setup
  150. showPumpSelection.toggle()
  151. } else {
  152. // sends user to pump settings
  153. state.setupPump.toggle()
  154. }
  155. }
  156. }
  157. var tempBasalString: String? {
  158. guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
  159. return nil
  160. }
  161. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  162. var manualBasalString = ""
  163. if let apsManager = state.apsManager, apsManager.isManualTempBasal {
  164. manualBasalString = NSLocalizedString(
  165. " - Manual Basal ⚠️",
  166. comment: "Manual Temp basal"
  167. )
  168. }
  169. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  170. }
  171. var overrideString: String? {
  172. guard let latestOverride = latestOverride.first else {
  173. return nil
  174. }
  175. let percent = latestOverride.percentage
  176. let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
  177. let unit = state.units
  178. var target = (latestOverride.target ?? 100) as Decimal
  179. target = unit == .mmolL ? target.asMmolL : target
  180. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  181. .rawValue
  182. if tempTargetString != nil {
  183. targetString = ""
  184. }
  185. let duration = latestOverride.duration ?? 0
  186. let addedMinutes = Int(truncating: duration)
  187. let date = latestOverride.date ?? Date()
  188. let newDuration = max(
  189. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  190. 0
  191. )
  192. let indefinite = latestOverride.indefinite
  193. var durationString = ""
  194. if !indefinite {
  195. if newDuration >= 1 {
  196. durationString =
  197. "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
  198. } else if newDuration > 0 {
  199. durationString =
  200. "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
  201. } else {
  202. /// Do not show the Override anymore
  203. Task {
  204. guard let objectID = self.latestOverride.first?.objectID else { return }
  205. await state.cancelOverride(withID: objectID)
  206. }
  207. }
  208. }
  209. let smbToggleString = latestOverride.smbIsOff ? " \u{20e0}" : ""
  210. let components = [percentString, targetString, durationString, smbToggleString].filter { !$0.isEmpty }
  211. return components.isEmpty ? nil : components.joined(separator: ", ")
  212. }
  213. var tempTargetString: String? {
  214. guard let tempTarget = state.tempTarget else {
  215. return nil
  216. }
  217. let target = tempTarget.targetBottom ?? 0
  218. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  219. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  220. .rawValue
  221. var string = ""
  222. if sliderTTpresets.first?.active ?? false {
  223. let hbt = sliderTTpresets.first?.hbt ?? 0
  224. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  225. }
  226. let percentString = state
  227. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  228. return tempTarget.displayName + " " + percentString
  229. }
  230. var infoPanel: some View {
  231. HStack(alignment: .center) {
  232. if state.pumpSuspended {
  233. Text("Pump suspended")
  234. .font(.system(size: 15, weight: .bold)).foregroundColor(.loopGray)
  235. .padding(.leading, 8)
  236. } else if let tempBasalString = tempBasalString {
  237. Text(tempBasalString)
  238. .font(.system(size: 15, weight: .bold))
  239. .foregroundColor(.insulin)
  240. .padding(.leading, 8)
  241. }
  242. if state.totalInsulinDisplayType == .totalInsulinInScope {
  243. Text(
  244. "TINS: \(state.calculateTINS())" +
  245. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  246. )
  247. .font(.system(size: 15, weight: .bold))
  248. .foregroundColor(.insulin)
  249. }
  250. if let tempTargetString = tempTargetString {
  251. Text(tempTargetString)
  252. .font(.caption)
  253. .foregroundColor(.secondary)
  254. }
  255. Spacer()
  256. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  257. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  258. }
  259. }
  260. .frame(maxWidth: .infinity, maxHeight: 30)
  261. }
  262. var timeInterval: some View {
  263. HStack(alignment: .center) {
  264. ForEach(timeButtons) { button in
  265. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  266. state.hours = button.hours
  267. }
  268. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  269. .frame(maxHeight: 30).padding(.horizontal, 8)
  270. .background(
  271. button.active ?
  272. // RGB(30, 60, 95)
  273. (
  274. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  275. Color.white
  276. ) :
  277. Color
  278. .clear
  279. )
  280. .cornerRadius(20)
  281. }
  282. Button(action: {
  283. state.isLegendPresented.toggle()
  284. }) {
  285. Image(systemName: "info")
  286. .foregroundColor(colorScheme == .dark ? Color.white : Color.black).opacity(0.9)
  287. .frame(width: 20, height: 20)
  288. .background(
  289. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  290. Color.white
  291. )
  292. .clipShape(Circle())
  293. }
  294. .padding([.top, .bottom])
  295. }
  296. .shadow(
  297. color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33),
  298. radius: colorScheme == .dark ? 5 : 3
  299. )
  300. .font(buttonFont)
  301. }
  302. @ViewBuilder func mainChart(geo: GeometryProxy) -> some View {
  303. ZStack {
  304. MainChartView(
  305. geo: geo,
  306. units: $state.units,
  307. announcement: $state.announcement,
  308. hours: .constant(state.filteredHours),
  309. maxBasal: $state.maxBasal,
  310. autotunedBasalProfile: $state.autotunedBasalProfile,
  311. basalProfile: $state.basalProfile,
  312. tempTargets: $state.tempTargets,
  313. smooth: $state.smooth,
  314. highGlucose: $state.highGlucose,
  315. lowGlucose: $state.lowGlucose,
  316. screenHours: $state.hours,
  317. displayXgridLines: $state.displayXgridLines,
  318. displayYgridLines: $state.displayYgridLines,
  319. thresholdLines: $state.thresholdLines,
  320. isTempTargetActive: $state.isTempTargetActive,
  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. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  556. }
  557. }
  558. }
  559. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  560. GeometryReader { geo in
  561. RoundedRectangle(cornerRadius: 15)
  562. .frame(height: 6)
  563. .foregroundColor(.clear)
  564. .background(
  565. LinearGradient(colors: [
  566. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  567. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  568. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  569. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  570. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  571. ], startPoint: .leading, endPoint: .trailing)
  572. .mask(alignment: .leading) {
  573. RoundedRectangle(cornerRadius: 15)
  574. .frame(width: geo.size.width * CGFloat(progress))
  575. }
  576. )
  577. }
  578. }
  579. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  580. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  581. /// - TRUE: show the pump bolus
  582. /// - FALSE: do not show a progress bar at all
  583. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  584. let bolusFraction = progress * (bolusTotal as Decimal)
  585. let bolusString =
  586. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  587. + " of " +
  588. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  589. + NSLocalizedString(" U", comment: "Insulin unit")
  590. ZStack {
  591. /// rectangle as background
  592. RoundedRectangle(cornerRadius: 15)
  593. .fill(
  594. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  595. .insulin
  596. .opacity(0.2)
  597. )
  598. .clipShape(RoundedRectangle(cornerRadius: 15))
  599. .frame(height: geo.size.height * 0.08)
  600. .shadow(
  601. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  602. Color.black.opacity(0.33),
  603. radius: 3
  604. )
  605. /// actual bolus view
  606. HStack {
  607. Image(systemName: "cross.vial.fill")
  608. .font(.system(size: 25))
  609. Spacer()
  610. VStack {
  611. Text("Bolusing")
  612. .font(.subheadline)
  613. .frame(maxWidth: .infinity, alignment: .leading)
  614. Text(bolusString)
  615. .font(.caption)
  616. .frame(maxWidth: .infinity, alignment: .leading)
  617. }.padding(.leading, 5)
  618. Spacer()
  619. Button {
  620. state.showProgressView()
  621. state.cancelBolus()
  622. } label: {
  623. Image(systemName: "xmark.app")
  624. .font(.system(size: 25))
  625. }
  626. }.padding(.horizontal, 10)
  627. .padding(.trailing, 8)
  628. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  629. .overlay(alignment: .bottom) {
  630. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 48)
  631. }.clipShape(RoundedRectangle(cornerRadius: 15))
  632. }
  633. }
  634. @ViewBuilder func mainView() -> some View {
  635. GeometryReader { geo in
  636. VStack(spacing: 0) {
  637. ZStack {
  638. /// glucose bobble
  639. glucoseView
  640. /// right panel with loop status and evBG
  641. HStack {
  642. Spacer()
  643. rightHeaderPanel(geo)
  644. }.padding(.trailing, 20)
  645. /// left panel with pump related info
  646. HStack {
  647. pumpView
  648. Spacer()
  649. }.padding(.leading, 20)
  650. }.padding(.top, 10)
  651. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  652. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  653. mainChart(geo: geo)
  654. timeInterval.padding(.top, UIDevice.adjustPadding(min: 0, max: 12))
  655. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 12))
  656. if let progress = state.bolusProgress {
  657. bolusView(geo: geo, progress).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  658. } else {
  659. profileView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  660. }
  661. }
  662. .background(color)
  663. }
  664. .onChange(of: state.hours) { _ in
  665. highlightButtons()
  666. }
  667. .onAppear {
  668. configureView {
  669. highlightButtons()
  670. }
  671. }
  672. .navigationTitle("Home")
  673. .navigationBarHidden(true)
  674. .ignoresSafeArea(.keyboard)
  675. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  676. popup
  677. .padding()
  678. .background(
  679. RoundedRectangle(cornerRadius: 8, style: .continuous)
  680. .fill(colorScheme == .dark ? Color(
  681. "Chart"
  682. ) : Color(UIColor.darkGray))
  683. )
  684. .onTapGesture {
  685. state.isStatusPopupPresented = false
  686. }
  687. .gesture(
  688. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  689. .onEnded { value in
  690. if value.translation.height < 0 {
  691. state.isStatusPopupPresented = false
  692. }
  693. }
  694. )
  695. }
  696. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  697. Button("Medtronic") { state.addPump(.minimed) }
  698. Button("Omnipod Eros") { state.addPump(.omnipod) }
  699. Button("Omnipod Dash") { state.addPump(.omnipodBLE) }
  700. Button("Pump Simulator") { state.addPump(.simulator) }
  701. } message: { Text("Select Pump Model") }
  702. .sheet(isPresented: $state.setupPump) {
  703. if let pumpManager = state.provider.apsManager.pumpManager {
  704. PumpConfig.PumpSettingsView(
  705. pumpManager: pumpManager,
  706. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  707. completionDelegate: state,
  708. setupDelegate: state
  709. )
  710. } else {
  711. PumpConfig.PumpSetupView(
  712. pumpType: state.setupPumpType,
  713. pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  714. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  715. completionDelegate: state,
  716. setupDelegate: state
  717. )
  718. }
  719. }
  720. .sheet(isPresented: $state.isLegendPresented) {
  721. NavigationStack {
  722. Text(
  723. "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  724. )
  725. .font(.subheadline)
  726. .foregroundColor(.secondary)
  727. if state.forecastDisplayType == .lines {
  728. List {
  729. DefinitionRow(
  730. term: "IOB (Insulin on Board)",
  731. definition: "Forecasts BG based on the amount of insulin still active in the body.",
  732. color: .insulin
  733. )
  734. DefinitionRow(
  735. term: "ZT (Zero-Temp)",
  736. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  737. color: .zt
  738. )
  739. DefinitionRow(
  740. term: "COB (Carbs on Board)",
  741. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  742. color: .loopYellow
  743. )
  744. DefinitionRow(
  745. term: "UAM (Unannounced Meal)",
  746. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  747. color: .uam
  748. )
  749. }
  750. .padding(.trailing, 10)
  751. .navigationBarTitle("Legend", displayMode: .inline)
  752. } else {
  753. List {
  754. DefinitionRow(
  755. term: "Cone of Uncertainty",
  756. 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.",
  757. color: Color.blue.opacity(0.5)
  758. )
  759. }
  760. .padding(.trailing, 10)
  761. .navigationBarTitle("Legend", displayMode: .inline)
  762. }
  763. Button { state.isLegendPresented.toggle() }
  764. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  765. .buttonStyle(.bordered)
  766. .padding(.top)
  767. }
  768. .padding()
  769. .presentationDetents(
  770. [.fraction(0.9), .large],
  771. selection: $state.legendSheetDetent
  772. )
  773. }
  774. }
  775. @State var settingsPath = NavigationPath()
  776. @ViewBuilder func tabBar() -> some View {
  777. ZStack(alignment: .bottom) {
  778. TabView(selection: $selectedTab) {
  779. let carbsRequiredBadge: String? = {
  780. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  781. state.showCarbsRequiredBadge
  782. else {
  783. return nil
  784. }
  785. let carbsRequiredDecimal = Decimal(carbsRequired)
  786. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  787. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  788. return (numberFormatter.string(from: numberAsNSNumber) ?? "") + " g"
  789. }
  790. return nil
  791. }()
  792. NavigationStack { mainView() }
  793. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  794. .badge(carbsRequiredBadge).tag(0)
  795. NavigationStack { DataTable.RootView(resolver: resolver) }
  796. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  797. Spacer()
  798. NavigationStack { OverrideConfig.RootView(resolver: resolver) }
  799. .tabItem {
  800. Label(
  801. "Adjustments",
  802. systemImage: "slider.horizontal.2.gobackward"
  803. ) }.tag(2)
  804. NavigationStack(path: self.$settingsPath) {
  805. Settings.RootView(resolver: resolver) }
  806. .tabItem { Label(
  807. "Settings",
  808. systemImage: "gear"
  809. ) }.tag(3)
  810. }
  811. .tint(Color.tabBar)
  812. Button(
  813. action: {
  814. state.showModal(for: .bolus) },
  815. label: {
  816. Image(systemName: "plus.circle.fill")
  817. .font(.system(size: 40))
  818. .foregroundStyle(Color.tabBar)
  819. .padding(.bottom, 1)
  820. .padding(.horizontal, 20)
  821. }
  822. )
  823. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  824. .onChange(of: selectedTab) { _ in
  825. print("current path is empty: \(settingsPath.isEmpty)")
  826. settingsPath = NavigationPath()
  827. }
  828. }
  829. var body: some View {
  830. ZStack(alignment: .center) {
  831. tabBar()
  832. if state.waitForSuggestion {
  833. CustomProgressView(text: "Updating IOB...")
  834. }
  835. }
  836. }
  837. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL: Bool) -> String {
  838. var updatedConclusion = reasonConclusion
  839. // Handle "minGuardBG x<y" pattern
  840. if let range = updatedConclusion.range(of: "minGuardBG\\s*-?\\d+<\\d+", options: .regularExpression) {
  841. let matchedString = updatedConclusion[range]
  842. let parts = matchedString.components(separatedBy: "<")
  843. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  844. let secondValue = Double(parts[1])
  845. {
  846. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  847. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  848. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  849. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  850. }
  851. }
  852. // Handle "Eventual BG x >= target" pattern
  853. if let range = updatedConclusion.range(of: "Eventual BG\\s*\\d+\\s*>?=\\s*\\d+", options: .regularExpression) {
  854. let matchedString = updatedConclusion[range]
  855. let parts = matchedString.components(separatedBy: " >= ")
  856. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  857. let secondValue = Double(parts[1])
  858. {
  859. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  860. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  861. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  862. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  863. }
  864. }
  865. return updatedConclusion.capitalizingFirstLetter()
  866. }
  867. private var popup: some View {
  868. VStack(alignment: .leading, spacing: 4) {
  869. Text(statusTitle).font(.headline).foregroundColor(.white)
  870. .padding(.bottom, 4)
  871. if let determination = state.determinationsFromPersistence.first {
  872. if determination.glucose == 400 {
  873. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  874. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  875. } else {
  876. TagCloudView(tags: determination.reasonParts, shouldParseToMmolL: state.units == .mmolL)
  877. .animation(.none, value: false)
  878. Text(
  879. self
  880. .parseReasonConclusion(
  881. determination.reasonConclusion,
  882. isMmolL: state.units == .mmolL
  883. )
  884. ).font(.caption).foregroundColor(.white)
  885. }
  886. } else {
  887. Text("No determination found").font(.body).foregroundColor(.white)
  888. }
  889. if let errorMessage = state.errorMessage, let date = state.errorDate {
  890. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  891. .foregroundColor(.white)
  892. .font(.headline)
  893. .padding(.bottom, 4)
  894. .padding(.top, 8)
  895. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  896. }
  897. }
  898. }
  899. private func setStatusTitle() {
  900. if let determination = state.determinationsFromPersistence.first {
  901. let dateFormatter = DateFormatter()
  902. dateFormatter.timeStyle = .short
  903. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  904. " " +
  905. dateFormatter
  906. .string(from: determination.deliverAt ?? Date())
  907. } else {
  908. statusTitle = "No Oref determination"
  909. return
  910. }
  911. }
  912. }
  913. }
  914. extension UIDevice {
  915. public enum DeviceSize: CGFloat {
  916. case smallDevice = 667 // Height for 4" iPhone SE
  917. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  918. }
  919. @usableFromInline static func adjustPadding(min: CGFloat? = nil, max: CGFloat? = nil) -> CGFloat? {
  920. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  921. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  922. return max
  923. } else {
  924. return min != nil ?
  925. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  926. }
  927. } else {
  928. return min
  929. }
  930. }
  931. }
  932. extension UIScreen {
  933. static var screenHeight: CGFloat {
  934. UIScreen.main.bounds.height
  935. }
  936. static var screenWidth: CGFloat {
  937. UIScreen.main.bounds.width
  938. }
  939. }