HomeRootView.swift 25 KB

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