HomeRootView.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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. (
  411. numberFormatter
  412. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  413. ) +
  414. NSLocalizedString(" U", comment: "Insulin unit")
  415. )
  416. .font(.system(size: 16, weight: .bold, design: .rounded))
  417. }
  418. Spacer()
  419. HStack {
  420. Image(systemName: "fork.knife")
  421. .font(.system(size: 16))
  422. .foregroundColor(.loopYellow)
  423. Text(
  424. (
  425. numberFormatter
  426. .string(from: (state.enactedAndNonEnactedDeterminations.first?.cob ?? 0) as NSNumber) ?? "0"
  427. ) +
  428. NSLocalizedString(" g", comment: "gram of carbs")
  429. )
  430. .font(.system(size: 16, weight: .bold, design: .rounded))
  431. }
  432. Spacer()
  433. HStack {
  434. if state.pumpSuspended {
  435. Text("Pump suspended")
  436. .font(.system(size: 12, weight: .bold, design: .rounded)).foregroundColor(.loopGray)
  437. } else if let tempBasalString = tempBasalString {
  438. Image(systemName: "drop.circle")
  439. .font(.system(size: 16))
  440. .foregroundColor(.insulinTintColor)
  441. Text(tempBasalString)
  442. .font(.system(size: 16, weight: .bold, design: .rounded))
  443. }
  444. }
  445. if !state.tins {
  446. Spacer()
  447. Text(
  448. "TDD: " +
  449. (
  450. numberFormatter
  451. .string(from: (state.determinationsFromPersistence.first?.totalDailyDose ?? 0) as NSNumber) ??
  452. "0"
  453. ) +
  454. NSLocalizedString(" U", comment: "Insulin unit")
  455. )
  456. .font(.system(size: 16, weight: .bold, design: .rounded))
  457. } else {
  458. Spacer()
  459. HStack {
  460. Text(
  461. "TINS: \(state.roundedTotalBolus)" +
  462. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  463. )
  464. .font(.system(size: 16, weight: .bold, design: .rounded))
  465. .onChange(of: state.hours) { _ in
  466. state.roundedTotalBolus = state.calculateTINS()
  467. }
  468. .onAppear {
  469. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  470. state.roundedTotalBolus = state.calculateTINS()
  471. }
  472. }
  473. }
  474. }
  475. }.padding(.horizontal, 10)
  476. }
  477. @ViewBuilder func profileView(_: GeometryProxy) -> some View {
  478. ZStack {
  479. /// rectangle as background
  480. RoundedRectangle(cornerRadius: 15)
  481. .fill(
  482. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  483. .opacity(0.1)
  484. )
  485. .clipShape(RoundedRectangle(cornerRadius: 15))
  486. .frame(height: UIScreen.main.bounds.height / 18)
  487. .shadow(
  488. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  489. Color.black.opacity(0.33),
  490. radius: 3
  491. )
  492. HStack {
  493. /// actual profile view
  494. Image(systemName: "person.fill")
  495. .font(.system(size: 25))
  496. Spacer()
  497. if let overrideString = overrideString {
  498. VStack {
  499. Text(selectedProfile().name)
  500. .font(.subheadline)
  501. .frame(maxWidth: .infinity, alignment: .leading)
  502. Text(overrideString)
  503. .font(.caption)
  504. .frame(maxWidth: .infinity, alignment: .leading)
  505. }.padding(.leading, 5)
  506. Spacer()
  507. Image(systemName: "xmark.app")
  508. .font(.system(size: 25))
  509. } else {
  510. if tempTargetString == nil {
  511. VStack {
  512. Text(selectedProfile().name)
  513. .font(.subheadline)
  514. .frame(maxWidth: .infinity, alignment: .leading)
  515. Text("100 %")
  516. .font(.caption)
  517. .frame(maxWidth: .infinity, alignment: .leading)
  518. }.padding(.leading, 5)
  519. Spacer()
  520. /// to ensure the same position....
  521. Image(systemName: "xmark.app")
  522. .font(.system(size: 25))
  523. .foregroundStyle(Color.clear)
  524. }
  525. }
  526. }.padding(.horizontal, 10)
  527. .alert(
  528. "Return to Normal?", isPresented: $showCancelAlert,
  529. actions: {
  530. Button("No", role: .cancel) {}
  531. Button("Yes", role: .destructive) {
  532. state.cancelProfile()
  533. }
  534. }, message: { Text("This will change settings back to your normal profile.") }
  535. )
  536. .padding(.trailing, 8)
  537. .onTapGesture {
  538. if selectedProfile().name != "Normal Profile" {
  539. showCancelAlert = true
  540. }
  541. }
  542. }.padding(.horizontal, 10).padding(.bottom, 10)
  543. .overlay {
  544. /// just show temp target if no profile is already active
  545. if overrideString == nil, let tempTargetString = tempTargetString {
  546. ZStack {
  547. /// rectangle as background
  548. RoundedRectangle(cornerRadius: 15)
  549. .fill(
  550. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  551. Color
  552. .insulin
  553. .opacity(0.2)
  554. )
  555. .clipShape(RoundedRectangle(cornerRadius: 15))
  556. .frame(height: UIScreen.main.bounds.height / 18)
  557. .shadow(
  558. color: colorScheme == .dark ? Color(
  559. red: 0.02745098039,
  560. green: 0.1098039216,
  561. blue: 0.1411764706
  562. ) :
  563. Color.black.opacity(0.33),
  564. radius: 3
  565. )
  566. HStack {
  567. Image(systemName: "person.fill")
  568. .font(.system(size: 25))
  569. Spacer()
  570. Text(tempTargetString)
  571. .font(.subheadline)
  572. Spacer()
  573. }.padding(.horizontal, 10)
  574. }.padding(.horizontal, 10).padding(.bottom, 10)
  575. }
  576. }
  577. }
  578. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  579. GeometryReader { geo in
  580. RoundedRectangle(cornerRadius: 15)
  581. .frame(height: 6)
  582. .foregroundColor(.clear)
  583. .background(
  584. LinearGradient(colors: [
  585. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  586. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  587. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  588. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  589. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  590. ], startPoint: .leading, endPoint: .trailing)
  591. .mask(alignment: .leading) {
  592. RoundedRectangle(cornerRadius: 15)
  593. .frame(width: geo.size.width * CGFloat(progress))
  594. }
  595. )
  596. }
  597. }
  598. @ViewBuilder func bolusView(_: GeometryProxy, _ progress: Decimal) -> some View {
  599. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  600. /// - TRUE: show the pump bolus
  601. /// - FALSE: do not show a progress bar at all
  602. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  603. let bolusFraction = progress * (bolusTotal as Decimal)
  604. let bolusString =
  605. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  606. + " of " +
  607. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  608. + NSLocalizedString(" U", comment: "Insulin unit")
  609. ZStack {
  610. /// rectangle as background
  611. RoundedRectangle(cornerRadius: 15)
  612. .fill(
  613. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  614. .insulin
  615. .opacity(0.2)
  616. )
  617. .clipShape(RoundedRectangle(cornerRadius: 15))
  618. .frame(height: UIScreen.main.bounds.height / 18)
  619. .shadow(
  620. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  621. Color.black.opacity(0.33),
  622. radius: 3
  623. )
  624. /// actual bolus view
  625. HStack {
  626. Image(systemName: "cross.vial.fill")
  627. .font(.system(size: 25))
  628. Spacer()
  629. VStack {
  630. Text("Bolusing")
  631. .font(.subheadline)
  632. .frame(maxWidth: .infinity, alignment: .leading)
  633. Text(bolusString)
  634. .font(.caption)
  635. .frame(maxWidth: .infinity, alignment: .leading)
  636. }.padding(.leading, 5)
  637. Spacer()
  638. Button {
  639. state.waitForSuggestion = true
  640. state.cancelBolus()
  641. } label: {
  642. Image(systemName: "xmark.app")
  643. .font(.system(size: 25))
  644. }
  645. }.padding(.horizontal, 10)
  646. .padding(.trailing, 8)
  647. }.padding(.horizontal, 10).padding(.bottom, 10)
  648. .overlay(alignment: .bottom) {
  649. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 45)
  650. }.clipShape(RoundedRectangle(cornerRadius: 15))
  651. }
  652. }
  653. @ViewBuilder func mainView() -> some View {
  654. GeometryReader { geo in
  655. VStack(spacing: 0) {
  656. // Spacer()
  657. // .frame(height: UIScreen.main.bounds.height / 40)
  658. ZStack {
  659. /// glucose bobble
  660. glucoseView
  661. /// right panel with loop status and evBG
  662. HStack {
  663. Spacer()
  664. rightHeaderPanel(geo)
  665. }.padding(.trailing, 20)
  666. /// left panel with pump related info
  667. HStack {
  668. pumpView
  669. Spacer()
  670. }.padding(.leading, 20)
  671. }.padding(.top, 10)
  672. mealPanel(geo).padding(.top, 30).padding(.bottom, 20)
  673. mainChart
  674. timeInterval.padding(.top, 20).padding(.bottom, 40)
  675. if let progress = state.bolusProgress {
  676. bolusView(geo, progress).padding(.bottom, 10)
  677. } else {
  678. profileView(geo).padding(.bottom, 10)
  679. }
  680. }
  681. .background(color)
  682. }
  683. .onChange(of: state.hours) { _ in
  684. highlightButtons()
  685. }
  686. .onAppear {
  687. configureView {
  688. highlightButtons()
  689. }
  690. }
  691. .navigationTitle("Home")
  692. .navigationBarHidden(true)
  693. .ignoresSafeArea(.keyboard)
  694. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  695. popup
  696. .padding()
  697. .background(
  698. RoundedRectangle(cornerRadius: 8, style: .continuous)
  699. .fill(colorScheme == .dark ? Color(
  700. "Chart"
  701. ) : Color(UIColor.darkGray))
  702. )
  703. .onTapGesture {
  704. state.isStatusPopupPresented = false
  705. }
  706. .gesture(
  707. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  708. .onEnded { value in
  709. if value.translation.height < 0 {
  710. state.isStatusPopupPresented = false
  711. }
  712. }
  713. )
  714. }
  715. }
  716. @State var settingsPath = NavigationPath()
  717. @ViewBuilder func tabBar() -> some View {
  718. ZStack(alignment: .bottom) {
  719. TabView(selection: $selectedTab) {
  720. let carbsRequiredBadge: String? = {
  721. guard let carbsRequired = state.determinationsFromPersistence.first?.carbsRequired as? Decimal
  722. else { return nil }
  723. if carbsRequired > state.settingsManager.settings.carbsRequiredThreshold {
  724. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequired)
  725. let formattedNumber = numberFormatter.string(from: numberAsNSNumber) ?? ""
  726. return formattedNumber + " g"
  727. } else {
  728. return nil
  729. }
  730. }()
  731. NavigationStack { mainView() }
  732. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  733. .badge(carbsRequiredBadge).tag(0)
  734. NavigationStack { DataTable.RootView(resolver: resolver) }
  735. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  736. Spacer()
  737. NavigationStack { OverrideProfilesConfig.RootView(resolver: resolver) }
  738. .tabItem {
  739. Label(
  740. "Profile",
  741. systemImage: "person.fill"
  742. ) }.tag(2)
  743. NavigationStack(path: self.$settingsPath) {
  744. Settings.RootView(resolver: resolver) }
  745. .tabItem { Label(
  746. "Menu",
  747. systemImage: "text.justify"
  748. ) }.tag(3)
  749. }
  750. .tint(Color.tabBar)
  751. Button(
  752. action: {
  753. state.showModal(for: .bolus) },
  754. label: {
  755. Image(systemName: "plus.circle.fill")
  756. .font(.system(size: 40))
  757. .foregroundStyle(Color.tabBar)
  758. .padding(.bottom, 1)
  759. .padding(.horizontal, 20)
  760. }
  761. )
  762. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  763. .onChange(of: selectedTab) { _ in
  764. print("current path is empty: \(settingsPath.isEmpty)")
  765. settingsPath = NavigationPath()
  766. }
  767. }
  768. var body: some View {
  769. ZStack(alignment: .center) {
  770. tabBar()
  771. if state.waitForSuggestion {
  772. CustomProgressView(text: "Updating IOB...")
  773. }
  774. }
  775. }
  776. private var popup: some View {
  777. VStack(alignment: .leading, spacing: 4) {
  778. Text(statusTitle).font(.headline).foregroundColor(.white)
  779. .padding(.bottom, 4)
  780. if let determination = state.determinationsFromPersistence.first {
  781. if determination.glucose == 400 {
  782. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  783. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  784. } else {
  785. TagCloudView(tags: determination.reasonParts).animation(.none, value: false)
  786. Text(determination.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  787. }
  788. } else {
  789. Text("No determination found").font(.body).foregroundColor(.white)
  790. }
  791. if let errorMessage = state.errorMessage, let date = state.errorDate {
  792. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  793. .foregroundColor(.white)
  794. .font(.headline)
  795. .padding(.bottom, 4)
  796. .padding(.top, 8)
  797. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  798. }
  799. }
  800. }
  801. private func setStatusTitle() {
  802. if let determination = state.determinationsFromPersistence.first {
  803. let dateFormatter = DateFormatter()
  804. dateFormatter.timeStyle = .short
  805. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  806. " " +
  807. dateFormatter
  808. .string(from: determination.deliverAt ?? Date())
  809. } else {
  810. statusTitle = "No Oref determination"
  811. return
  812. }
  813. }
  814. }
  815. }