HomeRootView.swift 45 KB

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