SPB Git

Repository Public License

InsightsView.swift 17.0 KB 282 lines swift

1// ORIX Alarm2// File: App/Features/Insights/InsightsView.swift3// Description: Local statistics dashboard built on recorded events only: period selector, headline tiles, charts, records, reading guide.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910enum InsightsPeriod: String, CaseIterable, Identifiable {11    case week, month, custom12    var id: String { rawValue }13    var title: String {14        switch self {15        case .week: String(localized: "7 days"); case .month: String(localized: "30 days"); case .custom: String(localized: "Custom")16        }17    }18}1920struct InsightsView: View {21    @Environment(AppModel.self) private var model22    @State private var period: InsightsPeriod = .week23    @State private var customStart = Date.now.addingTimeInterval(-13 * 86_400)24    @State private var customEnd = Date.now2526    private var use24h: Bool? { model.settings.use24HourClock }2728    /// Range of the selected period: start of the first day up to (excluded) the end of the last day, never past now.29    private var range: (start: Date, end: Date) {30        let cal = model.calendar, now = model.now()31        switch period {32        case .week, .month:33            let days = period == .week ? 7 : 3034            return (cal.date(byAdding: .day, value: -(days - 1), to: cal.startOfDay(for: now)) ?? now, now.addingTimeInterval(1))35        case .custom:36            let first = cal.startOfDay(for: min(customStart, customEnd))37            let lastDay = cal.startOfDay(for: max(customStart, customEnd))38            let end = cal.date(byAdding: .day, value: 1, to: lastDay) ?? lastDay39            return (first, min(end, now.addingTimeInterval(1)))40        }41    }4243    var body: some View {44        let range = range45        let stats = WakeStatistics.compute(events: model.events, from: range.start, to: range.end, calendar: model.calendar)46        let inRange = model.events.filter { $0.date >= range.start && $0.date < range.end }47        let fromSchedule = inRange.filter { $0.kind == .fired && $0.note == "from-schedule" }.count48        let hasHistory = model.events.contains { Self.meaningful.contains($0.kind) }49        let hasPeriodData = inRange.contains { Self.meaningful.contains($0.kind) }50        NavigationStack {51            ScrollView {52                VStack(spacing: Theme.spacing) {53                    periodSelector54                    if !hasHistory {55                        emptyHistory56                    } else if !hasPeriodData {57                        emptyPeriod(stats)58                    } else {59                        tiles(stats)60                        records(stats)61                        InsightChartCard(title: "Wake confirmations and snoozes", subtitle: "How many times per day you confirmed being up, and how many times you snoozed.") {62                            ConfirmationsSnoozesChart(days: stats.days)63                        }64                        InsightChartCard(title: "Confirmation delay",65                                         subtitle: "Time between the alarm ringing and your confirmation, in minutes. Snoozes and missions are part of it.",66                                         footnote: stats.averageConfirmationDelay.map { String(localized: "Average over the period: \(Fmt.duration($0)). Days without both events are skipped.") }) {67                            ConfirmationDelayChart(days: stats.days)68                        }69                        InsightChartCard(title: "Wake confirmation time", subtitle: "The time of day of your first confirmation each day. Points at the same height mean a regular rhythm.",70                                         footnote: consistencyText(stats)) {71                            ConfirmationTimeChart(days: stats.days, use24h: use24h)72                        }73                        InsightChartCard(title: "Mission performance", subtitle: "Average time to finish each mission, with completions and clean runs.") {74                            MissionPerformanceChart(missions: stats.missions)75                        }76                    }77                    if hasHistory { InsightsAdaptiveSection() }78                    readingGuide(fromSchedule: fromSchedule)79                }80                .padding(.horizontal, 20).padding(.top, 8)81            }82            .contentMargins(.bottom, 96, for: .scrollContent)83            .navigationTitle("Insights")84            .orixScreen()85        }86    }8788    /// Events that count as wake history (scheduling bookkeeping alone is not history).89    private static let meaningful: Set<WakeEvent.Kind> = [.fired, .acknowledged, .snoozed, .missionStepCompleted, .missionCompleted, .missionBypassed, .wakeConfirmed]9091    // MARK: Period92    private var periodSelector: some View {93        VStack(spacing: 12) {94            Picker("Period", selection: $period) {95                ForEach(InsightsPeriod.allCases) { Text($0.title).tag($0) }96            }97            .pickerStyle(.segmented)98            .accessibilityIdentifier("insights.period")99            if period == .custom {100                let today = model.now()101                HStack(spacing: 12) {102                    DatePicker("From", selection: $customStart, in: ...min(customEnd, today), displayedComponents: .date)103                        .accessibilityIdentifier("insights.period.from")104                    DatePicker("To", selection: $customEnd, in: customStart...today, displayedComponents: .date)105                        .accessibilityIdentifier("insights.period.to")106                }107                .font(.orixCaption)108                .datePickerStyle(.compact)109            }110            let r = range111            Text("\(r.start.formatted(.dateTime.day().month(.abbreviated))) – \(r.end.addingTimeInterval(-2).formatted(.dateTime.day().month(.abbreviated).year()))")112                .font(.orixCaption).foregroundStyle(Theme.textSecondary)113                .frame(maxWidth: .infinity, alignment: .leading)114                .accessibilityLabel("Period shown")115                .accessibilityValue("\(r.start.formatted(date: .long, time: .omitted)) to \(r.end.addingTimeInterval(-2).formatted(date: .long, time: .omitted))")116        }117        .onChange(of: period) { _, _ in Haptics.play(.selection) }118    }119120    // MARK: Tiles121    private func tiles(_ s: WakeStatistics) -> some View {122        LazyVGrid(columns: [GridItem(.flexible(), spacing: 12), GridItem(.flexible(), spacing: 12)], spacing: 12) {123            InsightTile(symbol: "bell.and.waves.left.and.right.fill", tint: Theme.sunrise, value: "\(s.alarmsFired)", title: "Alarms that rang", detail: "Recorded ringing")124            InsightTile(symbol: "hand.raised.fill", tint: Theme.azure, value: "\(s.acknowledgments)", title: "Alarms stopped", detail: "Stopped on the system alert")125            InsightTile(symbol: "checkmark.seal.fill", tint: Theme.success, value: "\(s.missionsCompleted)", title: "Missions completed", detail: "Whole sequence finished")126            InsightTile(symbol: "figure.walk.departure", tint: Theme.danger, value: "\(s.missionsBypassed)", title: "Missions bypassed", detail: "Emergency exit used")127            InsightTile(symbol: "sun.max.fill", tint: Theme.gold, value: "\(s.wakeConfirmations)", title: "Wake confirmations", detail: "You tapped “I'm up”")128            InsightTile(symbol: "zzz", tint: Theme.violet, value: "\(s.snoozes)", title: "Snoozes", detail: s.alarmsFired > 0 ? String(localized: "\(String(format: "%.1f", Double(s.snoozes) / Double(s.alarmsFired))) per alarm that rang") : String(localized: "No alarm rang"))129            InsightTile(symbol: "timer", tint: Theme.peach, value: s.averageMissionDuration.map(Fmt.duration) ?? "–", title: "Average mission duration", detail: "Per mission step")130            InsightTile(symbol: "scope", tint: Theme.success, value: s.accuracy.map { "\(Int(($0 * 100).rounded())) %" } ?? "–", title: "Accuracy", detail: "Missions without a mistake")131            InsightTile(symbol: "flame.fill", tint: Theme.ember, value: dayCount(s.currentStreak), title: "Current streak", detail: "Days in a row with a confirmation")132            InsightTile(symbol: "trophy.fill", tint: Theme.gold, value: dayCount(s.longestStreak), title: "Longest streak", detail: "Across all your history")133        }134        .accessibilityIdentifier("insights.tiles")135    }136137    private func dayCount(_ n: Int) -> String { n == 1 ? String(localized: "1 day") : String(localized: "\(n) days") }138139    // MARK: Records140    private func records(_ s: WakeStatistics) -> some View {141        VStack(alignment: .leading, spacing: 12) {142            Overline("Personal records")143            if let fastest = s.fastestMission, fastest.duration > 0 {144                recordRow(symbol: fastest.kind.symbol, tint: fastest.kind.tint, title: "Fastest mission",145                          value: "\(fastest.kind.title) in \(Fmt.duration(fastest.duration))", scope: "In this period")146            } else {147                recordRow(symbol: "bolt.fill", tint: Theme.textTertiary, title: "Fastest mission", value: String(localized: "No mission completed yet"), scope: "In this period")148            }149            Divider().overlay(Theme.hairline)150            recordRow(symbol: "trophy.fill", tint: Theme.gold, title: "Best streak",151                      value: s.longestStreak > 0 ? String(localized: "\(dayCount(s.longestStreak)) in a row with a wake confirmation") : String(localized: "No confirmation yet"),152                      scope: "All history")153        }154        .glassCard()155        .accessibilityIdentifier("insights.records")156    }157158    private func recordRow(symbol: String, tint: Color, title: LocalizedStringKey, value: String, scope: LocalizedStringKey) -> some View {159        HStack(spacing: 14) {160            Image(systemName: symbol).font(.title3).foregroundStyle(tint).frame(width: 40, height: 40)161                .background(Theme.surfaceRaised, in: Circle()).accessibilityHidden(true)162            VStack(alignment: .leading, spacing: 2) {163                Text(title).font(.orixCaption).foregroundStyle(Theme.textSecondary)164                Text(value).font(.orixHeadline)165                Text(scope).font(.orixCaption).foregroundStyle(Theme.textTertiary)166            }167            Spacer(minLength: 0)168        }169        .accessibilityElement(children: .combine)170    }171172    private func consistencyText(_ s: WakeStatistics) -> String {173        guard let sd = s.consistencyMinutes else {174            return String(localized: "Regularity is shown once confirmations exist on at least 3 days of the period.")175        }176        let minutes = Int(sd.rounded())177        let verdict = minutes <= 15 ? String(localized: "That is very regular.") : (minutes <= 40 ? String(localized: "That is fairly regular.") : String(localized: "Your confirmation times vary quite a lot."))178        return String(localized: "Regularity: your confirmation times are typically about \(minutes) min away from their average (the dashed line). Lower means more regular. \(verdict)")179    }180181    // MARK: Empty states182    private var emptyHistory: some View {183        VStack(spacing: 14) {184            Image(systemName: "chart.xyaxis.line").font(.system(size: 44)).foregroundStyle(Theme.nightGradient).accessibilityHidden(true)185            Text("No wake history yet").font(.orixTitle)186            Text("Insights are built only from what the app records: an alarm ringing, you stopping it, a mission finished, a wake confirmation. Nothing has been recorded so far, so there is nothing to show. Charts appear after your first alarm.")187                .font(.orixBody).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.center)188            if model.alarms.isEmpty {189                Button("Create an alarm") { model.editingAlarm = model.makeDraftAlarm() }190                    .buttonStyle(PrimaryButtonStyle())191                    .accessibilityIdentifier("insights.empty.create")192            }193        }194        .frame(maxWidth: .infinity)195        .glassCard(padding: 24)196        .accessibilityIdentifier("insights.empty")197    }198199    private func emptyPeriod(_ s: WakeStatistics) -> some View {200        VStack(spacing: 10) {201            Image(systemName: "calendar.badge.exclamationmark").font(.system(size: 36)).foregroundStyle(Theme.gold).accessibilityHidden(true)202            Text("Nothing recorded in this period").font(.orixHeadline)203            Text("No alarm rang and no mission or confirmation was recorded between these dates. Choose a longer or different period.")204                .font(.orixCaption).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.center)205            if s.longestStreak > 0 {206                Text("Best streak in all your history: \(dayCount(s.longestStreak)).").font(.orixCaption).foregroundStyle(Theme.textSecondary)207            }208        }209        .frame(maxWidth: .infinity)210        .glassCard(padding: 24)211        .accessibilityIdentifier("insights.emptyPeriod")212    }213214    // MARK: Reading guide215    private func readingGuide(fromSchedule: Int) -> some View {216        VStack(alignment: .leading, spacing: 14) {217            Label("How to read this", systemImage: "book.pages.fill").font(.orixHeadline).foregroundStyle(Theme.gold)218                .accessibilityAddTraits(.isHeader)219            Text("Three different events are counted separately. One never implies the next.")220                .font(.orixCaption).foregroundStyle(Theme.textSecondary)221            guideRow(symbol: "hand.raised.fill", tint: Theme.azure, title: "Alarm stopped",222                     text: "You stopped the ringing on the system alert. iOS always allows this. It says nothing about whether you got up.")223            guideRow(symbol: "checkmark.seal.fill", tint: Theme.success, title: "Mission completed",224                     text: "You finished every step of the alarm's mission. A mission left through the emergency exit is counted as bypassed, not completed.")225            guideRow(symbol: "sun.max.fill", tint: Theme.gold, title: "Wake confirmed",226                     text: "You tapped “I'm up” yourself. Streaks, delays and time-of-day charts use only this event.")227            Divider().overlay(Theme.hairline)228            guideRow(symbol: "calendar.badge.clock", tint: Theme.peach, title: "Ringing recorded from the schedule",229                     text: fromSchedule > 0230                        ? "\(fromSchedule) of the alarms counted as “rang” in this period were not observed directly: the app was closed, so the ring is deduced from the scheduled time having passed."231                        : "When the app is closed while an alarm rings, the ring is not observed directly: it is recorded from the scheduled time having passed. None in this period.")232            guideRow(symbol: "moon.zzz.fill", tint: Theme.violet, title: "Nothing here measures sleep",233                     text: "ORIX Alarm does not track sleep, sleep stages or how rested you are. These numbers describe what you did with your alarms, nothing more.")234            guideRow(symbol: "lock.shield.fill", tint: Theme.success, title: "Stays on this iPhone",235                     text: "Statistics are computed on the device from your local history. Nothing is sent anywhere.")236        }237        .glassCard()238        .accessibilityIdentifier("insights.guide")239    }240241    private func guideRow(symbol: String, tint: Color, title: LocalizedStringKey, text: LocalizedStringKey) -> some View {242        HStack(alignment: .top, spacing: 12) {243            Image(systemName: symbol).font(.callout).foregroundStyle(tint).frame(width: 26).accessibilityHidden(true)244            VStack(alignment: .leading, spacing: 3) {245                Text(title).font(.orixHeadline)246                Text(text).font(.orixCaption).foregroundStyle(Theme.textSecondary)247            }248        }249        .accessibilityElement(children: .combine)250    }251}252253/// One headline number with its label and a short qualifier.254struct InsightTile: View {255    let symbol: String256    let tint: Color257    let value: String258    let title: LocalizedStringKey259    let detail: String260261    init(symbol: String, tint: Color, value: String, title: LocalizedStringKey, detail: String) {262        self.symbol = symbol; self.tint = tint; self.value = value; self.title = title; self.detail = detail263    }264265    var body: some View {266        VStack(alignment: .leading, spacing: 6) {267            Image(systemName: symbol).font(.callout.weight(.semibold)).foregroundStyle(tint)268                .frame(width: 32, height: 32).background(tint.opacity(0.16), in: RoundedRectangle(cornerRadius: 10, style: .continuous))269                .accessibilityHidden(true)270            Text(value).font(.system(size: 28, weight: .semibold, design: .rounded).monospacedDigit())271                .lineLimit(1).minimumScaleFactor(0.5)272            Text(title).font(.orixCaption).foregroundStyle(Theme.textPrimary).lineLimit(2).fixedSize(horizontal: false, vertical: true)273            Text(detail).font(.system(.caption2, design: .rounded)).foregroundStyle(Theme.textTertiary).lineLimit(2).fixedSize(horizontal: false, vertical: true)274        }275        .frame(maxWidth: .infinity, minHeight: 104, alignment: .topLeading)276        .glassCard(padding: 14, radius: 20)277        .accessibilityElement(children: .ignore)278        .accessibilityLabel(title)279        .accessibilityValue("\(value). \(detail)")280    }281}282
Files main
Menu

Theme