HomeRootView.swift 48 KB

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