BolusStatsView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 selectedInterval: 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. /// The calculated total bolus insulin for the visible range.
  21. @State private var currentTotal: Double = 0
  22. /// Timer to throttle updates when scrolling.
  23. @State private var updateTimer = Stat.UpdateTimer()
  24. /// The actual chart plot's width in pixel
  25. @State private var chartWidth: CGFloat = 0
  26. /// Computes the visible date range based on the current scroll position.
  27. private var visibleDateRange: (start: Date, end: Date) {
  28. StatChartUtils.visibleDateRange(from: scrollPosition, for: selectedInterval)
  29. }
  30. /// Retrieves the bolus statistic for a given date.
  31. /// - Parameter date: The date for which to retrieve bolus data.
  32. /// - Returns: The `BolusStats` object if available, otherwise `nil`.
  33. private func getBolusForDate(_ date: Date) -> BolusStats? {
  34. bolusStats.first { stat in
  35. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedInterval)
  36. }
  37. }
  38. /// Updates the bolus insulin averages based on the visible date range.
  39. private func updateCalculatedValues() {
  40. currentAverages = state.getCachedBolusAverages(for: visibleDateRange)
  41. currentTotal = state.getCachedBolusTotals(for: visibleDateRange)
  42. }
  43. /// A view displaying the statistics summary including bolus insulin averages.
  44. private var statsView: some View {
  45. HStack {
  46. Grid(alignment: .leading) {
  47. GridRow {
  48. if selectedInterval != .day {
  49. Text("ø") + Text("\u{00A0}") + Text("Manual:")
  50. } else {
  51. Text("Manual:")
  52. }
  53. Text(currentAverages.manual.formatted(.number.precision(.fractionLength(1))))
  54. + Text("\u{00A0}") + Text("U")
  55. }
  56. GridRow {
  57. if selectedInterval != .day {
  58. Text("ø") + Text("\u{00A0}") + Text("SMB:")
  59. } else {
  60. Text("SMB:")
  61. }
  62. Text(currentAverages.smb.formatted(.number.precision(.fractionLength(1))))
  63. + Text("\u{00A0}") + Text("U")
  64. }
  65. GridRow {
  66. if selectedInterval != .day {
  67. Text("ø") + Text("\u{00A0}") + Text("External:")
  68. } else {
  69. Text("External:")
  70. }
  71. Text(currentAverages.external.formatted(.number.precision(.fractionLength(1))))
  72. + Text("\u{00A0}") + Text("U")
  73. }
  74. Divider()
  75. GridRow {
  76. Text("Total:")
  77. Text(
  78. currentTotal.formatted(.number.precision(.fractionLength(1)))
  79. )
  80. + Text("\u{00A0}") + Text("U")
  81. }
  82. }
  83. .font(.headline)
  84. Spacer()
  85. Text(
  86. StatChartUtils
  87. .formatVisibleDateRange(from: visibleDateRange.start, to: visibleDateRange.end, for: selectedInterval)
  88. )
  89. .font(.callout)
  90. .foregroundStyle(.secondary)
  91. }
  92. }
  93. var body: some View {
  94. VStack(alignment: .leading, spacing: 8) {
  95. statsView.padding(.bottom)
  96. VStack(alignment: .trailing) {
  97. Text("Bolus Insulin (U)")
  98. .foregroundStyle(.secondary)
  99. .font(.footnote)
  100. .padding(.bottom, 4)
  101. chartsView
  102. .background(
  103. GeometryReader { geo in
  104. Color.clear
  105. .onAppear { chartWidth = geo.size.width }
  106. .onChange(of: geo.size.width) { _, newValue in chartWidth = newValue }
  107. }
  108. )
  109. }
  110. }
  111. .onAppear {
  112. scrollPosition = StatChartUtils.getInitialScrollPosition(for: selectedInterval)
  113. // Delay the initial update to ensure scroll position has been processed
  114. DispatchQueue.main.async {
  115. updateCalculatedValues()
  116. }
  117. }
  118. .onChange(of: scrollPosition) {
  119. updateTimer.scheduleUpdate {
  120. updateCalculatedValues()
  121. }
  122. }
  123. .onChange(of: selectedInterval) {
  124. Task {
  125. scrollPosition = StatChartUtils.getInitialScrollPosition(for: selectedInterval)
  126. // Use async dispatch to ensure scroll position is updated before calculating values
  127. await MainActor.run {
  128. updateCalculatedValues()
  129. }
  130. }
  131. }
  132. }
  133. /// A view displaying the bar chart for bolus insulin statistics.
  134. private var chartsView: some View {
  135. Chart {
  136. ForEach(bolusStats) { stat in
  137. // Total Bolus Bar
  138. BarMark(
  139. x: .value("Date", stat.date, unit: selectedInterval == .day ? .hour : .day),
  140. y: .value("Amount", stat.manualBolus)
  141. )
  142. .foregroundStyle(by: .value("Type", "Manual"))
  143. .position(by: .value("Type", "Boluses"))
  144. .opacity(
  145. selectedDate.map { date in
  146. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedInterval) ? 1 : 0.3
  147. } ?? 1
  148. )
  149. // Carb Bolus Bar
  150. BarMark(
  151. x: .value("Date", stat.date, unit: selectedInterval == .day ? .hour : .day),
  152. y: .value("Amount", stat.smb)
  153. )
  154. .foregroundStyle(by: .value("Type", "SMB"))
  155. .position(by: .value("Type", "Boluses"))
  156. .opacity(
  157. selectedDate.map { date in
  158. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedInterval) ? 1 : 0.3
  159. } ?? 1
  160. )
  161. // Correction Bolus Bar
  162. BarMark(
  163. x: .value("Date", stat.date, unit: selectedInterval == .day ? .hour : .day),
  164. y: .value("Amount", stat.external)
  165. )
  166. .foregroundStyle(by: .value("Type", "External"))
  167. .position(by: .value("Type", "Boluses"))
  168. .opacity(
  169. selectedDate.map { date in
  170. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedInterval) ? 1 : 0.3
  171. } ?? 1
  172. )
  173. }
  174. // Dummy PointMark to force SwiftCharts to render a visible domain of 00:00-23:59
  175. // i.e. single day from midnight to midnight
  176. if selectedInterval == .day {
  177. let calendar = Calendar.current
  178. let midnight = calendar.startOfDay(for: Date())
  179. let nextMidnight = calendar.date(byAdding: .day, value: 1, to: midnight)!
  180. PointMark(
  181. x: .value("Time", nextMidnight),
  182. y: .value("Dummy", 0)
  183. )
  184. .opacity(0) // ensures dummy ChartContent is hidden
  185. }
  186. // Selection popover outside of the ForEach loop!
  187. if let selectedDate, let selectedBolus = getBolusForDate(selectedDate)
  188. {
  189. RuleMark(
  190. x: .value("Selected Date", selectedDate)
  191. )
  192. .foregroundStyle(Color.insulin.opacity(0.5))
  193. .annotation(
  194. position: .overlay,
  195. alignment: .top,
  196. spacing: 0,
  197. overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
  198. ) { _ in
  199. BolusSelectionPopover(
  200. selectedDate: selectedDate,
  201. bolus: selectedBolus,
  202. selectedInterval: selectedInterval,
  203. domain: visibleDateRange,
  204. chartWidth: chartWidth
  205. )
  206. }
  207. }
  208. }
  209. .chartForegroundStyleScale([
  210. "SMB": Color.blue,
  211. "Manual": Color.teal,
  212. "External": Color.purple
  213. ])
  214. .chartLegend(position: .bottom, alignment: .leading, spacing: 12) {
  215. let legendItems: [(String, Color)] = [
  216. (String(localized: "SMB"), Color.blue),
  217. (String(localized: "Manual"), Color.teal),
  218. (String(localized: "External"), Color.purple)
  219. ]
  220. let columns = [GridItem(.adaptive(minimum: 65), spacing: 4)]
  221. LazyVGrid(columns: columns, alignment: .leading, spacing: 4) {
  222. ForEach(legendItems, id: \.0) { item in
  223. StatChartUtils.legendItem(label: item.0, color: item.1)
  224. }
  225. }
  226. }
  227. .chartYAxis {
  228. AxisMarks(position: .trailing) { value in
  229. if let amount = value.as(Double.self) {
  230. AxisValueLabel {
  231. Text(amount.formatted(.number.precision(.fractionLength(0))))
  232. .font(.footnote)
  233. }
  234. AxisGridLine()
  235. }
  236. }
  237. }
  238. .chartXAxis {
  239. AxisMarks(preset: .aligned, values: .stride(by: selectedInterval == .day ? .hour : .day)) { value in
  240. if let date = value.as(Date.self) {
  241. switch selectedInterval {
  242. case .day:
  243. let hour = Calendar.current.component(.hour, from: date)
  244. if hour % 6 == 0 { // Show only every 6 hours
  245. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  246. .font(.footnote)
  247. AxisGridLine()
  248. }
  249. case .month:
  250. let weekday = calendar.component(.weekday, from: date)
  251. if weekday == calendar.firstWeekday { // Only show the first day of the week
  252. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  253. .font(.footnote)
  254. AxisGridLine()
  255. }
  256. case .total:
  257. // Show start of every month
  258. let day = Calendar.current.component(.day, from: date)
  259. if day == 1 {
  260. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  261. .font(.footnote)
  262. AxisGridLine()
  263. }
  264. default:
  265. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  266. .font(.footnote)
  267. AxisGridLine()
  268. }
  269. }
  270. }
  271. }
  272. .chartXSelection(value: $selectedDate.animation(.easeInOut))
  273. .chartScrollableAxes(.horizontal)
  274. .chartScrollPosition(x: $scrollPosition)
  275. .chartScrollTargetBehavior(
  276. .valueAligned(
  277. matching:
  278. selectedInterval == .day ?
  279. DateComponents(minute: 0) : // Align to next hour for Day view
  280. DateComponents(hour: 0), // Align to start of day for other views
  281. majorAlignment: .matching(
  282. StatChartUtils.alignmentComponents(for: selectedInterval)
  283. )
  284. )
  285. )
  286. .chartXVisibleDomain(length: StatChartUtils.visibleDomainLength(for: selectedInterval))
  287. .frame(height: 280)
  288. }
  289. }
  290. private struct BolusSelectionPopover: View {
  291. let selectedDate: Date
  292. let bolus: BolusStats
  293. let selectedInterval: Stat.StateModel.StatsTimeInterval
  294. let domain: (start: Date, end: Date)
  295. let chartWidth: CGFloat
  296. @State private var popoverSize: CGSize = .zero
  297. @Environment(\.colorScheme) var colorScheme
  298. private var timeText: String {
  299. if selectedInterval == .day {
  300. let hour = Calendar.current.component(.hour, from: selectedDate)
  301. return selectedDate.formatted(.dateTime.month().day().weekday()) + "\n" + "\(hour):00-\(hour + 1):00"
  302. } else {
  303. return selectedDate.formatted(.dateTime.month().day().weekday())
  304. }
  305. }
  306. private func xOffset() -> CGFloat {
  307. // If the selected date is outside the visible domain, hide the popover
  308. guard selectedDate >= domain.start && selectedDate <= domain.end else { return 0 }
  309. let domainDuration = domain.end.timeIntervalSince(domain.start)
  310. guard domainDuration > 0, chartWidth > 0 else { return 0 }
  311. let popoverWidth = popoverSize.width
  312. let padding: CGFloat = 10 // Padding from screen edges
  313. // Convert dates to pixel'd x-position
  314. let dateFraction = selectedDate.timeIntervalSince(domain.start) / domainDuration
  315. let x_selected = dateFraction * chartWidth
  316. // Calculate popover edges
  317. let x_left = x_selected - (popoverWidth / 2)
  318. let x_right = x_selected + (popoverWidth / 2)
  319. var offset: CGFloat = 0
  320. // Ensure the popover stays within screen bounds
  321. if x_left < padding {
  322. // Popover would extend past left edge, shift it right
  323. offset = padding - x_left
  324. } else if x_right > chartWidth - padding {
  325. // Popover would extend past right edge, shift it left
  326. offset = (chartWidth - padding) - x_right
  327. }
  328. return offset
  329. }
  330. var body: some View {
  331. VStack(alignment: .leading, spacing: 4) {
  332. Text(timeText)
  333. .font(.subheadline)
  334. .bold()
  335. .foregroundStyle(Color.secondary)
  336. Grid(alignment: .leading) {
  337. Divider()
  338. GridRow {
  339. Text("Manual:")
  340. Text(bolus.manualBolus.formatted(.number.precision(.fractionLength(1))))
  341. .gridColumnAlignment(.trailing).bold()
  342. Text("U").foregroundStyle(Color.secondary)
  343. }
  344. GridRow {
  345. Text("SMB:")
  346. Text(bolus.smb.formatted(.number.precision(.fractionLength(1))))
  347. .gridColumnAlignment(.trailing).bold()
  348. Text("U").foregroundStyle(Color.secondary)
  349. }
  350. GridRow {
  351. Text("External:")
  352. Text(bolus.external.formatted(.number.precision(.fractionLength(1))))
  353. .gridColumnAlignment(.trailing).bold()
  354. Text("U").foregroundStyle(Color.secondary)
  355. }
  356. Divider()
  357. GridRow {
  358. Text("Total:")
  359. Text(
  360. (bolus.manualBolus + bolus.smb + bolus.external).formatted(.number.precision(.fractionLength(1)))
  361. ).bold()
  362. Text("U").foregroundStyle(Color.secondary)
  363. }
  364. }
  365. .font(.headline)
  366. }
  367. .padding(20)
  368. .background {
  369. RoundedRectangle(cornerRadius: 10)
  370. .fill(colorScheme == .dark ? Color.bgDarkBlue.opacity(0.9) : Color.white.opacity(0.95))
  371. .shadow(color: Color.secondary, radius: 2)
  372. .overlay(
  373. RoundedRectangle(cornerRadius: 4)
  374. .stroke(Color.blue, lineWidth: 2)
  375. )
  376. }
  377. .frame(minWidth: 180, maxWidth: .infinity) // Ensures proper width
  378. .background(
  379. GeometryReader { geo in
  380. Color.clear
  381. .onAppear { popoverSize = geo.size }
  382. .onChange(of: geo.size) { _, newValue in popoverSize = newValue }
  383. }
  384. )
  385. // Apply calculated xOffset to keep within bounds
  386. .offset(x: xOffset(), y: 0)
  387. // Hide popover if selected date is outside visible domain
  388. .opacity(selectedDate >= domain.start && selectedDate <= domain.end ? 1 : 0)
  389. }
  390. }