HomeRootView.swift 37 KB

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