HomeRootView.swift 26 KB

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