HomeRootView.swift 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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 isConfirmStopOverrideShown = false
  12. @State var isMenuPresented = false
  13. @State var showTreatments = false
  14. @State var selectedTab: Int = 0
  15. @State private var statusTitle: String = ""
  16. @State var showPumpSelection: Bool = false
  17. struct Buttons: Identifiable {
  18. let label: String
  19. let number: String
  20. var active: Bool
  21. let hours: Int16
  22. var id: String { label }
  23. }
  24. @State var timeButtons: [Buttons] = [
  25. Buttons(label: "2 hours", number: "2", active: false, hours: 2),
  26. Buttons(label: "4 hours", number: "4", active: false, hours: 4),
  27. Buttons(label: "6 hours", number: "6", active: false, hours: 6),
  28. Buttons(label: "12 hours", number: "12", active: false, hours: 12),
  29. Buttons(label: "24 hours", number: "24", active: false, hours: 24)
  30. ]
  31. let buttonFont = Font.custom("TimeButtonFont", size: 14)
  32. @Environment(\.managedObjectContext) var moc
  33. @Environment(\.colorScheme) var colorScheme
  34. @FetchRequest(fetchRequest: OverrideStored.fetch(
  35. NSPredicate.lastActiveOverride,
  36. ascending: false,
  37. fetchLimit: 1
  38. )) var latestOverride: FetchedResults<OverrideStored>
  39. @FetchRequest(
  40. entity: TempTargets.entity(),
  41. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  42. ) var sliderTTpresets: FetchedResults<TempTargets>
  43. @FetchRequest(
  44. entity: TempTargetsSlider.entity(),
  45. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  46. ) var enactedSliderTT: FetchedResults<TempTargetsSlider>
  47. // TODO: end todo
  48. var bolusProgressFormatter: NumberFormatter {
  49. let formatter = NumberFormatter()
  50. formatter.numberStyle = .decimal
  51. formatter.minimum = 0
  52. formatter.maximumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  53. formatter.minimumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  54. formatter.allowsFloats = true
  55. formatter.roundingIncrement = Double(state.settingsManager.preferences.bolusIncrement) as NSNumber
  56. return formatter
  57. }
  58. private var numberFormatter: NumberFormatter {
  59. let formatter = NumberFormatter()
  60. formatter.numberStyle = .decimal
  61. formatter.maximumFractionDigits = 2
  62. return formatter
  63. }
  64. private var fetchedTargetFormatter: NumberFormatter {
  65. let formatter = NumberFormatter()
  66. formatter.numberStyle = .decimal
  67. if state.units == .mmolL {
  68. formatter.maximumFractionDigits = 1
  69. } else { formatter.maximumFractionDigits = 0 }
  70. return formatter
  71. }
  72. private var targetFormatter: NumberFormatter {
  73. let formatter = NumberFormatter()
  74. formatter.numberStyle = .decimal
  75. formatter.maximumFractionDigits = 1
  76. return formatter
  77. }
  78. private var tirFormatter: NumberFormatter {
  79. let formatter = NumberFormatter()
  80. formatter.numberStyle = .decimal
  81. formatter.maximumFractionDigits = 0
  82. return formatter
  83. }
  84. private var dateFormatter: DateFormatter {
  85. let dateFormatter = DateFormatter()
  86. dateFormatter.timeStyle = .short
  87. return dateFormatter
  88. }
  89. private var color: LinearGradient {
  90. colorScheme == .dark ? LinearGradient(
  91. gradient: Gradient(colors: [
  92. Color.bgDarkBlue,
  93. Color.bgDarkerDarkBlue
  94. ]),
  95. startPoint: .top,
  96. endPoint: .bottom
  97. )
  98. :
  99. LinearGradient(
  100. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  101. startPoint: .top,
  102. endPoint: .bottom
  103. )
  104. }
  105. private var historySFSymbol: String {
  106. if #available(iOS 17.0, *) {
  107. return "book.pages"
  108. } else {
  109. return "book"
  110. }
  111. }
  112. var glucoseView: some View {
  113. CurrentGlucoseView(
  114. timerDate: $state.timerDate,
  115. units: $state.units,
  116. alarm: $state.alarm,
  117. lowGlucose: $state.lowGlucose,
  118. highGlucose: $state.highGlucose,
  119. cgmAvailable: $state.cgmAvailable,
  120. glucose: state.latestTwoGlucoseValues
  121. ).scaleEffect(0.9)
  122. .onTapGesture {
  123. state.openCGM()
  124. }
  125. .onLongPressGesture {
  126. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  127. impactHeavy.impactOccurred()
  128. state.showModal(for: .snooze)
  129. }
  130. }
  131. var pumpView: some View {
  132. PumpView(
  133. reservoir: $state.reservoir,
  134. name: $state.pumpName,
  135. expiresAtDate: $state.pumpExpiresAtDate,
  136. timerDate: $state.timerDate,
  137. timeZone: $state.timeZone,
  138. pumpStatusHighlightMessage: $state.pumpStatusHighlightMessage,
  139. battery: $state.batteryFromPersistence
  140. ).onTapGesture {
  141. if state.pumpDisplayState == nil {
  142. // shows user confirmation dialog with pump model choices, then proceeds to setup
  143. showPumpSelection.toggle()
  144. } else {
  145. // sends user to pump settings
  146. state.setupPump.toggle()
  147. }
  148. }
  149. }
  150. var tempBasalString: String? {
  151. guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
  152. return nil
  153. }
  154. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  155. var manualBasalString = ""
  156. if let apsManager = state.apsManager, apsManager.isManualTempBasal {
  157. manualBasalString = NSLocalizedString(
  158. " - Manual Basal ⚠️",
  159. comment: "Manual Temp basal"
  160. )
  161. }
  162. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  163. }
  164. var overrideString: String? {
  165. guard let latestOverride = latestOverride.first else {
  166. return nil
  167. }
  168. let percent = latestOverride.percentage
  169. let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
  170. let unit = state.units
  171. var target = (latestOverride.target ?? 100) as Decimal
  172. target = unit == .mmolL ? target.asMmolL : target
  173. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  174. .rawValue
  175. if tempTargetString != nil {
  176. targetString = ""
  177. }
  178. let duration = latestOverride.duration ?? 0
  179. let addedMinutes = Int(truncating: duration)
  180. let date = latestOverride.date ?? Date()
  181. let newDuration = max(
  182. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  183. 0
  184. )
  185. let indefinite = latestOverride.indefinite
  186. var durationString = ""
  187. if !indefinite {
  188. if newDuration >= 1 {
  189. durationString = formatHrMin(Int(newDuration))
  190. } else if newDuration > 0 {
  191. durationString = "\(Int(newDuration * 60)) s"
  192. } else {
  193. /// Do not show the Override anymore
  194. Task {
  195. guard let objectID = self.latestOverride.first?.objectID else { return }
  196. await state.cancelOverride(withID: objectID)
  197. }
  198. }
  199. }
  200. let smbScheduleString = latestOverride
  201. .smbIsScheduledOff && ((latestOverride.start?.stringValue ?? "") != (latestOverride.end?.stringValue ?? ""))
  202. ? " \(formatTimeRange(start: latestOverride.start?.stringValue, end: latestOverride.end?.stringValue))"
  203. : ""
  204. let smbToggleString = latestOverride.smbIsOff || latestOverride
  205. .smbIsScheduledOff ? "SMBs Off\(smbScheduleString)" : ""
  206. let components = [durationString, percentString, targetString, smbToggleString].filter { !$0.isEmpty }
  207. return components.isEmpty ? nil : components.joined(separator: ", ")
  208. }
  209. var tempTargetString: String? {
  210. guard let tempTarget = state.tempTarget else {
  211. return nil
  212. }
  213. let target = tempTarget.targetBottom ?? 0
  214. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  215. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  216. .rawValue
  217. var string = ""
  218. if sliderTTpresets.first?.active ?? false {
  219. let hbt = sliderTTpresets.first?.hbt ?? 0
  220. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  221. }
  222. let percentString = state
  223. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  224. return tempTarget.displayName + " " + percentString
  225. }
  226. var infoPanel: some View {
  227. HStack(alignment: .center) {
  228. if state.pumpSuspended {
  229. Text("Pump suspended")
  230. .font(.system(size: 15, weight: .bold)).foregroundColor(.loopGray)
  231. .padding(.leading, 8)
  232. } else if let tempBasalString = tempBasalString {
  233. Text(tempBasalString)
  234. .font(.system(size: 15, weight: .bold))
  235. .foregroundColor(.insulin)
  236. .padding(.leading, 8)
  237. }
  238. if state.totalInsulinDisplayType == .totalInsulinInScope {
  239. Text(
  240. "TINS: \(state.calculateTINS())" +
  241. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  242. )
  243. .font(.system(size: 15, weight: .bold))
  244. .foregroundColor(.insulin)
  245. }
  246. if let tempTargetString = tempTargetString {
  247. Text(tempTargetString)
  248. .font(.caption)
  249. .foregroundColor(.secondary)
  250. }
  251. Spacer()
  252. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  253. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  254. }
  255. }
  256. .frame(maxWidth: .infinity, maxHeight: 30)
  257. }
  258. var timeInterval: some View {
  259. HStack(alignment: .center) {
  260. ForEach(timeButtons) { button in
  261. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  262. state.hours = button.hours
  263. }
  264. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  265. .frame(maxHeight: 30).padding(.horizontal, 8)
  266. .background(
  267. button.active ?
  268. // RGB(30, 60, 95)
  269. (
  270. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  271. Color.white
  272. ) :
  273. Color
  274. .clear
  275. )
  276. .cornerRadius(20)
  277. }
  278. Button(action: {
  279. state.isLegendPresented.toggle()
  280. }) {
  281. Image(systemName: "info")
  282. .foregroundColor(colorScheme == .dark ? Color.white : Color.black).opacity(0.9)
  283. .frame(width: 20, height: 20)
  284. .background(
  285. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  286. Color.white
  287. )
  288. .clipShape(Circle())
  289. }
  290. .padding([.top, .bottom])
  291. }
  292. .shadow(
  293. color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33),
  294. radius: colorScheme == .dark ? 5 : 3
  295. )
  296. .font(buttonFont)
  297. }
  298. @ViewBuilder func mainChart(geo: GeometryProxy) -> some View {
  299. ZStack {
  300. MainChartView(
  301. geo: geo,
  302. units: $state.units,
  303. hours: .constant(state.filteredHours),
  304. tempTargets: $state.tempTargets,
  305. highGlucose: $state.highGlucose,
  306. lowGlucose: $state.lowGlucose,
  307. screenHours: $state.hours,
  308. displayXgridLines: $state.displayXgridLines,
  309. displayYgridLines: $state.displayYgridLines,
  310. thresholdLines: $state.thresholdLines,
  311. state: state
  312. )
  313. }
  314. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: nil))
  315. }
  316. func highlightButtons() {
  317. for i in 0 ..< timeButtons.count {
  318. timeButtons[i].active = timeButtons[i].hours == state.hours
  319. }
  320. }
  321. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  322. VStack(alignment: .leading, spacing: 20) {
  323. /// Loop view at bottomLeading
  324. LoopView(
  325. closedLoop: $state.closedLoop,
  326. timerDate: $state.timerDate,
  327. isLooping: $state.isLooping,
  328. lastLoopDate: $state.lastLoopDate,
  329. manualTempBasal: $state.manualTempBasal,
  330. determination: state.determinationsFromPersistence
  331. ).onTapGesture {
  332. state.isStatusPopupPresented = true
  333. setStatusTitle()
  334. }.onLongPressGesture {
  335. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  336. impactHeavy.impactOccurred()
  337. state.runLoop()
  338. }
  339. /// eventualBG string at bottomTrailing
  340. if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
  341. let bg = eventualBG as Decimal
  342. HStack {
  343. Image(systemName: "arrow.right.circle")
  344. .font(.system(size: 16, weight: .bold))
  345. Text(
  346. numberFormatter.string(
  347. from: (
  348. state.units == .mmolL ? bg
  349. .asMmolL : bg
  350. ) as NSNumber
  351. )!
  352. )
  353. .font(.system(size: 16))
  354. }
  355. } else {
  356. HStack {
  357. Image(systemName: "arrow.right.circle")
  358. .font(.system(size: 16, weight: .bold))
  359. Text("--")
  360. .font(.system(size: 16))
  361. }
  362. }
  363. }
  364. }
  365. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  366. HStack {
  367. HStack {
  368. Image(systemName: "syringe.fill")
  369. .font(.system(size: 16))
  370. .foregroundColor(Color.insulin)
  371. Text(
  372. (
  373. numberFormatter
  374. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  375. ) +
  376. NSLocalizedString(" U", comment: "Insulin unit")
  377. )
  378. .font(.system(size: 16, weight: .bold, design: .rounded))
  379. }
  380. Spacer()
  381. HStack {
  382. Image(systemName: "fork.knife")
  383. .font(.system(size: 16))
  384. .foregroundColor(.loopYellow)
  385. Text(
  386. (
  387. numberFormatter
  388. .string(from: (state.enactedAndNonEnactedDeterminations.first?.cob ?? 0) as NSNumber) ?? "0"
  389. ) +
  390. NSLocalizedString(" g", comment: "gram of carbs")
  391. )
  392. .font(.system(size: 16, weight: .bold, design: .rounded))
  393. }
  394. Spacer()
  395. HStack {
  396. if state.pumpSuspended {
  397. Text("Pump suspended")
  398. .font(.system(size: 12, weight: .bold, design: .rounded)).foregroundColor(.loopGray)
  399. } else if let tempBasalString = tempBasalString {
  400. Image(systemName: "drop.circle")
  401. .font(.system(size: 16))
  402. .foregroundColor(.insulinTintColor)
  403. Text(tempBasalString)
  404. .font(.system(size: 16, weight: .bold, design: .rounded))
  405. } else {
  406. Image(systemName: "drop.circle")
  407. .font(.system(size: 16))
  408. .foregroundColor(.insulinTintColor)
  409. Text("No Data")
  410. .font(.system(size: 16, weight: .bold, design: .rounded))
  411. }
  412. }
  413. if state.totalInsulinDisplayType == .totalDailyDose {
  414. Spacer()
  415. Text(
  416. "TDD: " +
  417. (
  418. numberFormatter
  419. .string(from: (state.determinationsFromPersistence.first?.totalDailyDose ?? 0) as NSNumber) ??
  420. "0"
  421. ) +
  422. NSLocalizedString(" U", comment: "Insulin unit")
  423. )
  424. .font(.system(size: 16, weight: .bold, design: .rounded))
  425. } else {
  426. Spacer()
  427. HStack {
  428. Text(
  429. "TINS: \(state.roundedTotalBolus)" +
  430. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  431. )
  432. .font(.system(size: 16, weight: .bold, design: .rounded))
  433. .onChange(of: state.hours) { _ in
  434. state.roundedTotalBolus = state.calculateTINS()
  435. }
  436. .onAppear {
  437. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  438. state.roundedTotalBolus = state.calculateTINS()
  439. }
  440. }
  441. }
  442. }
  443. }.padding(.horizontal, 10)
  444. }
  445. @ViewBuilder func profileView(geo: GeometryProxy) -> some View {
  446. ZStack {
  447. /// rectangle as background
  448. RoundedRectangle(cornerRadius: 15)
  449. .fill(
  450. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  451. .opacity(0.1)
  452. )
  453. .clipShape(RoundedRectangle(cornerRadius: 15))
  454. .frame(height: geo.size.height * 0.08)
  455. .shadow(
  456. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  457. Color.black.opacity(0.33),
  458. radius: 3
  459. )
  460. HStack {
  461. /// actual profile view
  462. Image(systemName: "person.fill")
  463. .font(.system(size: 25))
  464. Spacer()
  465. if let overrideString = overrideString {
  466. VStack {
  467. Text(latestOverride.first?.name ?? "Custom Override")
  468. .font(.subheadline)
  469. .frame(maxWidth: .infinity, alignment: .leading)
  470. Text("\(overrideString)")
  471. .font(.caption)
  472. .frame(maxWidth: .infinity, alignment: .leading)
  473. }.padding(.leading, 5)
  474. Spacer()
  475. Image(systemName: "xmark.app")
  476. .font(.system(size: 25))
  477. } else {
  478. if tempTargetString == nil {
  479. VStack {
  480. Text("Normal Profile")
  481. .font(.subheadline)
  482. .frame(maxWidth: .infinity, alignment: .leading)
  483. Text("100 %")
  484. .font(.caption)
  485. .frame(maxWidth: .infinity, alignment: .leading)
  486. }.padding(.leading, 5)
  487. Spacer()
  488. /// to ensure the same position....
  489. Image(systemName: "xmark.app")
  490. .font(.system(size: 25))
  491. .foregroundStyle(Color.clear)
  492. }
  493. }
  494. }
  495. .padding(.horizontal, 10)
  496. .confirmationDialog(
  497. "Stop the Override \"\(latestOverride.first?.name ?? "")\"?",
  498. isPresented: $isConfirmStopOverrideShown,
  499. titleVisibility: .visible
  500. ) {
  501. Button("Stop", role: .destructive) {
  502. Task {
  503. guard let objectID = latestOverride.first?.objectID else { return }
  504. await state.cancelOverride(withID: objectID)
  505. }
  506. }
  507. Button("Cancel", role: .cancel) {}
  508. }
  509. .padding(.trailing, 8)
  510. .onTapGesture {
  511. if !latestOverride.isEmpty {
  512. isConfirmStopOverrideShown = 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. }
  937. // Helper function to convert a start and end hour to either 24-hour or AM/PM format
  938. func formatTimeRange(start: String?, end: String?) -> String {
  939. guard let start = start, let end = end else {
  940. return ""
  941. }
  942. // Check if the format is 24-hour or AM/PM
  943. if is24HourFormat() {
  944. // Return the original 24-hour format
  945. return "\(start)-\(end)"
  946. } else {
  947. // Convert to AM/PM format using DateFormatter
  948. let formatter = DateFormatter()
  949. formatter.dateFormat = "HH"
  950. if let startHour = Int(start), let endHour = Int(end) {
  951. let startDate = Calendar.current.date(bySettingHour: startHour, minute: 0, second: 0, of: Date()) ?? Date()
  952. let endDate = Calendar.current.date(bySettingHour: endHour, minute: 0, second: 0, of: Date()) ?? Date()
  953. // Customize the format to "2p" or "2a"
  954. formatter.dateFormat = "ha"
  955. let startFormatted = formatter.string(from: startDate).lowercased().replacingOccurrences(of: "m", with: "")
  956. let endFormatted = formatter.string(from: endDate).lowercased().replacingOccurrences(of: "m", with: "")
  957. return "\(startFormatted)-\(endFormatted)"
  958. } else {
  959. return ""
  960. }
  961. }
  962. }