ForeCastChart.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import Charts
  2. import CoreData
  3. import Foundation
  4. import SwiftUI
  5. struct ForeCastChart: View {
  6. @StateObject var state: Bolus.StateModel
  7. @Environment(\.colorScheme) var colorScheme
  8. @Binding var units: GlucoseUnits
  9. @State private var startMarker = Date(timeIntervalSinceNow: -4 * 60 * 60)
  10. private var endMarker: Date {
  11. state
  12. .displayForecastsAsLines ? Date(timeIntervalSinceNow: TimeInterval(hours: 3)) :
  13. Date(timeIntervalSinceNow: TimeInterval(
  14. Int(1.5) * 5 * state
  15. .minCount * 60
  16. )) // min is 1.5h -> (1.5*1h = 1.5*(5*12*60))
  17. }
  18. var body: some View {
  19. VStack {
  20. forecastChart
  21. .padding(.vertical, 3)
  22. HStack {
  23. Spacer()
  24. Image(systemName: "arrow.right.circle")
  25. .font(.system(size: 16, weight: .bold))
  26. if let eventualBG = state.simulatedDetermination?.eventualBG {
  27. HStack {
  28. Text("\(eventualBG)")
  29. .font(.footnote)
  30. .foregroundStyle(.primary)
  31. Text("\(units.rawValue)")
  32. .font(.footnote)
  33. .foregroundStyle(.secondary)
  34. }
  35. } else {
  36. Text("---")
  37. .font(.footnote)
  38. .foregroundStyle(.primary)
  39. Text("\(units.rawValue)")
  40. .font(.footnote)
  41. .foregroundStyle(.secondary)
  42. }
  43. }
  44. }
  45. }
  46. private var forecastChart: some View {
  47. Chart {
  48. drawGlucose()
  49. drawCurrentTimeMarker()
  50. if state.displayForecastsAsLines {
  51. drawForecastLines()
  52. } else {
  53. drawForecastCone()
  54. }
  55. }
  56. .chartXAxis { forecastChartXAxis }
  57. .chartXScale(domain: startMarker ... endMarker)
  58. .chartYAxis { forecastChartYAxis }
  59. .chartYScale(domain: units == .mgdL ? 0 ... 300 : 0.asMmolL ... 300.asMmolL)
  60. .backport.chartForegroundStyleScale(state: state)
  61. }
  62. private func drawGlucose() -> some ChartContent {
  63. ForEach(state.glucoseFromPersistence) { item in
  64. if item.glucose > Int(state.highGlucose) {
  65. PointMark(
  66. x: .value("Time", item.date ?? Date(), unit: .second),
  67. y: .value("Value", units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL)
  68. )
  69. .foregroundStyle(Color.orange.gradient)
  70. .symbolSize(20)
  71. } else if item.glucose < Int(state.lowGlucose) {
  72. PointMark(
  73. x: .value("Time", item.date ?? Date(), unit: .second),
  74. y: .value("Value", units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL)
  75. )
  76. .foregroundStyle(Color.red.gradient)
  77. .symbolSize(20)
  78. } else {
  79. PointMark(
  80. x: .value("Time", item.date ?? Date(), unit: .second),
  81. y: .value("Value", units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL)
  82. )
  83. .foregroundStyle(Color.green.gradient)
  84. .symbolSize(20)
  85. }
  86. }
  87. }
  88. private func timeForIndex(_ index: Int32) -> Date {
  89. let currentTime = Date()
  90. let timeInterval = TimeInterval(index * 300)
  91. return currentTime.addingTimeInterval(timeInterval)
  92. }
  93. private func drawForecastCone() -> some ChartContent {
  94. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  95. if index < state.minForecast.count, index < state.maxForecast.count {
  96. let yMinValue = Decimal(state.minForecast[index]) <= 300 ? Decimal(state.minForecast[index]) : Decimal(300)
  97. let yMaxValue = Decimal(state.maxForecast[index]) <= 300 ? Decimal(state.maxForecast[index]) : Decimal(300)
  98. AreaMark(
  99. x: .value("Time", timeForIndex(Int32(index)) <= endMarker ? timeForIndex(Int32(index)) : endMarker),
  100. yStart: .value("Min Value", units == .mgdL ? yMinValue : yMinValue.asMmolL),
  101. yEnd: .value("Max Value", units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  102. )
  103. .foregroundStyle(Color.blue.opacity(0.5))
  104. .interpolationMethod(.catmullRom)
  105. }
  106. }
  107. }
  108. private func drawForecastLines() -> some ChartContent {
  109. let predictions = state.predictionsForChart
  110. // Prepare the prediction data with only the first 36 values, i.e. 3 hours in the future
  111. let predictionData = [
  112. ("iob", predictions?.iob?.prefix(36)),
  113. ("zt", predictions?.zt?.prefix(36)),
  114. ("cob", predictions?.cob?.prefix(36)),
  115. ("uam", predictions?.uam?.prefix(36))
  116. ]
  117. return ForEach(predictionData, id: \.0) { name, values in
  118. if let values = values {
  119. ForEach(values.indices, id: \.self) { index in
  120. LineMark(
  121. x: .value("Time", timeForIndex(Int32(index))),
  122. y: .value("Value", units == .mgdL ? Decimal(values[index]) : Decimal(values[index]).asMmolL)
  123. )
  124. .foregroundStyle(by: .value("Prediction Type", name))
  125. }
  126. }
  127. }
  128. }
  129. private func drawCurrentTimeMarker() -> some ChartContent {
  130. RuleMark(
  131. x: .value(
  132. "",
  133. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  134. unit: .second
  135. )
  136. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  137. }
  138. private var forecastChartXAxis: some AxisContent {
  139. AxisMarks(values: .stride(by: .hour, count: 2)) { _ in
  140. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  141. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  142. .font(.footnote)
  143. .foregroundStyle(Color.primary)
  144. }
  145. }
  146. private var forecastChartYAxis: some AxisContent {
  147. AxisMarks(position: .trailing) { _ in
  148. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  149. AxisTick(length: 3, stroke: .init(lineWidth: 3)).foregroundStyle(Color.secondary)
  150. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  151. }
  152. }
  153. }