ForecastChart.swift 10.0 KB

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