ForecastChart.swift 16 KB

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