HomeRootView.swift 45 KB

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