HomeRootView.swift 49 KB

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