HomeRootView.swift 25 KB

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