BolusStatsView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. updateCalculatedValues()
  114. }
  115. .onChange(of: scrollPosition) {
  116. updateTimer.scheduleUpdate {
  117. updateCalculatedValues()
  118. }
  119. }
  120. .onChange(of: selectedInterval) {
  121. Task {
  122. scrollPosition = StatChartUtils.getInitialScrollPosition(for: selectedInterval)
  123. updateCalculatedValues()
  124. }
  125. }
  126. }
  127. /// A view displaying the bar chart for bolus insulin statistics.
  128. private var chartsView: some View {
  129. Chart {
  130. ForEach(bolusStats) { stat in
  131. // Total Bolus Bar
  132. BarMark(
  133. x: .value("Date", stat.date, unit: selectedInterval == .day ? .hour : .day),
  134. y: .value("Amount", stat.manualBolus)
  135. )
  136. .foregroundStyle(by: .value("Type", "Manual"))
  137. .position(by: .value("Type", "Boluses"))
  138. .opacity(
  139. selectedDate.map { date in
  140. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedInterval) ? 1 : 0.3
  141. } ?? 1
  142. )
  143. // Carb Bolus Bar
  144. BarMark(
  145. x: .value("Date", stat.date, unit: selectedInterval == .day ? .hour : .day),
  146. y: .value("Amount", stat.smb)
  147. )
  148. .foregroundStyle(by: .value("Type", "SMB"))
  149. .position(by: .value("Type", "Boluses"))
  150. .opacity(
  151. selectedDate.map { date in
  152. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedInterval) ? 1 : 0.3
  153. } ?? 1
  154. )
  155. // Correction Bolus Bar
  156. BarMark(
  157. x: .value("Date", stat.date, unit: selectedInterval == .day ? .hour : .day),
  158. y: .value("Amount", stat.external)
  159. )
  160. .foregroundStyle(by: .value("Type", "External"))
  161. .position(by: .value("Type", "Boluses"))
  162. .opacity(
  163. selectedDate.map { date in
  164. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedInterval) ? 1 : 0.3
  165. } ?? 1
  166. )
  167. }
  168. // Dummy PointMark to force SwiftCharts to render a visible domain of 00:00-23:59
  169. // i.e. single day from midnight to midnight
  170. if selectedInterval == .day {
  171. let calendar = Calendar.current
  172. let midnight = calendar.startOfDay(for: Date())
  173. let nextMidnight = calendar.date(byAdding: .day, value: 1, to: midnight)!
  174. PointMark(
  175. x: .value("Time", nextMidnight),
  176. y: .value("Dummy", 0)
  177. )
  178. .opacity(0) // ensures dummy ChartContent is hidden
  179. }
  180. // Selection popover outside of the ForEach loop!
  181. if let selectedDate, let selectedBolus = getBolusForDate(selectedDate)
  182. {
  183. RuleMark(
  184. x: .value("Selected Date", selectedDate)
  185. )
  186. .foregroundStyle(Color.insulin.opacity(0.5))
  187. .annotation(
  188. position: .overlay,
  189. alignment: .top,
  190. spacing: 0,
  191. overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
  192. ) { _ in
  193. BolusSelectionPopover(
  194. selectedDate: selectedDate,
  195. bolus: selectedBolus,
  196. selectedInterval: selectedInterval,
  197. domain: visibleDateRange,
  198. chartWidth: chartWidth
  199. )
  200. }
  201. }
  202. }
  203. .chartForegroundStyleScale([
  204. "SMB": Color.blue,
  205. "Manual": Color.teal,
  206. "External": Color.purple
  207. ])
  208. .chartLegend(position: .bottom, alignment: .leading, spacing: 12) {
  209. let legendItems: [(String, Color)] = [
  210. (String(localized: "SMB"), Color.blue),
  211. (String(localized: "Manual"), Color.teal),
  212. (String(localized: "External"), Color.purple)
  213. ]
  214. let columns = [GridItem(.adaptive(minimum: 65), spacing: 4)]
  215. LazyVGrid(columns: columns, alignment: .leading, spacing: 4) {
  216. ForEach(legendItems, id: \.0) { item in
  217. StatChartUtils.legendItem(label: item.0, color: item.1)
  218. }
  219. }
  220. }
  221. .chartYAxis {
  222. AxisMarks(position: .trailing) { value in
  223. if let amount = value.as(Double.self) {
  224. AxisValueLabel {
  225. Text(amount.formatted(.number.precision(.fractionLength(0))))
  226. .font(.footnote)
  227. }
  228. AxisGridLine()
  229. }
  230. }
  231. }
  232. .chartXAxis {
  233. AxisMarks(preset: .aligned, values: .stride(by: selectedInterval == .day ? .hour : .day)) { value in
  234. if let date = value.as(Date.self) {
  235. switch selectedInterval {
  236. case .day:
  237. let hour = Calendar.current.component(.hour, from: date)
  238. if hour % 6 == 0 { // Show only every 6 hours
  239. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  240. .font(.footnote)
  241. AxisGridLine()
  242. }
  243. case .month:
  244. let weekday = calendar.component(.weekday, from: date)
  245. if weekday == calendar.firstWeekday { // Only show the first day of the week
  246. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  247. .font(.footnote)
  248. AxisGridLine()
  249. }
  250. case .total:
  251. // Only show every other month
  252. let day = Calendar.current.component(.day, from: date)
  253. if day == 1 && Calendar.current.component(.month, from: date) % 2 == 1 {
  254. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  255. .font(.footnote)
  256. AxisGridLine()
  257. }
  258. default:
  259. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  260. .font(.footnote)
  261. AxisGridLine()
  262. }
  263. }
  264. }
  265. }
  266. .chartXSelection(value: $selectedDate.animation(.easeInOut))
  267. .chartScrollableAxes(.horizontal)
  268. .chartScrollPosition(x: $scrollPosition)
  269. .chartScrollTargetBehavior(
  270. .valueAligned(
  271. matching:
  272. selectedInterval == .day ?
  273. DateComponents(minute: 0) : // Align to next hour for Day view
  274. DateComponents(hour: 0), // Align to start of day for other views
  275. majorAlignment: .matching(
  276. StatChartUtils.alignmentComponents(for: selectedInterval)
  277. )
  278. )
  279. )
  280. .chartXVisibleDomain(length: StatChartUtils.visibleDomainLength(for: selectedInterval))
  281. .frame(height: 280)
  282. }
  283. }
  284. private struct BolusSelectionPopover: View {
  285. let selectedDate: Date
  286. let bolus: BolusStats
  287. let selectedInterval: Stat.StateModel.StatsTimeInterval
  288. let domain: (start: Date, end: Date)
  289. let chartWidth: CGFloat
  290. @State private var popoverSize: CGSize = .zero
  291. @Environment(\.colorScheme) var colorScheme
  292. private var timeText: String {
  293. if selectedInterval == .day {
  294. let hour = Calendar.current.component(.hour, from: selectedDate)
  295. return selectedDate.formatted(.dateTime.month().day().weekday()) + "\n" + "\(hour):00-\(hour + 1):00"
  296. } else {
  297. return selectedDate.formatted(.dateTime.month().day().weekday())
  298. }
  299. }
  300. private func xOffset() -> CGFloat {
  301. // If the selected date is outside the visible domain, hide the popover
  302. guard selectedDate >= domain.start && selectedDate <= domain.end else { return 0 }
  303. let domainDuration = domain.end.timeIntervalSince(domain.start)
  304. guard domainDuration > 0, chartWidth > 0 else { return 0 }
  305. let popoverWidth = popoverSize.width
  306. let padding: CGFloat = 10 // Padding from screen edges
  307. // Convert dates to pixel'd x-position
  308. let dateFraction = selectedDate.timeIntervalSince(domain.start) / domainDuration
  309. let x_selected = dateFraction * chartWidth
  310. // Calculate popover edges
  311. let x_left = x_selected - (popoverWidth / 2)
  312. let x_right = x_selected + (popoverWidth / 2)
  313. var offset: CGFloat = 0
  314. // Ensure the popover stays within screen bounds
  315. if x_left < padding {
  316. // Popover would extend past left edge, shift it right
  317. offset = padding - x_left
  318. } else if x_right > chartWidth - padding {
  319. // Popover would extend past right edge, shift it left
  320. offset = (chartWidth - padding) - x_right
  321. }
  322. return offset
  323. }
  324. var body: some View {
  325. VStack(alignment: .leading, spacing: 4) {
  326. Text(timeText)
  327. .font(.subheadline)
  328. .bold()
  329. .foregroundStyle(Color.secondary)
  330. Grid(alignment: .leading) {
  331. Divider()
  332. GridRow {
  333. Text("Manual:")
  334. Text(bolus.manualBolus.formatted(.number.precision(.fractionLength(1))))
  335. .gridColumnAlignment(.trailing).bold()
  336. Text("U").foregroundStyle(Color.secondary)
  337. }
  338. GridRow {
  339. Text("SMB:")
  340. Text(bolus.smb.formatted(.number.precision(.fractionLength(1))))
  341. .gridColumnAlignment(.trailing).bold()
  342. Text("U").foregroundStyle(Color.secondary)
  343. }
  344. GridRow {
  345. Text("External:")
  346. Text(bolus.external.formatted(.number.precision(.fractionLength(1))))
  347. .gridColumnAlignment(.trailing).bold()
  348. Text("U").foregroundStyle(Color.secondary)
  349. }
  350. Divider()
  351. GridRow {
  352. Text("Total:")
  353. Text(
  354. (bolus.manualBolus + bolus.smb + bolus.external).formatted(.number.precision(.fractionLength(1)))
  355. ).bold()
  356. Text("U").foregroundStyle(Color.secondary)
  357. }
  358. }
  359. .font(.headline)
  360. }
  361. .padding(20)
  362. .background {
  363. RoundedRectangle(cornerRadius: 10)
  364. .fill(colorScheme == .dark ? Color.bgDarkBlue.opacity(0.9) : Color.white.opacity(0.95))
  365. .shadow(color: Color.secondary, radius: 2)
  366. .overlay(
  367. RoundedRectangle(cornerRadius: 4)
  368. .stroke(Color.blue, lineWidth: 2)
  369. )
  370. }
  371. .frame(minWidth: 180, maxWidth: .infinity) // Ensures proper width
  372. .background(
  373. GeometryReader { geo in
  374. Color.clear
  375. .onAppear { popoverSize = geo.size }
  376. .onChange(of: geo.size) { _, newValue in popoverSize = newValue }
  377. }
  378. )
  379. // Apply calculated xOffset to keep within bounds
  380. .offset(x: xOffset(), y: 0)
  381. // Hide popover if selected date is outside visible domain
  382. .opacity(selectedDate >= domain.start && selectedDate <= domain.end ? 1 : 0)
  383. }
  384. }