HomeRootView.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 == "" { comma2 = "" }
  221. if percentString == "" { comma1 = "" }
  222. if indefinite, smbToggleString == "" { comma2 = "" }
  223. if percentString == "", targetString == "" {
  224. comma1 = ""
  225. comma2 = ""
  226. }
  227. if percentString == "", targetString == "", smbToggleString == "" {
  228. durationString = ""
  229. comma3 = ""
  230. }
  231. if durationString == "" {
  232. comma3 = ""
  233. }
  234. if smbToggleString == "" {
  235. comma3 = ""
  236. }
  237. return percentString + comma1 + targetString + comma2 + durationString + comma3 + smbToggleString
  238. }
  239. var infoPanel: some View {
  240. HStack(alignment: .center) {
  241. if state.pumpSuspended {
  242. Text("Pump suspended")
  243. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGray)
  244. .padding(.leading, 8)
  245. } else if let tempBasalString = tempBasalString {
  246. Text(tempBasalString)
  247. .font(.system(size: 12, weight: .bold))
  248. .foregroundColor(.insulin)
  249. .padding(.leading, 8)
  250. }
  251. if let tempTargetString = tempTargetString {
  252. Text(tempTargetString)
  253. .font(.caption)
  254. .foregroundColor(.secondary)
  255. }
  256. Spacer()
  257. if let overrideString = overrideString {
  258. Text(overrideString)
  259. .font(.system(size: 12))
  260. .foregroundColor(.orange)
  261. .padding(.trailing, 8)
  262. }
  263. if let progress = state.bolusProgress {
  264. Text("Bolusing")
  265. .font(.system(size: 12, weight: .bold)).foregroundColor(.insulin)
  266. ProgressView(value: Double(progress))
  267. .progressViewStyle(BolusProgressViewStyle())
  268. .padding(.trailing, 8)
  269. .onTapGesture {
  270. state.cancelBolus()
  271. }
  272. }
  273. }
  274. .frame(maxWidth: .infinity, maxHeight: 30)
  275. }
  276. var legendPanel: some View {
  277. ZStack {
  278. HStack(alignment: .center) {
  279. Group {
  280. Circle().fill(Color.loopGreen).frame(width: 8, height: 8)
  281. Text("BG")
  282. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGreen)
  283. }
  284. Group {
  285. Circle().fill(Color.insulin).frame(width: 8, height: 8)
  286. .padding(.leading, 8)
  287. Text("IOB")
  288. .font(.system(size: 12, weight: .bold)).foregroundColor(.insulin)
  289. }
  290. Group {
  291. Circle().fill(Color.zt).frame(width: 8, height: 8)
  292. .padding(.leading, 8)
  293. Text("ZT")
  294. .font(.system(size: 12, weight: .bold)).foregroundColor(.zt)
  295. }
  296. Group {
  297. Circle().fill(Color.loopYellow).frame(width: 8, height: 8)
  298. .padding(.leading, 8)
  299. Text("COB")
  300. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopYellow)
  301. }
  302. Group {
  303. Circle().fill(Color.uam).frame(width: 8, height: 8)
  304. .padding(.leading, 8)
  305. Text("UAM")
  306. .font(.system(size: 12, weight: .bold)).foregroundColor(.uam)
  307. }
  308. if let eventualBG = state.eventualBG {
  309. Text(
  310. "⇢ " + numberFormatter.string(
  311. from: (state.units == .mmolL ? eventualBG.asMmolL : Decimal(eventualBG)) as NSNumber
  312. )!
  313. )
  314. .font(.system(size: 12, weight: .bold)).foregroundColor(.secondary)
  315. }
  316. }
  317. .frame(maxWidth: .infinity)
  318. .padding([.bottom], 20)
  319. }
  320. }
  321. var mainChart: some View {
  322. ZStack {
  323. if state.animatedBackground {
  324. SpriteView(scene: spriteScene, options: [.allowsTransparency])
  325. .ignoresSafeArea()
  326. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  327. }
  328. MainChartView(
  329. glucose: $state.glucose,
  330. suggestion: $state.suggestion,
  331. tempBasals: $state.tempBasals,
  332. boluses: $state.boluses,
  333. suspensions: $state.suspensions,
  334. hours: .constant(state.filteredHours),
  335. maxBasal: $state.maxBasal,
  336. autotunedBasalProfile: $state.autotunedBasalProfile,
  337. basalProfile: $state.basalProfile,
  338. tempTargets: $state.tempTargets,
  339. carbs: $state.carbs,
  340. timerDate: $state.timerDate,
  341. units: $state.units,
  342. smooth: $state.smooth,
  343. highGlucose: $state.highGlucose,
  344. lowGlucose: $state.lowGlucose,
  345. screenHours: $state.screenHours,
  346. displayXgridLines: $state.displayXgridLines,
  347. displayYgridLines: $state.displayYgridLines,
  348. thresholdLines: $state.thresholdLines
  349. )
  350. }
  351. .padding(.bottom)
  352. .modal(for: .dataTable, from: self)
  353. }
  354. @ViewBuilder private func bottomPanel(_ geo: GeometryProxy) -> some View {
  355. ZStack {
  356. Rectangle().fill(Color.gray.opacity(0.2)).frame(height: 50 + geo.safeAreaInsets.bottom)
  357. HStack {
  358. Button { state.showModal(for: .addCarbs) }
  359. label: {
  360. ZStack(alignment: Alignment(horizontal: .trailing, vertical: .bottom)) {
  361. Image("carbs")
  362. .renderingMode(.template)
  363. .resizable()
  364. .frame(width: 24, height: 24)
  365. .foregroundColor(.loopYellow)
  366. .padding(8)
  367. if let carbsReq = state.carbsRequired {
  368. Text(numberFormatter.string(from: carbsReq as NSNumber)!)
  369. .font(.caption)
  370. .foregroundColor(.white)
  371. .padding(4)
  372. .background(Capsule().fill(Color.red))
  373. }
  374. }
  375. }
  376. Spacer()
  377. Button { state.showModal(for: .addTempTarget) }
  378. label: {
  379. Image("target")
  380. .renderingMode(.template)
  381. .resizable()
  382. .frame(width: 24, height: 24)
  383. .padding(8)
  384. }.foregroundColor(.loopGreen)
  385. Spacer()
  386. Button { state.showModal(for: .bolus(waitForSuggestion: false)) }
  387. label: {
  388. Image("bolus")
  389. .renderingMode(.template)
  390. .resizable()
  391. .frame(width: 24, height: 24)
  392. .padding(8)
  393. }.foregroundColor(.insulin)
  394. Spacer()
  395. if state.allowManualTemp {
  396. Button { state.showModal(for: .manualTempBasal) }
  397. label: {
  398. Image("bolus1")
  399. .renderingMode(.template)
  400. .resizable()
  401. .frame(width: 24, height: 24)
  402. .padding(8)
  403. }.foregroundColor(.insulin)
  404. Spacer()
  405. }
  406. Button { state.showModal(for: .statistics)
  407. }
  408. label: {
  409. Image(systemName: "chart.xyaxis.line")
  410. .renderingMode(.template)
  411. .resizable()
  412. .frame(width: 24, height: 24)
  413. .padding(8)
  414. }.foregroundColor(.purple)
  415. Spacer()
  416. Button { state.showModal(for: .settings) }
  417. label: {
  418. Image("settings1")
  419. .renderingMode(.template)
  420. .resizable()
  421. .frame(width: 24, height: 24)
  422. .padding(8)
  423. }.foregroundColor(.loopGray)
  424. }
  425. .padding(.horizontal, 24)
  426. .padding(.bottom, geo.safeAreaInsets.bottom)
  427. }
  428. }
  429. var body: some View {
  430. GeometryReader { geo in
  431. VStack(spacing: 0) {
  432. header(geo)
  433. infoPanel
  434. mainChart
  435. legendPanel
  436. bottomPanel(geo)
  437. }
  438. .edgesIgnoringSafeArea(.vertical)
  439. }
  440. .onAppear(perform: configureView)
  441. .navigationTitle("Home")
  442. .navigationBarHidden(true)
  443. .ignoresSafeArea(.keyboard)
  444. .popup(isPresented: isStatusPopupPresented, alignment: .top, direction: .top) {
  445. popup
  446. .padding()
  447. .background(
  448. RoundedRectangle(cornerRadius: 8, style: .continuous)
  449. .fill(Color(UIColor.darkGray))
  450. )
  451. .onTapGesture {
  452. isStatusPopupPresented = false
  453. }
  454. .gesture(
  455. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  456. .onEnded { value in
  457. if value.translation.height < 0 {
  458. isStatusPopupPresented = false
  459. }
  460. }
  461. )
  462. }
  463. }
  464. private var popup: some View {
  465. VStack(alignment: .leading, spacing: 4) {
  466. Text(state.statusTitle).font(.headline).foregroundColor(.white)
  467. .padding(.bottom, 4)
  468. if let suggestion = state.suggestion {
  469. TagCloudView(tags: suggestion.reasonParts).animation(.none, value: false)
  470. Text(suggestion.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  471. } else {
  472. Text("No sugestion found").font(.body).foregroundColor(.white)
  473. }
  474. if let errorMessage = state.errorMessage, let date = state.errorDate {
  475. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  476. .foregroundColor(.white)
  477. .font(.headline)
  478. .padding(.bottom, 4)
  479. .padding(.top, 8)
  480. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  481. }
  482. }
  483. }
  484. }
  485. }