HomeRootView.swift 21 KB

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