GlucosePercentileChart.swift 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import Charts
  2. import SwiftUI
  3. struct GlucosePercentileChart: View {
  4. let glucose: [GlucoseStored]
  5. let highLimit: Decimal
  6. let lowLimit: Decimal
  7. let units: GlucoseUnits
  8. let hourlyStats: [HourlyStats]
  9. let isToday: Bool
  10. @State private var selection: Date? = nil
  11. private var selectedStats: HourlyStats? {
  12. guard let selection = selection else { return nil }
  13. // Don't show stats for future times if viewing today
  14. if isToday && selection > Date() {
  15. return nil
  16. }
  17. let calendar = Calendar.current
  18. let hour = calendar.component(.hour, from: selection)
  19. return hourlyStats.first { Int($0.hour) == hour }
  20. }
  21. var body: some View {
  22. VStack(alignment: .leading, spacing: 8) {
  23. Text("Ambulatory Glucose Profile (AGP)")
  24. .font(.headline)
  25. Chart {
  26. // TODO: ensure data is still correct
  27. // TODO: ensure area marks and line mark take color of respective range
  28. // Statistical view for longer periods
  29. ForEach(hourlyStats, id: \.hour) { stats in
  30. // 10-90 percentile area
  31. AreaMark(
  32. x: .value("Hour", Calendar.current.dateForChartHour(stats.hour)),
  33. yStart: .value("10th Percentile", stats.percentile10),
  34. yEnd: .value("90th Percentile", stats.percentile90),
  35. series: .value("10-90", "10-90")
  36. )
  37. .foregroundStyle(.blue.opacity(stats.median > 0 ? 0.2 : 0))
  38. // 25-75 percentile area
  39. AreaMark(
  40. x: .value("Hour", Calendar.current.dateForChartHour(stats.hour)),
  41. yStart: .value("25th Percentile", stats.percentile25),
  42. yEnd: .value("75th Percentile", stats.percentile75),
  43. series: .value("25-75", "25-75")
  44. )
  45. .foregroundStyle(.blue.opacity(stats.median > 0 ? 0.3 : 0))
  46. // Median line
  47. if stats.median > 0 {
  48. LineMark(
  49. x: .value("Hour", Calendar.current.dateForChartHour(stats.hour)),
  50. y: .value("Median", stats.median),
  51. series: .value("Median", "Median")
  52. )
  53. .lineStyle(StrokeStyle(lineWidth: 2))
  54. .foregroundStyle(.blue)
  55. }
  56. }
  57. // High/Low limit lines
  58. RuleMark(y: .value("High Limit", Double(highLimit)))
  59. .lineStyle(StrokeStyle(lineWidth: 1, dash: [5, 5]))
  60. .foregroundStyle(.orange)
  61. RuleMark(y: .value("Low Limit", Double(lowLimit)))
  62. .lineStyle(StrokeStyle(lineWidth: 1, dash: [5, 5]))
  63. .foregroundStyle(.red)
  64. if let selectedStats, let selection {
  65. RuleMark(x: .value("Selection", selection))
  66. .foregroundStyle(.secondary.opacity(0.5))
  67. .annotation(
  68. position: .top,
  69. spacing: 0,
  70. overflowResolution: .init(x: .fit, y: .disabled)
  71. ) {
  72. AGPSelectionPopover(
  73. stats: selectedStats,
  74. time: selection,
  75. units: units
  76. )
  77. }
  78. }
  79. }
  80. .chartYAxis {
  81. AxisMarks(position: .trailing) { value in
  82. if let glucose = value.as(Double.self) {
  83. AxisValueLabel {
  84. Text(
  85. units == .mmolL ? glucose.asMmolL.formatted(.number.precision(.fractionLength(0))) : glucose
  86. .formatted(.number.precision(.fractionLength(0)))
  87. )
  88. .font(.footnote)
  89. }
  90. AxisGridLine()
  91. }
  92. }
  93. }
  94. .chartYAxisLabel(alignment: .trailing) {
  95. Text("\(units.rawValue)")
  96. .foregroundStyle(.primary)
  97. .font(.footnote)
  98. .padding(.vertical, 3)
  99. }
  100. .chartXAxis {
  101. AxisMarks(values: .stride(by: .hour, count: 3)) { _ in
  102. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  103. .font(.footnote)
  104. AxisGridLine()
  105. }
  106. }
  107. .chartXSelection(value: $selection.animation(.easeInOut))
  108. .frame(height: 200)
  109. legend
  110. }
  111. }
  112. private var legend: some View {
  113. HStack(spacing: 20) {
  114. VStack {
  115. // 10-90 Percentile
  116. HStack(spacing: 8) {
  117. Rectangle()
  118. .frame(width: 20, height: 8)
  119. .foregroundStyle(.blue.opacity(0.2))
  120. Text("10% - 90%")
  121. .font(.caption)
  122. .foregroundStyle(.secondary)
  123. }
  124. // 25-75 Percentile
  125. HStack(spacing: 8) {
  126. Rectangle()
  127. .frame(width: 20, height: 8)
  128. .foregroundStyle(.blue.opacity(0.3))
  129. Text("25% - 75%")
  130. .font(.caption)
  131. .foregroundStyle(.secondary)
  132. }
  133. }
  134. // Median
  135. HStack(spacing: 8) {
  136. Rectangle()
  137. .frame(width: 20, height: 2)
  138. .foregroundStyle(.blue)
  139. Text("Median")
  140. .font(.caption)
  141. .foregroundStyle(.secondary)
  142. }
  143. VStack {
  144. // High Limit
  145. HStack(spacing: 8) {
  146. Rectangle()
  147. .frame(width: 20, height: 1)
  148. .foregroundStyle(.orange)
  149. Text("High Limit")
  150. .font(.caption)
  151. .foregroundStyle(.secondary)
  152. }
  153. // Low Limit
  154. HStack(spacing: 8) {
  155. Rectangle()
  156. .frame(width: 20, height: 1)
  157. .foregroundStyle(.red)
  158. Text("Low Limit")
  159. .font(.caption)
  160. .foregroundStyle(.secondary)
  161. }
  162. }
  163. }
  164. .padding(.horizontal)
  165. }
  166. }
  167. struct AGPSelectionPopover: View {
  168. let stats: HourlyStats
  169. let time: Date
  170. let units: GlucoseUnits
  171. private var timeText: String {
  172. if let hour = Calendar.current.dateComponents([.hour], from: time).hour {
  173. return "\(hour):00-\(hour + 1):00"
  174. } else {
  175. return time.formatted(.dateTime.hour().minute())
  176. }
  177. }
  178. var body: some View {
  179. VStack(alignment: .leading, spacing: 4) {
  180. HStack {
  181. Image(systemName: "clock")
  182. Text(timeText)
  183. .fontWeight(.bold)
  184. }
  185. .font(.subheadline)
  186. Grid(alignment: .leading, horizontalSpacing: 8) {
  187. GridRow {
  188. Text("90%:")
  189. Text(units == .mmolL ? stats.percentile90.asMmolL.formatted(.number) : stats.percentile90.formatted(.number))
  190. Text(units.rawValue)
  191. .foregroundStyle(.secondary)
  192. }
  193. GridRow {
  194. Text("75%:")
  195. Text(units == .mmolL ? stats.percentile75.asMmolL.formatted(.number) : stats.percentile75.formatted(.number))
  196. Text(units.rawValue)
  197. .foregroundStyle(.secondary)
  198. }
  199. GridRow {
  200. Text("Median:")
  201. Text(units == .mmolL ? stats.median.asMmolL.formatted(.number) : stats.median.formatted(.number))
  202. Text(units.rawValue)
  203. .foregroundStyle(.secondary)
  204. }
  205. GridRow {
  206. Text("25%:")
  207. Text(units == .mmolL ? stats.percentile25.asMmolL.formatted(.number) : stats.percentile25.formatted(.number))
  208. Text(units.rawValue)
  209. .foregroundStyle(.secondary)
  210. }
  211. GridRow {
  212. Text("10%:")
  213. Text(units == .mmolL ? stats.percentile10.asMmolL.formatted(.number) : stats.percentile10.formatted(.number))
  214. Text(units.rawValue)
  215. .foregroundStyle(.secondary)
  216. }
  217. }
  218. .font(.headline.bold())
  219. }
  220. .foregroundStyle(.white)
  221. .padding(20)
  222. .background {
  223. RoundedRectangle(cornerRadius: 10)
  224. .fill(Color.blue.gradient)
  225. }
  226. }
  227. }
  228. private extension Calendar {
  229. func startOfHour(for date: Date) -> Date {
  230. let components = dateComponents([.year, .month, .day, .hour], from: date)
  231. return self.date(from: components) ?? date
  232. }
  233. }