HomeRootView.swift 40 KB

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