HomeRootView.swift 48 KB

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