HomeRootView.swift 45 KB

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