Repository Public License
1// ORIX Alarm2// File: App/Features/Editor/MissionStepsEditor.swift3// Description: Morning Combo editor: ordered mission steps with drag reordering, mission picker and per-step settings (difficulty, rounds, step goal, QR tag, language).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910extension MissionKind {11 /// Whether difficulty and rounds apply (the hardware missions are defined by their goal instead).12 var hasPuzzleSettings: Bool { !needsHardware }13 var hardwareName: String? {14 switch self {15 case .qrEscape: String(localized: "camera")16 case .steps: String(localized: "step counter")17 default: nil18 }19 }20}2122struct MissionStepsEditor: View {23 @Binding var steps: [MissionStep]24 @Environment(AppModel.self) private var model2526 private struct StepRef: Identifiable { let id: UUID }27 @State private var showPicker = false28 @State private var editing: StepRef?29 @State private var dragID: UUID?30 @State private var dragStartIndex = 031 @State private var dragTranslation: CGFloat = 03233 private let rowHeight: CGFloat = 6634 private let rowSpacing: CGFloat = 835 private var stride: CGFloat { rowHeight + rowSpacing }36 private var isFull: Bool { steps.count >= WakeScenario.maxMissionSteps }3738 var body: some View {39 VStack(alignment: .leading, spacing: 12) {40 if steps.isEmpty {41 Text("No mission yet. Add one to make sure you are really up: the alarm leads straight into it.")42 .font(.orixCaption).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)43 } else {44 VStack(spacing: rowSpacing) {45 ForEach(Array(steps.enumerated()), id: \.element.id) { index, step in46 row(step, index: index)47 .zIndex(dragID == step.id ? 1 : 0)48 .offset(y: dragID == step.id ? dragTranslation - CGFloat(index - dragStartIndex) * stride : 0)49 }50 }51 if steps.count > 1 {52 Text("Drag the handle to reorder. Steps are played from top to bottom.")53 .font(.system(size: 11, weight: .medium, design: .rounded)).foregroundStyle(Theme.textTertiary)54 }55 }5657 Button {58 Haptics.play(.selection); showPicker = true59 } label: {60 HStack(spacing: 8) {61 Image(systemName: "plus.circle.fill")62 Text(isFull ? "Maximum of \(WakeScenario.maxMissionSteps) missions reached" : "Add mission")63 Spacer()64 Text("\(steps.count)/\(WakeScenario.maxMissionSteps)").monospacedDigit().foregroundStyle(Theme.textTertiary)65 }66 .font(.orixHeadline).foregroundStyle(isFull ? Theme.textTertiary : Theme.gold)67 .padding(.horizontal, 16).frame(minHeight: 52)68 .background(Theme.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))69 .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Theme.gold.opacity(isFull ? 0.1 : 0.4), style: StrokeStyle(lineWidth: 1, dash: [5, 4])))70 }71 .buttonStyle(.plain)72 .disabled(isFull)73 .accessibilityIdentifier("editor.addMission")7475 if steps.contains(where: { $0.kind.needsHardware }) {76 InfoNote(symbol: "arrow.triangle.swap", tint: Theme.azure,77 text: "If the camera or the step counter is unavailable in the morning (permission refused, sensor missing), ORIX Alarm offers a fallback mission instead, so a step can never trap you.")78 }79 }80 .sheet(isPresented: $showPicker) {81 MissionPickerSheet { kind in add(kind) }82 }83 .sheet(item: $editing) { ref in84 MissionStepSettingsSheet(step: binding(for: ref.id), position: (steps.firstIndex { $0.id == ref.id } ?? 0) + 1) {85 editing = nil86 withAnimation(.smooth) { steps.removeAll { $0.id == ref.id } }87 }88 }89 }9091 // MARK: Rows92 private func row(_ step: MissionStep, index: Int) -> some View {93 let qrMissing = step.kind == .qrEscape && model.qrTag(step.qrTagID) == nil94 let isDragged = dragID == step.id95 let fill: Color = isDragged ? Color.white.opacity(0.18) : Theme.surface96 let border: Color = qrMissing ? Theme.danger.opacity(0.6) : Theme.hairline97 let summary: String = qrMissing ? String(localized: "Needs a QR tag") : step.settingsSummary(qrLabel: model.qrTag(step.qrTagID)?.label)98 return rowContent(step, index: index, qrMissing: qrMissing, summary: summary)99 .padding(.leading, 12)100 .frame(height: rowHeight)101 .background(fill, in: RoundedRectangle(cornerRadius: 16, style: .continuous))102 .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(border))103 .shadow(color: .black.opacity(isDragged ? 0.4 : 0), radius: 12, y: 6)104 .contentShape(RoundedRectangle(cornerRadius: 16, style: .continuous))105 .onTapGesture { Haptics.play(.selection); editing = StepRef(id: step.id) }106 .contextMenu {107 Button("Settings", systemImage: "slider.horizontal.3") { editing = StepRef(id: step.id) }108 if index > 0 { Button("Move up", systemImage: "arrow.up") { move(step.id, by: -1) } }109 if index < steps.count - 1 { Button("Move down", systemImage: "arrow.down") { move(step.id, by: 1) } }110 Button("Remove", systemImage: "trash", role: .destructive) { remove(step.id) }111 }112 .accessibilityElement(children: .ignore)113 .accessibilityLabel(Text("Step \(index + 1), \(step.kind.title)"))114 .accessibilityValue(Text(summary))115 .accessibilityHint(Text("Opens the settings of this mission"))116 .accessibilityAddTraits(.isButton)117 .accessibilityAction { editing = StepRef(id: step.id) }118 .accessibilityAction(named: Text("Move up")) { move(step.id, by: -1) }119 .accessibilityAction(named: Text("Move down")) { move(step.id, by: 1) }120 .accessibilityAction(named: Text("Remove")) { remove(step.id) }121 .accessibilityIdentifier("editor.step.\(index)")122 }123124 private func remove(_ id: UUID) { withAnimation(.smooth) { steps.removeAll { $0.id == id } } }125126 private func rowContent(_ step: MissionStep, index: Int, qrMissing: Bool, summary: String) -> some View {127 HStack(spacing: 12) {128 ZStack(alignment: .topLeading) {129 Image(systemName: step.kind.symbol).font(.system(size: 17, weight: .semibold)).foregroundStyle(step.kind.tint)130 .frame(width: 42, height: 42)131 .background(step.kind.tint.opacity(0.16), in: RoundedRectangle(cornerRadius: 12, style: .continuous))132 Text("\(index + 1)").font(.system(size: 10, weight: .heavy, design: .rounded)).foregroundStyle(Theme.midnight)133 .frame(width: 17, height: 17).background(Theme.gold, in: Circle()).offset(x: -5, y: -5)134 }135 .accessibilityHidden(true)136 VStack(alignment: .leading, spacing: 3) {137 Text(step.kind.title).font(.system(.subheadline, design: .rounded, weight: .semibold)).lineLimit(1)138 if qrMissing {139 Label("Needs a QR tag", systemImage: "exclamationmark.triangle.fill").font(.orixCaption).foregroundStyle(Theme.danger).lineLimit(1)140 } else {141 Text(summary).font(.orixCaption).foregroundStyle(Theme.textSecondary).lineLimit(1)142 }143 }144 Spacer(minLength: 4)145 Image(systemName: "slider.horizontal.3").font(.footnote).foregroundStyle(Theme.textTertiary).accessibilityHidden(true)146 Image(systemName: "line.3.horizontal").font(.system(size: 17, weight: .semibold)).foregroundStyle(Theme.textSecondary)147 .frame(width: 44, height: rowHeight).contentShape(Rectangle())148 .gesture(reorderGesture(step, index: index))149 .accessibilityHidden(true)150 }151 }152153 private func reorderGesture(_ step: MissionStep, index: Int) -> some Gesture {154 DragGesture(minimumDistance: 1, coordinateSpace: .global)155 .onChanged { value in156 if dragID == nil {157 dragID = step.id; dragStartIndex = index158 Haptics.play(.selection)159 }160 guard dragID == step.id, let current = steps.firstIndex(where: { $0.id == step.id }) else { return }161 dragTranslation = value.translation.height162 let target = min(max(dragStartIndex + Int((dragTranslation / stride).rounded()), 0), steps.count - 1)163 if target != current {164 withAnimation(.snappy(duration: 0.22)) { steps.move(fromOffsets: IndexSet(integer: current), toOffset: target > current ? target + 1 : target) }165 Haptics.play(.tick)166 }167 }168 .onEnded { _ in169 // The row keeps its slot; only the visual offset returns to zero.170 if let id = dragID, let current = steps.firstIndex(where: { $0.id == id }) {171 dragTranslation -= CGFloat(current - dragStartIndex) * stride172 dragStartIndex = current173 }174 withAnimation(.snappy(duration: 0.22)) { dragTranslation = 0 } completion: { dragID = nil }175 }176 }177178 // MARK: Edits179 private func add(_ kind: MissionKind) {180 guard !isFull else { return }181 var step = MissionStep(kind: kind, language: model.settings.wordLanguage)182 if kind == .steps { step.stepGoal = 40 }183 if kind == .qrEscape { step.qrTagID = model.qrTags.first?.id }184 withAnimation(.smooth) { steps.append(step) }185 Haptics.play(.success)186 if kind == .qrEscape, step.qrTagID == nil {187 // A QR step is useless without a tag: go straight to its settings.188 Task { try? await Task.sleep(for: .milliseconds(450)); editing = StepRef(id: step.id) }189 }190 }191192 private func move(_ id: UUID, by delta: Int) {193 guard let i = steps.firstIndex(where: { $0.id == id }) else { return }194 let j = i + delta195 guard steps.indices.contains(j) else { return }196 withAnimation(.snappy) { steps.swapAt(i, j) }197 Haptics.play(.tick)198 }199200 private func binding(for id: UUID) -> Binding<MissionStep> {201 Binding {202 steps.first { $0.id == id } ?? MissionStep(id: id, kind: .math)203 } set: { newValue in204 if let i = steps.firstIndex(where: { $0.id == id }) { steps[i] = newValue }205 }206 }207}208209// MARK: - Mission picker210211struct MissionPickerSheet: View {212 let onPick: (MissionKind) -> Void213 @Environment(\.dismiss) private var dismiss214215 var body: some View {216 NavigationStack {217 ScrollView {218 VStack(spacing: 10) {219 ForEach(MissionKind.allCases, id: \.self) { kind in220 Button {221 onPick(kind); dismiss()222 } label: {223 HStack(spacing: 14) {224 Image(systemName: kind.symbol).font(.system(size: 20, weight: .semibold)).foregroundStyle(kind.tint)225 .frame(width: 48, height: 48)226 .background(kind.tint.opacity(0.16), in: RoundedRectangle(cornerRadius: 14, style: .continuous))227 .accessibilityHidden(true)228 VStack(alignment: .leading, spacing: 3) {229 Text(kind.title).font(.orixHeadline).foregroundStyle(Theme.textPrimary)230 Text(kind.summary).font(.orixCaption).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.leading)231 if let hardware = kind.hardwareName {232 Label("Uses the \(hardware) · fallback offered", systemImage: "arrow.triangle.swap")233 .font(.system(size: 10, weight: .bold, design: .rounded)).foregroundStyle(Theme.azure)234 }235 }236 Spacer(minLength: 0)237 Image(systemName: "plus").font(.footnote.weight(.bold)).foregroundStyle(Theme.textTertiary).accessibilityHidden(true)238 }239 .frame(maxWidth: .infinity, alignment: .leading)240 .glassCard(padding: 14, radius: 20)241 }242 .buttonStyle(.plain)243 .accessibilityIdentifier("editor.missionPicker.\(kind.rawValue)")244 }245 }246 .padding(18)247 }248 .navigationTitle("Add a mission").navigationBarTitleDisplayMode(.inline)249 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }250 .orixScreen()251 }252 .presentationDetents([.large])253 }254}255256// MARK: - Step settings257258struct MissionStepSettingsSheet: View {259 @Binding var step: MissionStep260 let position: Int261 let onDelete: () -> Void262 @Environment(AppModel.self) private var model263 @Environment(\.dismiss) private var dismiss264265 private let goalPresets = [20, 40, 60, 100]266267 var body: some View {268 NavigationStack {269 ScrollView {270 VStack(spacing: 16) {271 header272 if step.kind.hasPuzzleSettings { difficultyCard; roundsCard }273 if step.kind == .steps { stepGoalCard }274 if step.kind == .qrEscape { qrCard }275 if step.kind == .wordScramble { languageCard }276 if let hardware = step.kind.hardwareName {277 InfoNote(symbol: "arrow.triangle.swap", tint: Theme.azure,278 text: "If the \(hardware) is not available when the alarm rings, ORIX Alarm offers \(MissionFallback.alternative(for: step.kind).title) instead.")279 }280 Button(role: .destructive) { onDelete() } label: {281 Label("Remove this mission", systemImage: "trash").font(.orixHeadline).foregroundStyle(Theme.danger).frame(maxWidth: .infinity, minHeight: 50)282 }283 .buttonStyle(.plain)284 .accessibilityIdentifier("editor.step.delete")285 }286 .padding(18)287 }288 .navigationTitle("Step \(position)").navigationBarTitleDisplayMode(.inline)289 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() }.accessibilityIdentifier("editor.step.done") } }290 .orixScreen()291 }292 .presentationDetents([.medium, .large])293 }294295 private var header: some View {296 HStack(spacing: 14) {297 Image(systemName: step.kind.symbol).font(.system(size: 24, weight: .semibold)).foregroundStyle(step.kind.tint)298 .frame(width: 56, height: 56).background(step.kind.tint.opacity(0.16), in: RoundedRectangle(cornerRadius: 16, style: .continuous))299 .accessibilityHidden(true)300 VStack(alignment: .leading, spacing: 3) {301 Text(step.kind.title).font(.orixTitle)302 Text(step.kind.summary).font(.orixCaption).foregroundStyle(Theme.textSecondary)303 }304 Spacer(minLength: 0)305 }306 .accessibilityElement(children: .combine)307 }308309 private var difficultyCard: some View {310 EditorCard(title: "Difficulty", symbol: "gauge.with.dots.needle.67percent", tint: step.kind.tint) {311 FlowLayout(spacing: 8) {312 ForEach(Difficulty.allCases, id: \.self) { level in313 Chip(title: level.title, symbol: level == .adaptive ? "wand.and.stars" : nil, isSelected: step.difficulty == level) {314 Haptics.play(.selection); step.difficulty = level315 }316 .accessibilityIdentifier("editor.step.difficulty.\(level.rawValue)")317 }318 }319 if step.difficulty == .adaptive {320 let explanation = AdaptiveEngine.explain(kind: step.kind, history: model.events)321 Text(explanation.reason == .notEnoughData322 ? "Adaptive starts at Normal and adjusts once three completions of this mission are recorded."323 : "Adaptive follows your last recorded completions of this mission. Right now it would play at \(Difficulty.fixed(level: explanation.level).title).")324 .font(.orixCaption).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)325 }326 }327 }328329 private var roundsCard: some View {330 EditorCard(title: "Length", symbol: "repeat", tint: step.kind.tint) {331 ValueStepper(title: "Rounds", value: "\(step.rounds)", canDecrement: step.rounds > 1, canIncrement: step.rounds < 10,332 onDecrement: { step.rounds -= 1 }, onIncrement: { step.rounds += 1 })333 .accessibilityIdentifier("editor.step.rounds")334 }335 }336337 private var stepGoalCard: some View {338 EditorCard(title: "Step goal", symbol: "figure.walk", tint: step.kind.tint) {339 FlowLayout(spacing: 8) {340 ForEach(goalPresets, id: \.self) { goal in341 Chip(title: "\(goal)", isSelected: step.stepGoal == goal) { Haptics.play(.selection); step.stepGoal = goal }342 .accessibilityLabel("\(goal) steps")343 .accessibilityIdentifier("editor.step.goal.\(goal)")344 }345 }346 ValueStepper(title: "Custom goal", value: "\(step.stepGoal)", canDecrement: step.stepGoal > 10, canIncrement: step.stepGoal < 300,347 onDecrement: { step.stepGoal = max(10, step.stepGoal - 5) }, onIncrement: { step.stepGoal = min(300, step.stepGoal + 5) })348 .accessibilityIdentifier("editor.step.goal.custom")349 Text("Steps are counted by the iPhone's motion sensor while you carry it.").font(.orixCaption).foregroundStyle(Theme.textSecondary)350 }351 }352353 private var qrCard: some View {354 let tag = model.qrTag(step.qrTagID)355 return EditorCard(title: "QR tag", symbol: "qrcode", tint: step.kind.tint) {356 if let tag {357 Label(tag.label.isEmpty ? String(localized: "Unnamed tag") : tag.label, systemImage: "checkmark.circle.fill").font(.orixBody).foregroundStyle(Theme.success)358 } else {359 Label("No tag chosen. This step cannot be saved without one.", systemImage: "exclamationmark.triangle.fill")360 .font(.orixCaption).foregroundStyle(Theme.danger).fixedSize(horizontal: false, vertical: true)361 }362 NavigationLink {363 QRTagManagerView(selection: $step.qrTagID).navigationTitle("QR tags").orixScreen()364 } label: {365 HStack {366 Text(tag == nil ? "Choose or register a QR tag" : "Change tag")367 Spacer()368 Image(systemName: "chevron.right").font(.footnote.weight(.bold))369 }370 .font(.orixHeadline).foregroundStyle(Theme.textPrimary)371 .padding(.horizontal, 16).frame(minHeight: 50)372 .background(Theme.surfaceRaised, in: Capsule())373 }374 .buttonStyle(.plain)375 .accessibilityIdentifier("editor.step.qrTag")376 Text("Print or display a QR code somewhere away from the bed, register it once, then scan it to complete the step.")377 .font(.orixCaption).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true)378 }379 }380381 private var languageCard: some View {382 EditorCard(title: "Word language", symbol: "character.book.closed", tint: step.kind.tint) {383 HStack(spacing: 8) {384 Chip(title: String(localized: "English"), isSelected: step.language == .english) { Haptics.play(.selection); step.language = .english }385 .accessibilityIdentifier("editor.step.language.english")386 Chip(title: String(localized: "French"), isSelected: step.language == .french) { Haptics.play(.selection); step.language = .french }387 .accessibilityIdentifier("editor.step.language.french")388 }389 }390 }391}392