MealStatsView.swift 17 KB

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