HomeRootView.swift 37 KB

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