BolusStatsView.swift 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import Charts
  2. import SwiftUI
  3. struct BolusStatsView: View {
  4. let bolusStats: [BolusStats]
  5. @Binding var selectedDays: Int
  6. @Binding var selectedEndDate: Date
  7. private var hasData: Bool {
  8. bolusStats.contains { $0.manualBolus > 0 || $0.smb > 0 || $0.external > 0 }
  9. }
  10. var body: some View {
  11. if bolusStats.isEmpty || !hasData {
  12. ContentUnavailableView(
  13. "No Bolus Data",
  14. systemImage: "cross.vial",
  15. description: Text("Bolus statistics will appear here once data is available.")
  16. )
  17. } else {
  18. StatCard {
  19. VStack(alignment: .leading, spacing: 8) {
  20. Text("Bolus Distribution")
  21. .font(.headline)
  22. Chart(bolusStats) { stat in
  23. // External Bolus (Bottom)
  24. BarMark(
  25. x: .value("Date", stat.date, unit: .day),
  26. y: .value("Amount", stat.external)
  27. )
  28. .foregroundStyle(by: .value("Type", "External"))
  29. // SMB (Middle)
  30. BarMark(
  31. x: .value("Date", stat.date, unit: .day),
  32. y: .value("Amount", stat.smb)
  33. )
  34. .foregroundStyle(by: .value("Type", "SMB"))
  35. // Manual Bolus (Top)
  36. BarMark(
  37. x: .value("Date", stat.date, unit: .day),
  38. y: .value("Amount", stat.manualBolus)
  39. )
  40. .foregroundStyle(by: .value("Type", "Manual"))
  41. }
  42. .chartForegroundStyleScale([
  43. "Manual": Color.teal,
  44. "SMB": Color.blue,
  45. "External": Color.purple
  46. ])
  47. .chartLegend(position: .top, alignment: .leading, spacing: 12)
  48. .frame(height: 200)
  49. .chartXAxis {
  50. bolusStatsChartXAxisMarks
  51. }
  52. .chartYAxis {
  53. bolusStatsChartYAxisMarks
  54. }
  55. }
  56. }
  57. .padding()
  58. }
  59. }
  60. private var bolusStatsChartXAxisMarks: some AxisContent {
  61. AxisMarks { value in
  62. if let date = value.as(Date.self) {
  63. AxisValueLabel {
  64. if selectedDays < 8 {
  65. Text(date, format: .dateTime.weekday(.abbreviated))
  66. } else {
  67. Text(date, format: .dateTime.day().month(.defaultDigits))
  68. }
  69. }
  70. AxisGridLine()
  71. }
  72. }
  73. }
  74. private var bolusStatsChartYAxisMarks: some AxisContent {
  75. AxisMarks(position: .leading) { value in
  76. if let amount = value.as(Double.self) {
  77. AxisValueLabel {
  78. Text(amount.formatted(.number.precision(.fractionLength(1))) + " U")
  79. }
  80. AxisGridLine()
  81. }
  82. }
  83. }
  84. }