HomeRootView.swift 45 KB

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