HomeRootView.swift 21 KB

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