HomeRootView.swift 19 KB

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