HomeRootView.swift 48 KB

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