LoopBarChartView.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import Charts
  2. import SwiftUI
  3. struct LoopBarChartView: View {
  4. let loopStatRecords: [LoopStatRecord]
  5. let selectedInterval: Stat.StateModel.StatsTimeIntervalWithToday
  6. let statsData: [LoopStatsProcessedData]
  7. var body: some View {
  8. VStack(spacing: 20) {
  9. Chart(statsData, id: \.category) { data in
  10. BarMark(
  11. x: .value("Percentage", data.percentage),
  12. y: .value("Category", data.category.displayName)
  13. )
  14. .cornerRadius(5)
  15. .foregroundStyle(data.category == .successfulLoop ? Color.blue : Color.green)
  16. .annotation(position: .overlay) {
  17. HStack {
  18. Text(annotationText(for: data))
  19. .font(.callout)
  20. .foregroundStyle(.white)
  21. }
  22. }
  23. }
  24. .chartYAxis {
  25. AxisMarks { value in
  26. if let category = value.as(String.self) {
  27. AxisValueLabel {
  28. Text(category)
  29. .font(.footnote)
  30. }
  31. }
  32. }
  33. }
  34. .chartXAxis {
  35. AxisMarks(position: .bottom) { value in
  36. if let percentage = value.as(Double.self) {
  37. AxisValueLabel {
  38. Text("\(Int(percentage))%")
  39. .font(.footnote)
  40. }
  41. AxisGridLine()
  42. }
  43. }
  44. }
  45. .chartXScale(domain: 0 ... 100)
  46. .frame(height: 200)
  47. .padding()
  48. }
  49. }
  50. private func annotationText(for data: LoopStatsProcessedData) -> String {
  51. if data.category == .successfulLoop {
  52. switch selectedInterval {
  53. case .day,
  54. .today:
  55. return "\(data.count) " + String(localized: "Loops")
  56. case .month,
  57. .total,
  58. .week:
  59. return "\(data.count) " + String(localized: "Loops per Day")
  60. }
  61. } else {
  62. // For Glucose Count, show different text based on duration
  63. switch selectedInterval {
  64. case .day,
  65. .today:
  66. return "\(data.count) " + String(localized: "Readings")
  67. case .month,
  68. .total,
  69. .week:
  70. return "\(data.count) " + String(localized: "Readings per Day")
  71. }
  72. }
  73. }
  74. }