HomeRootView.swift 47 KB

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