SPB Git

Repository Public License

SleepConsistencyCard.swift 7.1 KB 135 lines swift

1// ORIX Alarm2// File: App/Features/Sleep/SleepConsistencyCard.swift3// Description: Weekly overview: planned wake time against the recorded wake confirmation of each of the last seven days.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import Charts9import SwiftUI1011struct SleepConsistencyCard: View {12    @Environment(AppModel.self) private var model1314    private var use24h: Bool? { model.settings.use24HourClock }15    private func timeText(_ minute: Int) -> String { Fmt.timeString(ClockTime(minutesSinceMidnight: minute), use24h: use24h) }1617    var body: some View {18        let planned = model.sleepPlan.wakeTime19        let series = SleepPlanner.weeklyConsistency(events: model.events, plannedWake: planned, now: model.now(), calendar: model.calendar)20        let summary = SleepPlanner.summarize(series)21        VStack(alignment: .leading, spacing: 14) {22            Overline("This week")23            Text("Planned wake time and recorded confirmations").font(.orixHeadline)24            if summary.recordedDays == 0 {25                emptyState(planned: planned)26            } else {27                legend28                chart(series, planned: planned.minutesSinceMidnight)29                    .frame(height: 190)30                    .accessibilityElement(children: .ignore)31                    .accessibilityLabel("Chart: planned wake time and recorded wake confirmations over the last 7 days")32                    .accessibilityValue(spokenSummary(series, summary: summary))33                    .accessibilityIdentifier("sleep.consistency.chart")34                if let mean = summary.averageAbsoluteDeviation {35                    Text("Confirmed on \(summary.recordedDays) of \(series.count) days, on average \(Fmt.duration((mean.rounded()) * 60)) away from your planned \(timeText(planned.minutesSinceMidnight)). \(summary.daysWithinTolerance) within 15 minutes of it.")36                        .font(.orixCaption).foregroundStyle(Theme.textPrimary)37                        .accessibilityIdentifier("sleep.consistency.summary")38                }39            }40            Text("Each point is the time you tapped “I'm up” after an alarm, as recorded by the app. These are confirmations, not measured sleep or wake times, and days without a confirmation are left empty.")41                .font(.orixCaption).foregroundStyle(Theme.textSecondary)42        }43        .glassCard()44    }4546    private func emptyState(planned: ClockTime) -> some View {47        VStack(alignment: .leading, spacing: 8) {48            Label("No wake confirmation recorded in the last 7 days", systemImage: "chart.dots.scatter")49                .font(.orixBody).foregroundStyle(Theme.textSecondary)50            Text("When you confirm being up after an alarm, the time appears here next to your planned wake time (\(Fmt.timeString(planned, use24h: use24h))).")51                .font(.orixCaption).foregroundStyle(Theme.textTertiary)52        }53        .frame(maxWidth: .infinity, alignment: .leading)54        .padding(14)55        .background(Theme.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))56        .accessibilityElement(children: .combine)57        .accessibilityIdentifier("sleep.consistency.empty")58    }5960    private var legend: some View {61        HStack(spacing: 18) {62            HStack(spacing: 6) {63                ChartLegendLine().stroke(Theme.gold, style: StrokeStyle(lineWidth: 2, dash: [5, 4])).frame(width: 24, height: 2)64                Text("Planned").font(.orixCaption).foregroundStyle(Theme.textSecondary)65            }66            HStack(spacing: 6) {67                Circle().fill(Theme.azure).overlay(Circle().strokeBorder(.white.opacity(0.9), lineWidth: 1.5)).frame(width: 11, height: 11)68                Text("Recorded confirmation").font(.orixCaption).foregroundStyle(Theme.textSecondary)69            }70        }71        .accessibilityHidden(true)72    }7374    private func chart(_ series: [SleepPlanner.ConsistencyDay], planned: Int) -> some View {75        let values = series.compactMap(\.confirmedMinute) + [planned]76        let low = Double((values.min() ?? planned) - 30), high = Double((values.max() ?? planned) + 30)77        let lastDay = series.last?.day ?? model.now()78        let end = model.calendar.date(byAdding: .day, value: 1, to: lastDay) ?? lastDay79        return Chart {80            RuleMark(y: .value("Planned wake time", planned))81                .foregroundStyle(Theme.gold)82                .lineStyle(StrokeStyle(lineWidth: 2, dash: [5, 4]))83            ForEach(series) { day in84                if let minute = day.confirmedMinute {85                    // Thin stem from the plan to the recorded time, so the gap reads without colour.86                    RuleMark(x: .value("Day", day.day, unit: .day), yStart: .value("Planned", planned), yEnd: .value("Recorded", minute))87                        .foregroundStyle(Theme.azure.opacity(0.55))88                        .lineStyle(StrokeStyle(lineWidth: 2))89                    PointMark(x: .value("Day", day.day, unit: .day), y: .value("Recorded confirmation", minute))90                        .symbol { Circle().fill(Theme.azure).overlay(Circle().strokeBorder(.white.opacity(0.9), lineWidth: 1.5)).frame(width: 12, height: 12) }91                }92            }93        }94        .chartXScale(domain: (series.first?.day ?? lastDay)...end)95        .chartYScale(domain: low...high)96        .chartXAxis {97            AxisMarks(values: .stride(by: .day)) { _ in98                AxisGridLine().foregroundStyle(Theme.hairline)99                AxisValueLabel(format: .dateTime.weekday(.abbreviated), centered: true).foregroundStyle(Theme.textSecondary)100            }101        }102        .chartYAxis {103            AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { value in104                AxisGridLine().foregroundStyle(Theme.hairline)105                AxisValueLabel {106                    if let minute = value.as(Double.self) { Text(timeText(Int(minute.rounded()))).foregroundStyle(Theme.textSecondary) }107                }108            }109        }110    }111112    private func spokenSummary(_ series: [SleepPlanner.ConsistencyDay], summary: SleepPlanner.ConsistencySummary) -> String {113        var parts = [String(localized: "Planned wake time \(timeText(series.first?.plannedMinute ?? 0)).")]114        for day in series {115            let name = day.day.formatted(.dateTime.weekday(.wide))116            if let minute = day.confirmedMinute, let deviation = day.deviationMinutes {117                let gap = deviation == 0 ? String(localized: "on time") : (deviation > 0 ? String(localized: "\(deviation) minutes later") : String(localized: "\(-deviation) minutes earlier"))118                parts.append(String(localized: "\(name): confirmed at \(timeText(minute)), \(gap)."))119            } else {120                parts.append(String(localized: "\(name): no confirmation recorded."))121            }122        }123        return parts.joined(separator: " ")124    }125}126127/// Horizontal line used in chart legends.128nonisolated struct ChartLegendLine: Shape {129    func path(in rect: CGRect) -> Path {130        var p = Path()131        p.move(to: CGPoint(x: rect.minX, y: rect.midY)); p.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))132        return p133    }134}135
Files main
Menu

Theme