| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422 |
- import Charts
- import SwiftUI
- struct BolusStatsView: View {
- @Binding var selectedDuration: Stat.StateModel.StatsTimeInterval
- let bolusStats: [BolusStats]
- let state: Stat.StateModel
- @State private var scrollPosition = Date() // gets updated in onAppear block
- @State private var selectedDate: Date?
- @State private var currentAverages: (manual: Double, smb: Double, external: Double) = (0, 0, 0)
- @State private var updateTimer = Stat.UpdateTimer()
- /// Returns the time interval length for the visible domain based on selected duration
- private var visibleDomainLength: TimeInterval {
- switch selectedDuration {
- case .Day: return 24 * 3600 // One day in seconds
- case .Week: return 7 * 24 * 3600 // One week in seconds
- case .Month: return 30 * 24 * 3600 // One month in seconds
- case .Total: return 90 * 24 * 3600 // Three months in seconds
- }
- }
- /// Calculates the visible date range based on scroll position and domain length
- private var visibleDateRange: (start: Date, end: Date) {
- let start = scrollPosition // Current scroll position marks the start
- let end = start.addingTimeInterval(visibleDomainLength)
- return (start, end)
- }
- /// Returns the appropriate date format style based on the selected time interval
- private var dateFormat: Date.FormatStyle {
- switch selectedDuration {
- case .Day:
- return .dateTime.hour()
- case .Week:
- return .dateTime.weekday(.abbreviated)
- case .Month:
- return .dateTime.day()
- case .Total:
- return .dateTime.month(.abbreviated)
- }
- }
- /// Returns DateComponents for aligning dates based on the selected duration
- private var alignmentComponents: DateComponents {
- switch selectedDuration {
- case .Day:
- return DateComponents(hour: 0) // Align to midnight
- case .Week:
- return DateComponents(weekday: 2) // Monday is weekday 2
- case .Month,
- .Total:
- return DateComponents(day: 1) // First day of month
- }
- }
- /// Returns bolus statistics for a specific date
- private func getBolusForDate(_ date: Date) -> BolusStats? {
- let calendar = Calendar.current
- return bolusStats.first { stat in
- switch selectedDuration {
- case .Day:
- return calendar.isDate(stat.date, equalTo: date, toGranularity: .hour)
- default:
- return calendar.isDate(stat.date, inSameDayAs: date)
- }
- }
- }
- /// Updates the current averages for bolus insulin based on the visible date range
- private func updateAverages() {
- currentAverages = state.getCachedBolusAverages(for: visibleDateRange)
- }
- /// Formats the visible date range into a human-readable string
- private func formatVisibleDateRange() -> String {
- let start = visibleDateRange.start
- let end = visibleDateRange.end
- let calendar = Calendar.current
- let today = Date()
- // Special handling for Day view with relative dates
- if selectedDuration == .Day {
- let startDateText: String
- let endDateText: String
- let timeFormat = start.formatted(.dateTime.hour().minute())
- // Format start date
- if calendar.isDate(start, inSameDayAs: today) {
- startDateText = "Today"
- } else if calendar.isDate(start, inSameDayAs: calendar.date(byAdding: .day, value: -1, to: today)!) {
- startDateText = "Yesterday"
- } else if calendar.isDate(start, inSameDayAs: calendar.date(byAdding: .day, value: 1, to: today)!) {
- startDateText = "Tomorrow"
- } else {
- startDateText = start.formatted(.dateTime.day().month())
- }
- // Format end date
- if calendar.isDate(end, inSameDayAs: today) {
- endDateText = "Today"
- } else if calendar.isDate(end, inSameDayAs: calendar.date(byAdding: .day, value: -1, to: today)!) {
- endDateText = "Yesterday"
- } else if calendar.isDate(end, inSameDayAs: calendar.date(byAdding: .day, value: 1, to: today)!) {
- endDateText = "Tomorrow"
- } else {
- endDateText = end.formatted(.dateTime.day().month())
- }
- // If start and end are on the same day, show date only once
- if calendar.isDate(start, inSameDayAs: end) {
- return "\(startDateText), \(timeFormat) - \(end.formatted(.dateTime.hour().minute()))"
- }
- return "\(startDateText), \(timeFormat) - \(endDateText), \(end.formatted(.dateTime.hour().minute()))"
- }
- // Standard format for other views - only show dates without time
- let startText: String
- let endText: String
- // Check for relative dates
- if calendar.isDate(start, inSameDayAs: today) {
- startText = "Today"
- } else if calendar.isDate(start, inSameDayAs: calendar.date(byAdding: .day, value: -1, to: today)!) {
- startText = "Yesterday"
- } else if calendar.isDate(start, inSameDayAs: calendar.date(byAdding: .day, value: 1, to: today)!) {
- startText = "Tomorrow"
- } else {
- startText = start.formatted(.dateTime.day().month())
- }
- if calendar.isDate(end, inSameDayAs: today) {
- endText = "Today"
- } else if calendar.isDate(end, inSameDayAs: calendar.date(byAdding: .day, value: -1, to: today)!) {
- endText = "Yesterday"
- } else if calendar.isDate(end, inSameDayAs: calendar.date(byAdding: .day, value: 1, to: today)!) {
- endText = "Tomorrow"
- } else {
- endText = end.formatted(.dateTime.day().month())
- }
- return "\(startText) - \(endText)"
- }
- private func isSameTimeUnit(_ date1: Date, _ date2: Date) -> Bool {
- switch selectedDuration {
- case .Day:
- return Calendar.current.isDate(date1, equalTo: date2, toGranularity: .hour)
- default:
- return Calendar.current.isDate(date1, inSameDayAs: date2)
- }
- }
- /// Returns the initial scroll position date based on the selected duration
- private func getInitialScrollPosition() -> Date {
- let calendar = Calendar.current
- let now = Date()
- switch selectedDuration {
- case .Day:
- return calendar.date(byAdding: .day, value: -1, to: now)!
- case .Week:
- return calendar.date(byAdding: .day, value: -7, to: now)!
- case .Month:
- return calendar.date(byAdding: .month, value: -1, to: now)!
- case .Total:
- return calendar.date(byAdding: .month, value: -3, to: now)!
- }
- }
- var body: some View {
- VStack(alignment: .leading, spacing: 8) {
- statsView
- chartsView
- }
- .onAppear {
- scrollPosition = getInitialScrollPosition()
- updateAverages()
- }
- .onChange(of: scrollPosition) {
- updateTimer.scheduleUpdate {
- updateAverages()
- }
- }
- .onChange(of: selectedDuration) {
- Task {
- scrollPosition = getInitialScrollPosition()
- updateAverages()
- }
- }
- }
- private var statsView: some View {
- HStack {
- Grid(alignment: .leading) {
- GridRow {
- Text("Manual:")
- .font(.headline)
- .foregroundStyle(.secondary)
- Text(currentAverages.manual.formatted(.number.precision(.fractionLength(1))))
- .font(.headline)
- .foregroundStyle(.secondary)
- .gridColumnAlignment(.trailing)
- Text("U")
- .font(.headline)
- .foregroundStyle(.secondary)
- }
- GridRow {
- Text("SMB:")
- .font(.headline)
- .foregroundStyle(.secondary)
- Text(currentAverages.smb.formatted(.number.precision(.fractionLength(1))))
- .font(.headline)
- .foregroundStyle(.secondary)
- .gridColumnAlignment(.trailing)
- Text("U")
- .font(.headline)
- .foregroundStyle(.secondary)
- }
- GridRow {
- Text("External:")
- .font(.headline)
- .foregroundStyle(.secondary)
- Text(currentAverages.external.formatted(.number.precision(.fractionLength(1))))
- .font(.headline)
- .foregroundStyle(.secondary)
- .gridColumnAlignment(.trailing)
- Text("U")
- .font(.headline)
- .foregroundStyle(.secondary)
- }
- }
- Spacer()
- Text(formatVisibleDateRange())
- .font(.footnote)
- .foregroundStyle(.secondary)
- }
- }
- private var chartsView: some View {
- Chart {
- ForEach(bolusStats) { stat in
- // Total Bolus Bar
- BarMark(
- x: .value("Date", stat.date, unit: selectedDuration == .Day ? .hour : .day),
- y: .value("Amount", stat.manualBolus)
- )
- .foregroundStyle(by: .value("Type", "Manual"))
- .position(by: .value("Type", "Boluses"))
- .opacity(
- selectedDate.map { date in
- isSameTimeUnit(stat.date, date) ? 1 : 0.3
- } ?? 1
- )
- // Carb Bolus Bar
- BarMark(
- x: .value("Date", stat.date, unit: selectedDuration == .Day ? .hour : .day),
- y: .value("Amount", stat.smb)
- )
- .foregroundStyle(by: .value("Type", "SMB"))
- .position(by: .value("Type", "Boluses"))
- .opacity(
- selectedDate.map { date in
- isSameTimeUnit(stat.date, date) ? 1 : 0.3
- } ?? 1
- )
- // Correction Bolus Bar
- BarMark(
- x: .value("Date", stat.date, unit: selectedDuration == .Day ? .hour : .day),
- y: .value("Amount", stat.external)
- )
- .foregroundStyle(by: .value("Type", "External"))
- .position(by: .value("Type", "Boluses"))
- .opacity(
- selectedDate.map { date in
- isSameTimeUnit(stat.date, date) ? 1 : 0.3
- } ?? 1
- )
- }
- // Selection popover outside of the ForEach loop!
- if let selectedDate, let selectedBolus = getBolusForDate(selectedDate)
- {
- RuleMark(
- x: .value("Selected Date", selectedDate)
- )
- .foregroundStyle(.secondary.opacity(0.5))
- .annotation(
- position: .top,
- spacing: 0,
- overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
- ) {
- BolusSelectionPopover(date: selectedDate, bolus: selectedBolus, selectedDuration: selectedDuration)
- }
- }
- }
- .chartForegroundStyleScale([
- "SMB": Color.blue,
- "Manual": Color.teal,
- "External": Color.purple
- ])
- .chartLegend(position: .bottom, alignment: .leading, spacing: 12)
- .chartYAxis {
- AxisMarks(position: .trailing) { value in
- if let amount = value.as(Double.self) {
- AxisValueLabel {
- Text(amount.formatted(.number.precision(.fractionLength(0))) + " U")
- .font(.footnote)
- }
- AxisGridLine()
- }
- }
- }
- .chartXAxis {
- AxisMarks(preset: .aligned, values: .stride(by: selectedDuration == .Day ? .hour : .day)) { value in
- if let date = value.as(Date.self) {
- let day = Calendar.current.component(.day, from: date)
- let hour = Calendar.current.component(.hour, from: date)
- switch selectedDuration {
- case .Day:
- if hour % 6 == 0 { // Show only every 6 hours
- AxisValueLabel(format: dateFormat, centered: true)
- .font(.footnote)
- AxisGridLine()
- }
- case .Month:
- if day % 5 == 0 { // Only show every 5th day
- AxisValueLabel(format: dateFormat, centered: true)
- .font(.footnote)
- AxisGridLine()
- }
- case .Total:
- // Only show January, April, July, October
- if day == 1 && Calendar.current.component(.month, from: date) % 3 == 1 {
- AxisValueLabel(format: dateFormat, centered: true)
- .font(.footnote)
- AxisGridLine()
- }
- default:
- AxisValueLabel(format: dateFormat, centered: true)
- .font(.footnote)
- AxisGridLine()
- }
- }
- }
- }
- .chartScrollableAxes(.horizontal)
- .chartXSelection(value: $selectedDate.animation(.easeInOut))
- .chartScrollPosition(x: $scrollPosition)
- .chartScrollTargetBehavior(
- .valueAligned(
- matching: selectedDuration == .Day ?
- DateComponents(minute: 0) : // Align to next hour for Day view
- DateComponents(hour: 0), // Align to start of day for other views
- majorAlignment: .matching(
- alignmentComponents
- )
- )
- )
- .chartXVisibleDomain(length: visibleDomainLength)
- .frame(height: 250)
- }
- }
- private struct BolusSelectionPopover: View {
- let date: Date
- let bolus: BolusStats
- let selectedDuration: Stat.StateModel.StatsTimeInterval
- private var timeText: String {
- if selectedDuration == .Day {
- let hour = Calendar.current.component(.hour, from: date)
- return "\(hour):00-\(hour + 1):00"
- } else {
- return date.formatted(.dateTime.month().day())
- }
- }
- var body: some View {
- VStack(alignment: .leading, spacing: 4) {
- Text(timeText)
- .font(.footnote)
- .fontWeight(.bold)
- Grid(alignment: .leading) {
- GridRow {
- Text("Manual:")
- Text(bolus.manualBolus.formatted(.number.precision(.fractionLength(1))))
- .gridColumnAlignment(.trailing)
- Text("U")
- }
- GridRow {
- Text("SMB:")
- Text(bolus.smb.formatted(.number.precision(.fractionLength(1))))
- .gridColumnAlignment(.trailing)
- Text("U")
- }
- GridRow {
- Text("External:")
- Text(bolus.external.formatted(.number.precision(.fractionLength(1))))
- .gridColumnAlignment(.trailing)
- Text("U")
- }
- }
- .font(.headline.bold())
- }
- .foregroundStyle(.white)
- .padding(20)
- .background(
- RoundedRectangle(cornerRadius: 10)
- .fill(Color.blue.gradient)
- )
- }
- }
|