BolusStatsView.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import Charts
  2. import SwiftUI
  3. /// A view that displays a bar chart for bolus insulin statistics.
  4. ///
  5. /// This view presents different types of bolus insulin (manual, SMB, and external) over time,
  6. /// allowing users to adjust the time interval and scroll through historical data.
  7. struct BolusStatsView: View {
  8. /// The selected time interval for displaying statistics.
  9. @Binding var selectedDuration: Stat.StateModel.StatsTimeInterval
  10. /// The list of bolus statistics data.
  11. let bolusStats: [BolusStats]
  12. /// The state model containing cached statistics data.
  13. let state: Stat.StateModel
  14. /// The current scroll position in the chart.
  15. @State private var scrollPosition = Date()
  16. /// The currently selected date in the chart.
  17. @State private var selectedDate: Date?
  18. /// The calculated bolus insulin averages for the visible range.
  19. @State private var currentAverages: (manual: Double, smb: Double, external: Double) = (0, 0, 0)
  20. /// Timer to throttle updates when scrolling.
  21. @State private var updateTimer = Stat.UpdateTimer()
  22. /// Computes the visible date range based on the current scroll position.
  23. private var visibleDateRange: (start: Date, end: Date) {
  24. StatChartUtils.visibleDateRange(from: scrollPosition, for: selectedDuration)
  25. }
  26. /// Retrieves the bolus statistic for a given date.
  27. /// - Parameter date: The date for which to retrieve bolus data.
  28. /// - Returns: The `BolusStats` object if available, otherwise `nil`.
  29. private func getBolusForDate(_ date: Date) -> BolusStats? {
  30. bolusStats.first { stat in
  31. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedDuration)
  32. }
  33. }
  34. /// Updates the bolus insulin averages based on the visible date range.
  35. private func updateAverages() {
  36. currentAverages = state.getCachedBolusAverages(for: visibleDateRange)
  37. }
  38. /// A view displaying the statistics summary including bolus insulin averages.
  39. private var statsView: some View {
  40. HStack {
  41. Grid(alignment: .leading) {
  42. GridRow {
  43. Text("Manual:")
  44. Text(currentAverages.manual.formatted(.number.precision(.fractionLength(1))))
  45. Text("U")
  46. }
  47. GridRow {
  48. Text("SMB:")
  49. Text(currentAverages.smb.formatted(.number.precision(.fractionLength(1))))
  50. Text("U")
  51. }
  52. GridRow {
  53. Text("External:")
  54. Text(currentAverages.external.formatted(.number.precision(.fractionLength(1))))
  55. Text("U")
  56. }
  57. }
  58. .font(.headline)
  59. Spacer()
  60. Text(
  61. StatChartUtils
  62. .formatVisibleDateRange(from: visibleDateRange.start, to: visibleDateRange.end, for: selectedDuration)
  63. )
  64. .font(.callout)
  65. .foregroundStyle(.secondary)
  66. }
  67. }
  68. var body: some View {
  69. VStack(alignment: .leading, spacing: 8) {
  70. statsView.padding(.bottom)
  71. VStack(alignment: .trailing) {
  72. Text("Bolus Insulin (U)")
  73. .foregroundStyle(.secondary)
  74. .font(.footnote)
  75. .padding(.bottom, 4)
  76. chartsView
  77. }
  78. }
  79. .onAppear {
  80. scrollPosition = StatChartUtils.getInitialScrollPosition(for: selectedDuration)
  81. updateAverages()
  82. }
  83. .onChange(of: scrollPosition) {
  84. updateTimer.scheduleUpdate {
  85. updateAverages()
  86. }
  87. }
  88. .onChange(of: selectedDuration) {
  89. Task {
  90. scrollPosition = StatChartUtils.getInitialScrollPosition(for: selectedDuration)
  91. updateAverages()
  92. }
  93. }
  94. }
  95. /// A view displaying the bar chart for bolus insulin statistics.
  96. private var chartsView: some View {
  97. Chart {
  98. ForEach(bolusStats) { stat in
  99. // Total Bolus Bar
  100. BarMark(
  101. x: .value("Date", stat.date, unit: selectedDuration == .day ? .hour : .day),
  102. y: .value("Amount", stat.manualBolus)
  103. )
  104. .foregroundStyle(by: .value("Type", "Manual"))
  105. .position(by: .value("Type", "Boluses"))
  106. .opacity(
  107. selectedDate.map { date in
  108. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedDuration) ? 1 : 0.3
  109. } ?? 1
  110. )
  111. // Carb Bolus Bar
  112. BarMark(
  113. x: .value("Date", stat.date, unit: selectedDuration == .day ? .hour : .day),
  114. y: .value("Amount", stat.smb)
  115. )
  116. .foregroundStyle(by: .value("Type", "SMB"))
  117. .position(by: .value("Type", "Boluses"))
  118. .opacity(
  119. selectedDate.map { date in
  120. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedDuration) ? 1 : 0.3
  121. } ?? 1
  122. )
  123. // Correction Bolus Bar
  124. BarMark(
  125. x: .value("Date", stat.date, unit: selectedDuration == .day ? .hour : .day),
  126. y: .value("Amount", stat.external)
  127. )
  128. .foregroundStyle(by: .value("Type", "External"))
  129. .position(by: .value("Type", "Boluses"))
  130. .opacity(
  131. selectedDate.map { date in
  132. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedDuration) ? 1 : 0.3
  133. } ?? 1
  134. )
  135. }
  136. // Selection popover outside of the ForEach loop!
  137. if let selectedDate, let selectedBolus = getBolusForDate(selectedDate)
  138. {
  139. RuleMark(
  140. x: .value("Selected Date", selectedDate)
  141. )
  142. .foregroundStyle(.secondary.opacity(0.5))
  143. .annotation(
  144. position: .top,
  145. spacing: 0,
  146. overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
  147. ) {
  148. BolusSelectionPopover(date: selectedDate, bolus: selectedBolus, selectedDuration: selectedDuration)
  149. }
  150. }
  151. }
  152. .chartForegroundStyleScale([
  153. "SMB": Color.blue,
  154. "Manual": Color.teal,
  155. "External": Color.purple
  156. ])
  157. .chartLegend(position: .bottom, alignment: .leading, spacing: 12) {
  158. let legendItems: [(String, Color)] = [
  159. (String(localized: "SMB"), Color.blue),
  160. (String(localized: "Manual"), Color.teal),
  161. (String(localized: "External"), Color.purple)
  162. ]
  163. let columns = [GridItem(.adaptive(minimum: 65), spacing: 4)]
  164. LazyVGrid(columns: columns, alignment: .leading, spacing: 4) {
  165. ForEach(legendItems, id: \.0) { item in
  166. StatChartUtils.legendItem(label: item.0, color: item.1)
  167. }
  168. }
  169. }
  170. .chartYAxis {
  171. AxisMarks(position: .trailing) { value in
  172. if let amount = value.as(Double.self) {
  173. AxisValueLabel {
  174. Text(amount.formatted(.number.precision(.fractionLength(0))))
  175. .font(.footnote)
  176. }
  177. AxisGridLine()
  178. }
  179. }
  180. }
  181. .chartXAxis {
  182. AxisMarks(preset: .aligned, values: .stride(by: selectedDuration == .day ? .hour : .day)) { value in
  183. if let date = value.as(Date.self) {
  184. let day = Calendar.current.component(.day, from: date)
  185. let hour = Calendar.current.component(.hour, from: date)
  186. switch selectedDuration {
  187. case .day:
  188. if hour % 6 == 0 { // Show only every 6 hours
  189. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedDuration), centered: true)
  190. .font(.footnote)
  191. AxisGridLine()
  192. }
  193. case .month:
  194. if day % 3 == 0 { // Only show every 3rd day
  195. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedDuration), centered: true)
  196. .font(.footnote)
  197. AxisGridLine()
  198. }
  199. case .total:
  200. // Only show every other month
  201. if day == 1 && Calendar.current.component(.month, from: date) % 2 == 1 {
  202. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedDuration), centered: true)
  203. .font(.footnote)
  204. AxisGridLine()
  205. }
  206. default:
  207. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedDuration), centered: true)
  208. .font(.footnote)
  209. AxisGridLine()
  210. }
  211. }
  212. }
  213. }
  214. .chartScrollableAxes(.horizontal)
  215. .chartXSelection(value: $selectedDate.animation(.easeInOut))
  216. .chartScrollPosition(x: $scrollPosition)
  217. .chartScrollTargetBehavior(
  218. .valueAligned(
  219. matching: selectedDuration == .day ?
  220. DateComponents(minute: 0) : // Align to next hour for Day view
  221. DateComponents(hour: 0), // Align to start of day for other views
  222. majorAlignment: .matching(
  223. StatChartUtils.alignmentComponents(for: selectedDuration)
  224. )
  225. )
  226. )
  227. .chartXVisibleDomain(length: StatChartUtils.visibleDomainLength(for: selectedDuration))
  228. .frame(height: 250)
  229. }
  230. }
  231. private struct BolusSelectionPopover: View {
  232. let date: Date
  233. let bolus: BolusStats
  234. let selectedDuration: Stat.StateModel.StatsTimeInterval
  235. private var timeText: String {
  236. if selectedDuration == .day {
  237. let hour = Calendar.current.component(.hour, from: date)
  238. return "\(hour):00-\(hour + 1):00"
  239. } else {
  240. return date.formatted(.dateTime.month().day())
  241. }
  242. }
  243. var body: some View {
  244. VStack(alignment: .leading, spacing: 4) {
  245. Text(timeText)
  246. .font(.footnote)
  247. .fontWeight(.bold)
  248. Grid(alignment: .leading) {
  249. GridRow {
  250. Text("Manual:")
  251. Text(bolus.manualBolus.formatted(.number.precision(.fractionLength(1))))
  252. .gridColumnAlignment(.trailing)
  253. Text("U")
  254. }
  255. GridRow {
  256. Text("SMB:")
  257. Text(bolus.smb.formatted(.number.precision(.fractionLength(1))))
  258. .gridColumnAlignment(.trailing)
  259. Text("U")
  260. }
  261. GridRow {
  262. Text("External:")
  263. Text(bolus.external.formatted(.number.precision(.fractionLength(1))))
  264. .gridColumnAlignment(.trailing)
  265. Text("U")
  266. }
  267. }
  268. .font(.headline.bold())
  269. }
  270. .foregroundStyle(.white)
  271. .padding(20)
  272. .background(
  273. RoundedRectangle(cornerRadius: 10)
  274. .fill(Color.insulin)
  275. )
  276. }
  277. }