SPB Git

Repository Public License

PatternLockMissionView.swift 13.7 KB 278 lines swift

1// ORIX Alarm2// File: App/Features/Missions/PatternLockMissionView.swift3// Description: Pattern Lock mission: a path through a constellation of stars is traced, then redrawn by dragging or by tapping the stars in order.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct PatternLockMissionView: View {11    let mission: ResolvedMission12    let onFinish: (MissionOutcome) -> Void1314    private enum Phase: Equatable { case showing, input, solved, failed }1516    @Environment(\.accessibilityReduceMotion) private var reduceMotion17    @Environment(\.accessibilityVoiceOverEnabled) private var voiceOver18    @State private var round = 019    @State private var phase: Phase = .showing20    /// Number of path nodes revealed so far during the presentation.21    @State private var revealed = 022    /// Animated head of the traced line, in segments.23    @State private var reveal: CGFloat = 024    /// `true` when the full path stays visible with its order numbers (Reduce Motion, VoiceOver).25    @State private var staticPresentation = false26    @State private var waitingForReady = false27    @State private var drawn: [Int] = []28    @State private var finger: CGPoint?29    @State private var mistakes = 030    @State private var shake = 031    @State private var playToken = 032    @State private var finished = false33    @State private var startedAt = Date()3435    private var puzzle: PatternLockEngine.Puzzle { PatternLockEngine.generate(level: mission.level, round: round, seed: mission.seed) }3637    var body: some View {38        let puzzle = puzzle39        MissionScaffold(instruction: String(localized: "Watch the path, then redraw it: drag across the stars or tap them in order."),40                        round: round + 1, totalRounds: mission.puzzleRounds) {41            VStack(spacing: 14) {42                PuzzleRoundProgress(current: round, total: mission.puzzleRounds, currentSolved: phase == .solved)43                board(puzzle)44                    .modifier(PuzzleShake(trigger: shake, enabled: !reduceMotion))45                PuzzleStatusLine(text: statusText(puzzle), feedback: phase == .solved ? .correct : (phase == .failed ? .wrong : .none))46                    .accessibilityIdentifier("pattern.status")47                footer48            }49        }50        .onAppear { startedAt = Date() }51        .task(id: playToken) { await present() }52    }5354    // MARK: Board5556    /// Star positions: a grid, nudged a little so that it reads as a constellation rather than a keypad.57    private func positions(_ puzzle: PatternLockEngine.Puzzle, side: CGFloat) -> [CGPoint] {58        let step = side / CGFloat(puzzle.size)59        var g = SeededGenerator(seed: mission.seed).fork(0x5354_4152 &+ UInt64(round))60        return (0..<(puzzle.size * puzzle.size)).map { node in61            let dx = CGFloat.random(in: -0.11...0.11, using: &g) * step, dy = CGFloat.random(in: -0.11...0.11, using: &g) * step62            return CGPoint(x: (CGFloat(puzzle.column(of: node)) + 0.5) * step + dx, y: (CGFloat(puzzle.row(of: node)) + 0.5) * step + dy)63        }64    }6566    private var trailColors: [Color] {67        switch phase {68        case .showing: [Theme.gold, Theme.sunrise]69        case .input: [Theme.azure, Theme.violet]70        case .solved: [Theme.success, Theme.success]71        case .failed: [Theme.danger, Theme.danger]72        }73    }7475    private func board(_ puzzle: PatternLockEngine.Puzzle) -> some View {76        GeometryReader { proxy in77            let side = min(proxy.size.width, proxy.size.height)78            let step = side / CGFloat(puzzle.size)79            let points = positions(puzzle, side: side)80            let trail: [Int] = phase == .showing ? puzzle.path : (phase == .solved ? puzzle.path : drawn)81            let head: CGFloat = phase == .showing ? reveal : CGFloat(max(trail.count - 1, 0))82            let gradient = LinearGradient(colors: trailColors, startPoint: .topLeading, endPoint: .bottomTrailing)83            ZStack {84                RoundedRectangle(cornerRadius: 28, style: .continuous).fill(Theme.midnight.opacity(0.35))85                    .overlay(RoundedRectangle(cornerRadius: 28, style: .continuous).strokeBorder(Theme.hairline))86                Canvas { context, size in87                    var g = SeededGenerator(seed: mission.seed ^ 0xA57E)88                    for _ in 0..<46 {89                        let x = CGFloat.random(in: 0...size.width, using: &g), y = CGFloat.random(in: 0...size.height, using: &g)90                        let r = CGFloat.random(in: 0.5...1.5, using: &g)91                        context.fill(Path(ellipseIn: CGRect(x: x, y: y, width: r * 2, height: r * 2)), with: .color(.white.opacity(Double.random(in: 0.12...0.4, using: &g))))92                    }93                }94                .accessibilityHidden(true)9596                let line = TrailShape(points: trail.map { points[$0] }, head: head)97                line.stroke(gradient, style: StrokeStyle(lineWidth: 12, lineCap: .round, lineJoin: .round)).blur(radius: 9).opacity(0.7)98                line.stroke(gradient, style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))99                if phase == .input, let finger, let last = drawn.last {100                    Path { $0.move(to: points[last]); $0.addLine(to: finger) }101                        .stroke(Theme.azure.opacity(0.5), style: StrokeStyle(lineWidth: 3, lineCap: .round, dash: [2, 8]))102                }103                ForEach(0..<points.count, id: \.self) { node in104                    nodeView(puzzle, node: node, step: step).position(points[node])105                }106            }107            .frame(width: side, height: side)108            .contentShape(Rectangle())109            .gesture(DragGesture(minimumDistance: 0)110                .onChanged { value in111                    guard phase == .input else { return }112                    finger = value.location113                    if let node = points.firstIndex(where: { hypot($0.x - value.location.x, $0.y - value.location.y) <= step * 0.36 }) { connect(puzzle, node) }114                }115                .onEnded { _ in finger = nil })116            .frame(maxWidth: .infinity, maxHeight: .infinity)117        }118        .aspectRatio(1, contentMode: .fit)119        .frame(maxHeight: .infinity)120    }121122    private func nodeView(_ puzzle: PatternLockEngine.Puzzle, node: Int, step: CGFloat) -> some View {123        let order: Int? = {124            switch phase {125            case .showing: return puzzle.path.firstIndex(of: node).flatMap { $0 < revealed ? $0 + 1 : nil }126            case .input, .failed: return drawn.firstIndex(of: node).map { $0 + 1 }127            case .solved: return puzzle.path.firstIndex(of: node).map { $0 + 1 }128            }129        }()130        let active = order != nil131        let tint = active ? trailColors[0] : Color.white132        let showNumber = active && (phase != .showing || staticPresentation)133        let isStart = phase == .showing && order == 1134        let halo = step * 0.42135        return ZStack {136            Circle().fill(RadialGradient(colors: [tint.opacity(active ? 0.6 : 0.16), tint.opacity(0)], center: .center, startRadius: 0, endRadius: halo))137                .frame(width: halo * 2, height: halo * 2)138            if isStart { Circle().strokeBorder(Theme.gold, style: StrokeStyle(lineWidth: 2, dash: [5, 4])).frame(width: 52, height: 52) }139            if active {140                Circle().fill(tint).frame(width: 34, height: 34).shadow(color: tint.opacity(0.8), radius: 8)141                Group {142                    if showNumber { Text("\(order ?? 0)").font(.system(size: 17, weight: .bold, design: .rounded)).monospacedDigit() }143                    else if isStart { Image(systemName: "play.fill").font(.system(size: 13, weight: .bold)) }144                    else { Image(systemName: "sparkle").font(.system(size: 13, weight: .bold)) }145                }146                .foregroundStyle(Theme.midnight)147            } else {148                Image(systemName: "sparkle").font(.system(size: 22, weight: .semibold)).foregroundStyle(.white.opacity(0.85))149                    .shadow(color: .white.opacity(0.6), radius: 5)150            }151        }152        .frame(width: max(halo * 2, 56), height: max(halo * 2, 56))153        .scaleEffect(active && !reduceMotion ? 1.06 : 1)154        .animation(reduceMotion ? nil : .snappy(duration: 0.2), value: active)155        .allowsHitTesting(false)156        .accessibilityElement()157        .accessibilityLabel(String(localized: "Star, row \(puzzle.row(of: node) + 1), column \(puzzle.column(of: node) + 1)"))158        .accessibilityValue(order.map { phase == .showing ? String(localized: "step \($0) of the path") : String(localized: "connected, number \($0)") } ?? "")159        .accessibilityAddTraits(.isButton)160        .accessibilityAction { connect(puzzle, node) }161        .accessibilityIdentifier("pattern.node.\(node)")162    }163164    private func statusText(_ puzzle: PatternLockEngine.Puzzle) -> String {165        switch phase {166        case .showing: waitingForReady ? String(localized: "Explore the path, then continue.") : String(localized: "Watch the path…")167        case .input: String(localized: "\(drawn.count) of \(puzzle.path.count) stars connected")168        case .solved: String(localized: "Correct")169        case .failed: String(localized: "Not quite. Watch again.")170        }171    }172173    @ViewBuilder174    private var footer: some View {175        if phase == .showing && waitingForReady {176            Button("Hide and draw") {177                waitingForReady = false; staticPresentation = false178                phase = .input179            }180            .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("pattern.ready")181        } else {182            HStack(spacing: 10) {183                PuzzleAuxButton(title: "Clear", symbol: "arrow.uturn.backward", isEnabled: phase == .input && !drawn.isEmpty) {184                    drawn = []; Haptics.play(.tick)185                }186                .accessibilityIdentifier("pattern.clear")187                PuzzleAuxButton(title: "Watch again", symbol: "eye", isEnabled: phase == .input) {188                    mistakes += 1; playToken += 1189                }190                .accessibilityHint("Counts as a mistake")191                .accessibilityIdentifier("pattern.replay")192            }193        }194    }195196    // MARK: Flow197198    private func present() async {199        let puzzle = puzzle200        phase = .showing; drawn = []; finger = nil; revealed = 0; reveal = 0201        waitingForReady = false; staticPresentation = false202        guard await PuzzleTiming.pause(0.5) else { return }203        let count = puzzle.path.count204        if voiceOver || reduceMotion {205            staticPresentation = true; revealed = count; reveal = CGFloat(count - 1)206            if voiceOver {207                waitingForReady = true208                AccessibilityNotification.Announcement(String(localized: "A path of \(count) stars is shown. Explore it, then choose Hide and draw.")).post()209                return210            }211            guard await PuzzleTiming.pause(1.6 + 0.4 * Double(count)) else { return }212        } else {213            let stepDuration = [0.46, 0.42, 0.38, 0.34][mission.level - 1]214            revealed = 1; Haptics.play(.tick)215            guard await PuzzleTiming.pause(0.5) else { return }216            for index in 1..<count {217                withAnimation(.linear(duration: stepDuration)) { reveal = CGFloat(index) }218                guard await PuzzleTiming.pause(stepDuration) else { return }219                revealed = index + 1; Haptics.play(.tick)220            }221            guard await PuzzleTiming.pause(0.9 + 0.1 * Double(count)) else { return }222        }223        withAnimation(reduceMotion ? nil : .smooth(duration: 0.3)) { phase = .input; staticPresentation = false }224    }225226    private func connect(_ puzzle: PatternLockEngine.Puzzle, _ node: Int) {227        guard phase == .input, !drawn.contains(node), drawn.count < puzzle.path.count else { return }228        drawn.append(node)229        Haptics.play(.tick); SoundFX.play(.tap)230        guard drawn.count == puzzle.path.count else { return }231        finger = nil232        if PatternLockEngine.validate(puzzle, answer: drawn) {233            phase = .solved234            PuzzleFeedback.correct.signal(announcement: String(localized: "Correct"))235            Task {236                guard await PuzzleTiming.pause(0.9), !finished else { return }237                if round + 1 >= mission.puzzleRounds {238                    finished = true239                    onFinish(MissionOutcome(result: .completed, mistakes: mistakes, duration: Date().timeIntervalSince(startedAt), rounds: mission.puzzleRounds))240                } else {241                    round += 1; playToken += 1242                }243            }244        } else {245            mistakes += 1246            phase = .failed247            withAnimation(.linear(duration: 0.4)) { shake += 1 }248            PuzzleFeedback.wrong.signal(announcement: String(localized: "Not quite. The path is shown again."))249            Task {250                guard await PuzzleTiming.pause(1.3) else { return }251                playToken += 1252            }253        }254    }255}256257/// Polyline through the given points, drawn up to `head` segments (fractional values draw part of a segment).258nonisolated private struct TrailShape: Shape {259    var points: [CGPoint]260    var head: CGFloat261    var animatableData: CGFloat {262        get { head }263        set { head = newValue }264    }265    func path(in rect: CGRect) -> Path {266        var path = Path()267        guard let first = points.first, head > 0 else { return path }268        path.move(to: first)269        for index in 1..<points.count {270            let remaining = head - CGFloat(index - 1)271            if remaining <= 0 { break }272            let a = points[index - 1], b = points[index], t = min(remaining, 1)273            path.addLine(to: CGPoint(x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t))274        }275        return path276    }277}278
Files main
Menu

Theme