LiveActivityChartView.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 forecastCount = max(
  42. additionalState.minForecast.count,
  43. additionalState.forecastLines.max(by: { $0.values.count < $1.values.count })?.values.count ?? 0
  44. )
  45. let predictionEnd = anchorDate.addingTimeInterval(TimeInterval(forecastCount * 300))
  46. return max(baseEnd, predictionEnd)
  47. }()
  48. // 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
  49. let hardCodedLow = isMgdL ? Decimal(55) : 55.asMmolL
  50. let hardCodedHigh = isMgdL ? Decimal(220) : 220.asMmolL
  51. let hasStaticColorScheme = context.state.glucoseColorScheme == "staticColor"
  52. let highColor = Color.getDynamicGlucoseColor(
  53. glucoseValue: yAxisRuleMarkMax,
  54. highGlucoseColorValue: !hasStaticColorScheme ? hardCodedHigh : yAxisRuleMarkMax,
  55. lowGlucoseColorValue: !hasStaticColorScheme ? hardCodedLow : yAxisRuleMarkMin,
  56. targetGlucose: target,
  57. glucoseColorScheme: context.state.glucoseColorScheme
  58. )
  59. let lowColor = Color.getDynamicGlucoseColor(
  60. glucoseValue: yAxisRuleMarkMin,
  61. highGlucoseColorValue: !hasStaticColorScheme ? hardCodedHigh : yAxisRuleMarkMax,
  62. lowGlucoseColorValue: !hasStaticColorScheme ? hardCodedLow : yAxisRuleMarkMin,
  63. targetGlucose: target,
  64. glucoseColorScheme: context.state.glucoseColorScheme
  65. )
  66. Chart {
  67. RuleMark(y: .value("High", yAxisRuleMarkMax))
  68. .foregroundStyle(highColor)
  69. .lineStyle(.init(lineWidth: 1, dash: [5]))
  70. RuleMark(y: .value("Low", yAxisRuleMarkMin))
  71. .foregroundStyle(lowColor)
  72. .lineStyle(.init(lineWidth: 1, dash: [5]))
  73. RuleMark(y: .value("Target", target))
  74. .foregroundStyle(.green.gradient)
  75. .lineStyle(.init(lineWidth: 1.5))
  76. if isOverrideActive {
  77. drawActiveOverrides()
  78. }
  79. if isTempTargetActive {
  80. drawActiveTempTarget()
  81. }
  82. if hasForecast, let anchorDate = state.date {
  83. if additionalState.forecastDisplayType == "lines" {
  84. drawForecastLines(anchorDate: anchorDate, isMgdL: isMgdL)
  85. } else {
  86. drawForecastCone(anchorDate: anchorDate, isMgdL: isMgdL, maxValue: maxValue)
  87. }
  88. }
  89. drawChart(yAxisRuleMarkMin: yAxisRuleMarkMin, yAxisRuleMarkMax: yAxisRuleMarkMax)
  90. }
  91. .chartYAxis {
  92. AxisMarks(position: .trailing) { _ in
  93. AxisGridLine(stroke: .init(lineWidth: 0.65, dash: [2, 3]))
  94. .foregroundStyle(Color.white.opacity(colorScheme == .light ? 1 : 0.5))
  95. AxisValueLabel().foregroundStyle(.primary).font(.footnote)
  96. }
  97. }
  98. .chartYScale(domain: state.unit == "mg/dL" ? minValue ... maxValue : minValue.asMmolL ... maxValue.asMmolL)
  99. .chartYAxis(.hidden)
  100. .chartPlotStyle { plotContent in
  101. plotContent
  102. .background(
  103. RoundedRectangle(cornerRadius: 12)
  104. .fill(colorScheme == .light ? Color.black.opacity(0.2) : .clear)
  105. )
  106. .clipShape(RoundedRectangle(cornerRadius: 12))
  107. }
  108. .chartXScale(domain: startDate ... endDate)
  109. .chartXAxis {
  110. AxisMarks(position: .automatic) { _ in
  111. AxisGridLine(stroke: .init(lineWidth: 0.65, dash: [2, 3]))
  112. .foregroundStyle(Color.primary.opacity(colorScheme == .light ? 1 : 0.5))
  113. }
  114. }
  115. }
  116. private func drawActiveOverrides() -> some ChartContent {
  117. let start: Date = context.state.detailedViewState.overrideDate
  118. let duration = context.state.detailedViewState.overrideDuration
  119. let durationAsTimeInterval = TimeInterval((duration as NSDecimalNumber).doubleValue * 60) // return seconds
  120. let end: Date = duration == 0
  121. ? Date(timeIntervalSinceNow: 7200)
  122. : start.addingTimeInterval(durationAsTimeInterval)
  123. let target = context.state.detailedViewState.overrideTarget
  124. return RuleMark(
  125. xStart: .value("Start", start, unit: .second),
  126. xEnd: .value("End", end, unit: .second),
  127. y: .value("Value", target)
  128. )
  129. .foregroundStyle(Color.purple.opacity(0.6))
  130. .lineStyle(.init(lineWidth: 8))
  131. }
  132. private func drawActiveTempTarget() -> some ChartContent {
  133. let start: Date = context.state.detailedViewState.tempTargetDate
  134. let duration = context.state.detailedViewState.tempTargetDuration
  135. let durationAsTimeInterval = TimeInterval((duration as NSDecimalNumber).doubleValue * 60) // return seconds
  136. let end: Date = start.addingTimeInterval(durationAsTimeInterval)
  137. let target = context.state.detailedViewState.tempTargetTarget
  138. return RuleMark(
  139. xStart: .value("Start", start, unit: .second),
  140. xEnd: .value("End", end, unit: .second),
  141. y: .value("Value", target)
  142. )
  143. .foregroundStyle(Color("LoopGreen").opacity(0.6))
  144. .lineStyle(.init(lineWidth: 8))
  145. }
  146. private func timeForIndex(_ index: Int, anchorDate: Date) -> Date {
  147. anchorDate.addingTimeInterval(TimeInterval(index * 300))
  148. }
  149. private func drawForecastCone(anchorDate: Date, isMgdL: Bool, maxValue: Decimal) -> some ChartContent {
  150. let minForecast = additionalState.minForecast
  151. let maxForecast = additionalState.maxForecast
  152. let cappedMax = isMgdL ? maxValue : maxValue.asMmolL
  153. let count = min(minForecast.count, maxForecast.count)
  154. // Pre-compute cone data to avoid conditionals inside the ForEach closure
  155. let coneData: [(date: Date, yMin: Decimal, yMax: Decimal)] = (0 ..< count).map { index in
  156. let xValue = timeForIndex(index, anchorDate: anchorDate)
  157. let delta = minForecast[index] - maxForecast[index]
  158. let yMin: Decimal
  159. let yMax: Decimal
  160. if delta == 0 {
  161. let base = isMgdL ? Decimal(minForecast[index]) : Decimal(minForecast[index]).asMmolL
  162. yMin = base - 1
  163. yMax = base + 1
  164. } else {
  165. yMin = isMgdL ? Decimal(minForecast[index]) : Decimal(minForecast[index]).asMmolL
  166. yMax = isMgdL ? Decimal(maxForecast[index]) : Decimal(maxForecast[index]).asMmolL
  167. }
  168. return (date: xValue, yMin: min(yMin, cappedMax), yMax: min(yMax, cappedMax))
  169. }
  170. return ForEach(coneData.indices, id: \.self) { i in
  171. AreaMark(
  172. x: .value("Time", coneData[i].date),
  173. yStart: .value("Min", coneData[i].yMin),
  174. yEnd: .value("Max", coneData[i].yMax)
  175. )
  176. .foregroundStyle(Color.blue.opacity(0.5))
  177. .interpolationMethod(.linear)
  178. }
  179. }
  180. private func drawForecastLines(anchorDate: Date, isMgdL: Bool) -> some ChartContent {
  181. let colorMap: [String: Color] = [
  182. "iob": Color(red: 0.118, green: 0.588, blue: 0.988),
  183. "cob": Color.orange,
  184. "uam": Color("UAM"),
  185. "zt": Color("ZT")
  186. ]
  187. let points: [(series: String, date: Date, value: Decimal)] = additionalState.forecastLines.flatMap { line in
  188. line.values.enumerated().map { index, value in
  189. let displayValue = isMgdL ? Decimal(value) : Decimal(value).asMmolL
  190. return (series: line.type, date: timeForIndex(index, anchorDate: anchorDate), value: displayValue)
  191. }
  192. }
  193. return ForEach(0 ..< points.count, id: \.self) { i in
  194. let point = points[i]
  195. LineMark(
  196. x: .value("Time", point.date),
  197. y: .value("Value", point.value),
  198. series: .value("Type", point.series)
  199. )
  200. .foregroundStyle(colorMap[point.series] ?? Color.gray)
  201. .lineStyle(.init(lineWidth: 1.5))
  202. .interpolationMethod(.linear)
  203. }
  204. }
  205. private func drawChart(yAxisRuleMarkMin _: Decimal, yAxisRuleMarkMax _: Decimal) -> some ChartContent {
  206. // 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
  207. let hardCodedLow = Decimal(55)
  208. let hardCodedHigh = Decimal(220)
  209. let hasStaticColorScheme = context.state.glucoseColorScheme == "staticColor"
  210. let isMgdL = context.state.unit == "mg/dL"
  211. let threeHours = TimeInterval(10800)
  212. let chartData = isWatchOS ? additionalState.chart
  213. .filter { abs($0.date.timeIntervalSinceNow) < threeHours } : additionalState
  214. .chart
  215. return ForEach(chartData, id: \.self) { item in
  216. let displayValue = isMgdL ? item.value : item.value.asMmolL
  217. let pointMarkColor = Color.getDynamicGlucoseColor(
  218. glucoseValue: item.value,
  219. highGlucoseColorValue: !hasStaticColorScheme ? hardCodedHigh : context.state.highGlucose,
  220. lowGlucoseColorValue: !hasStaticColorScheme ? hardCodedLow : context.state.lowGlucose,
  221. targetGlucose: context.state.target,
  222. glucoseColorScheme: context.state.glucoseColorScheme
  223. )
  224. let pointMark = PointMark(
  225. x: .value("Time", item.date),
  226. y: .value("Value", displayValue)
  227. )
  228. .symbolSize(16)
  229. .shadow(color: Color.black.opacity(0.25), radius: 2, x: 0, y: 0)
  230. pointMark.foregroundStyle(pointMarkColor)
  231. }
  232. }
  233. }