SPB Git

Repository Public License

AlarmEditorView.swift 19.8 KB 390 lines swift

1// ORIX Alarm2// File: App/Features/Editor/AlarmEditorView.swift3// Description: Alarm editor sheet: circular time dial, name, recurrence, scenario sections, live timeline, validation, save with honest scheduling feedback, delete.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct AlarmEditorView: View {11    let alarm: AlarmDefinition12    let isNew: Bool1314    @Environment(AppModel.self) private var model15    @Environment(\.dismiss) private var dismiss16    @State private var draft: AlarmDefinition17    @State private var isSaving = false18    @State private var saveError: String?19    /// True once the draft reached the library (even when scheduling failed).20    @State private var isStored: Bool21    @State private var showDelete = false22    @State private var showDiscard = false23    @State private var showTimeEntry = false24    @State private var showSaveScenario = false25    @State private var scenarioSavedName: String?2627    init(alarm: AlarmDefinition, isNew: Bool) {28        self.alarm = alarm; self.isNew = isNew29        _draft = State(initialValue: alarm)30        _isStored = State(initialValue: !isNew)31    }3233    private var issues: [Recurrence.ValidationIssue] { model.validationIssues(for: draft) }34    private var hasChanges: Bool { draft != alarm }35    private var hourValue: Double { Double(draft.time.hour) + Double(draft.time.minute) / 60 }3637    var body: some View {38        NavigationStack {39            ScrollView {40                VStack(spacing: 18) {41                    timeCard42                    detailsCard43                    ScenarioSectionsView(scenario: $draft.scenario, soundID: $draft.soundID, time: draft.time,44                                         previewName: draft.name.isEmpty ? String(localized: "Preview") : draft.name)45                    footerActions46                }47                .padding(.horizontal, 18).padding(.top, 8).padding(.bottom, 28)48            }49            .scrollDismissesKeyboard(.interactively)50            .safeAreaInset(edge: .bottom, spacing: 0) { bottomBanner }51            .navigationTitle(isNew ? "New alarm" : "Edit alarm")52            .navigationBarTitleDisplayMode(.inline)53            .toolbar {54                ToolbarItem(placement: .cancellationAction) {55                    Button("Cancel") { if hasChanges && saveError == nil { showDiscard = true } else { close() } }56                        .accessibilityIdentifier("editor.cancel")57                }58                ToolbarItem(placement: .confirmationAction) {59                    Button(isSaving ? "Saving…" : "Save") { save() }60                        .fontWeight(.semibold)61                        .disabled(isSaving || !issues.isEmpty)62                        .accessibilityIdentifier("editor.save")63                }64            }65            .orixScreen(warmth: DayTint.warmth(hour: hourValue) * 0.45)66            .animation(.smooth(duration: 0.6), value: draft.time.hour)67        }68        .interactiveDismissDisabled(hasChanges || isSaving)69        .presentationDetents([.large])70        .sheet(isPresented: $showTimeEntry) { TimeEntrySheet(time: $draft.time, use24h: model.settings.use24HourClock) }71        .sheet(isPresented: $showSaveScenario) {72            SaveScenarioSheet(suggestedName: draft.name, suggestedSymbol: ScenarioTemplates.template(draft.scenario.templateID)?.symbol ?? "sparkles") { name, symbol in73                var scenario = draft.scenario74                scenario.missions = scenario.missions.map { var m = $0; m.id = UUID(); return m }75                model.saveScenario(SavedScenario(name: name, symbol: symbol, scenario: scenario, soundID: draft.soundID))76                Haptics.play(.success)77                withAnimation(.smooth) { scenarioSavedName = name }78            }79        }80        .confirmationDialog("Delete this alarm?", isPresented: $showDelete, titleVisibility: .visible) {81            Button("Delete alarm", role: .destructive) {82                SoundPlayer.shared.stopPreview()83                model.delete(draft.id); Haptics.play(.warning); close()84            }85            .accessibilityIdentifier("editor.delete.confirm")86            Button("Keep", role: .cancel) {}87        } message: { Text("The alarm is removed from this iPhone and from the system schedule. Its history stays in your statistics.") }88        .confirmationDialog("Discard your changes?", isPresented: $showDiscard, titleVisibility: .visible) {89            Button("Discard changes", role: .destructive) { close() }90            Button("Keep editing", role: .cancel) {}91        }92    }9394    // MARK: Time95    private var timeCard: some View {96        VStack(spacing: 16) {97            TimeDial(time: $draft.time, use24h: model.settings.use24HourClock)98            Button { showTimeEntry = true } label: {99                Label("Enter time", systemImage: "keyboard").font(.orixCaption).foregroundStyle(Theme.textSecondary)100                    .padding(.horizontal, 16).frame(minHeight: 44)101            }102            .buttonStyle(.plain)103            .accessibilityHint("Shows a standard time picker")104            .accessibilityIdentifier("editor.timeFallback")105        }106        .frame(maxWidth: .infinity)107        .glassCard(padding: 16)108    }109110    // MARK: Name and recurrence111    private var detailsCard: some View {112        EditorCard(title: "Alarm", symbol: "alarm.fill", tint: Theme.gold) {113            TextField("Name (optional)", text: $draft.name)114                .font(.orixBody).textInputAutocapitalization(.sentences).submitLabel(.done)115                .padding(.horizontal, 14).frame(minHeight: 48)116                .background(Theme.surface, in: RoundedRectangle(cornerRadius: 14, style: .continuous))117                .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Theme.hairline))118                .accessibilityLabel("Alarm name")119                .accessibilityIdentifier("editor.name")120121            VStack(alignment: .leading, spacing: 10) {122                Text("Repeat").font(.orixBody)123                HStack(spacing: 0) {124                    ForEach(Array(Weekday.ordered(firstWeekday: model.calendar.firstWeekday).enumerated()), id: \.element) { index, day in125                        if index > 0 { Spacer(minLength: 2) }126                        dayChip(day)127                    }128                }129                HStack(spacing: 6) {130                    shortcut(String(localized: "Once"), [], id: "once")131                    shortcut(String(localized: "Weekdays"), Weekday.weekdays, id: "weekdays")132                    shortcut(String(localized: "Weekends"), Weekday.weekend, id: "weekends")133                    shortcut(String(localized: "Every day"), Weekday.everyDay, id: "everyday")134                }135            }136137            nextOccurrence138139            if !isNew {140                Divider().overlay(Theme.hairline)141                ToggleRow(title: "Enabled", detail: "When off, the alarm stays saved but is not scheduled.", isOn: $draft.isEnabled)142                    .accessibilityIdentifier("editor.enabled")143            }144        }145    }146147    private func dayChip(_ day: Weekday) -> some View {148        let isOn = draft.weekdays.contains(day)149        return Button {150            Haptics.play(.selection)151            withAnimation(.snappy(duration: 0.18)) { if isOn { draft.weekdays.remove(day) } else { draft.weekdays.insert(day) } }152        } label: {153            VStack(spacing: 3) {154                Text(Fmt.weekdaySymbol(day, style: 1).prefix(2)).font(.system(size: 13, weight: .bold, design: .rounded))155                Image(systemName: isOn ? "checkmark" : "circle").font(.system(size: 7, weight: .heavy)).opacity(isOn ? 1 : 0.35)156            }157            .foregroundStyle(isOn ? Theme.midnight : Theme.textSecondary)158            .frame(width: 40, height: 48)159            .background(isOn ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Theme.surfaceRaised), in: RoundedRectangle(cornerRadius: 14, style: .continuous))160            .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(isOn ? .clear : Theme.hairline))161            .frame(minWidth: 44)162            .contentShape(Rectangle())163        }164        .buttonStyle(.plain)165        .accessibilityLabel(Fmt.weekdaySymbol(day, style: 2))166        .accessibilityValue(isOn ? Text("On") : Text("Off"))167        .accessibilityAddTraits(isOn ? .isSelected : [])168        .accessibilityIdentifier("editor.weekday.\(day.rawValue)")169    }170171    private func shortcut(_ title: String, _ days: Set<Weekday>, id: String) -> some View {172        let isOn = draft.weekdays == days173        return Button {174            Haptics.play(.selection)175            withAnimation(.snappy(duration: 0.18)) { draft.weekdays = days }176        } label: {177            Text(title).font(.orixCaption).lineLimit(1).minimumScaleFactor(0.75)178                .foregroundStyle(isOn ? Theme.midnight : Theme.textPrimary)179                .padding(.horizontal, 6).frame(maxWidth: .infinity, minHeight: 36)180                .background(isOn ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Theme.surfaceRaised), in: Capsule())181                .overlay(Capsule().strokeBorder(isOn ? .clear : Theme.hairline))182                .frame(minHeight: 44).contentShape(Rectangle())183        }184        .buttonStyle(.plain)185        .accessibilityAddTraits(isOn ? .isSelected : [])186        .accessibilityIdentifier("editor.repeat.\(id)")187    }188189    private var nextOccurrence: some View {190        let now = model.now()191        let next = Recurrence.nextFireDate(time: draft.time, weekdays: draft.weekdays, after: now, calendar: model.calendar)192        return HStack(alignment: .top, spacing: 10) {193            Image(systemName: draft.isEnabled ? "bell.badge.fill" : "bell.slash.fill").font(.footnote)194                .foregroundStyle(draft.isEnabled ? Theme.gold : Theme.textTertiary).padding(.top, 2).accessibilityHidden(true)195            VStack(alignment: .leading, spacing: 2) {196                if let next {197                    Text(draft.isEnabled ? "Next: \(dayText(next, now: now)) at \(clockText(next))" : "Off. If enabled: \(dayText(next, now: now)) at \(clockText(next))")198                        .font(.system(.subheadline, design: .rounded, weight: .semibold))199                    Text("\(Fmt.countdown(to: next, from: now)) · \(draft.weekdays.isEmpty ? String(localized: "rings once, then turns itself off") : Fmt.recurrence(draft.weekdays))")200                        .font(.orixCaption).foregroundStyle(Theme.textSecondary)201                    if isShiftedByClockChange(next) {202                        Text("That day the clocks change: this time does not exist, so the alarm rings at the first valid time after it.")203                            .font(.orixCaption).foregroundStyle(Theme.gold).fixedSize(horizontal: false, vertical: true)204                    }205                } else {206                    Text("No upcoming occurrence").font(.system(.subheadline, design: .rounded, weight: .semibold)).foregroundStyle(Theme.danger)207                }208            }209            Spacer(minLength: 0)210        }211        .padding(12)212        .background(Theme.midnight.opacity(0.35), in: RoundedRectangle(cornerRadius: 14, style: .continuous))213        .accessibilityElement(children: .combine)214        .accessibilityIdentifier("editor.nextOccurrence")215    }216217    private func dayText(_ date: Date, now: Date) -> String {218        let calendar = model.calendar219        if calendar.isDate(date, inSameDayAs: now) { return String(localized: "today") }220        if let tomorrow = calendar.date(byAdding: .day, value: 1, to: now), calendar.isDate(date, inSameDayAs: tomorrow) { return String(localized: "tomorrow") }221        return date.formatted(.dateTime.weekday(.wide).month(.abbreviated).day())222    }223224    private func clockText(_ date: Date) -> String {225        let c = model.calendar.dateComponents([.hour, .minute], from: date)226        return Fmt.timeString(ClockTime(hour: c.hour ?? draft.time.hour, minute: c.minute ?? draft.time.minute), use24h: model.settings.use24HourClock)227    }228229    private func isShiftedByClockChange(_ date: Date) -> Bool {230        let c = model.calendar.dateComponents([.hour, .minute], from: date)231        return c.hour != draft.time.hour || c.minute != draft.time.minute232    }233234    // MARK: Footer235    private var footerActions: some View {236        VStack(spacing: 12) {237            Button { showSaveScenario = true } label: { Label("Save as scenario", systemImage: "square.and.arrow.down.on.square") }238                .buttonStyle(SecondaryButtonStyle())239                .accessibilityHint("Keeps this sound, gentle wake, missions and snooze rules in Alarm Studio for reuse")240                .accessibilityIdentifier("editor.saveScenario")241            if let scenarioSavedName {242                Label("“\(scenarioSavedName)” saved to Alarm Studio", systemImage: "checkmark.circle.fill")243                    .font(.orixCaption).foregroundStyle(Theme.success).transition(.opacity)244            }245            if isStored {246                Button(role: .destructive) { showDelete = true } label: {247                    Label("Delete alarm", systemImage: "trash").font(.orixHeadline).foregroundStyle(Theme.danger).frame(maxWidth: .infinity, minHeight: 50)248                }249                .buttonStyle(.plain)250                .accessibilityIdentifier("editor.delete")251            }252        }253        .padding(.top, 4)254    }255256    // MARK: Validation and scheduling feedback257    @ViewBuilder private var bottomBanner: some View {258        if let saveError {259            banner(symbol: "exclamationmark.triangle.fill", tint: Theme.danger, title: "Saved, but NOT scheduled",260                   text: String(localized: "This alarm is saved on this iPhone, but iOS did not schedule it: it will not ring until scheduling succeeds. Reason: \(saveError)")) {261                HStack(spacing: 10) {262                    Button("Close") { close() }.buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("editor.error.close")263                    Button("Try again") { save() }.buttonStyle(PrimaryButtonStyle()).disabled(isSaving).accessibilityIdentifier("editor.error.retry")264                }265            }266            .accessibilityElement(children: .contain).accessibilityIdentifier("editor.error")267        } else if !issues.isEmpty {268            banner(symbol: "exclamationmark.circle.fill", tint: Theme.gold, title: "This alarm cannot be saved yet",269                   text: issues.map(ScenarioValidation.message).joined(separator: "\n")) { EmptyView() }270                .accessibilityElement(children: .contain).accessibilityIdentifier("editor.issues")271        }272    }273274    private func banner<Actions: View>(symbol: String, tint: Color, title: LocalizedStringKey, text: String, @ViewBuilder actions: () -> Actions) -> some View {275        VStack(alignment: .leading, spacing: 10) {276            Label(title, systemImage: symbol).font(.orixHeadline).foregroundStyle(tint)277            Text(text).font(.orixCaption).foregroundStyle(Theme.textPrimary.opacity(0.85)).fixedSize(horizontal: false, vertical: true)278            actions()279        }280        .frame(maxWidth: .infinity, alignment: .leading)281        .padding(16)282        .background {283            RoundedRectangle(cornerRadius: 22, style: .continuous).fill(Theme.midnight)284                .overlay(RoundedRectangle(cornerRadius: 22, style: .continuous).fill(tint.opacity(0.14)))285                .overlay(RoundedRectangle(cornerRadius: 22, style: .continuous).strokeBorder(tint.opacity(0.55)))286        }287        .padding(.horizontal, 14).padding(.bottom, 8).padding(.top, 6)288        .transition(.move(edge: .bottom).combined(with: .opacity))289    }290291    // MARK: Actions292    private func save() {293        guard !isSaving, issues.isEmpty else { return }294        isSaving = true295        SoundPlayer.shared.stopPreview()296        Task {297            let error = await model.save(draft)298            isSaving = false299            if let error {300                isStored = true301                Haptics.play(.failure)302                withAnimation(.smooth) { saveError = error }303            } else {304                Haptics.play(.alarmSet)305                close()306            }307        }308    }309310    private func close() {311        SoundPlayer.shared.stopPreview()312        model.editingAlarm = nil313        dismiss()314    }315}316317/// Name and symbol prompt used to keep a scenario in Alarm Studio.318struct SaveScenarioSheet: View {319    @State private var name: String320    @State private var symbol: String321    let onSave: (String, String) -> Void322    @Environment(\.dismiss) private var dismiss323324    static let symbols = ["sparkles", "sun.horizon.fill", "sunrise.fill", "moon.stars.fill", "bolt.fill", "figure.run", "briefcase.fill", "cup.and.saucer.fill",325                          "airplane.departure", "graduationcap.fill", "leaf.fill", "flame.fill", "heart.fill", "book.fill", "dumbbell.fill", "music.note"]326327    init(suggestedName: String, suggestedSymbol: String, onSave: @escaping (String, String) -> Void) {328        _name = State(initialValue: suggestedName)329        _symbol = State(initialValue: Self.symbols.contains(suggestedSymbol) ? suggestedSymbol : "sparkles")330        self.onSave = onSave331    }332333    private var trimmed: String { name.trimmingCharacters(in: .whitespacesAndNewlines) }334335    var body: some View {336        NavigationStack {337            ScrollView {338                VStack(spacing: 16) {339                    ScenarioIdentityFields(name: $name, symbol: $symbol)340                    Text("The scenario keeps the sound, gentle wake, missions, snooze rules and confirmation. Time and days stay with the alarm.")341                        .font(.orixCaption).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)342                }343                .padding(18)344            }345            .navigationTitle("Save as scenario").navigationBarTitleDisplayMode(.inline)346            .toolbar {347                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }348                ToolbarItem(placement: .confirmationAction) {349                    Button("Save") { onSave(trimmed, symbol); dismiss() }.fontWeight(.semibold).disabled(trimmed.isEmpty)350                        .accessibilityIdentifier("editor.saveScenario.confirm")351                }352            }353            .orixScreen()354        }355        .presentationDetents([.medium, .large])356    }357}358359/// Name field and symbol grid of a saved scenario.360struct ScenarioIdentityFields: View {361    @Binding var name: String362    @Binding var symbol: String363364    var body: some View {365        EditorCard(title: "Scenario", symbol: symbol, tint: Theme.gold) {366            TextField("Scenario name", text: $name)367                .font(.orixBody).submitLabel(.done)368                .padding(.horizontal, 14).frame(minHeight: 48)369                .background(Theme.surface, in: RoundedRectangle(cornerRadius: 14, style: .continuous))370                .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Theme.hairline))371                .accessibilityIdentifier("scenario.name")372            LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 8), spacing: 6) {373                ForEach(SaveScenarioSheet.symbols, id: \.self) { candidate in374                    Button {375                        Haptics.play(.selection); symbol = candidate376                    } label: {377                        Image(systemName: candidate).font(.system(size: 15, weight: .semibold))378                            .foregroundStyle(symbol == candidate ? Theme.midnight : Theme.textSecondary)379                            .frame(maxWidth: .infinity).frame(height: 44)380                            .background(symbol == candidate ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Theme.surface), in: RoundedRectangle(cornerRadius: 12, style: .continuous))381                    }382                    .buttonStyle(.plain)383                    .accessibilityLabel(candidate.replacingOccurrences(of: ".fill", with: "").replacingOccurrences(of: ".", with: " "))384                    .accessibilityAddTraits(symbol == candidate ? .isSelected : [])385                }386            }387        }388    }389}390
Files main
Menu

Theme