HomeRootView.swift 25 KB

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