ForecastChart.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. @State var selection: Date? = nil
  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 state.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. private var selectedGlucose: GlucoseStored? {
  31. guard let selection = selection else { return nil }
  32. let range = selection.addingTimeInterval(-150) ... selection.addingTimeInterval(150)
  33. return state.glucoseFromPersistence.first { $0.date.map(range.contains) ?? false }
  34. }
  35. var body: some View {
  36. VStack {
  37. forecastChartLabels
  38. .padding(.bottom, 8)
  39. forecastChart
  40. }
  41. }
  42. private var forecastChartLabels: some View {
  43. HStack {
  44. HStack {
  45. Image(systemName: "fork.knife")
  46. Text("\(state.carbs.description) g")
  47. }
  48. .font(.footnote)
  49. .foregroundStyle(.orange)
  50. .padding(8)
  51. .background {
  52. RoundedRectangle(cornerRadius: 10)
  53. .fill(Color.orange.opacity(0.2))
  54. }
  55. Spacer()
  56. HStack {
  57. Image(systemName: "syringe.fill")
  58. Text("\(state.amount.description) U")
  59. }
  60. .font(.footnote)
  61. .foregroundStyle(.blue)
  62. .padding(8)
  63. .background {
  64. RoundedRectangle(cornerRadius: 10)
  65. .fill(Color.blue.opacity(0.2))
  66. }
  67. Spacer()
  68. HStack {
  69. Image(systemName: "arrow.right.circle")
  70. if let simulatedDetermination = state.simulatedDetermination, let eventualBG = simulatedDetermination.eventualBG {
  71. HStack {
  72. Text(
  73. state.units == .mgdL ? Decimal(eventualBG).description : eventualBG.formattedAsMmolL
  74. )
  75. .font(.footnote)
  76. .foregroundStyle(.primary)
  77. Text("\(state.units.rawValue)")
  78. .font(.footnote)
  79. .foregroundStyle(.secondary)
  80. }
  81. } else {
  82. Text("---")
  83. .font(.footnote)
  84. .foregroundStyle(.primary)
  85. Text("\(state.units.rawValue)")
  86. .font(.footnote)
  87. .foregroundStyle(.secondary)
  88. }
  89. }
  90. .font(.footnote)
  91. .foregroundStyle(.primary)
  92. .padding(8)
  93. .background {
  94. RoundedRectangle(cornerRadius: 10)
  95. .fill(Color.primary.opacity(0.2))
  96. }
  97. }
  98. }
  99. private var forecastChart: some View {
  100. Chart {
  101. drawGlucose()
  102. drawCurrentTimeMarker()
  103. if state.forecastDisplayType == .lines {
  104. drawForecastLines()
  105. } else {
  106. drawForecastsCone()
  107. }
  108. if let selectedGlucose {
  109. RuleMark(x: .value("Selection", selectedGlucose.date ?? Date.now, unit: .minute))
  110. .foregroundStyle(Color.tabBar)
  111. .lineStyle(.init(lineWidth: 2))
  112. .annotation(
  113. position: .top,
  114. overflowResolution: .init(x: .fit(to: .chart), y: .disabled)
  115. ) {
  116. selectionPopover
  117. }
  118. PointMark(
  119. x: .value("Time", selectedGlucose.date ?? Date.now, unit: .minute),
  120. y: .value("Value", selectedGlucose.glucose)
  121. )
  122. .zIndex(-1)
  123. .symbolSize(CGSize(width: 15, height: 15))
  124. .foregroundStyle(
  125. Decimal(selectedGlucose.glucose) > state.highGlucose ? Color.orange
  126. .opacity(0.8) :
  127. (
  128. Decimal(selectedGlucose.glucose) < state.lowGlucose ? Color.red.opacity(0.8) : Color.green
  129. .opacity(0.8)
  130. )
  131. )
  132. PointMark(
  133. x: .value("Time", selectedGlucose.date ?? Date.now, unit: .minute),
  134. y: .value("Value", selectedGlucose.glucose)
  135. )
  136. .zIndex(-1)
  137. .symbolSize(CGSize(width: 6, height: 6))
  138. .foregroundStyle(Color.primary)
  139. }
  140. }
  141. .chartXSelection(value: $selection)
  142. .chartXAxis { forecastChartXAxis }
  143. .chartXScale(domain: startMarker ... endMarker)
  144. .chartYAxis { forecastChartYAxis }
  145. .chartYScale(domain: state.units == .mgdL ? 0 ... 300 : 0.asMmolL ... 300.asMmolL)
  146. .backport.chartForegroundStyleScale(state: state)
  147. }
  148. @ViewBuilder var selectionPopover: some View {
  149. if let sgv = selectedGlucose?.glucose {
  150. VStack(alignment: .leading) {
  151. HStack {
  152. Image(systemName: "clock")
  153. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  154. .font(.footnote).bold()
  155. }.font(.footnote).padding(.bottom, 5)
  156. // 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
  157. let hardCodedLow = Decimal(55)
  158. let hardCodedHigh = Decimal(220)
  159. let isDynamicColorScheme = state.glucoseColorScheme == .dynamicColor
  160. let glucoseColor = FreeAPS.getDynamicGlucoseColor(
  161. glucoseValue: Decimal(sgv),
  162. highGlucoseColorValue: isDynamicColorScheme ? hardCodedHigh : state.highGlucose,
  163. lowGlucoseColorValue: isDynamicColorScheme ? hardCodedLow : state.lowGlucose,
  164. targetGlucose: state.currentBGTarget,
  165. glucoseColorScheme: state.glucoseColorScheme
  166. )
  167. HStack {
  168. Text(state.units == .mgdL ? Decimal(sgv).description : Decimal(sgv).formattedAsMmolL)
  169. .bold()
  170. + Text(" \(state.units.rawValue)")
  171. }.foregroundStyle(
  172. Color(glucoseColor)
  173. ).font(.footnote)
  174. }
  175. .padding(7)
  176. .background {
  177. RoundedRectangle(cornerRadius: 4)
  178. .fill(Color.chart.opacity(0.85))
  179. .shadow(color: Color.secondary, radius: 2)
  180. .overlay(
  181. RoundedRectangle(cornerRadius: 4)
  182. .stroke(Color.secondary, lineWidth: 2)
  183. )
  184. }
  185. }
  186. }
  187. private func drawGlucose() -> some ChartContent {
  188. ForEach(state.glucoseFromPersistence) { item in
  189. let glucoseToDisplay = state.units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL
  190. let targetGlucose = (state.determination.first?.currentTarget ?? state.currentBGTarget as NSDecimalNumber) as Decimal
  191. // 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
  192. let hardCodedLow = Decimal(55)
  193. let hardCodedHigh = Decimal(220)
  194. let isDynamicColorScheme = state.glucoseColorScheme == .dynamicColor
  195. let pointMarkColor: Color = FreeAPS.getDynamicGlucoseColor(
  196. glucoseValue: Decimal(item.glucose),
  197. highGlucoseColorValue: isDynamicColorScheme ? hardCodedHigh : state.highGlucose,
  198. lowGlucoseColorValue: isDynamicColorScheme ? hardCodedLow : state.lowGlucose,
  199. targetGlucose: targetGlucose,
  200. glucoseColorScheme: state.glucoseColorScheme
  201. )
  202. if !state.isSmoothingEnabled {
  203. PointMark(
  204. x: .value("Time", item.date ?? Date(), unit: .second),
  205. y: .value("Value", glucoseToDisplay)
  206. )
  207. .foregroundStyle(pointMarkColor)
  208. .symbolSize(18)
  209. } else {
  210. PointMark(
  211. x: .value("Time", item.date ?? Date(), unit: .second),
  212. y: .value("Value", glucoseToDisplay)
  213. )
  214. .symbol {
  215. Image(systemName: "record.circle.fill")
  216. .font(.system(size: 6))
  217. .bold()
  218. .foregroundStyle(pointMarkColor)
  219. }
  220. }
  221. }
  222. }
  223. private func timeForIndex(_ index: Int32) -> Date {
  224. let currentTime = Date()
  225. let timeInterval = TimeInterval(index * 300)
  226. return currentTime.addingTimeInterval(timeInterval)
  227. }
  228. private func drawForecastsCone() -> some ChartContent {
  229. // Draw AreaMark for the forecast bounds
  230. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  231. if index < state.minForecast.count, index < state.maxForecast.count {
  232. let yMinMaxDelta = Decimal(state.minForecast[index] - state.maxForecast[index])
  233. let xValue = timeForIndex(Int32(index))
  234. // if distance between respective min and max is 0, provide a default range
  235. if yMinMaxDelta == 0 {
  236. let yMinValue = state.units == .mgdL ? Decimal(state.minForecast[index] - 1) :
  237. Decimal(state.minForecast[index] - 1)
  238. .asMmolL
  239. let yMaxValue = state.units == .mgdL ? Decimal(state.minForecast[index] + 1) :
  240. Decimal(state.minForecast[index] + 1)
  241. .asMmolL
  242. AreaMark(
  243. x: .value("Time", xValue <= endMarker ? xValue : endMarker),
  244. yStart: .value("Min Value", state.units == .mgdL ? yMinValue : yMinValue.asMmolL),
  245. yEnd: .value("Max Value", state.units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  246. )
  247. .foregroundStyle(Color.blue.opacity(0.5))
  248. .interpolationMethod(.catmullRom)
  249. } else {
  250. let yMinValue = Decimal(state.minForecast[index]) <= 300 ? Decimal(state.minForecast[index]) : Decimal(300)
  251. let yMaxValue = Decimal(state.maxForecast[index]) <= 300 ? Decimal(state.maxForecast[index]) : Decimal(300)
  252. AreaMark(
  253. x: .value("Time", timeForIndex(Int32(index)) <= endMarker ? timeForIndex(Int32(index)) : endMarker),
  254. yStart: .value("Min Value", state.units == .mgdL ? yMinValue : yMinValue.asMmolL),
  255. yEnd: .value("Max Value", state.units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  256. )
  257. .foregroundStyle(Color.blue.opacity(0.5))
  258. .interpolationMethod(.catmullRom)
  259. }
  260. }
  261. }
  262. }
  263. private func drawForecastLines() -> some ChartContent {
  264. let predictions = state.predictionsForChart
  265. // Prepare the prediction data with only the first 36 values, i.e. 3 hours in the future
  266. let predictionData = [
  267. ("iob", predictions?.iob?.prefix(36)),
  268. ("zt", predictions?.zt?.prefix(36)),
  269. ("cob", predictions?.cob?.prefix(36)),
  270. ("uam", predictions?.uam?.prefix(36))
  271. ]
  272. return ForEach(predictionData, id: \.0) { name, values in
  273. if let values = values {
  274. ForEach(values.indices, id: \.self) { index in
  275. LineMark(
  276. x: .value("Time", timeForIndex(Int32(index))),
  277. y: .value("Value", state.units == .mgdL ? Decimal(values[index]) : Decimal(values[index]).asMmolL)
  278. )
  279. .foregroundStyle(by: .value("Prediction Type", name))
  280. }
  281. }
  282. }
  283. }
  284. private func drawCurrentTimeMarker() -> some ChartContent {
  285. RuleMark(
  286. x: .value(
  287. "",
  288. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  289. unit: .second
  290. )
  291. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  292. }
  293. private var forecastChartXAxis: some AxisContent {
  294. AxisMarks(values: .stride(by: .hour, count: 2)) { _ in
  295. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  296. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  297. .font(.caption2)
  298. .foregroundStyle(Color.secondary)
  299. }
  300. }
  301. private var forecastChartYAxis: some AxisContent {
  302. AxisMarks(position: .trailing) { _ in
  303. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  304. AxisTick(length: 3, stroke: .init(lineWidth: 3)).foregroundStyle(Color.secondary)
  305. AxisValueLabel().font(.caption2).foregroundStyle(Color.secondary)
  306. }
  307. }
  308. }