SPB Git

Repository Public License

NightstandView.swift 22.1 KB 400 lines swift

1// ORIX Alarm2// File: App/Features/Nightstand/NightstandView.swift3// Description: Nightstand mode: dimmed bedside clock, countdown, wake stages, sunrise simulation and soundscape while the app stays open.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910/// The bedside screen for the night. Shown full screen from `model.nightstandAlarmID`; closing sets it to nil.11struct NightstandView: View {12    let alarm: AlarmDefinition1314    @Environment(AppModel.self) private var model15    @Environment(\.scenePhase) private var scenePhase16    @Environment(\.accessibilityReduceMotion) private var reduceMotion17    @Environment(\.accessibilityVoiceOverEnabled) private var voiceOver18    @State private var session = NightstandSession()19    @State private var controlsVisible = true20    @State private var lastInteraction = Date()21    @State private var showsInfo = false2223    /// Seconds without a touch after which the controls fade away, leaving only the clock.24    private static let controlsTimeout: TimeInterval = 202526    private var snapshot: NightstandSession.Snapshot { session.snapshot }27    private var light: Double { snapshot.sunriseProgress }28    private var isMorning: Bool { snapshot.stage == .mainAlarm || snapshot.stage == .finished }2930    var body: some View {31        ZStack {32            SunriseSkyView(progress: light, updateInterval: session.tickInterval)33            TimelineView(.periodic(from: .now, by: 1)) { context in34                clockBlock(date: context.date)35                    .offset(driftOffset(at: context.date))36            }37            VStack(spacing: 0) {38                topBar39                Spacer(minLength: 0)40                controlPanel41            }42            .padding(.horizontal, 16).padding(.bottom, 8)43            .opacity(controlsVisible ? 1 : 0)44            .allowsHitTesting(controlsVisible)45            .accessibilityHidden(!controlsVisible)46        }47        .contentShape(Rectangle())48        .onTapGesture { touch() }49        .accessibilityAction(named: Text("Show controls")) { touch() }50        .statusBarHidden()51        .persistentSystemOverlays(.hidden)52        .preferredColorScheme(.dark)53        .sheet(isPresented: $showsInfo) { NightstandInfoSheet(alarm: alarm, session: session) }54        .task {55            session.begin(alarm: alarm, now: model.now) { [model, id = alarm.id] in model.alarm(id).flatMap { model.nextFireDate(for: $0) } }56            if NightstandLaunch.pendingDemo { NightstandLaunch.pendingDemo = false; session.startDemo() }57            while !Task.isCancelled {58                session.tick()59                hideControlsIfIdle()60                try? await Task.sleep(for: .seconds(session.tickInterval))61            }62        }63        .onDisappear { session.end() }64        .onChange(of: scenePhase) { _, phase in65            if phase == .active { session.resume(); touch() } else { session.suspend() }66        }67        .accessibilityIdentifier("nightstand.screen")68    }6970    // MARK: Clock7172    private func clockBlock(date: Date) -> some View {73        let parts = model.calendar.dateComponents([.hour, .minute], from: date)74        let time = Fmt.time(ClockTime(hour: parts.hour ?? 0, minute: parts.minute ?? 0), use24h: model.settings.use24HourClock)75        let ink = clockInk76        return VStack(spacing: 10) {77            if isMorning {78                Label("Good morning", systemImage: "sun.max.fill")79                    .font(.system(.title, design: .rounded, weight: .semibold))80                    .accessibilityIdentifier("nightstand.goodMorning")81            }82            HStack(alignment: .firstTextBaseline, spacing: 6) {83                Text(time.digits).font(.clock(104)).minimumScaleFactor(0.5).lineLimit(1)84                if !time.period.isEmpty { Text(time.period).font(.system(.title2, design: .rounded, weight: .medium)) }85            }86            .accessibilityElement(children: .ignore)87            .accessibilityLabel(Text("Current time"))88            .accessibilityValue(Text(date, style: .time))89            Text(date, format: .dateTime.weekday(.wide).month(.wide).day())90                .font(.orixBody)91            alarmLine.padding(.top, 14)92            if !controlsVisible { compactStage.padding(.top, 6) }93        }94        .foregroundStyle(ink)95        .opacity(clockOpacity)96        .padding(.horizontal, 28)97        .padding(.bottom, controlsVisible ? 250 : 40)98        .animation(reduceMotion ? nil : .easeInOut(duration: 0.6), value: controlsVisible)99        .animation(reduceMotion ? nil : .linear(duration: session.tickInterval), value: light)100    }101102    /// Before the wake window the clock is a dim warm amber (little blue light, little glare); it turns white as the103    /// sky lights up, then dark once the background is bright enough to need it.104    private var clockInk: Color {105        if light < 0.45 { return Theme.gold.mix(with: .white, by: light / 0.45) }106        // White holds on the violet sky; the switch to dark ink is quick, placed where the background turns orange.107        return Color.white.mix(with: Theme.midnight, by: SunriseSkyView.smooth((light - 0.66) / 0.10))108    }109110    private var clockOpacity: Double {111        if isMorning || light > 0 { return 0.55 + 0.45 * SunriseSkyView.smooth(light / 0.3) }112        return controlsVisible ? 0.55 : 0.34113    }114115    private var alarmLine: some View {116        HStack(spacing: 8) {117            Image(systemName: fireDescription == nil ? "bell.slash.fill" : "alarm.fill").accessibilityHidden(true)118            Text(alarmLineText).font(.orixHeadline).multilineTextAlignment(.center).contentTransition(.identity)119        }120        .accessibilityElement(children: .combine)121        .accessibilityIdentifier("nightstand.alarmLine")122    }123124    private var alarmTime: String { Fmt.timeString(alarm.time, use24h: model.settings.use24HourClock) }125126    /// Countdown text, or nil when the alarm has no upcoming occurrence.127    private var fireDescription: String? {128        guard let fire = session.fireDate else { return nil }129        if session.isDemo { return String(localized: "in \(max(0, Int(snapshot.timeUntilFire.rounded(.up)))) s") }130        return Fmt.countdown(to: fire, from: model.now())131    }132133    private var alarmLineText: String {134        guard let countdown = fireDescription else { return String(localized: "\(alarmTime) · this alarm is off") }135        if isMorning { return session.isDemo ? String(localized: "Demo · alarm time reached") : String(localized: "Alarm · \(alarmTime)") }136        return session.isDemo ? String(localized: "Demo · alarm \(countdown)") : String(localized: "Alarm \(alarmTime) · \(countdown)")137    }138139    /// Burn-in protection: the clock block wanders a few points along a slow closed path (one loop every ten minutes or so).140    /// The movement is far below what the eye notices, so it also runs with Reduce Motion.141    private func driftOffset(at date: Date) -> CGSize {142        let t = date.timeIntervalSinceReferenceDate143        return CGSize(width: 12 * sin(t / 97), height: 18 * sin(t / 151 + 1.3))144    }145146    // MARK: Stages147148    private struct StageInfo { let stage: ProgressiveWakeTimeline.Stage; let title: String; let symbol: String }149    private static let stages: [StageInfo] = [150        .init(stage: .idle, title: String(localized: "Night"), symbol: "moon.stars.fill"),151        .init(stage: .preparation, title: String(localized: "Preparing"), symbol: "sun.horizon.fill"),152        .init(stage: .gentleWake, title: String(localized: "Gentle wake"), symbol: "sunrise.fill"),153        .init(stage: .mainAlarm, title: String(localized: "Alarm"), symbol: "alarm.fill"),154    ]155    private var currentStageIndex: Int {156        switch snapshot.stage { case .idle: 0; case .preparation: 1; case .gentleWake: 2; case .mainAlarm, .finished: 3 }157    }158    private var currentStageTitle: String { snapshot.stage == .finished ? String(localized: "Morning") : Self.stages[currentStageIndex].title }159160    /// Shown under the clock when the controls are hidden: symbol and name of the current stage.161    private var compactStage: some View {162        Label(currentStageTitle, systemImage: Self.stages[currentStageIndex].symbol)163            .font(.orixCaption)164            .accessibilityLabel(Text("Stage: \(currentStageTitle)"))165    }166167    private var stageIndicator: some View {168        VStack(spacing: 10) {169            HStack(spacing: 6) {170                ForEach(Array(Self.stages.enumerated()), id: \.offset) { index, info in171                    let isCurrent = index == currentStageIndex172                    HStack(spacing: 6) {173                        Image(systemName: index < currentStageIndex ? "checkmark" : info.symbol).imageScale(.small)174                        if isCurrent { Text(currentStageTitle).lineLimit(1).minimumScaleFactor(0.8) }175                    }176                    .font(.orixCaption)177                    .foregroundStyle(isCurrent ? Theme.midnight : (index < currentStageIndex ? Theme.textSecondary : Theme.textTertiary))178                    .padding(.horizontal, isCurrent ? 14 : 0)179                    .frame(maxWidth: isCurrent ? .infinity : 44, minHeight: 34)180                    .background(isCurrent ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Theme.surface), in: Capsule())181                    .overlay(Capsule().strokeBorder(isCurrent ? .clear : Theme.hairline))182                }183            }184            if session.hasProgressiveWake {185                // Position inside the wake window.186                GeometryReader { geo in187                    ZStack(alignment: .leading) {188                        Capsule().fill(Theme.surfaceRaised)189                        Capsule().fill(Theme.sunriseGradient).frame(width: max(4, geo.size.width * snapshot.progress))190                    }191                }192                .frame(height: 4)193                .animation(reduceMotion ? nil : .linear(duration: session.tickInterval), value: snapshot.progress)194            }195        }196        .accessibilityElement(children: .ignore)197        .accessibilityLabel(Text("Wake stage"))198        .accessibilityValue(Text(session.hasProgressiveWake199                                 ? "\(currentStageTitle), \(Int((snapshot.progress * 100).rounded())) percent of the wake window"200                                 : currentStageTitle))201        .accessibilityIdentifier("nightstand.stage")202    }203204    private var statusText: String {205        let scape = session.soundscape?.title ?? ""206        switch snapshot.stage {207        case .idle:208            guard let timeline = session.timeline else { return String(localized: "Turn this alarm on to use Nightstand with it.") }209            guard session.hasProgressiveWake else { return String(localized: "Progressive wake is off for this alarm: this screen stays a quiet clock until iOS rings it.") }210            if session.isDemo { return String(localized: "Night. The sunrise and \(scape) are about to begin.") }211            let parts = model.calendar.dateComponents([.hour, .minute], from: timeline.windowStart)212            let start = Fmt.timeString(ClockTime(hour: parts.hour ?? 0, minute: parts.minute ?? 0), use24h: model.settings.use24HourClock)213            return timeline.sunrise ? String(localized: "The sunrise and \(scape) begin at \(start).") : String(localized: "\(scape) begins at \(start).")214        case .preparation:215            return session.soundEnabled ? String(localized: "First light. \(scape) is coming in very softly.") : String(localized: "First light. Sound is off.")216        case .gentleWake:217            let percent = Int((snapshot.audioIntensity * 100).rounded())218            return session.soundEnabled ? String(localized: "\(scape) at \(percent) % of its level, rising until the alarm.") : String(localized: "Light is rising. Sound is off.")219        case .mainAlarm:220            return session.isDemo221                ? String(localized: "Demo: at this moment iOS rings your alarm. Here you hear a preview of its sound.")222                : String(localized: "iOS is ringing your alarm. Stop it there; your wake mission then opens in ORIX Alarm.")223        case .finished:224            return session.isDemo ? String(localized: "Demo finished.") : String(localized: "The alarm time has passed.")225        }226    }227228    // MARK: Controls229230    private var topBar: some View {231        HStack {232            circleButton("xmark", label: String(localized: "Close Nightstand")) { model.nightstandAlarmID = nil }233                .accessibilityIdentifier("nightstand.close")234            Spacer()235            VStack(spacing: 2) {236                Text("NIGHTSTAND").font(.orixOverline).kerning(1.4)237                if !alarm.name.isEmpty { Text(alarm.name).font(.orixCaption).lineLimit(1) }238            }239            .foregroundStyle(.white.opacity(0.8))240            .padding(.horizontal, 14).padding(.vertical, 6)241            .background(Theme.midnight.opacity(0.45), in: Capsule())242            .accessibilityElement(children: .combine)243            Spacer()244            circleButton("info", label: String(localized: "How Nightstand works")) { showsInfo = true; touch() }245                .accessibilityIdentifier("nightstand.info")246        }247        .padding(.top, 6)248    }249250    private func circleButton(_ symbol: String, label: String, action: @escaping () -> Void) -> some View {251        Button(action: action) {252            Image(systemName: symbol).font(.system(size: 16, weight: .semibold)).foregroundStyle(.white.opacity(0.85))253                .frame(width: 44, height: 44)254                .background(Theme.midnight.opacity(0.55), in: Circle())255                .overlay(Circle().strokeBorder(Theme.hairline))256        }257        .buttonStyle(.plain)258        .accessibilityLabel(Text(label))259    }260261    private var controlPanel: some View {262        VStack(alignment: .leading, spacing: 14) {263            stageIndicator264            Text(statusText).font(.orixBody).foregroundStyle(Theme.textPrimary)265                .fixedSize(horizontal: false, vertical: true)266                .accessibilityIdentifier("nightstand.status")267            hints268            HStack(spacing: 8) {269                toggleButton(session.soundEnabled ? "speaker.wave.2.fill" : "speaker.slash.fill",270                             title: session.soundEnabled ? String(localized: "Sound on") : String(localized: "Sound off"), isOn: session.soundEnabled) {271                    session.soundEnabled.toggle(); Haptics.play(.selection)272                }273                .accessibilityIdentifier("nightstand.sound")274                toggleButton(session.raisesBrightness ? "sun.max.fill" : "sun.min",275                             title: session.raisesBrightness ? String(localized: "Brighten on") : String(localized: "Brighten off"), isOn: session.raisesBrightness) {276                    session.raisesBrightness.toggle(); Haptics.play(.selection)277                }278                .accessibilityHint(Text("Raises the screen brightness with the sunrise and restores it when you leave."))279                .accessibilityIdentifier("nightstand.brightness")280                toggleButton(session.isDemo ? "stop.fill" : "play.fill",281                             title: session.isDemo ? String(localized: "End demo") : String(localized: "Demo"), isOn: session.isDemo) {282                    if session.isDemo { session.stopDemo() } else { session.startDemo() }283                    Haptics.play(.selection)284                }285                .accessibilityHint(Text("Plays the whole wake window in about forty seconds."))286                .accessibilityIdentifier("nightstand.demo")287            }288            Text("Works only while ORIX Alarm stays open on this screen. If the app is closed or the iPhone is locked, the alarm still rings at \(alarmTime), without sunrise or soundscape.")289                .font(.orixCaption).foregroundStyle(Theme.textSecondary)290                .fixedSize(horizontal: false, vertical: true)291                .accessibilityIdentifier("nightstand.limits")292        }293        .padding(18)294        .background {295            RoundedRectangle(cornerRadius: Theme.cornerRadius, style: .continuous).fill(Theme.midnight.opacity(0.72))296                .background(.ultraThinMaterial.opacity(0.6), in: RoundedRectangle(cornerRadius: Theme.cornerRadius, style: .continuous))297                .overlay(RoundedRectangle(cornerRadius: Theme.cornerRadius, style: .continuous).strokeBorder(Theme.hairline))298        }299        .onTapGesture { touch() }300    }301302    /// Short, factual notes about things the app does not control: power and device volume.303    @ViewBuilder private var hints: some View {304        let onBattery = session.batteryState == .unplugged305        let quiet = session.soundEnabled && session.hasProgressiveWake && session.deviceVolume < 0.25306        if onBattery || quiet {307            VStack(alignment: .leading, spacing: 6) {308                if onBattery {309                    Label("On battery. Plug the iPhone in: the screen stays on all night.", systemImage: "battery.25")310                        .accessibilityIdentifier("nightstand.hint.battery")311                }312                if quiet {313                    Label("iPhone volume is at \(Int((session.deviceVolume * 100).rounded())) %. The soundscape cannot be louder than that: raise it with the side buttons.",314                          systemImage: "speaker.wave.1")315                        .accessibilityIdentifier("nightstand.hint.volume")316                }317            }318            .font(.orixCaption).foregroundStyle(Theme.gold)319            .fixedSize(horizontal: false, vertical: true)320        }321    }322323    private func toggleButton(_ symbol: String, title: String, isOn: Bool, action: @escaping () -> Void) -> some View {324        Button { action(); touch() } label: {325            VStack(spacing: 4) {326                Image(systemName: symbol).font(.system(size: 17, weight: .semibold))327                Text(title).font(.orixCaption).lineLimit(1).minimumScaleFactor(0.7)328            }329            .foregroundStyle(isOn ? Theme.gold : Theme.textSecondary)330            .frame(maxWidth: .infinity, minHeight: 56)331            .background(isOn ? Theme.gold.opacity(0.14) : Theme.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))332            .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(isOn ? Theme.gold.opacity(0.5) : Theme.hairline))333        }334        .buttonStyle(.plain)335        .accessibilityLabel(Text(title))336        .accessibilityAddTraits(isOn ? .isSelected : [])337    }338339    private func touch() {340        lastInteraction = Date()341        if !controlsVisible { withAnimation(reduceMotion ? nil : .easeOut(duration: 0.3)) { controlsVisible = true } }342    }343344    /// The controls fade out after a while so the night screen is only a dim clock. Never while VoiceOver is on or during the demo.345    private func hideControlsIfIdle() {346        guard controlsVisible, !voiceOver, !session.isDemo, !showsInfo, !isMorning,347              Date().timeIntervalSince(lastInteraction) > Self.controlsTimeout else { return }348        withAnimation(reduceMotion ? nil : .easeInOut(duration: 1.2)) { controlsVisible = false }349    }350}351352/// Plain-language explanation of what Nightstand does and where iOS draws the line.353struct NightstandInfoSheet: View {354    let alarm: AlarmDefinition355    let session: NightstandSession356    @Environment(\.dismiss) private var dismiss357358    var body: some View {359        NavigationStack {360            ScrollView {361                VStack(alignment: .leading, spacing: 16) {362                    section("sunrise.fill", "What it does",363                            "Leave ORIX Alarm open on this screen at bedtime. Before the alarm, the screen slowly turns from black to a warm sunrise and the soundscape fades in, following the intensity curve you chose for this alarm.")364                    section("lock.fill", "Where it stops",365                            "iOS does not let an app light the screen or start sound on its own while it is closed or the iPhone is locked. If that happens, your alarm still rings on time through iOS; only the sunrise and the soundscape are skipped.")366                    section("alarm.fill", "At alarm time",367                            "The alarm is rung by iOS, not by this screen. Stop it from the system alert; when you come back, ORIX Alarm opens your wake mission.")368                    section("battery.100percent.bolt", "Power",369                            "The screen stays on while Nightstand is visible, which uses battery. Plug the iPhone in for the night. The screen sleeps normally again as soon as you leave this mode.")370                    section("sun.max.fill", "Brightness",371                            "The sunrise is only as bright as the screen. For a stronger light, turn Brighten on: ORIX Alarm then raises the screen brightness with the sunrise and puts it back when you leave. Otherwise your own brightness setting is left alone. Night Shift, True Tone and auto-brightness remain under your control in Settings.")372                    section("speaker.wave.2.fill", "Volume",373                            "ORIX Alarm never changes the iPhone volume. The soundscape plays at up to 80 % of the volume you set with the side buttons, even with the silent switch on. The alarm itself follows the system alarm settings.")374                    Button(session.isDemo ? "Restart the 40-second demo" : "Play the 40-second demo") { session.startDemo(); dismiss() }375                        .buttonStyle(PrimaryButtonStyle())376                        .accessibilityIdentifier("nightstand.info.demo")377                }378                .padding(20)379            }380            .navigationTitle("Nightstand")381            .navigationBarTitleDisplayMode(.inline)382            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() }.accessibilityIdentifier("nightstand.info.done") } }383            .orixScreen()384        }385    }386387    private func section(_ symbol: String, _ title: LocalizedStringKey, _ text: LocalizedStringKey) -> some View {388        HStack(alignment: .top, spacing: 14) {389            Image(systemName: symbol).font(.title3).foregroundStyle(Theme.gold).frame(width: 30).accessibilityHidden(true)390            VStack(alignment: .leading, spacing: 4) {391                Text(title).font(.orixHeadline)392                Text(text).font(.orixCaption).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)393            }394        }395        .frame(maxWidth: .infinity, alignment: .leading)396        .glassCard()397        .accessibilityElement(children: .combine)398    }399}400
Files main
Menu

Theme