HomeRootView.swift 45 KB

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