ForecastChart.swift 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. .forecastDisplayType == .lines ? 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. forecastChartLabels
  33. .padding(.bottom, 8)
  34. forecastChart
  35. }
  36. }
  37. private var forecastChartLabels: some View {
  38. HStack {
  39. HStack {
  40. Image(systemName: "fork.knife")
  41. Text("\(state.carbs.description) g")
  42. }
  43. .font(.footnote)
  44. .foregroundStyle(.orange)
  45. .padding(8)
  46. .background {
  47. RoundedRectangle(cornerRadius: 10)
  48. .fill(Color.orange.opacity(0.2))
  49. }
  50. Spacer()
  51. HStack {
  52. Image(systemName: "syringe.fill")
  53. Text("\(state.amount.description) U")
  54. }
  55. .font(.footnote)
  56. .foregroundStyle(.blue)
  57. .padding(8)
  58. .background {
  59. RoundedRectangle(cornerRadius: 10)
  60. .fill(Color.blue.opacity(0.2))
  61. }
  62. Spacer()
  63. HStack {
  64. Image(systemName: "arrow.right.circle")
  65. if let simulatedDetermination = state.simulatedDetermination, let eventualBG = simulatedDetermination.eventualBG {
  66. HStack {
  67. Text(
  68. (units == .mgdL ? Decimal(eventualBG).description : eventualBG.formattedAsMmolL) + units.rawValue
  69. )
  70. }
  71. } else {
  72. Text("---")
  73. }
  74. }
  75. .font(.footnote)
  76. .foregroundStyle(.primary)
  77. .padding(8)
  78. .background {
  79. RoundedRectangle(cornerRadius: 10)
  80. .fill(Color.primary.opacity(0.2))
  81. }
  82. }
  83. }
  84. private var forecastChart: some View {
  85. Chart {
  86. drawGlucose()
  87. drawCurrentTimeMarker()
  88. if state.forecastDisplayType == .lines {
  89. drawForecastLines()
  90. } else {
  91. drawForecastsCone()
  92. }
  93. }
  94. .chartXAxis { forecastChartXAxis }
  95. .chartXScale(domain: startMarker ... endMarker)
  96. .chartYAxis { forecastChartYAxis }
  97. .chartYScale(domain: units == .mgdL ? 0 ... 300 : 0.asMmolL ... 300.asMmolL)
  98. .backport.chartForegroundStyleScale(state: state)
  99. }
  100. private func drawGlucose() -> some ChartContent {
  101. ForEach(state.glucoseFromPersistence) { item in
  102. let glucoseToDisplay = state.units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL
  103. // low and high glucose is parsed in state to mmol/L; parse it back to mg/dl here for comparison
  104. let lowGlucose = units == .mgdL ? state.lowGlucose : state.lowGlucose.asMgdL
  105. let highGlucose = units == .mgdL ? state.highGlucose : state.highGlucose.asMgdL
  106. let targetGlucose = (state.determination.first?.currentTarget ?? state.currentBGTarget as NSDecimalNumber) as Decimal
  107. // TODO: workaround for now: set low value to 55, to have dynamic color shades between 55 and user-set low (approx. 70); same for high glucose
  108. let hardCodedLow = Decimal(55)
  109. let hardCodedHigh = Decimal(220)
  110. let pointMarkColor: Color = FreeAPS.getDynamicGlucoseColor(
  111. glucoseValue: Decimal(item.glucose),
  112. highGlucoseColorValue: hardCodedHigh,
  113. lowGlucoseColorValue: hardCodedLow,
  114. targetGlucose: targetGlucose,
  115. glucoseColorScheme: state.glucoseColorScheme
  116. )
  117. if !state.isSmoothingEnabled {
  118. PointMark(
  119. x: .value("Time", item.date ?? Date(), unit: .second),
  120. y: .value("Value", glucoseToDisplay)
  121. )
  122. .foregroundStyle(pointMarkColor)
  123. .symbolSize(18)
  124. } else {
  125. PointMark(
  126. x: .value("Time", item.date ?? Date(), unit: .second),
  127. y: .value("Value", glucoseToDisplay)
  128. )
  129. .symbol {
  130. Image(systemName: "record.circle.fill")
  131. .font(.system(size: 6))
  132. .bold()
  133. .foregroundStyle(pointMarkColor)
  134. }
  135. }
  136. }
  137. }
  138. private func timeForIndex(_ index: Int32) -> Date {
  139. let currentTime = Date()
  140. let timeInterval = TimeInterval(index * 300)
  141. return currentTime.addingTimeInterval(timeInterval)
  142. }
  143. private func drawForecastsCone() -> some ChartContent {
  144. // Draw AreaMark for the forecast bounds
  145. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  146. if index < state.minForecast.count, index < state.maxForecast.count {
  147. let yMinMaxDelta = Decimal(state.minForecast[index] - state.maxForecast[index])
  148. let xValue = timeForIndex(Int32(index))
  149. // if distance between respective min and max is 0, provide a default range
  150. if yMinMaxDelta == 0 {
  151. let yMinValue = units == .mgdL ? Decimal(state.minForecast[index] - 1) :
  152. Decimal(state.minForecast[index] - 1)
  153. .asMmolL
  154. let yMaxValue = units == .mgdL ? Decimal(state.minForecast[index] + 1) :
  155. Decimal(state.minForecast[index] + 1)
  156. .asMmolL
  157. AreaMark(
  158. x: .value("Time", xValue <= endMarker ? xValue : endMarker),
  159. yStart: .value("Min Value", units == .mgdL ? yMinValue : yMinValue.asMmolL),
  160. yEnd: .value("Max Value", units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  161. )
  162. .foregroundStyle(Color.blue.opacity(0.5))
  163. .interpolationMethod(.catmullRom)
  164. } else {
  165. let yMinValue = Decimal(state.minForecast[index]) <= 300 ? Decimal(state.minForecast[index]) : Decimal(300)
  166. let yMaxValue = Decimal(state.maxForecast[index]) <= 300 ? Decimal(state.maxForecast[index]) : Decimal(300)
  167. AreaMark(
  168. x: .value("Time", timeForIndex(Int32(index)) <= endMarker ? timeForIndex(Int32(index)) : endMarker),
  169. yStart: .value("Min Value", units == .mgdL ? yMinValue : yMinValue.asMmolL),
  170. yEnd: .value("Max Value", units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  171. )
  172. .foregroundStyle(Color.blue.opacity(0.5))
  173. .interpolationMethod(.catmullRom)
  174. }
  175. }
  176. }
  177. }
  178. private func drawForecastLines() -> some ChartContent {
  179. let predictions = state.predictionsForChart
  180. // Prepare the prediction data with only the first 36 values, i.e. 3 hours in the future
  181. let predictionData = [
  182. ("iob", predictions?.iob?.prefix(36)),
  183. ("zt", predictions?.zt?.prefix(36)),
  184. ("cob", predictions?.cob?.prefix(36)),
  185. ("uam", predictions?.uam?.prefix(36))
  186. ]
  187. return ForEach(predictionData, id: \.0) { name, values in
  188. if let values = values {
  189. ForEach(values.indices, id: \.self) { index in
  190. LineMark(
  191. x: .value("Time", timeForIndex(Int32(index))),
  192. y: .value("Value", units == .mgdL ? Decimal(values[index]) : Decimal(values[index]).asMmolL)
  193. )
  194. .foregroundStyle(by: .value("Prediction Type", name))
  195. }
  196. }
  197. }
  198. }
  199. private func drawCurrentTimeMarker() -> some ChartContent {
  200. RuleMark(
  201. x: .value(
  202. "",
  203. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  204. unit: .second
  205. )
  206. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  207. }
  208. private var forecastChartXAxis: some AxisContent {
  209. AxisMarks(values: .stride(by: .hour, count: 2)) { _ in
  210. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  211. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  212. .font(.caption2)
  213. .foregroundStyle(Color.secondary)
  214. }
  215. }
  216. private var forecastChartYAxis: some AxisContent {
  217. AxisMarks(position: .trailing) { _ in
  218. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  219. AxisTick(length: 3, stroke: .init(lineWidth: 3)).foregroundStyle(Color.secondary)
  220. AxisValueLabel().font(.caption2).foregroundStyle(Color.secondary)
  221. }
  222. }
  223. }