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