HomeRootView.swift 38 KB

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