HomeRootView.swift 45 KB

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