ForeCastChart.swift 7.2 KB

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