ForecastChart.swift 16 KB

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