LiveActivityChartView.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. //
  2. // LiveActivityChartView.swift
  3. // Trio
  4. //
  5. // Created by Cengiz Deniz on 17.10.24.
  6. //
  7. import Charts
  8. import Foundation
  9. import SwiftUI
  10. import WidgetKit
  11. struct LiveActivityChartView: View {
  12. @Environment(\.colorScheme) var colorScheme
  13. @Environment(\.isWatchOS) var isWatchOS
  14. var context: ActivityViewContext<LiveActivityAttributes>
  15. var additionalState: LiveActivityAttributes.ContentAdditionalState
  16. var body: some View {
  17. let state = context.state
  18. let isMgdL: Bool = state.unit == "mg/dL"
  19. let maxThreshhold: Decimal = isWatchOS ? 220 : 300
  20. // Determine scale, accounting for both glucose history and prediction values
  21. let chartMin = additionalState.chart.min(by: { $0.value < $1.value })?.value ?? 39
  22. let chartMax = additionalState.chart.max(by: { $0.value < $1.value })?.value ?? maxThreshhold
  23. let forecastMin = additionalState.minForecast.min().map { Decimal($0) } ?? chartMin
  24. let forecastMax = additionalState.maxForecast.max().map { Decimal($0) } ?? chartMax
  25. let minValue = min(min(chartMin, forecastMin), 39)
  26. let maxValue = max(max(chartMax, forecastMax), maxThreshhold)
  27. let yAxisRuleMarkMin = isMgdL ? state.lowGlucose : state.lowGlucose
  28. .asMmolL
  29. let yAxisRuleMarkMax = isMgdL ? state.highGlucose : state.highGlucose
  30. .asMmolL
  31. let target = isMgdL ? state.target : state.target.asMmolL
  32. let isOverrideActive = additionalState.isOverrideActive == true
  33. let isTempTargetActive = additionalState.isTempTargetActive == true
  34. let hasForecast = !additionalState.minForecast.isEmpty || !additionalState.forecastLines.isEmpty
  35. let calendar = Calendar.current
  36. let now = Date()
  37. let startDate = calendar.date(byAdding: .hour, value: isWatchOS ? -3 : -6, to: now) ?? now
  38. let endDate: Date = {
  39. let baseEnd = calendar.date(byAdding: .minute, value: isWatchOS ? 5 : 0, to: now) ?? now
  40. guard hasForecast, let anchorDate = state.date else { return baseEnd }
  41. let predictionEnd = anchorDate.addingTimeInterval(TimeInterval(150 * 60)) // 2.5h from determination
  42. return max(baseEnd, predictionEnd)
  43. }()
  44. // 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
  45. let hardCodedLow = isMgdL ? Decimal(55) : 55.asMmolL
  46. let hardCodedHigh = isMgdL ? Decimal(220) : 220.asMmolL
  47. let hasStaticColorScheme = context.state.glucoseColorScheme == "staticColor"
  48. let highColor = Color.getDynamicGlucoseColor(
  49. glucoseValue: yAxisRuleMarkMax,
  50. highGlucoseColorValue: !hasStaticColorScheme ? hardCodedHigh : yAxisRuleMarkMax,
  51. lowGlucoseColorValue: !hasStaticColorScheme ? hardCodedLow : yAxisRuleMarkMin,
  52. targetGlucose: target,
  53. glucoseColorScheme: context.state.glucoseColorScheme
  54. )
  55. let lowColor = Color.getDynamicGlucoseColor(
  56. glucoseValue: yAxisRuleMarkMin,
  57. highGlucoseColorValue: !hasStaticColorScheme ? hardCodedHigh : yAxisRuleMarkMax,
  58. lowGlucoseColorValue: !hasStaticColorScheme ? hardCodedLow : yAxisRuleMarkMin,
  59. targetGlucose: target,
  60. glucoseColorScheme: context.state.glucoseColorScheme
  61. )
  62. Chart {
  63. RuleMark(y: .value("High", yAxisRuleMarkMax))
  64. .foregroundStyle(highColor)
  65. .lineStyle(.init(lineWidth: 1, dash: [5]))
  66. RuleMark(y: .value("Low", yAxisRuleMarkMin))
  67. .foregroundStyle(lowColor)
  68. .lineStyle(.init(lineWidth: 1, dash: [5]))
  69. RuleMark(y: .value("Target", target))
  70. .foregroundStyle(.green.gradient)
  71. .lineStyle(.init(lineWidth: 1.5))
  72. if isOverrideActive {
  73. drawActiveOverrides()
  74. }
  75. if isTempTargetActive {
  76. drawActiveTempTarget()
  77. }
  78. if hasForecast, let anchorDate = state.date {
  79. if additionalState.forecastDisplayType == "lines" {
  80. drawForecastLines(anchorDate: anchorDate, isMgdL: isMgdL)
  81. } else {
  82. drawForecastCone(anchorDate: anchorDate, isMgdL: isMgdL, maxValue: maxValue)
  83. }
  84. }
  85. drawChart(yAxisRuleMarkMin: yAxisRuleMarkMin, yAxisRuleMarkMax: yAxisRuleMarkMax)
  86. }
  87. .chartYAxis {
  88. AxisMarks(position: .trailing) { _ in
  89. AxisGridLine(stroke: .init(lineWidth: 0.65, dash: [2, 3]))
  90. .foregroundStyle(Color.white.opacity(colorScheme == .light ? 1 : 0.5))
  91. AxisValueLabel().foregroundStyle(.primary).font(.footnote)
  92. }
  93. }
  94. .chartYScale(domain: state.unit == "mg/dL" ? minValue ... maxValue : minValue.asMmolL ... maxValue.asMmolL)
  95. .chartYAxis(.hidden)
  96. .chartPlotStyle { plotContent in
  97. plotContent
  98. .background(
  99. RoundedRectangle(cornerRadius: 12)
  100. .fill(colorScheme == .light ? Color.black.opacity(0.2) : .clear)
  101. )
  102. .clipShape(RoundedRectangle(cornerRadius: 12))
  103. }
  104. .chartXScale(domain: startDate ... endDate)
  105. .chartXAxis {
  106. AxisMarks(position: .automatic) { _ in
  107. AxisGridLine(stroke: .init(lineWidth: 0.65, dash: [2, 3]))
  108. .foregroundStyle(Color.primary.opacity(colorScheme == .light ? 1 : 0.5))
  109. }
  110. }
  111. }
  112. private func drawActiveOverrides() -> some ChartContent {
  113. let start: Date = context.state.detailedViewState.overrideDate
  114. let duration = context.state.detailedViewState.overrideDuration
  115. let durationAsTimeInterval = TimeInterval((duration as NSDecimalNumber).doubleValue * 60) // return seconds
  116. let end: Date = duration == 0
  117. ? Date(timeIntervalSinceNow: 7200)
  118. : start.addingTimeInterval(durationAsTimeInterval)
  119. let target = context.state.detailedViewState.overrideTarget
  120. return RuleMark(
  121. xStart: .value("Start", start, unit: .second),
  122. xEnd: .value("End", end, unit: .second),
  123. y: .value("Value", target)
  124. )
  125. .foregroundStyle(Color.purple.opacity(0.6))
  126. .lineStyle(.init(lineWidth: 8))
  127. }
  128. private func drawActiveTempTarget() -> some ChartContent {
  129. let start: Date = context.state.detailedViewState.tempTargetDate
  130. let duration = context.state.detailedViewState.tempTargetDuration
  131. let durationAsTimeInterval = TimeInterval((duration as NSDecimalNumber).doubleValue * 60) // return seconds
  132. let end: Date = start.addingTimeInterval(durationAsTimeInterval)
  133. let target = context.state.detailedViewState.tempTargetTarget
  134. return RuleMark(
  135. xStart: .value("Start", start, unit: .second),
  136. xEnd: .value("End", end, unit: .second),
  137. y: .value("Value", target)
  138. )
  139. .foregroundStyle(Color("LoopGreen").opacity(0.6))
  140. .lineStyle(.init(lineWidth: 8))
  141. }
  142. private func timeForIndex(_ index: Int, anchorDate: Date) -> Date {
  143. anchorDate.addingTimeInterval(TimeInterval(index * 300))
  144. }
  145. private func drawForecastCone(anchorDate: Date, isMgdL: Bool, maxValue: Decimal) -> some ChartContent {
  146. let minForecast = additionalState.minForecast
  147. let maxForecast = additionalState.maxForecast
  148. let cappedMax = isMgdL ? maxValue : maxValue.asMmolL
  149. let count = min(minForecast.count, maxForecast.count)
  150. // Pre-compute cone data to avoid conditionals inside the ForEach closure
  151. let coneData: [(date: Date, yMin: Decimal, yMax: Decimal)] = (0 ..< count).map { index in
  152. let xValue = timeForIndex(index, anchorDate: anchorDate)
  153. let delta = minForecast[index] - maxForecast[index]
  154. let yMin: Decimal
  155. let yMax: Decimal
  156. if delta == 0 {
  157. let base = isMgdL ? Decimal(minForecast[index]) : Decimal(minForecast[index]).asMmolL
  158. yMin = base - 1
  159. yMax = base + 1
  160. } else {
  161. yMin = isMgdL ? Decimal(minForecast[index]) : Decimal(minForecast[index]).asMmolL
  162. yMax = isMgdL ? Decimal(maxForecast[index]) : Decimal(maxForecast[index]).asMmolL
  163. }
  164. return (date: xValue, yMin: min(yMin, cappedMax), yMax: min(yMax, cappedMax))
  165. }
  166. return ForEach(coneData.indices, id: \.self) { i in
  167. AreaMark(
  168. x: .value("Time", coneData[i].date),
  169. yStart: .value("Min", coneData[i].yMin),
  170. yEnd: .value("Max", coneData[i].yMax)
  171. )
  172. .foregroundStyle(Color.blue.opacity(0.5))
  173. .interpolationMethod(.catmullRom)
  174. }
  175. }
  176. private func drawForecastLines(anchorDate: Date, isMgdL: Bool) -> some ChartContent {
  177. // Colors match the main app's chartForegroundStyleScale
  178. let colorMap: [String: Color] = [
  179. "iob": Color(red: 0.118, green: 0.588, blue: 0.988),
  180. "cob": Color.orange,
  181. "uam": Color(red: 0.820, green: 0.169, blue: 0.969),
  182. "zt": Color(red: 0.443, green: 0.380, blue: 0.937)
  183. ]
  184. // Flatten lines into a single array to avoid nested ForEach in ChartContentBuilder
  185. let points: [(series: String, date: Date, value: Decimal)] = additionalState.forecastLines.flatMap { line in
  186. line.values.enumerated().map { index, value in
  187. let displayValue = isMgdL ? Decimal(value) : Decimal(value).asMmolL
  188. return (series: line.type, date: timeForIndex(index, anchorDate: anchorDate), value: displayValue)
  189. }
  190. }
  191. let indices = Array(0 ..< points.count)
  192. return ForEach(indices, id: \.self) { i in
  193. let point = points[i]
  194. LineMark(
  195. x: .value("Time", point.date),
  196. y: .value("Value", point.value),
  197. series: .value("Type", point.series)
  198. )
  199. .foregroundStyle(colorMap[point.series] ?? Color.gray)
  200. .lineStyle(.init(lineWidth: 1.5))
  201. .interpolationMethod(.catmullRom)
  202. }
  203. }
  204. private func drawChart(yAxisRuleMarkMin _: Decimal, yAxisRuleMarkMax _: Decimal) -> some ChartContent {
  205. // 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
  206. let hardCodedLow = Decimal(55)
  207. let hardCodedHigh = Decimal(220)
  208. let hasStaticColorScheme = context.state.glucoseColorScheme == "staticColor"
  209. let isMgdL = context.state.unit == "mg/dL"
  210. let threeHours = TimeInterval(10800)
  211. let chartData = isWatchOS ? additionalState.chart
  212. .filter { abs($0.date.timeIntervalSinceNow) < threeHours } : additionalState
  213. .chart
  214. return ForEach(chartData, id: \.self) { item in
  215. let displayValue = isMgdL ? item.value : item.value.asMmolL
  216. let pointMarkColor = Color.getDynamicGlucoseColor(
  217. glucoseValue: item.value,
  218. highGlucoseColorValue: !hasStaticColorScheme ? hardCodedHigh : context.state.highGlucose,
  219. lowGlucoseColorValue: !hasStaticColorScheme ? hardCodedLow : context.state.lowGlucose,
  220. targetGlucose: context.state.target,
  221. glucoseColorScheme: context.state.glucoseColorScheme
  222. )
  223. let pointMark = PointMark(
  224. x: .value("Time", item.date),
  225. y: .value("Value", displayValue)
  226. )
  227. .symbolSize(16)
  228. .shadow(color: Color.black.opacity(0.25), radius: 2, x: 0, y: 0)
  229. pointMark.foregroundStyle(pointMarkColor)
  230. }
  231. }
  232. }