Repository Public License
1// ORIX Alarm2// File: App/Features/Studio/ScenarioEditorSheet.swift3// Description: Alarm Studio sheets: saved-scenario editor (reusing the editor's scenario sections) and the picker that applies a scenario to an existing alarm.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct ScenarioEditorSheet: View {11 struct Target: Identifiable {12 var scenario: SavedScenario13 var isNew: Bool14 var id: UUID { scenario.id }15 }1617 let target: Target18 @Environment(AppModel.self) private var model19 @Environment(\.dismiss) private var dismiss20 @State private var draft: SavedScenario21 @State private var showDelete = false22 @State private var showDiscard = false2324 init(target: Target) {25 self.target = target26 _draft = State(initialValue: target.scenario)27 }2829 private var trimmedName: String { draft.name.trimmingCharacters(in: .whitespacesAndNewlines) }30 private var problems: [String] {31 (trimmedName.isEmpty ? [String(localized: "Give the scenario a name.")] : []) + ScenarioValidation.messages(for: draft.scenario, qrTags: model.qrTags)32 }3334 var body: some View {35 NavigationStack {36 ScrollView {37 VStack(spacing: 18) {38 ScenarioIdentityFields(name: $draft.name, symbol: $draft.symbol)39 ScenarioSectionsView(scenario: $draft.scenario, soundID: $draft.soundID, time: nil,40 previewName: trimmedName.isEmpty ? String(localized: "Preview") : trimmedName)41 if !target.isNew {42 Button(role: .destructive) { showDelete = true } label: {43 Label("Delete scenario", systemImage: "trash").font(.orixHeadline).foregroundStyle(Theme.danger).frame(maxWidth: .infinity, minHeight: 50)44 }45 .buttonStyle(.plain)46 .accessibilityIdentifier("studio.editor.delete")47 }48 }49 .padding(.horizontal, 18).padding(.top, 8).padding(.bottom, 28)50 }51 .scrollDismissesKeyboard(.interactively)52 .safeAreaInset(edge: .bottom, spacing: 0) {53 if !problems.isEmpty {54 VStack(alignment: .leading, spacing: 6) {55 Label("This scenario cannot be saved yet", systemImage: "exclamationmark.circle.fill").font(.orixHeadline).foregroundStyle(Theme.gold)56 Text(problems.joined(separator: "\n")).font(.orixCaption).foregroundStyle(Theme.textPrimary.opacity(0.85)).fixedSize(horizontal: false, vertical: true)57 }58 .frame(maxWidth: .infinity, alignment: .leading)59 .padding(16)60 .background {61 RoundedRectangle(cornerRadius: 22, style: .continuous).fill(Theme.midnight)62 .overlay(RoundedRectangle(cornerRadius: 22, style: .continuous).fill(Theme.gold.opacity(0.14)))63 .overlay(RoundedRectangle(cornerRadius: 22, style: .continuous).strokeBorder(Theme.gold.opacity(0.55)))64 }65 .padding(.horizontal, 14).padding(.vertical, 8)66 .accessibilityElement(children: .contain).accessibilityIdentifier("studio.editor.issues")67 }68 }69 .navigationTitle(target.isNew ? "New scenario" : "Edit scenario").navigationBarTitleDisplayMode(.inline)70 .toolbar {71 ToolbarItem(placement: .cancellationAction) {72 Button("Cancel") { if draft != target.scenario { showDiscard = true } else { dismiss() } }.accessibilityIdentifier("studio.editor.cancel")73 }74 ToolbarItem(placement: .confirmationAction) {75 Button("Save") {76 var saved = draft; saved.name = trimmedName77 model.saveScenario(saved)78 Haptics.play(.success); dismiss()79 }80 .fontWeight(.semibold).disabled(!problems.isEmpty)81 .accessibilityIdentifier("studio.editor.save")82 }83 }84 .orixScreen(warmth: 0.2)85 }86 .interactiveDismissDisabled(draft != target.scenario)87 .confirmationDialog("Delete this scenario?", isPresented: $showDelete, titleVisibility: .visible) {88 Button("Delete scenario", role: .destructive) { model.deleteScenario(draft.id); Haptics.play(.warning); dismiss() }89 Button("Keep", role: .cancel) {}90 } message: { Text("Alarms that already use it keep their own copy and are not changed.") }91 .confirmationDialog("Discard your changes?", isPresented: $showDiscard, titleVisibility: .visible) {92 Button("Discard changes", role: .destructive) { dismiss() }93 Button("Keep editing", role: .cancel) {}94 }95 }96}9798/// Picks the existing alarm that receives a saved scenario (its scenario and sound are replaced).99struct ApplyScenarioSheet: View {100 let scenario: SavedScenario101 /// Reports the outcome (title, message) once the alarm has been saved.102 let onResult: (String, String) -> Void103 @Environment(AppModel.self) private var model104 @Environment(\.dismiss) private var dismiss105 @State private var isWorking = false106107 var body: some View {108 NavigationStack {109 ScrollView {110 VStack(alignment: .leading, spacing: 12) {111 Text("The chosen alarm keeps its time, days and name. Its sound, gentle wake, missions, snooze rules and confirmation are replaced by “\(scenario.name)”.")112 .font(.orixCaption).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)113 if model.alarms.isEmpty {114 Text("There is no alarm yet. Use “Apply to a new alarm” instead.").font(.orixBody).frame(maxWidth: .infinity, alignment: .leading).glassCard()115 }116 ForEach(model.alarms) { alarm in117 Button { apply(to: alarm) } label: {118 HStack(spacing: 14) {119 VStack(alignment: .leading, spacing: 3) {120 Text(Fmt.timeString(alarm.time, use24h: model.settings.use24HourClock)).font(.system(size: 24, weight: .medium, design: .rounded)).monospacedDigit()121 Text([alarm.name, Fmt.recurrence(alarm.weekdays)].filter { !$0.isEmpty }.joined(separator: " · "))122 .font(.orixCaption).foregroundStyle(Theme.textSecondary).lineLimit(1)123 }124 Spacer()125 if !alarm.isEnabled { Text("Off").font(.orixCaption).foregroundStyle(Theme.textTertiary) }126 Image(systemName: "arrow.right.circle.fill").font(.title3).foregroundStyle(Theme.gold).accessibilityHidden(true)127 }128 .frame(maxWidth: .infinity, alignment: .leading)129 .glassCard(padding: 16, radius: 20)130 }131 .buttonStyle(.plain)132 .disabled(isWorking)133 .accessibilityIdentifier("studio.apply.\(alarm.id.uuidString)")134 }135 }136 .padding(18)137 }138 .navigationTitle("Apply to an alarm").navigationBarTitleDisplayMode(.inline)139 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } }140 .orixScreen()141 }142 .presentationDetents([.medium, .large])143 }144145 private func apply(to alarm: AlarmDefinition) {146 isWorking = true147 var updated = alarm148 updated.scenario = scenario.detachedScenario149 updated.soundID = scenario.soundID150 let label = alarm.name.isEmpty ? Fmt.timeString(alarm.time, use24h: model.settings.use24HourClock) : alarm.name151 Task {152 let error = await model.save(updated)153 isWorking = false154 dismiss()155 if let error {156 Haptics.play(.failure)157 onResult(String(localized: "Saved, but NOT scheduled"),158 String(localized: "“\(scenario.name)” was applied to \(label) and saved on this iPhone, but iOS did not schedule the alarm: it will not ring until scheduling succeeds. Reason: \(error)"))159 } else {160 Haptics.play(.success)161 onResult(String(localized: "Scenario applied"),162 alarm.isEnabled ? String(localized: "\(label) now uses “\(scenario.name)” and is scheduled.")163 : String(localized: "\(label) now uses “\(scenario.name)”. The alarm is off, so it is not scheduled."))164 }165 }166 }167}168