HomeRootView.swift 38 KB

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