HomeRootView.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. // Average/Median/Readings and CV/SD titles and values switches when you tap them
  12. @State var averageOrMedianTitle = NSLocalizedString("Average", comment: "")
  13. @State var median_ = ""
  14. @State var average_ = ""
  15. @State var readings = ""
  16. @State var averageOrmedian = ""
  17. @State var CV_or_SD_Title = NSLocalizedString("CV", comment: "CV")
  18. @State var cv_ = ""
  19. @State var sd_ = ""
  20. @State var CVorSD = ""
  21. // Switch between Loops and Errors when tapping in statPanel
  22. @State var loopStatTitle = NSLocalizedString("Loops", comment: "Nr of Loops in statPanel")
  23. @FetchRequest(
  24. entity: Override.entity(),
  25. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  26. ) var fetchedPercent: FetchedResults<Override>
  27. @FetchRequest(
  28. entity: TempTargets.entity(),
  29. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  30. ) var sliderTTpresets: FetchedResults<TempTargets>
  31. @FetchRequest(
  32. entity: TempTargetsSlider.entity(),
  33. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  34. ) var enactedSliderTT: FetchedResults<TempTargetsSlider>
  35. private var numberFormatter: NumberFormatter {
  36. let formatter = NumberFormatter()
  37. formatter.numberStyle = .decimal
  38. formatter.maximumFractionDigits = 2
  39. return formatter
  40. }
  41. private var fetchedTargetFormatter: NumberFormatter {
  42. let formatter = NumberFormatter()
  43. formatter.numberStyle = .decimal
  44. if state.units == .mmolL {
  45. formatter.maximumFractionDigits = 1
  46. } else { formatter.maximumFractionDigits = 0 }
  47. return formatter
  48. }
  49. private var targetFormatter: NumberFormatter {
  50. let formatter = NumberFormatter()
  51. formatter.numberStyle = .decimal
  52. formatter.maximumFractionDigits = 1
  53. return formatter
  54. }
  55. private var tirFormatter: NumberFormatter {
  56. let formatter = NumberFormatter()
  57. formatter.numberStyle = .decimal
  58. formatter.maximumFractionDigits = 0
  59. return formatter
  60. }
  61. private var dateFormatter: DateFormatter {
  62. let dateFormatter = DateFormatter()
  63. dateFormatter.timeStyle = .short
  64. return dateFormatter
  65. }
  66. private var spriteScene: SKScene {
  67. let scene = SnowScene()
  68. scene.scaleMode = .resizeFill
  69. scene.backgroundColor = .clear
  70. return scene
  71. }
  72. @ViewBuilder func header(_ geo: GeometryProxy) -> some View {
  73. HStack(alignment: .bottom) {
  74. Spacer()
  75. cobIobView
  76. Spacer()
  77. glucoseView
  78. Spacer()
  79. pumpView
  80. Spacer()
  81. loopView
  82. Spacer()
  83. }
  84. .frame(maxWidth: .infinity)
  85. .padding(.top, geo.safeAreaInsets.top)
  86. .padding(.bottom, 6)
  87. .background(Color.gray.opacity(0.2))
  88. }
  89. var cobIobView: some View {
  90. VStack(alignment: .leading, spacing: 12) {
  91. HStack {
  92. Text("IOB").font(.footnote).foregroundColor(.secondary)
  93. Text(
  94. (numberFormatter.string(from: (state.suggestion?.iob ?? 0) as NSNumber) ?? "0") +
  95. NSLocalizedString(" U", comment: "Insulin unit")
  96. )
  97. .font(.footnote).fontWeight(.bold)
  98. }.frame(alignment: .top)
  99. HStack {
  100. Text("COB").font(.footnote).foregroundColor(.secondary)
  101. Text(
  102. (numberFormatter.string(from: (state.suggestion?.cob ?? 0) as NSNumber) ?? "0") +
  103. NSLocalizedString(" g", comment: "gram of carbs")
  104. )
  105. .font(.footnote).fontWeight(.bold)
  106. }.frame(alignment: .bottom)
  107. }
  108. }
  109. var glucoseView: some View {
  110. CurrentGlucoseView(
  111. recentGlucose: $state.recentGlucose,
  112. delta: $state.glucoseDelta,
  113. units: $state.units,
  114. alarm: $state.alarm,
  115. lowGlucose: $state.lowGlucose,
  116. highGlucose: $state.highGlucose
  117. )
  118. .onTapGesture {
  119. if state.alarm == nil {
  120. state.openCGM()
  121. } else {
  122. state.showModal(for: .snooze)
  123. }
  124. }
  125. .onLongPressGesture {
  126. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  127. impactHeavy.impactOccurred()
  128. if state.alarm == nil {
  129. state.showModal(for: .snooze)
  130. } else {
  131. state.openCGM()
  132. }
  133. }
  134. }
  135. var pumpView: some View {
  136. PumpView(
  137. reservoir: $state.reservoir,
  138. battery: $state.battery,
  139. name: $state.pumpName,
  140. expiresAtDate: $state.pumpExpiresAtDate,
  141. timerDate: $state.timerDate
  142. )
  143. .onTapGesture {
  144. if state.pumpDisplayState != nil {
  145. state.setupPump = true
  146. }
  147. }
  148. }
  149. var loopView: some View {
  150. LoopView(
  151. suggestion: $state.suggestion,
  152. enactedSuggestion: $state.enactedSuggestion,
  153. closedLoop: $state.closedLoop,
  154. timerDate: $state.timerDate,
  155. isLooping: $state.isLooping,
  156. lastLoopDate: $state.lastLoopDate,
  157. manualTempBasal: $state.manualTempBasal
  158. ).onTapGesture {
  159. isStatusPopupPresented = true
  160. }.onLongPressGesture {
  161. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  162. impactHeavy.impactOccurred()
  163. state.runLoop()
  164. }
  165. }
  166. var tempBasalString: String? {
  167. guard let tempRate = state.tempRate else {
  168. return nil
  169. }
  170. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  171. var manualBasalString = ""
  172. if state.apsManager.isManualTempBasal {
  173. manualBasalString = NSLocalizedString(
  174. " - Manual Basal ⚠️",
  175. comment: "Manual Temp basal"
  176. )
  177. }
  178. return rateString + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  179. }
  180. var tempTargetString: String? {
  181. guard let tempTarget = state.tempTarget else {
  182. return nil
  183. }
  184. let target = tempTarget.targetBottom ?? 0
  185. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  186. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  187. .rawValue
  188. var string = ""
  189. if sliderTTpresets.first?.active ?? false {
  190. let hbt = sliderTTpresets.first?.hbt ?? 0
  191. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  192. } /* else if enactedSliderTT.first?.enabled ?? false {
  193. let hbt = enactedSliderTT.first?.hbt ?? 0
  194. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  195. } */
  196. let percentString = state
  197. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  198. return tempTarget.displayName + " " + percentString
  199. }
  200. var overrideString: String? {
  201. guard fetchedPercent.first?.enabled ?? false else {
  202. return nil
  203. }
  204. var percentString = "\((fetchedPercent.first?.percentage ?? 100).formatted(.number)) %"
  205. var target = (fetchedPercent.first?.target ?? 100) as Decimal
  206. let indefinite = (fetchedPercent.first?.indefinite ?? false)
  207. let unit = state.units.rawValue
  208. if state.units == .mmolL {
  209. target = target.asMmolL
  210. }
  211. var targetString = (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  212. if tempTargetString != nil || target == 0 { targetString = "" }
  213. percentString = percentString == "100 %" ? "" : percentString
  214. var durationString = indefinite ?
  215. "" : ((tirFormatter.string(from: (fetchedPercent.first?.duration ?? 0) as NSNumber) ?? "") + " min")
  216. let smbToggleString = (fetchedPercent.first?.smbIsOff ?? false) ? " \u{20e0}" : ""
  217. var comma1 = ", "
  218. var comma2 = comma1
  219. var comma3 = comma1
  220. if targetString == "" || percentString == "" { comma1 = "" }
  221. if durationString == "" { comma2 = "" }
  222. if smbToggleString == "" { comma3 = "" }
  223. if percentString == "", targetString == "" {
  224. comma1 = ""
  225. comma2 = ""
  226. }
  227. if percentString == "", targetString == "", smbToggleString == "" {
  228. durationString = ""
  229. comma1 = ""
  230. comma2 = ""
  231. comma3 = ""
  232. }
  233. if durationString == "" {
  234. comma2 = ""
  235. }
  236. if smbToggleString == "" {
  237. comma3 = ""
  238. }
  239. return percentString + comma1 + targetString + comma2 + durationString + comma3 + smbToggleString
  240. }
  241. var infoPanel: some View {
  242. HStack(alignment: .center) {
  243. if state.pumpSuspended {
  244. Text("Pump suspended")
  245. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGray)
  246. .padding(.leading, 8)
  247. } else if let tempBasalString = tempBasalString {
  248. Text(tempBasalString)
  249. .font(.system(size: 12, weight: .bold))
  250. .foregroundColor(.insulin)
  251. .padding(.leading, 8)
  252. }
  253. if let tempTargetString = tempTargetString {
  254. Text(tempTargetString)
  255. .font(.caption)
  256. .foregroundColor(.secondary)
  257. }
  258. Spacer()
  259. if let overrideString = overrideString {
  260. Text(overrideString)
  261. .font(.system(size: 12))
  262. .foregroundColor(.orange)
  263. .padding(.trailing, 8)
  264. }
  265. if let progress = state.bolusProgress {
  266. Text("Bolusing")
  267. .font(.system(size: 12, weight: .bold)).foregroundColor(.insulin)
  268. ProgressView(value: Double(progress))
  269. .progressViewStyle(BolusProgressViewStyle())
  270. .padding(.trailing, 8)
  271. .onTapGesture {
  272. state.cancelBolus()
  273. }
  274. }
  275. }
  276. .frame(maxWidth: .infinity, maxHeight: 30)
  277. }
  278. var legendPanel: some View {
  279. ZStack {
  280. HStack(alignment: .center) {
  281. Group {
  282. Circle().fill(Color.loopGreen).frame(width: 8, height: 8)
  283. Text("BG")
  284. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGreen)
  285. }
  286. Group {
  287. Circle().fill(Color.insulin).frame(width: 8, height: 8)
  288. .padding(.leading, 8)
  289. Text("IOB")
  290. .font(.system(size: 12, weight: .bold)).foregroundColor(.insulin)
  291. }
  292. Group {
  293. Circle().fill(Color.zt).frame(width: 8, height: 8)
  294. .padding(.leading, 8)
  295. Text("ZT")
  296. .font(.system(size: 12, weight: .bold)).foregroundColor(.zt)
  297. }
  298. Group {
  299. Circle().fill(Color.loopYellow).frame(width: 8, height: 8)
  300. .padding(.leading, 8)
  301. Text("COB")
  302. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopYellow)
  303. }
  304. Group {
  305. Circle().fill(Color.uam).frame(width: 8, height: 8)
  306. .padding(.leading, 8)
  307. Text("UAM")
  308. .font(.system(size: 12, weight: .bold)).foregroundColor(.uam)
  309. }
  310. if let eventualBG = state.eventualBG {
  311. Text(
  312. "⇢ " + numberFormatter.string(
  313. from: (state.units == .mmolL ? eventualBG.asMmolL : Decimal(eventualBG)) as NSNumber
  314. )!
  315. )
  316. .font(.system(size: 12, weight: .bold)).foregroundColor(.secondary)
  317. }
  318. }
  319. .frame(maxWidth: .infinity)
  320. .padding([.bottom], 20)
  321. }
  322. }
  323. var mainChart: some View {
  324. ZStack {
  325. if state.animatedBackground {
  326. SpriteView(scene: spriteScene, options: [.allowsTransparency])
  327. .ignoresSafeArea()
  328. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  329. }
  330. MainChartView(
  331. glucose: $state.glucose,
  332. suggestion: $state.suggestion,
  333. tempBasals: $state.tempBasals,
  334. boluses: $state.boluses,
  335. suspensions: $state.suspensions,
  336. hours: .constant(state.filteredHours),
  337. maxBasal: $state.maxBasal,
  338. autotunedBasalProfile: $state.autotunedBasalProfile,
  339. basalProfile: $state.basalProfile,
  340. tempTargets: $state.tempTargets,
  341. carbs: $state.carbs,
  342. timerDate: $state.timerDate,
  343. units: $state.units,
  344. smooth: $state.smooth,
  345. highGlucose: $state.highGlucose,
  346. lowGlucose: $state.lowGlucose,
  347. screenHours: $state.screenHours,
  348. displayXgridLines: $state.displayXgridLines,
  349. displayYgridLines: $state.displayYgridLines,
  350. thresholdLines: $state.thresholdLines
  351. )
  352. }
  353. .padding(.bottom)
  354. .modal(for: .dataTable, from: self)
  355. }
  356. @ViewBuilder private func bottomPanel(_ geo: GeometryProxy) -> some View {
  357. ZStack {
  358. Rectangle().fill(Color.gray.opacity(0.2)).frame(height: 50 + geo.safeAreaInsets.bottom)
  359. HStack {
  360. Button { state.showModal(for: .addCarbs) }
  361. label: {
  362. ZStack(alignment: Alignment(horizontal: .trailing, vertical: .bottom)) {
  363. Image("carbs")
  364. .renderingMode(.template)
  365. .resizable()
  366. .frame(width: 24, height: 24)
  367. .foregroundColor(.loopYellow)
  368. .padding(8)
  369. if let carbsReq = state.carbsRequired {
  370. Text(numberFormatter.string(from: carbsReq as NSNumber)!)
  371. .font(.caption)
  372. .foregroundColor(.white)
  373. .padding(4)
  374. .background(Capsule().fill(Color.red))
  375. }
  376. }
  377. }
  378. Spacer()
  379. Button { state.showModal(for: .addTempTarget) }
  380. label: {
  381. Image("target")
  382. .renderingMode(.template)
  383. .resizable()
  384. .frame(width: 24, height: 24)
  385. .padding(8)
  386. }.foregroundColor(.loopGreen)
  387. Spacer()
  388. Button { state.showModal(for: .bolus(waitForSuggestion: false)) }
  389. label: {
  390. Image("bolus")
  391. .renderingMode(.template)
  392. .resizable()
  393. .frame(width: 24, height: 24)
  394. .padding(8)
  395. }.foregroundColor(.insulin)
  396. Spacer()
  397. if state.allowManualTemp {
  398. Button { state.showModal(for: .manualTempBasal) }
  399. label: {
  400. Image("bolus1")
  401. .renderingMode(.template)
  402. .resizable()
  403. .frame(width: 24, height: 24)
  404. .padding(8)
  405. }.foregroundColor(.insulin)
  406. Spacer()
  407. }
  408. Button { state.showModal(for: .statistics)
  409. }
  410. label: {
  411. Image(systemName: "chart.xyaxis.line")
  412. .renderingMode(.template)
  413. .resizable()
  414. .frame(width: 24, height: 24)
  415. .padding(8)
  416. }.foregroundColor(.purple)
  417. Spacer()
  418. Button { state.showModal(for: .settings) }
  419. label: {
  420. Image("settings1")
  421. .renderingMode(.template)
  422. .resizable()
  423. .frame(width: 24, height: 24)
  424. .padding(8)
  425. }.foregroundColor(.loopGray)
  426. }
  427. .padding(.horizontal, 24)
  428. .padding(.bottom, geo.safeAreaInsets.bottom)
  429. }
  430. }
  431. var body: some View {
  432. GeometryReader { geo in
  433. VStack(spacing: 0) {
  434. header(geo)
  435. infoPanel
  436. mainChart
  437. legendPanel
  438. bottomPanel(geo)
  439. }
  440. .edgesIgnoringSafeArea(.vertical)
  441. }
  442. .onAppear(perform: configureView)
  443. .navigationTitle("Home")
  444. .navigationBarHidden(true)
  445. .ignoresSafeArea(.keyboard)
  446. .popup(isPresented: isStatusPopupPresented, alignment: .top, direction: .top) {
  447. popup
  448. .padding()
  449. .background(
  450. RoundedRectangle(cornerRadius: 8, style: .continuous)
  451. .fill(Color(UIColor.darkGray))
  452. )
  453. .onTapGesture {
  454. isStatusPopupPresented = false
  455. }
  456. .gesture(
  457. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  458. .onEnded { value in
  459. if value.translation.height < 0 {
  460. isStatusPopupPresented = false
  461. }
  462. }
  463. )
  464. }
  465. }
  466. private var popup: some View {
  467. VStack(alignment: .leading, spacing: 4) {
  468. Text(state.statusTitle).font(.headline).foregroundColor(.white)
  469. .padding(.bottom, 4)
  470. if let suggestion = state.suggestion {
  471. TagCloudView(tags: suggestion.reasonParts).animation(.none, value: false)
  472. Text(suggestion.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  473. } else {
  474. Text("No sugestion found").font(.body).foregroundColor(.white)
  475. }
  476. if let errorMessage = state.errorMessage, let date = state.errorDate {
  477. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  478. .foregroundColor(.white)
  479. .font(.headline)
  480. .padding(.bottom, 4)
  481. .padding(.top, 8)
  482. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  483. }
  484. }
  485. }
  486. }
  487. }