SPB Git

Repository Public License

DashboardView.swift 9.2 KB 202 lines swift

1// ORIX Alarm2// File: App/Features/Dashboard/DashboardView.swift3// Description: Today dashboard: hero clock, next alarm, scheduling problems, quick alarms, upcoming occurrences, sleep plan, recorded wake performance, tips, focus timer.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct DashboardView: View {11    @Environment(AppModel.self) private var model12    @State private var showsSettings = false1314    var body: some View {15        NavigationStack {16            // Countdowns and the "next alarm" are re-evaluated once per minute; the clock runs on its own timeline.17            TimelineView(.everyMinute) { _ in18                ScrollViewReader { proxy in19                    ScrollView {20                        content21                            .padding(.horizontal, Theme.spacing)22                            .padding(.top, 4)23                    }24                    .contentMargins(.bottom, 28, for: .scrollContent)25                    #if DEBUG26                    .task { await DashboardDebug.apply(model: model, proxy: proxy) }27                    #endif28                }29            }30            .navigationTitle("Today")31            .toolbar {32                ToolbarItem(placement: .topBarLeading) {33                    Button { showsSettings = true } label: { Label("Settings", systemImage: "gearshape.fill").labelStyle(.iconOnly) }34                        .accessibilityIdentifier("dashboard.settings")35                }36                ToolbarItem(placement: .topBarTrailing) {37                    Button {38                        Haptics.play(.selection)39                        model.editingAlarm = model.makeDraftAlarm()40                    } label: { Label("New alarm", systemImage: "plus").labelStyle(.iconOnly).fontWeight(.bold) }41                    .buttonStyle(.glassProminent).tint(Theme.sunrise)42                    .accessibilityIdentifier("dashboard.quickAdd")43                }44            }45            .orixScreen(warmth: warmth)46            .sheet(isPresented: $showsSettings) { SettingsView() }47        }48    }4950    /// A little warmth in the sky around sunrise and sunset hours.51    private var warmth: Double {52        let hour = model.calendar.component(.hour, from: model.now())53        switch hour { case 5...8: return 0.42; case 17...19: return 0.30; case 9...16: return 0.14; default: return 0 }54    }5556    @ViewBuilder57    private var content: some View {58        let now = model.now()59        let next = model.nextAlarm60        let failing = model.alarms.filter { model.schedulingErrors[$0.id] != nil }61        VStack(spacing: Theme.spacing) {62            #if DEBUG63            if DashboardDebug.showsGallery { ClockGallery() }64            #endif65            AuthorizationBanner()66            if !failing.isEmpty { SchedulingProblemsCard(alarms: failing) }67            // The dial only marks an alarm that iOS really holds.68            HeroClock(nextAlarm: next.flatMap { model.schedulingErrors[$0.alarm.id] == nil && model.status(for: $0.alarm.id) != .missing ? $0.date : nil })69            if model.alarms.isEmpty {70                DashboardEmptyState().id("next")71            } else if let next {72                NextAlarmCard(alarm: next.alarm, date: next.date, now: now).id("next")73            } else {74                NoActiveAlarmCard().id("next")75            }76            QuickAlarmCard().id("quick")77            UpcomingCard(now: now).id("upcoming")78            if model.sleepPlan.isEnabled { SleepPrepCard(plan: model.sleepPlan, now: now).id("sleep") }79            PerformanceCard(stats: model.statistics(days: 7)).id("performance")80            SuggestionsCard(suggestions: model.suggestions).id("tips")81            FocusTimerCard().id("focus")82        }83    }84}8586/// Clock in the user's style. Tap or swipe horizontally to change the style; the choice is saved.87private struct HeroClock: View {88    let nextAlarm: Date?89    @Environment(AppModel.self) private var model90    @Environment(\.accessibilityReduceMotion) private var reduceMotion9192    var body: some View {93        let style = model.settings.clockStyle94        VStack(spacing: 10) {95            ClockFaceView(style: style, nextAlarm: nextAlarm)96                .frame(width: 264, height: 264)97                .id(style)98                .transition(reduceMotion ? .opacity : .opacity.combined(with: .scale(scale: 0.92)))99                .contentShape(Circle())100                .onTapGesture { step(1) }101                .simultaneousGesture(DragGesture(minimumDistance: 28).onEnded { value in102                    let dx = value.translation.width, dy = value.translation.height103                    guard abs(dx) > 2 * abs(dy) else { return }104                    step(dx < 0 ? 1 : -1)105                })106                .accessibilityIdentifier("dashboard.clock")107            Button { step(1) } label: {108                HStack(spacing: 10) {109                    Text(style.displayName).font(.orixCaption).foregroundStyle(Theme.textSecondary)110                    HStack(spacing: 6) {111                        ForEach(ClockStyle.allCases, id: \.self) { s in112                            Capsule().fill(s == style ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Color.white.opacity(0.22)))113                                .frame(width: s == style ? 18 : 6, height: 6)114                        }115                    }116                }117                .padding(.horizontal, 16).frame(minHeight: 44)118                .contentShape(Rectangle())119            }120            .buttonStyle(.plain)121            .accessibilityLabel(Text("Clock style"))122            .accessibilityValue(Text(style.displayName))123            .accessibilityHint(Text("Changes the clock face"))124            .accessibilityAdjustableAction { direction in step(direction == .increment ? 1 : -1) }125            .accessibilityIdentifier("dashboard.clockStyle")126        }127        .frame(maxWidth: .infinity)128        .padding(.top, 4)129    }130131    private func step(_ delta: Int) {132        let all = ClockStyle.allCases133        guard let i = all.firstIndex(of: model.settings.clockStyle) else { return }134        let next = all[(i + delta + all.count) % all.count]135        Haptics.play(.selection)136        withAnimation(reduceMotion ? .easeInOut(duration: 0.2) : .spring(duration: 0.45, bounce: 0.25)) {137            model.updateSettings { $0.clockStyle = next }138        }139    }140}141142/// No alarm at all: an invitation and the scenario templates.143private struct DashboardEmptyState: View {144    @Environment(AppModel.self) private var model145146    var body: some View {147        VStack(spacing: 14) {148            VStack(spacing: 12) {149                Image(systemName: "sun.horizon.fill").font(.system(size: 40)).foregroundStyle(Theme.sunriseGradient).accessibilityHidden(true)150                Text("Set your first wake-up").font(.orixTitle).multilineTextAlignment(.center)151                Text("Pick a time, add a mission if you want one, and ORIX Alarm schedules it with iOS. You can also start from a scenario below.")152                    .font(.orixBody).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.center)153                Button {154                    Haptics.play(.selection)155                    model.editingAlarm = model.makeDraftAlarm()156                } label: { Label("Create an alarm", systemImage: "plus") }157                .buttonStyle(PrimaryButtonStyle())158                .accessibilityIdentifier("dashboard.createFirst")159                .padding(.top, 4)160            }161            .frame(maxWidth: .infinity)162            .glassCard(padding: 22)163            Overline("Start from a scenario").padding(.horizontal, 6).padding(.top, 4)164            TemplateShortcuts(identifierPrefix: "dashboard.template")165                .padding(.horizontal, -Theme.spacing)166        }167    }168}169170#if DEBUG171/// Screenshot hooks (debug builds only): `-ORIXDashAnchor next|quick|upcoming|sleep|performance|tips|focus` scrolls to a card,172/// `-ORIXClockStyle <style>` selects a face, `-ORIXDashSleep YES` enables the sleep plan, `-ORIXDashFocus YES` starts a timer,173/// `-ORIXClockGallery YES` shows every face at 120 pt.174private enum DashboardDebug {175    static var showsGallery: Bool { UserDefaults.standard.bool(forKey: "ORIXClockGallery") }176177    static func apply(model: AppModel, proxy: ScrollViewProxy) async {178        let defaults = UserDefaults.standard179        try? await Task.sleep(for: .seconds(1.2))180        if let style = defaults.string(forKey: "ORIXClockStyle").flatMap(ClockStyle.init(rawValue:)) { model.updateSettings { $0.clockStyle = style } }181        if defaults.bool(forKey: "ORIXDashSleep") { model.updateSleepPlan { $0.isEnabled = true } }182        if defaults.bool(forKey: "ORIXDashFocus") { await model.startFocusTimer(minutes: 25) }183        if let anchor = defaults.string(forKey: "ORIXDashAnchor") {184            try? await Task.sleep(for: .seconds(0.4))185            proxy.scrollTo(anchor, anchor: .top)186        }187    }188}189190private struct ClockGallery: View {191    var body: some View {192        AlarmFlowLayout(spacing: 10) {193            ForEach(ClockStyle.allCases, id: \.self) { style in194                ClockFaceView(style: style, nextAlarm: Date.now.addingTimeInterval(5 * 3600))195                    .frame(width: 120, height: 120)196                    .glassCard(padding: 6, radius: 18)197            }198        }199    }200}201#endif202
Files main
Menu

Theme