ForecastChart.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import Charts
  2. import CoreData
  3. import Foundation
  4. import SwiftUI
  5. struct ForecastChart: View {
  6. var state: Treatments.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. .chartLegend {
  147. if state.forecastDisplayType == ForecastDisplayType.lines {
  148. HStack(spacing: 10) {
  149. HStack(spacing: 4) {
  150. Image(systemName: "circle.fill").foregroundStyle(Color.insulin)
  151. Text("IOB").foregroundStyle(Color.secondary)
  152. }
  153. HStack(spacing: 4) {
  154. Image(systemName: "circle.fill").foregroundStyle(Color.uam)
  155. Text("UAM").foregroundStyle(Color.secondary)
  156. }
  157. HStack(spacing: 4) {
  158. Image(systemName: "circle.fill").foregroundStyle(Color.zt)
  159. Text("ZT").foregroundStyle(Color.secondary)
  160. }
  161. HStack(spacing: 4) {
  162. Image(systemName: "circle.fill").foregroundStyle(Color.orange)
  163. Text("COB").foregroundStyle(Color.secondary)
  164. }
  165. }.font(.caption2)
  166. }
  167. }
  168. }
  169. @ViewBuilder var selectionPopover: some View {
  170. if let sgv = selectedGlucose?.glucose {
  171. VStack(alignment: .leading) {
  172. HStack {
  173. Image(systemName: "clock")
  174. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  175. .font(.footnote).bold()
  176. }.font(.footnote).padding(.bottom, 5)
  177. // 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
  178. let hardCodedLow = Decimal(55)
  179. let hardCodedHigh = Decimal(220)
  180. let isDynamicColorScheme = state.glucoseColorScheme == .dynamicColor
  181. let glucoseColor = FreeAPS.getDynamicGlucoseColor(
  182. glucoseValue: Decimal(sgv),
  183. highGlucoseColorValue: isDynamicColorScheme ? hardCodedHigh : state.highGlucose,
  184. lowGlucoseColorValue: isDynamicColorScheme ? hardCodedLow : state.lowGlucose,
  185. targetGlucose: state.currentBGTarget,
  186. glucoseColorScheme: state.glucoseColorScheme
  187. )
  188. HStack {
  189. Text(state.units == .mgdL ? Decimal(sgv).description : Decimal(sgv).formattedAsMmolL)
  190. .bold()
  191. + Text(" \(state.units.rawValue)")
  192. }.foregroundStyle(
  193. Color(glucoseColor)
  194. ).font(.footnote)
  195. }
  196. .padding(7)
  197. .background {
  198. RoundedRectangle(cornerRadius: 4)
  199. .fill(Color.chart.opacity(0.85))
  200. .shadow(color: Color.secondary, radius: 2)
  201. .overlay(
  202. RoundedRectangle(cornerRadius: 4)
  203. .stroke(Color.secondary, lineWidth: 2)
  204. )
  205. }
  206. }
  207. }
  208. private func drawGlucose() -> some ChartContent {
  209. ForEach(state.glucoseFromPersistence) { item in
  210. let glucoseToDisplay = state.units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL
  211. let targetGlucose = (state.determination.first?.currentTarget ?? state.currentBGTarget as NSDecimalNumber) as Decimal
  212. // 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
  213. let hardCodedLow = Decimal(55)
  214. let hardCodedHigh = Decimal(220)
  215. let isDynamicColorScheme = state.glucoseColorScheme == .dynamicColor
  216. let pointMarkColor: Color = FreeAPS.getDynamicGlucoseColor(
  217. glucoseValue: Decimal(item.glucose),
  218. highGlucoseColorValue: isDynamicColorScheme ? hardCodedHigh : state.highGlucose,
  219. lowGlucoseColorValue: isDynamicColorScheme ? hardCodedLow : state.lowGlucose,
  220. targetGlucose: targetGlucose,
  221. glucoseColorScheme: state.glucoseColorScheme
  222. )
  223. if !state.isSmoothingEnabled {
  224. PointMark(
  225. x: .value("Time", item.date ?? Date(), unit: .second),
  226. y: .value("Value", glucoseToDisplay)
  227. )
  228. .foregroundStyle(pointMarkColor)
  229. .symbolSize(18)
  230. } else {
  231. PointMark(
  232. x: .value("Time", item.date ?? Date(), unit: .second),
  233. y: .value("Value", glucoseToDisplay)
  234. )
  235. .symbol {
  236. Image(systemName: "record.circle.fill")
  237. .font(.system(size: 6))
  238. .bold()
  239. .foregroundStyle(pointMarkColor)
  240. }
  241. }
  242. }
  243. }
  244. private func timeForIndex(_ index: Int32) -> Date {
  245. let currentTime = Date()
  246. let timeInterval = TimeInterval(index * 300)
  247. return currentTime.addingTimeInterval(timeInterval)
  248. }
  249. private func drawForecastsCone() -> some ChartContent {
  250. // Draw AreaMark for the forecast bounds
  251. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  252. if index < state.minForecast.count, index < state.maxForecast.count {
  253. let yMinMaxDelta = Decimal(state.minForecast[index] - state.maxForecast[index])
  254. let xValue = timeForIndex(Int32(index))
  255. // if distance between respective min and max is 0, provide a default range
  256. if yMinMaxDelta == 0 {
  257. let yMinValue = state.units == .mgdL ? Decimal(state.minForecast[index] - 1) :
  258. Decimal(state.minForecast[index] - 1)
  259. .asMmolL
  260. let yMaxValue = state.units == .mgdL ? Decimal(state.minForecast[index] + 1) :
  261. Decimal(state.minForecast[index] + 1)
  262. .asMmolL
  263. AreaMark(
  264. x: .value("Time", xValue <= endMarker ? xValue : endMarker),
  265. yStart: .value("Min Value", state.units == .mgdL ? yMinValue : yMinValue.asMmolL),
  266. yEnd: .value("Max Value", state.units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  267. )
  268. .foregroundStyle(Color.blue.opacity(0.5))
  269. .interpolationMethod(.catmullRom)
  270. } else {
  271. let yMinValue = Decimal(state.minForecast[index]) <= 300 ? Decimal(state.minForecast[index]) : Decimal(300)
  272. let yMaxValue = Decimal(state.maxForecast[index]) <= 300 ? Decimal(state.maxForecast[index]) : Decimal(300)
  273. AreaMark(
  274. x: .value("Time", timeForIndex(Int32(index)) <= endMarker ? timeForIndex(Int32(index)) : endMarker),
  275. yStart: .value("Min Value", state.units == .mgdL ? yMinValue : yMinValue.asMmolL),
  276. yEnd: .value("Max Value", state.units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  277. )
  278. .foregroundStyle(Color.blue.opacity(0.5))
  279. .interpolationMethod(.catmullRom)
  280. }
  281. }
  282. }
  283. }
  284. private func drawForecastLines() -> some ChartContent {
  285. let predictions = state.predictionsForChart
  286. // Prepare the prediction data with only the first 36 values, i.e. 3 hours in the future
  287. let predictionData = [
  288. ("iob", predictions?.iob?.prefix(36)),
  289. ("zt", predictions?.zt?.prefix(36)),
  290. ("cob", predictions?.cob?.prefix(36)),
  291. ("uam", predictions?.uam?.prefix(36))
  292. ]
  293. return ForEach(predictionData, id: \.0) { name, values in
  294. if let values = values {
  295. ForEach(values.indices, id: \.self) { index in
  296. LineMark(
  297. x: .value("Time", timeForIndex(Int32(index))),
  298. y: .value("Value", state.units == .mgdL ? Decimal(values[index]) : Decimal(values[index]).asMmolL)
  299. )
  300. .foregroundStyle(by: .value("Prediction Type", name))
  301. }
  302. }
  303. }
  304. }
  305. private func drawCurrentTimeMarker() -> some ChartContent {
  306. RuleMark(
  307. x: .value(
  308. "",
  309. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  310. unit: .second
  311. )
  312. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  313. }
  314. private var forecastChartXAxis: some AxisContent {
  315. AxisMarks(values: .stride(by: .hour, count: 2)) { _ in
  316. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  317. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  318. .font(.caption2)
  319. .foregroundStyle(Color.secondary)
  320. }
  321. }
  322. private var forecastChartYAxis: some AxisContent {
  323. AxisMarks(position: .trailing) { _ in
  324. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  325. AxisTick(length: 3, stroke: .init(lineWidth: 3)).foregroundStyle(Color.secondary)
  326. AxisValueLabel().font(.caption2).foregroundStyle(Color.secondary)
  327. }
  328. }
  329. }