SPB Git

Repository Public License

SleepView.swift 20.5 KB 377 lines swift

1// ORIX Alarm2// File: App/Features/Sleep/SleepView.swift3// Description: Sleep planner: bedtime and wake time dial, time in bed, bedtime helper from the next alarm, wind-down, reminders, routine checklist, weekly consistency.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct SleepView: View {11    @Environment(AppModel.self) private var model12    @Environment(\.openURL) private var openURL13    @Environment(\.scenePhase) private var scenePhase14    @AppStorage("sleep.desiredMinutes") private var desiredMinutes = 48015    /// Dial position while dragging; written to the model once when the drag ends.16    @State private var draftBedtime: Int?17    @State private var draftWake: Int?18    @State private var permission: SleepReminders.Permission = .notDetermined19    @State private var isRequestingPermission = false20    @State private var showsRoutineEditor = false2122    private var plan: SleepPlan { model.sleepPlan }23    private var use24h: Bool? { model.settings.use24HourClock }24    private var bedtimeMinute: Int { draftBedtime ?? plan.bedtime.minutesSinceMidnight }25    private var wakeMinute: Int { draftWake ?? plan.wakeTime.minutesSinceMidnight }26    private func timeText(_ minute: Int) -> String { Fmt.timeString(ClockTime(minutesSinceMidnight: minute), use24h: use24h) }2728    var body: some View {29        NavigationStack {30            ScrollView {31                VStack(spacing: Theme.spacing) {32                    planCard33                    scheduleCard34                    helperCard35                    windDownCard36                    routineCard37                    SleepConsistencyCard()38                    Text("ORIX Alarm plans time in bed and records the moments you confirm being up. It does not measure sleep, and nothing here is medical advice.")39                        .font(.orixCaption).foregroundStyle(Theme.textTertiary)40                        .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 4)41                }42                .padding(.horizontal, 20).padding(.top, 8)43            }44            .contentMargins(.bottom, 96, for: .scrollContent)45            .navigationTitle("Sleep")46            .orixScreen()47        }48        .sheet(isPresented: $showsRoutineEditor) { RoutineEditorView() }49        .task { permission = await SleepReminders.permission() }50        .onChange(of: scenePhase) { _, phase in51            // The user may come back from Settings with a different notification permission.52            guard phase == .active else { return }53            Task {54                permission = await SleepReminders.permission()55                if plan.remindersEnabled { await SleepReminders.sync(plan: plan) }56            }57        }58    }5960    // MARK: Plan toggle61    private var planCard: some View {62        VStack(alignment: .leading, spacing: 10) {63            Toggle(isOn: Binding(get: { plan.isEnabled }, set: { on in64                Haptics.play(.selection)65                model.updateSleepPlan { $0.isEnabled = on }66            })) {67                Label { Text("Sleep plan").font(.orixHeadline) } icon: {68                    Image(systemName: "moon.stars.fill").foregroundStyle(Theme.nightGradient)69                }70            }71            .tint(Theme.violet)72            .accessibilityIdentifier("sleep.enable")73            Text(plan.isEnabled74                 ? "Your target bedtime and wake time guide the evening reminders and the weekly overview below."75                 : "Set a target bedtime and wake time to plan your time in bed. While the plan is off, no evening reminder is sent.")76                .font(.orixCaption).foregroundStyle(Theme.textSecondary)77        }78        .glassCard()79    }8081    // MARK: Dial and pickers82    private var scheduleCard: some View {83        VStack(spacing: 18) {84            Overline("Schedule")85            SleepDial(bedtime: Binding(get: { bedtimeMinute }, set: { draftBedtime = $0 }),86                      wake: Binding(get: { wakeMinute }, set: { draftWake = $0 }),87                      use24h: use24h, onCommit: commitDial)88                .frame(maxWidth: 300)89                .padding(.vertical, 4)90            HStack(spacing: 12) {91                timeField(title: "Bedtime", symbol: "bed.double.fill", tint: Theme.violet, minute: bedtimeMinute, identifier: "sleep.bedtime") { minute in92                    model.updateSleepPlan { $0.bedtime = ClockTime(minutesSinceMidnight: minute) }93                }94                timeField(title: "Wake time", symbol: "alarm.fill", tint: Theme.sunrise, minute: wakeMinute, identifier: "sleep.wake") { minute in95                    model.updateSleepPlan { $0.wakeTime = ClockTime(minutesSinceMidnight: minute) }96                }97            }98            Text("Going to bed at \(timeText(bedtimeMinute)) and getting up at \(timeText(wakeMinute)) leaves \(SleepFmt.span(opportunityMinutes)) in bed. Time asleep is usually shorter than time in bed.")99                .font(.orixCaption).foregroundStyle(Theme.textSecondary)100                .frame(maxWidth: .infinity, alignment: .leading)101        }102        .glassCard()103    }104105    private var opportunityMinutes: Int {106        SleepPlanner.minutes(from: ClockTime(minutesSinceMidnight: bedtimeMinute), to: ClockTime(minutesSinceMidnight: wakeMinute))107    }108109    private func commitDial() {110        let bed = draftBedtime, wake = draftWake111        draftBedtime = nil; draftWake = nil112        guard bed != nil || wake != nil else { return }113        let newBed = ClockTime(minutesSinceMidnight: bed ?? plan.bedtime.minutesSinceMidnight)114        let newWake = ClockTime(minutesSinceMidnight: wake ?? plan.wakeTime.minutesSinceMidnight)115        guard newBed != plan.bedtime || newWake != plan.wakeTime else { return }116        model.updateSleepPlan { $0.bedtime = newBed; $0.wakeTime = newWake }117    }118119    private func timeField(title: LocalizedStringKey, symbol: String, tint: Color, minute: Int, identifier: String, set: @escaping (Int) -> Void) -> some View {120        VStack(alignment: .leading, spacing: 6) {121            Label { Text(title).font(.orixCaption).foregroundStyle(Theme.textSecondary) } icon: {122                Image(systemName: symbol).font(.caption).foregroundStyle(tint)123            }124            DatePicker(title, selection: Binding(125                get: { model.calendar.date(bySettingHour: minute / 60, minute: minute % 60, second: 0, of: model.now()) ?? model.now() },126                set: { date in127                    let c = model.calendar.dateComponents([.hour, .minute], from: date)128                    set((c.hour ?? 0) * 60 + (c.minute ?? 0))129                }), displayedComponents: .hourAndMinute)130                .labelsHidden()131                // The wheel follows the app's 12/24-hour setting, like every other time in the app.132                .environment(\.locale, Locale(identifier: Fmt.time(ClockTime(hour: 13, minute: 0), use24h: use24h).period.isEmpty ? "en_GB" : "en_US"))133                .frame(minHeight: 44)134                .accessibilityIdentifier(identifier)135        }136        .frame(maxWidth: .infinity, alignment: .leading)137        .padding(12)138        .background(Theme.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))139    }140141    // MARK: Bedtime helper142    private var helperCard: some View {143        let desired = min(max(desiredMinutes, SleepPlanner.desiredRange.lowerBound), SleepPlanner.desiredRange.upperBound)144        let durationText = SleepFmt.span(desired)145        return VStack(alignment: .leading, spacing: 14) {146            Overline("Bedtime helper")147            Stepper(value: Binding(get: { desired }, set: { desiredMinutes = $0; Haptics.play(.tick) }), in: SleepPlanner.desiredRange, step: 15) {148                VStack(alignment: .leading, spacing: 2) {149                    Text("Desired time in bed").font(.orixCaption).foregroundStyle(Theme.textSecondary)150                    Text(durationText).font(.system(.title3, design: .rounded, weight: .semibold).monospacedDigit())151                }152            }153            .accessibilityValue(durationText)154            .accessibilityIdentifier("sleep.desired")155            Divider().overlay(Theme.hairline)156            if let next = model.nextAlarm {157                let bedDate = SleepPlanner.suggestedBedtimeDate(wakeDate: next.date, desiredMinutes: desired)158                let c = model.calendar.dateComponents([.hour, .minute], from: bedDate)159                let bedClock = ClockTime(hour: c.hour ?? 0, minute: c.minute ?? 0)160                let alarmName = next.alarm.name.isEmpty ? String(localized: "alarm") : String(localized: "“\(next.alarm.name)” alarm")161                HStack(alignment: .firstTextBaseline, spacing: 10) {162                    Image(systemName: "bed.double.fill").foregroundStyle(Theme.violet).accessibilityHidden(true)163                    Text("To get about \(durationText) in bed before your \(Fmt.timeString(next.alarm.time, use24h: use24h)) \(alarmName) (\(dayText(next.date))), go to bed by **\(Fmt.timeString(bedClock, use24h: use24h))**.")164                        .font(.orixBody)165                }166                .accessibilityElement(children: .combine)167                .accessibilityIdentifier("sleep.helper.text")168                if bedDate <= model.now() {169                    let left = max(0, next.date.timeIntervalSince(model.now()))170                    Label("That time has already passed. Going to bed now leaves about \(Fmt.duration((left / 60).rounded() * 60)) in bed.", systemImage: "clock.badge.exclamationmark")171                        .font(.orixCaption).foregroundStyle(Theme.gold)172                }173                if bedClock != plan.bedtime || next.alarm.time != plan.wakeTime {174                    Button("Use these times in my plan") {175                        Haptics.play(.success)176                        model.updateSleepPlan { $0.bedtime = bedClock; $0.wakeTime = next.alarm.time }177                    }178                    .buttonStyle(SecondaryButtonStyle())179                    .accessibilityIdentifier("sleep.helper.apply")180                } else {181                    Label("Your plan already uses these times.", systemImage: "checkmark.circle.fill")182                        .font(.orixCaption).foregroundStyle(Theme.success)183                }184            } else {185                let bedClock = SleepPlanner.suggestedBedtime(wake: plan.wakeTime, desiredMinutes: desired)186                HStack(alignment: .firstTextBaseline, spacing: 10) {187                    Image(systemName: "bed.double.fill").foregroundStyle(Theme.violet).accessibilityHidden(true)188                    Text("No alarm is switched on, so this uses your planned wake time. To get about \(durationText) in bed before \(Fmt.timeString(plan.wakeTime, use24h: use24h)), go to bed by **\(Fmt.timeString(bedClock, use24h: use24h))**.")189                        .font(.orixBody)190                }191                .accessibilityElement(children: .combine)192                .accessibilityIdentifier("sleep.helper.text")193                if bedClock != plan.bedtime {194                    Button("Use this bedtime in my plan") {195                        Haptics.play(.success)196                        model.updateSleepPlan { $0.bedtime = bedClock }197                    }198                    .buttonStyle(SecondaryButtonStyle())199                    .accessibilityIdentifier("sleep.helper.apply")200                }201            }202        }203        .glassCard()204    }205206    private func dayText(_ date: Date) -> String {207        let cal = model.calendar208        if cal.isDate(date, inSameDayAs: model.now()) { return String(localized: "today") }209        if let tomorrow = cal.date(byAdding: .day, value: 1, to: model.now()), cal.isDate(date, inSameDayAs: tomorrow) { return String(localized: "tomorrow") }210        return date.formatted(.dateTime.weekday(.wide))211    }212213    // MARK: Wind-down and reminders214    private var windDownCard: some View {215        let windDownStart = SleepPlanner.windDownStart(bedtime: plan.bedtime, windDownMinutes: plan.windDownMinutes)216        return VStack(alignment: .leading, spacing: 14) {217            Overline("Evening")218            VStack(alignment: .leading, spacing: 10) {219                Text("Wind-down").font(.orixHeadline)220                ScrollView(.horizontal, showsIndicators: false) {221                    HStack(spacing: 8) {222                        ForEach([0, 15, 30, 45, 60, 90], id: \.self) { minutes in223                            Chip(title: windDownLabel(minutes), isSelected: plan.windDownMinutes == minutes) {224                                Haptics.play(.selection)225                                model.updateSleepPlan { $0.windDownMinutes = minutes }226                            }227                            .frame(minHeight: 44)228                        }229                    }230                }231                .accessibilityIdentifier("sleep.windDown")232                Text(plan.windDownMinutes == 0233                     ? "No wind-down period before bedtime."234                     : "Wind-down starts at \(Fmt.timeString(windDownStart, use24h: use24h)), \(SleepFmt.span(plan.windDownMinutes)) before bedtime.")235                    .font(.orixCaption).foregroundStyle(Theme.textSecondary)236            }237            Divider().overlay(Theme.hairline)238            Toggle(isOn: Binding(get: { plan.remindersEnabled }, set: setReminders)) {239                VStack(alignment: .leading, spacing: 2) {240                    Text("Evening reminders").font(.orixHeadline)241                    Text("A notification when wind-down starts and one at bedtime, every day.")242                        .font(.orixCaption).foregroundStyle(Theme.textSecondary)243                }244            }245            .tint(Theme.violet)246            .disabled(!plan.isEnabled || isRequestingPermission)247            .accessibilityIdentifier("sleep.reminders")248            reminderStatus249        }250        .glassCard()251    }252253    private func windDownLabel(_ minutes: Int) -> String {254        switch minutes {255        case 0: String(localized: "None")256        case 60: String(localized: "1 h")257        case 90: String(localized: "1 h 30")258        default: String(localized: "\(minutes) min")259        }260    }261262    @ViewBuilder private var reminderStatus: some View {263        if !plan.isEnabled {264            Label("Turn on the sleep plan to use reminders.", systemImage: "info.circle")265                .font(.orixCaption).foregroundStyle(Theme.textSecondary)266        } else if permission == .denied {267            VStack(alignment: .leading, spacing: 10) {268                Label("Notifications are turned off", systemImage: "bell.slash.fill").font(.orixHeadline).foregroundStyle(Theme.gold)269                Text(plan.remindersEnabled270                     ? "Reminders are on in your plan, but iOS does not allow ORIX Alarm to send notifications, so none will arrive. Allow notifications in Settings. Your alarms are not affected: they do not use notifications."271                     : "iOS does not allow ORIX Alarm to send notifications, so evening reminders cannot be turned on. Allow notifications in Settings, then come back. Your alarms are not affected: they do not use notifications.")272                    .font(.orixCaption).foregroundStyle(Theme.textSecondary)273                Button("Open Settings") {274                    if let url = URL(string: UIApplication.openSettingsURLString) { openURL(url) }275                }276                .buttonStyle(SecondaryButtonStyle())277                .accessibilityIdentifier("sleep.reminders.settings")278            }279            .padding(14)280            .background(Theme.gold.opacity(0.12), in: RoundedRectangle(cornerRadius: 16, style: .continuous))281            .accessibilityIdentifier("sleep.reminders.denied")282        } else if plan.remindersEnabled {283            VStack(alignment: .leading, spacing: 6) {284                ForEach(SleepPlanner.reminders(for: plan)) { reminder in285                    Label {286                        Text(reminder.kind == .windDown287                             ? "Wind-down reminder every day at \(Fmt.timeString(reminder.time, use24h: use24h))"288                             : "Bedtime reminder every day at \(Fmt.timeString(reminder.time, use24h: use24h))")289                    } icon: { Image(systemName: reminder.kind == .windDown ? "sparkles" : "bed.double.fill") }290                        .font(.orixCaption).foregroundStyle(Theme.textSecondary)291                }292            }293            .accessibilityIdentifier("sleep.reminders.schedule")294        }295    }296297    private func setReminders(_ on: Bool) {298        Haptics.play(.selection)299        guard on else { model.updateSleepPlan { $0.remindersEnabled = false }; return }300        isRequestingPermission = true301        Task {302            // The permission is requested here, at the moment the user asks for reminders, never earlier.303            permission = await SleepReminders.requestPermission()304            isRequestingPermission = false305            if permission == .allowed { model.updateSleepPlan { $0.remindersEnabled = true } } else { Haptics.play(.warning) }306        }307    }308309    // MARK: Routine310    private var eveningKey: String { SleepPlanner.eveningDayKey(for: model.now(), calendar: model.calendar) }311    private var checked: Set<UUID> {312        SleepPlanner.checkedItems(storedDay: model.settings.routineDay, stored: model.settings.routineChecked, key: eveningKey, routine: plan.routine)313    }314315    private var routineCard: some View {316        let done = checked317        return VStack(alignment: .leading, spacing: 12) {318            HStack {319                Overline("Bedtime routine")320                Button("Edit") { showsRoutineEditor = true }321                    .font(.orixCaption).foregroundStyle(Theme.sunrise).frame(minWidth: 44, minHeight: 44)322                    .accessibilityIdentifier("sleep.routine.edit")323            }324            if plan.routine.isEmpty {325                Text("Your routine is empty. Add a few steps you want to do before bed.")326                    .font(.orixCaption).foregroundStyle(Theme.textSecondary)327                Button("Add routine items") { showsRoutineEditor = true }.buttonStyle(SecondaryButtonStyle())328            } else {329                ProgressView(value: Double(done.count), total: Double(plan.routine.count))330                    .tint(Theme.success)331                    .accessibilityLabel("Routine progress")332                    .accessibilityValue("\(done.count) of \(plan.routine.count) done")333                VStack(spacing: 0) {334                    ForEach(plan.routine) { item in335                        let isDone = done.contains(item.id)336                        Button { toggle(item.id) } label: {337                            HStack(spacing: 12) {338                                Image(systemName: isDone ? "checkmark.circle.fill" : "circle")339                                    .font(.title3).foregroundStyle(isDone ? Theme.success : Theme.textTertiary)340                                Image(systemName: item.symbol).foregroundStyle(Theme.gold).frame(width: 26)341                                Text(item.title).font(.orixBody)342                                    .foregroundStyle(isDone ? Theme.textSecondary : Theme.textPrimary)343                                    .strikethrough(isDone, color: Theme.textTertiary)344                                    .multilineTextAlignment(.leading)345                                Spacer(minLength: 0)346                            }347                            .frame(minHeight: 48)348                            .contentShape(Rectangle())349                        }350                        .buttonStyle(.plain)351                        .accessibilityLabel(item.title)352                        .accessibilityValue(isDone ? "Done" : "Not done")353                        .accessibilityAddTraits(isDone ? .isSelected : [])354                        .accessibilityIdentifier("sleep.routine.item")355                    }356                }357                Text(done.count == plan.routine.count358                     ? "All done for tonight. The checklist starts fresh tomorrow at noon."359                     : "\(done.count) of \(plan.routine.count) done tonight. The checklist starts fresh every day at noon.")360                    .font(.orixCaption).foregroundStyle(Theme.textSecondary)361                    .accessibilityIdentifier("sleep.routine.progress")362            }363        }364        .glassCard()365    }366367    private func toggle(_ id: UUID) {368        let key = eveningKey369        var wasCompleted = false370        model.updateSettings { settings in371            if settings.routineDay != key { settings.routineDay = key; settings.routineChecked = [] }372            if settings.routineChecked.contains(id) { settings.routineChecked.remove(id) } else { settings.routineChecked.insert(id); wasCompleted = true }373        }374        Haptics.play(wasCompleted && checked.count == plan.routine.count ? .success : .selection)375    }376}377
Files main
Menu

Theme