HomeRootView.swift 45 KB

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