HomeRootView.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. @Environment(\.managedObjectContext) var moc
  13. @Environment(\.colorScheme) var colorScheme
  14. @FetchRequest(
  15. entity: Override.entity(),
  16. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  17. ) var fetchedPercent: FetchedResults<Override>
  18. @FetchRequest(
  19. entity: OverridePresets.entity(),
  20. sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(
  21. format: "name != %@", "" as String
  22. )
  23. ) var fetchedProfiles: FetchedResults<OverridePresets>
  24. @FetchRequest(
  25. entity: TempTargets.entity(),
  26. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  27. ) var sliderTTpresets: FetchedResults<TempTargets>
  28. @FetchRequest(
  29. entity: TempTargetsSlider.entity(),
  30. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  31. ) var enactedSliderTT: FetchedResults<TempTargetsSlider>
  32. private var numberFormatter: NumberFormatter {
  33. let formatter = NumberFormatter()
  34. formatter.numberStyle = .decimal
  35. formatter.maximumFractionDigits = 2
  36. return formatter
  37. }
  38. private var fetchedTargetFormatter: NumberFormatter {
  39. let formatter = NumberFormatter()
  40. formatter.numberStyle = .decimal
  41. if state.units == .mmolL {
  42. formatter.maximumFractionDigits = 1
  43. } else { formatter.maximumFractionDigits = 0 }
  44. return formatter
  45. }
  46. private var targetFormatter: NumberFormatter {
  47. let formatter = NumberFormatter()
  48. formatter.numberStyle = .decimal
  49. formatter.maximumFractionDigits = 1
  50. return formatter
  51. }
  52. private var tirFormatter: NumberFormatter {
  53. let formatter = NumberFormatter()
  54. formatter.numberStyle = .decimal
  55. formatter.maximumFractionDigits = 0
  56. return formatter
  57. }
  58. private var dateFormatter: DateFormatter {
  59. let dateFormatter = DateFormatter()
  60. dateFormatter.timeStyle = .short
  61. return dateFormatter
  62. }
  63. private var spriteScene: SKScene {
  64. let scene = SnowScene()
  65. scene.scaleMode = .resizeFill
  66. scene.backgroundColor = .clear
  67. return scene
  68. }
  69. @ViewBuilder func header(_ geo: GeometryProxy) -> some View {
  70. HStack(alignment: .bottom) {
  71. Spacer()
  72. cobIobView
  73. Spacer()
  74. glucoseView
  75. Spacer()
  76. pumpView
  77. Spacer()
  78. loopView
  79. Spacer()
  80. }
  81. .frame(maxWidth: .infinity)
  82. .padding(.top, 10 + geo.safeAreaInsets.top)
  83. .padding(.bottom, 10)
  84. .background(Color.gray.opacity(0.2))
  85. }
  86. var cobIobView: some View {
  87. VStack(alignment: .leading, spacing: 12) {
  88. HStack {
  89. Text("IOB").font(.footnote).foregroundColor(.secondary)
  90. Text(
  91. (numberFormatter.string(from: (state.suggestion?.iob ?? 0) as NSNumber) ?? "0") +
  92. NSLocalizedString(" U", comment: "Insulin unit")
  93. )
  94. .font(.footnote).fontWeight(.bold)
  95. }.frame(alignment: .top)
  96. HStack {
  97. Text("COB").font(.footnote).foregroundColor(.secondary)
  98. Text(
  99. (numberFormatter.string(from: (state.suggestion?.cob ?? 0) as NSNumber) ?? "0") +
  100. NSLocalizedString(" g", comment: "gram of carbs")
  101. )
  102. .font(.footnote).fontWeight(.bold)
  103. }.frame(alignment: .bottom)
  104. }
  105. }
  106. var glucoseView: some View {
  107. CurrentGlucoseView(
  108. recentGlucose: $state.recentGlucose,
  109. timerDate: $state.timerDate,
  110. delta: $state.glucoseDelta,
  111. units: $state.units,
  112. alarm: $state.alarm,
  113. lowGlucose: $state.lowGlucose,
  114. highGlucose: $state.highGlucose,
  115. cgmAvailable: $state.cgmAvailable
  116. )
  117. .onTapGesture {
  118. state.openCGM()
  119. }
  120. .onLongPressGesture {
  121. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  122. impactHeavy.impactOccurred()
  123. state.showModal(for: .snooze)
  124. }
  125. }
  126. var pumpView: some View {
  127. PumpView(
  128. reservoir: $state.reservoir,
  129. battery: $state.battery,
  130. name: $state.pumpName,
  131. expiresAtDate: $state.pumpExpiresAtDate,
  132. timerDate: $state.timerDate,
  133. pumpStatusHighlightMessage: $state.pumpStatusHighlightMessage
  134. )
  135. .onTapGesture {
  136. state.setupPump = true
  137. }
  138. }
  139. var loopView: some View {
  140. LoopView(
  141. suggestion: $state.suggestion,
  142. enactedSuggestion: $state.enactedSuggestion,
  143. closedLoop: $state.closedLoop,
  144. timerDate: $state.timerDate,
  145. isLooping: $state.isLooping,
  146. lastLoopDate: $state.lastLoopDate,
  147. manualTempBasal: $state.manualTempBasal
  148. ).onTapGesture {
  149. isStatusPopupPresented = true
  150. }.onLongPressGesture {
  151. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  152. impactHeavy.impactOccurred()
  153. state.runLoop()
  154. }
  155. }
  156. var tempBasalString: String? {
  157. guard let tempRate = state.tempRate else {
  158. return nil
  159. }
  160. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  161. var manualBasalString = ""
  162. if state.apsManager.isManualTempBasal {
  163. manualBasalString = NSLocalizedString(
  164. " - Manual Basal ⚠️",
  165. comment: "Manual Temp basal"
  166. )
  167. }
  168. return rateString + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  169. }
  170. var tempTargetString: String? {
  171. guard let tempTarget = state.tempTarget else {
  172. return nil
  173. }
  174. let target = tempTarget.targetBottom ?? 0
  175. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  176. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  177. .rawValue
  178. var string = ""
  179. if sliderTTpresets.first?.active ?? false {
  180. let hbt = sliderTTpresets.first?.hbt ?? 0
  181. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  182. }
  183. let percentString = state
  184. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  185. return tempTarget.displayName + " " + percentString
  186. }
  187. var overrideString: String? {
  188. guard fetchedPercent.first?.enabled ?? false else {
  189. return nil
  190. }
  191. var percentString = "\((fetchedPercent.first?.percentage ?? 100).formatted(.number)) %"
  192. var target = (fetchedPercent.first?.target ?? 100) as Decimal
  193. let indefinite = (fetchedPercent.first?.indefinite ?? false)
  194. let unit = state.units.rawValue
  195. if state.units == .mmolL {
  196. target = target.asMmolL
  197. }
  198. var targetString = (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  199. if tempTargetString != nil || target == 0 { targetString = "" }
  200. percentString = percentString == "100 %" ? "" : percentString
  201. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  202. let addedMinutes = Int(duration)
  203. let date = fetchedPercent.first?.date ?? Date()
  204. var newDuration: Decimal = 0
  205. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() {
  206. newDuration = Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes)
  207. }
  208. var durationString = indefinite ?
  209. "" : newDuration >= 1 ?
  210. (newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " min") :
  211. (
  212. newDuration > 0 ? (
  213. (newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " s"
  214. ) :
  215. ""
  216. )
  217. if durationString == "", !indefinite {
  218. return nil
  219. }
  220. let smbToggleString = (
  221. (fetchedPercent.first?.smbIsOff ?? false) || fetchedPercent.first?.smbIsScheduledOff ?? false
  222. ) ?
  223. " \u{20e0}" : ""
  224. let smbScheduleString = (fetchedPercent.first?.smbIsScheduledOff ?? false) &&
  225. !(fetchedPercent.first?.smbIsOff ?? false) ?
  226. " \(fetchedPercent.first?.start ?? 0)-\(fetchedPercent.first?.end ?? 0)" : ""
  227. let comma1 = (percentString == "" || (targetString == "" && durationString == "" && smbToggleString == ""))
  228. ? "" : " , "
  229. let comma2 = (targetString == "" || (durationString == "" && smbToggleString == ""))
  230. ? "" : " , "
  231. let comma3 = (durationString == "" || smbToggleString == "")
  232. ? "" : " , "
  233. return percentString + comma1 + targetString + comma2 + durationString + comma3 + smbToggleString + smbScheduleString
  234. }
  235. var infoPanel: some View {
  236. HStack(alignment: .center) {
  237. if state.pumpSuspended {
  238. Text("Pump suspended")
  239. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGray)
  240. .padding(.leading, 8)
  241. } else if let tempBasalString = tempBasalString {
  242. Text(tempBasalString)
  243. .font(.system(size: 12, weight: .bold))
  244. .foregroundColor(.insulin)
  245. .padding(.leading, 8)
  246. }
  247. if let tempTargetString = tempTargetString {
  248. Text(tempTargetString)
  249. .font(.caption)
  250. .foregroundColor(.secondary)
  251. }
  252. Spacer()
  253. if let overrideString = overrideString {
  254. Text("👤 " + overrideString)
  255. .font(.system(size: 12))
  256. .foregroundColor(.secondary)
  257. .padding(.trailing, 8)
  258. }
  259. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  260. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  261. }
  262. if let progress = state.bolusProgress {
  263. Text("Bolusing")
  264. .font(.system(size: 12, weight: .bold)).foregroundColor(.insulin)
  265. ProgressView(value: Double(progress))
  266. .progressViewStyle(BolusProgressViewStyle())
  267. .padding(.trailing, 8)
  268. .onTapGesture {
  269. state.cancelBolus()
  270. }
  271. }
  272. }
  273. .frame(maxWidth: .infinity, maxHeight: 30)
  274. }
  275. var legendPanel: some View {
  276. ZStack {
  277. HStack(alignment: .center) {
  278. Group {
  279. Circle().fill(Color.loopGreen).frame(width: 8, height: 8)
  280. Text("BG")
  281. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGreen)
  282. }
  283. Group {
  284. Circle().fill(Color.insulin).frame(width: 8, height: 8)
  285. .padding(.leading, 8)
  286. Text("IOB")
  287. .font(.system(size: 12, weight: .bold)).foregroundColor(.insulin)
  288. }
  289. Group {
  290. Circle().fill(Color.zt).frame(width: 8, height: 8)
  291. .padding(.leading, 8)
  292. Text("ZT")
  293. .font(.system(size: 12, weight: .bold)).foregroundColor(.zt)
  294. }
  295. Group {
  296. Circle().fill(Color.loopYellow).frame(width: 8, height: 8)
  297. .padding(.leading, 8)
  298. Text("COB")
  299. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopYellow)
  300. }
  301. Group {
  302. Circle().fill(Color.uam).frame(width: 8, height: 8)
  303. .padding(.leading, 8)
  304. Text("UAM")
  305. .font(.system(size: 12, weight: .bold)).foregroundColor(.uam)
  306. }
  307. if let eventualBG = state.eventualBG {
  308. Text(
  309. "⇢ " + targetFormatter.string(
  310. from: (state.units == .mmolL ? eventualBG.asMmolL : Decimal(eventualBG)) as NSNumber
  311. )!
  312. )
  313. .font(.system(size: 12, weight: .bold)).foregroundColor(.secondary)
  314. }
  315. }
  316. .frame(maxWidth: .infinity)
  317. .padding([.bottom], 20)
  318. }
  319. }
  320. var mainChart: some View {
  321. ZStack {
  322. if state.animatedBackground {
  323. SpriteView(scene: spriteScene, options: [.allowsTransparency])
  324. .ignoresSafeArea()
  325. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  326. }
  327. MainChartView(
  328. glucose: $state.glucose,
  329. suggestion: $state.suggestion,
  330. tempBasals: $state.tempBasals,
  331. boluses: $state.boluses,
  332. suspensions: $state.suspensions,
  333. hours: .constant(state.filteredHours),
  334. maxBasal: $state.maxBasal,
  335. autotunedBasalProfile: $state.autotunedBasalProfile,
  336. basalProfile: $state.basalProfile,
  337. tempTargets: $state.tempTargets,
  338. carbs: $state.carbs,
  339. timerDate: $state.timerDate,
  340. units: $state.units,
  341. smooth: $state.smooth,
  342. highGlucose: $state.highGlucose,
  343. lowGlucose: $state.lowGlucose,
  344. screenHours: $state.screenHours,
  345. displayXgridLines: $state.displayXgridLines,
  346. displayYgridLines: $state.displayYgridLines,
  347. thresholdLines: $state.thresholdLines
  348. )
  349. }
  350. .padding(.bottom)
  351. .modal(for: .dataTable, from: self)
  352. }
  353. @ViewBuilder private func profiles(_: GeometryProxy) -> some View {
  354. let colour: Color = colorScheme == .dark ? .black : .white
  355. // Rectangle().fill(colour).frame(maxHeight: 1)
  356. ZStack {
  357. Rectangle().fill(Color.gray.opacity(0.2)).frame(maxHeight: 40)
  358. let cancel = fetchedPercent.first?.enabled ?? false
  359. HStack(spacing: cancel ? 25 : 15) {
  360. Text(selectedProfile().name).foregroundColor(.secondary)
  361. if cancel, selectedProfile().isOn {
  362. Button { showCancelAlert.toggle() }
  363. label: {
  364. Image(systemName: "xmark")
  365. .foregroundStyle(.secondary)
  366. }
  367. }
  368. Button { state.showModal(for: .overrideProfilesConfig) }
  369. label: {
  370. Image(systemName: "person.3.sequence.fill")
  371. .symbolRenderingMode(.palette)
  372. .foregroundStyle(
  373. !(fetchedPercent.first?.enabled ?? false) ? .green : .cyan,
  374. !(fetchedPercent.first?.enabled ?? false) ? .cyan : .green,
  375. .purple
  376. )
  377. }
  378. }
  379. }
  380. .alert(
  381. "Return to Normal?", isPresented: $showCancelAlert,
  382. actions: {
  383. Button("No", role: .cancel) {}
  384. Button("Yes", role: .destructive) {
  385. state.cancelProfile()
  386. }
  387. }, message: { Text("This will change settings back to your normal profile.") }
  388. )
  389. Rectangle().fill(colour).frame(maxHeight: 1)
  390. }
  391. private func selectedProfile() -> (name: String, isOn: Bool) {
  392. var profileString = ""
  393. var display: Bool = false
  394. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  395. let indefinite = fetchedPercent.first?.indefinite ?? false
  396. let addedMinutes = Int(duration)
  397. let date = fetchedPercent.first?.date ?? Date()
  398. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() || indefinite {
  399. display.toggle()
  400. }
  401. if fetchedPercent.first?.enabled ?? false, !(fetchedPercent.first?.isPreset ?? false), display {
  402. profileString = NSLocalizedString("Custom Profile", comment: "Custom but unsaved Profile")
  403. } else if !(fetchedPercent.first?.enabled ?? false) || !display {
  404. profileString = NSLocalizedString("Normal Profile", comment: "Your normal Profile. Use a short string")
  405. } else {
  406. let id_ = fetchedPercent.first?.id ?? ""
  407. let profile = fetchedProfiles.filter({ $0.id == id_ }).first
  408. if profile != nil {
  409. profileString = profile?.name?.description ?? ""
  410. }
  411. }
  412. return (name: profileString, isOn: display)
  413. }
  414. @ViewBuilder private func bottomPanel(_ geo: GeometryProxy) -> some View {
  415. ZStack {
  416. Rectangle().fill(Color.gray.opacity(0.2)).frame(height: 50 + geo.safeAreaInsets.bottom)
  417. HStack {
  418. Button { state.showModal(for: .addCarbs) }
  419. label: {
  420. ZStack(alignment: Alignment(horizontal: .trailing, vertical: .bottom)) {
  421. Image("carbs")
  422. .renderingMode(.template)
  423. .resizable()
  424. .frame(width: 24, height: 24)
  425. .foregroundColor(.loopYellow)
  426. .padding(8)
  427. if let carbsReq = state.carbsRequired {
  428. Text(numberFormatter.string(from: carbsReq as NSNumber)!)
  429. .font(.caption)
  430. .foregroundColor(.white)
  431. .padding(4)
  432. .background(Capsule().fill(Color.red))
  433. }
  434. }
  435. }.buttonStyle(.borderless)
  436. Spacer()
  437. Button { state.showModal(for: .addTempTarget) }
  438. label: {
  439. Image("target")
  440. .renderingMode(.template)
  441. .resizable()
  442. .frame(width: 24, height: 24)
  443. .padding(8)
  444. }
  445. .foregroundColor(.loopGreen)
  446. .buttonStyle(.borderless)
  447. Spacer()
  448. Button { state.showModal(for: .bolus(waitForSuggestion: false)) }
  449. label: {
  450. Image("bolus")
  451. .renderingMode(.template)
  452. .resizable()
  453. .frame(width: 24, height: 24)
  454. .padding(8)
  455. }
  456. .foregroundColor(.insulin)
  457. .buttonStyle(.borderless)
  458. Spacer()
  459. if state.allowManualTemp {
  460. Button { state.showModal(for: .manualTempBasal) }
  461. label: {
  462. Image("bolus1")
  463. .renderingMode(.template)
  464. .resizable()
  465. .frame(width: 24, height: 24)
  466. .padding(8)
  467. }
  468. .foregroundColor(.insulin)
  469. .buttonStyle(.borderless)
  470. Spacer()
  471. }
  472. Button { state.showModal(for: .statistics)
  473. }
  474. label: {
  475. Image(systemName: "chart.xyaxis.line")
  476. .renderingMode(.template)
  477. .resizable()
  478. .frame(width: 24, height: 24)
  479. .padding(8)
  480. }
  481. .foregroundColor(.purple)
  482. .buttonStyle(.borderless)
  483. Spacer()
  484. Button { state.showModal(for: .settings) }
  485. label: {
  486. Image("settings1")
  487. .renderingMode(.template)
  488. .resizable()
  489. .frame(width: 24, height: 24)
  490. .padding(8)
  491. }
  492. .foregroundColor(.loopGray)
  493. .buttonStyle(.borderless)
  494. }
  495. .padding(.horizontal, 24)
  496. .padding(.bottom, geo.safeAreaInsets.bottom)
  497. }
  498. }
  499. var body: some View {
  500. GeometryReader { geo in
  501. VStack(spacing: 0) {
  502. header(geo)
  503. infoPanel
  504. mainChart
  505. legendPanel
  506. profiles(geo)
  507. bottomPanel(geo)
  508. }
  509. .edgesIgnoringSafeArea(.vertical)
  510. }
  511. .onAppear(perform: configureView)
  512. .navigationTitle("Home")
  513. .navigationBarHidden(true)
  514. .ignoresSafeArea(.keyboard)
  515. .popup(isPresented: isStatusPopupPresented, alignment: .top, direction: .top) {
  516. popup
  517. .padding()
  518. .background(
  519. RoundedRectangle(cornerRadius: 8, style: .continuous)
  520. .fill(Color(UIColor.darkGray))
  521. )
  522. .onTapGesture {
  523. isStatusPopupPresented = false
  524. }
  525. .gesture(
  526. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  527. .onEnded { value in
  528. if value.translation.height < 0 {
  529. isStatusPopupPresented = false
  530. }
  531. }
  532. )
  533. }
  534. }
  535. private var popup: some View {
  536. VStack(alignment: .leading, spacing: 4) {
  537. Text(state.statusTitle).font(.headline).foregroundColor(.white)
  538. .padding(.bottom, 4)
  539. if let suggestion = state.suggestion {
  540. TagCloudView(tags: suggestion.reasonParts).animation(.none, value: false)
  541. Text(suggestion.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  542. } else {
  543. Text("No sugestion found").font(.body).foregroundColor(.white)
  544. }
  545. if let errorMessage = state.errorMessage, let date = state.errorDate {
  546. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  547. .foregroundColor(.white)
  548. .font(.headline)
  549. .padding(.bottom, 4)
  550. .padding(.top, 8)
  551. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  552. } else if let suggestion = state.suggestion, (suggestion.bg ?? 100) == 400 {
  553. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  554. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  555. }
  556. }
  557. }
  558. }
  559. }