TotalDailyDoseChart.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import Charts
  2. import SwiftUI
  3. /// A view that displays a bar chart for Total Daily Dose (TDD) statistics.
  4. ///
  5. /// This view presents insulin usage over time, with the ability to adjust the time interval
  6. /// and scroll through historical data.
  7. struct TotalDailyDoseChart: View {
  8. /// The selected time interval for displaying statistics.
  9. @Binding var selectedInterval: Stat.StateModel.StatsTimeInterval
  10. /// The list of TDD statistics data.
  11. let tddStats: [TDDStats]
  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 average TDD for the visible range.
  19. @State private var currentAverage: Double = 0
  20. /// Timer to throttle updates when scrolling.
  21. @State private var updateTimer = Stat.UpdateTimer()
  22. /// Sum of hourly doses for `Day` view
  23. @State private var sumOfHourlyDoses: Double = 0
  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 TDD statistic for a given date.
  31. /// - Parameter date: The date for which to retrieve TDD data.
  32. /// - Returns: The `TDDStats` object if available, otherwise `nil`.
  33. private func getTDDForDate(_ date: Date) -> TDDStats? {
  34. tddStats.first { stat in
  35. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedInterval)
  36. }
  37. }
  38. /// Updates the average TDD value based on the visible date range.
  39. private func updateAverages() {
  40. currentAverage = state.getCachedTDDAverages(for: visibleDateRange)
  41. }
  42. /// Updates the total of hourly doses for `Day` view
  43. private func updateTotalDoses() {
  44. sumOfHourlyDoses = tddStats.filter({ $0.date >= visibleDateRange.start && $0.date <= visibleDateRange.end })
  45. .reduce(0, { result, stat in
  46. result + stat.amount
  47. })
  48. }
  49. var body: some View {
  50. VStack(alignment: .leading, spacing: 8) {
  51. statsView.padding(.bottom)
  52. VStack(alignment: .trailing) {
  53. Text("Total Daily Dose (U)")
  54. .foregroundStyle(.secondary)
  55. .font(.footnote)
  56. .padding(.bottom, 4)
  57. chartsView
  58. .background(
  59. GeometryReader { geo in
  60. Color.clear
  61. .onAppear { chartWidth = geo.size.width }
  62. .onChange(of: geo.size.width) { _, newValue in chartWidth = newValue }
  63. }
  64. )
  65. }
  66. }
  67. .onAppear {
  68. scrollPosition = StatChartUtils.getInitialScrollPosition(for: selectedInterval)
  69. updateAverages()
  70. updateTotalDoses()
  71. }
  72. .onChange(of: scrollPosition) {
  73. updateTimer.scheduleUpdate {
  74. updateAverages()
  75. if selectedInterval == .day {
  76. updateTotalDoses()
  77. }
  78. }
  79. }
  80. .onChange(of: selectedInterval) {
  81. Task {
  82. scrollPosition = StatChartUtils.getInitialScrollPosition(for: selectedInterval)
  83. updateAverages()
  84. if selectedInterval == .day {
  85. updateTotalDoses()
  86. }
  87. }
  88. }
  89. }
  90. /// A view displaying the statistics summary including average TDD.
  91. private var statsView: some View {
  92. HStack {
  93. if selectedInterval == .day {
  94. Grid(alignment: .leading) {
  95. GridRow {
  96. Text("Average:")
  97. Text(currentAverage.formatted(.number.precision(.fractionLength(1))))
  98. + Text("\u{00A0}") + Text("U")
  99. }
  100. GridRow {
  101. Text("Total:")
  102. Text(sumOfHourlyDoses.formatted(.number.precision(.fractionLength(1))))
  103. + Text("\u{00A0}") + Text("U")
  104. }
  105. }
  106. .font(.headline)
  107. } else {
  108. Group {
  109. Text("Average:")
  110. Text(currentAverage.formatted(.number.precision(.fractionLength(1))))
  111. + Text("\u{00A0}") + Text("U")
  112. }
  113. .font(.headline)
  114. }
  115. Spacer()
  116. Text(
  117. StatChartUtils
  118. .formatVisibleDateRange(from: visibleDateRange.start, to: visibleDateRange.end, for: selectedInterval)
  119. )
  120. .font(.callout)
  121. .foregroundStyle(.secondary)
  122. }
  123. }
  124. /// A view displaying the bar chart for TDD statistics.
  125. private var chartsView: some View {
  126. Chart {
  127. ForEach(tddStats) { stat in
  128. BarMark(
  129. x: .value("Date", stat.date, unit: selectedInterval == .day ? .hour : .day),
  130. y: .value("Amount", stat.amount)
  131. )
  132. .foregroundStyle(Color.insulin)
  133. .opacity(
  134. selectedDate.map { date in
  135. StatChartUtils.isSameTimeUnit(stat.date, date, for: selectedInterval) ? 1 : 0.3
  136. } ?? 1
  137. )
  138. }
  139. // Selection popover outside of the ForEach loop!
  140. if let selectedDate,
  141. let selectedTDD = getTDDForDate(selectedDate)
  142. {
  143. RuleMark(
  144. x: .value("Selected Date", selectedDate)
  145. )
  146. .foregroundStyle(Color.insulin.opacity(0.5))
  147. .annotation(
  148. position: .top,
  149. spacing: 0,
  150. overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
  151. ) {
  152. TDDSelectionPopover(
  153. selectedDate: selectedDate,
  154. tdd: selectedTDD,
  155. selectedInterval: selectedInterval,
  156. domain: visibleDateRange,
  157. chartWidth: chartWidth
  158. )
  159. }
  160. }
  161. // Dummy PointMark to force SwiftCharts to render a visible domain of 00:00-23:59
  162. // i.e. single day from midnight to midnight
  163. if selectedInterval == .day {
  164. let calendar = Calendar.current
  165. let midnight = calendar.startOfDay(for: Date())
  166. let nextMidnight = calendar.date(byAdding: .day, value: 1, to: midnight)!
  167. PointMark(
  168. x: .value("Time", nextMidnight),
  169. y: .value("Dummy", 0)
  170. )
  171. .opacity(0) // ensures dummy ChartContent is hidden
  172. }
  173. }
  174. .chartYAxis {
  175. AxisMarks(position: .trailing) { value in
  176. if let amount = value.as(Double.self) {
  177. AxisValueLabel {
  178. Text(amount.formatted(.number.precision(.fractionLength(0))))
  179. .font(.footnote)
  180. }
  181. AxisGridLine()
  182. }
  183. }
  184. }
  185. .chartXAxis {
  186. AxisMarks(preset: .aligned, values: .stride(by: selectedInterval == .day ? .hour : .day)) { value in
  187. if let date = value.as(Date.self) {
  188. let day = Calendar.current.component(.day, from: date)
  189. let hour = Calendar.current.component(.hour, from: date)
  190. switch selectedInterval {
  191. case .day:
  192. if hour % 6 == 0 { // Show only every 6 hours
  193. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  194. .font(.footnote)
  195. AxisGridLine()
  196. }
  197. case .month:
  198. let weekday = calendar.component(.weekday, from: date)
  199. if weekday == calendar.firstWeekday { // Only show the first day of the week
  200. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  201. .font(.footnote)
  202. AxisGridLine()
  203. }
  204. case .total:
  205. // Only show every other month
  206. if day == 1 && Calendar.current.component(.month, from: date) % 2 == 1 {
  207. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  208. .font(.footnote)
  209. AxisGridLine()
  210. }
  211. default:
  212. AxisValueLabel(format: StatChartUtils.dateFormat(for: selectedInterval), centered: true)
  213. .font(.footnote)
  214. AxisGridLine()
  215. }
  216. }
  217. }
  218. }
  219. .chartScrollableAxes(.horizontal)
  220. .chartXSelection(value: $selectedDate.animation(.easeInOut))
  221. .chartScrollPosition(x: $scrollPosition)
  222. .chartScrollTargetBehavior(
  223. .valueAligned(
  224. matching: selectedInterval == .day ?
  225. DateComponents(minute: 0) :
  226. DateComponents(hour: 0),
  227. majorAlignment: .matching(StatChartUtils.alignmentComponents(for: selectedInterval))
  228. )
  229. )
  230. .chartXVisibleDomain(length: StatChartUtils.visibleDomainLength(for: selectedInterval))
  231. .frame(height: 250)
  232. }
  233. }
  234. /// A popover view displaying TDD (Total Daily Dose) for a given time period.
  235. /// Shows the insulin amount in units (U) for an hourly or daily interval, depending on `selectedInterval`.
  236. ///
  237. /// - Parameters:
  238. /// - date: The reference date for determining the displayed time range.
  239. /// - tdd: The TDDStats containing insulin usage data.
  240. /// - selectedInterval: The selected time interval (hourly or daily).
  241. private struct TDDSelectionPopover: View {
  242. let selectedDate: Date
  243. let tdd: TDDStats
  244. let selectedInterval: Stat.StateModel.StatsTimeInterval
  245. let domain: (start: Date, end: Date)
  246. let chartWidth: CGFloat
  247. @State private var popoverSize: CGSize = .zero
  248. @Environment(\.colorScheme) var colorScheme
  249. private var timeText: String {
  250. if selectedInterval == .day {
  251. let hour = Calendar.current.component(.hour, from: selectedDate)
  252. return selectedDate.formatted(.dateTime.month().day().weekday()) + "\n" + "\(hour):00-\(hour + 1):00"
  253. } else {
  254. return selectedDate.formatted(.dateTime.month().day().weekday())
  255. }
  256. }
  257. private func xOffset() -> CGFloat {
  258. let domainDuration = domain.end.timeIntervalSince(domain.start)
  259. guard domainDuration > 0, chartWidth > 0 else { return 0 }
  260. let popoverWidth = popoverSize.width
  261. // Convert dates to pixel'd x-condition
  262. let dateFraction = selectedDate.timeIntervalSince(domain.start) / domainDuration
  263. let x_selected = dateFraction * chartWidth
  264. // TODO: this is semi hacky, can this be improved?
  265. let x_left = x_selected - (popoverWidth / 2) // Left edge of popover
  266. let x_right = x_selected + (popoverWidth / 2) // Right edge of popover
  267. var offset: CGFloat = 0 // Default = no shift
  268. // Push popover to right if its left edge is (nearing) out-of-bounds
  269. if x_left < 0 {
  270. offset = abs(x_left) // push to right
  271. }
  272. // Push popover to left if its right edge is (nearing) out-of-bounds)
  273. if x_right > chartWidth {
  274. offset = -(x_right - chartWidth) // push to left
  275. }
  276. return offset
  277. }
  278. var body: some View {
  279. VStack(alignment: .leading, spacing: 4) {
  280. Text(timeText)
  281. .font(.subheadline)
  282. .bold()
  283. .foregroundStyle(Color.secondary)
  284. Divider()
  285. HStack {
  286. Text(tdd.amount.formatted(.number.precision(.fractionLength(1))))
  287. Text("U").foregroundStyle(Color.secondary)
  288. }
  289. .font(.headline)
  290. }
  291. .padding(20)
  292. .background {
  293. RoundedRectangle(cornerRadius: 10)
  294. .fill(colorScheme == .dark ? Color.bgDarkBlue.opacity(0.9) : Color.white.opacity(0.95))
  295. .shadow(color: Color.secondary, radius: 2)
  296. .overlay(
  297. RoundedRectangle(cornerRadius: 4)
  298. .stroke(Color.blue, lineWidth: 2)
  299. )
  300. }
  301. .frame(minWidth: 100, maxWidth: .infinity) // Ensures proper width
  302. .background(
  303. GeometryReader { geo in
  304. Color.clear
  305. .onAppear { popoverSize = geo.size }
  306. .onChange(of: geo.size) { _, newValue in popoverSize = newValue }
  307. }
  308. )
  309. // Apply calculated xOffset to keep within bounds
  310. .offset(x: xOffset(), y: 0)
  311. }
  312. }