Repository Public License
1// ORIX Alarm2// File: App/Features/Missions/MissionRunnerView.swift3// Description: Runs a mission sequence (Morning Combo): progress, per-step hosting, fallback for unavailable hardware, emergency exit, wake confirmation and morning summary.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910/// Maps a resolved mission to its view. Every mission view takes the mission and reports one `MissionOutcome`.11enum MissionRegistry {12 @ViewBuilder13 static func view(for mission: ResolvedMission, onFinish: @escaping (MissionOutcome) -> Void) -> some View {14 switch mission.kind {15 case .math: MathMissionView(mission: mission, onFinish: onFinish)16 case .memoryMatrix: MemoryMatrixMissionView(mission: mission, onFinish: onFinish)17 case .qrEscape: QRMissionView(mission: mission, onFinish: onFinish)18 case .steps: StepMissionView(mission: mission, onFinish: onFinish)19 case .patternLock: PatternLockMissionView(mission: mission, onFinish: onFinish)20 case .wordScramble: WordScrambleMissionView(mission: mission, onFinish: onFinish)21 case .logicGates: LogicGatesMissionView(mission: mission, onFinish: onFinish)22 case .maze: MazeMissionView(mission: mission, onFinish: onFinish)23 case .colorSequence: ColorSequenceMissionView(mission: mission, onFinish: onFinish)24 }25 }26}2728struct MissionRunnerView: View {29 @Environment(AppModel.self) private var model30 let run: MissionRun31 /// Called when the runner should close. Defaults to clearing `AppModel.missionRun`.32 var onClose: (() -> Void)? = nil3334 private enum Stage: Equatable { case playing, confirm, summary }35 @State private var missions: [ResolvedMission] = []36 @State private var index = 037 @State private var stage: Stage = .playing38 @State private var outcomes: [MissionOutcome] = []39 @State private var notice: String?40 @State private var showExit = false41 @State private var bypassed = false4243 var body: some View {44 ZStack {45 AuroraBackground(warmth: stage == .playing ? 0.15 + 0.5 * progress : 0.9)46 VStack(spacing: 0) {47 header48 Group {49 switch stage {50 case .playing:51 if missions.indices.contains(index) {52 let mission = missions[index]53 MissionRegistry.view(for: mission) { finish(mission, $0) }54 .id(mission.id)55 .transition(.asymmetric(insertion: .move(edge: .trailing).combined(with: .opacity), removal: .move(edge: .leading).combined(with: .opacity)))56 }57 case .confirm: confirmation58 case .summary: summary59 }60 }61 .frame(maxWidth: .infinity, maxHeight: .infinity)62 }63 }64 .preferredColorScheme(.dark)65 .interactiveDismissDisabled()66 .onAppear {67 missions = run.missions68 if missions.isEmpty { stage = run.requiresConfirmation ? .confirm : .summary }69 }70 .confirmationDialog("Leave the wake mission?", isPresented: $showExit, titleVisibility: .visible) {71 Button(run.isPreview ? "End preview" : "Use emergency exit", role: .destructive) { emergencyExit() }72 Button("Keep going", role: .cancel) {}73 } message: {74 Text(run.isPreview ? "Nothing is recorded during a preview." : "The emergency exit is always available. It is recorded as a bypass in your statistics.")75 }76 }7778 private var progress: Double { missions.isEmpty ? 1 : Double(index) / Double(missions.count) }7980 private var header: some View {81 VStack(spacing: 12) {82 HStack {83 VStack(alignment: .leading, spacing: 2) {84 Text(run.isPreview ? "Preview" : (run.alarmName.isEmpty ? "Wake mission" : run.alarmName)).font(.orixOverline).kerning(1.2).foregroundStyle(Theme.textTertiary)85 if stage == .playing, missions.indices.contains(index) {86 Label(missions[index].kind.title, systemImage: missions[index].kind.symbol).font(.orixHeadline)87 }88 }89 Spacer()90 if stage != .summary {91 Menu {92 if stage == .playing, missions.indices.contains(index) {93 Button("Switch to an alternative mission", systemImage: "arrow.triangle.swap") { swapToAlternative(reason: nil) }94 }95 Button(run.isPreview ? "End preview" : "Emergency exit", systemImage: "door.right.hand.open", role: .destructive) { showExit = true }96 } label: {97 Image(systemName: "ellipsis.circle.fill").font(.title2).foregroundStyle(Theme.textSecondary).frame(width: 44, height: 44)98 }99 .accessibilityLabel("Mission options")100 .accessibilityIdentifier("mission.options")101 }102 }103 if stage == .playing, missions.count > 1 {104 HStack(spacing: 6) {105 ForEach(missions.indices, id: \.self) { i in106 Capsule().fill(i < index ? AnyShapeStyle(Theme.success) : (i == index ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Theme.surfaceRaised)))107 .frame(height: 5)108 }109 }110 .accessibilityElement().accessibilityLabel("Step \(index + 1) of \(missions.count)")111 }112 if let notice {113 Text(notice).font(.orixCaption).foregroundStyle(Theme.gold).frame(maxWidth: .infinity, alignment: .leading)114 }115 }116 .padding(.horizontal, 20).padding(.top, 8)117 }118119 private var confirmation: some View {120 VStack(spacing: 28) {121 Spacer()122 Image(systemName: "sun.max.fill").font(.system(size: 84)).foregroundStyle(Theme.sunriseGradient).symbolEffect(.breathe).accessibilityHidden(true)123 Text("Are you up?").font(.system(size: 34, weight: .bold, design: .rounded))124 Text("Confirm once you are out of bed. Only this confirmation counts as a wake-up in your statistics.")125 .font(.orixBody).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.center)126 Spacer()127 Button("I'm up") {128 model.confirmWake(run); Haptics.play(.wakeConfirmed)129 withAnimation(.smooth) { stage = .summary }130 }131 .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("mission.confirmWake")132 }133 .padding(24)134 }135136 private var summary: some View {137 VStack(spacing: 22) {138 Spacer()139 Image(systemName: bypassed ? "door.right.hand.open" : "checkmark.seal.fill").font(.system(size: 72))140 .foregroundStyle(bypassed ? AnyShapeStyle(Theme.textSecondary) : AnyShapeStyle(Theme.sunriseGradient)).accessibilityHidden(true)141 Text(bypassed ? "Mission skipped" : (run.isPreview ? "Preview complete" : "Good morning")).font(.system(size: 34, weight: .bold, design: .rounded))142 .accessibilityIdentifier("mission.summaryTitle")143 if !outcomes.isEmpty {144 HStack(spacing: 12) {145 stat(Fmt.duration(outcomes.map(\.duration).reduce(0, +)), "Total time")146 stat("\(outcomes.map(\.mistakes).reduce(0, +))", "Mistakes")147 stat("\(outcomes.count)", outcomes.count == 1 ? "Mission" : "Missions")148 }149 }150 if let next = model.nextAlarm {151 Label("Next alarm \(Fmt.countdown(to: next.date, from: model.now()))", systemImage: "alarm").font(.orixCaption).foregroundStyle(Theme.textSecondary)152 }153 Spacer()154 Button("Done") { close() }.buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("mission.done")155 }156 .padding(24)157 }158159 private func stat(_ value: String, _ label: LocalizedStringKey) -> some View {160 VStack(spacing: 4) {161 Text(value).font(.system(.title3, design: .rounded, weight: .semibold)).monospacedDigit()162 Text(label).font(.orixCaption).foregroundStyle(Theme.textSecondary)163 }164 .frame(maxWidth: .infinity).glassCard(padding: 14).accessibilityElement(children: .combine)165 }166167 private func finish(_ mission: ResolvedMission, _ outcome: MissionOutcome) {168 guard stage == .playing, missions.indices.contains(index), missions[index].id == mission.id else { return }169 if outcome.result == .unavailable {170 swapToAlternative(reason: String(localized: "\(mission.kind.title) is not available on this device right now. Here is an alternative."))171 return172 }173 outcomes.append(outcome)174 model.missionStepCompleted(run, mission: mission, outcome: outcome)175 Haptics.play(.missionComplete); SoundFX.play(.complete)176 notice = nil177 withAnimation(.smooth(duration: 0.45)) {178 if index + 1 < missions.count { index += 1 } else {179 model.missionSequenceEnded(run, bypassed: false)180 stage = run.requiresConfirmation ? .confirm : .summary181 }182 }183 }184185 /// Replaces the current step by its alternative mission (hardware unavailable, or chosen for accessibility).186 private func swapToAlternative(reason: String?) {187 guard missions.indices.contains(index) else { return }188 let current = missions[index]189 let kind = MissionFallback.alternative(for: current.kind)190 let step = MissionStep(kind: kind, difficulty: .fixed(level: current.level), rounds: 3, language: model.settings.wordLanguage)191 withAnimation(.smooth) {192 missions[index] = ResolvedMission(step: step, level: current.level, seed: current.seed &+ 977)193 notice = reason ?? String(localized: "Alternative mission: \(kind.title).")194 }195 }196197 private func close() { if let onClose { onClose() } else { model.dismissMissionRun() } }198199 private func emergencyExit() {200 if run.isPreview { close(); return }201 bypassed = true202 model.missionSequenceEnded(run, bypassed: true)203 Haptics.play(.warning)204 withAnimation(.smooth) { stage = .summary }205 }206}207208/// Shared chrome for mission screens: instruction line, round counter, content, optional footer.209struct MissionScaffold<Content: View>: View {210 let instruction: String211 var round: Int? = nil212 var totalRounds: Int? = nil213 @ViewBuilder var content: Content214 var body: some View {215 VStack(spacing: 18) {216 HStack(alignment: .firstTextBaseline) {217 Text(instruction).font(.orixBody).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)218 Spacer()219 if let round, let totalRounds, totalRounds > 1 {220 Text("\(round)/\(totalRounds)").font(.orixCaption).monospacedDigit().foregroundStyle(Theme.textTertiary)221 .accessibilityLabel("Round \(round) of \(totalRounds)")222 }223 }224 content.frame(maxWidth: .infinity, maxHeight: .infinity)225 }226 .padding(.horizontal, 20).padding(.top, 14).padding(.bottom, 12)227 }228}229