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