HomeRootView.swift 25 KB

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