HomeRootView.swift 25 KB

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