Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Features/Scanner/ScannerFlowView.swift8// Module : SPVault9// Repository : https://git.spboucher.ai/sp-id-card-vault10// Project Website : Not specified11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI4243/// Smart Card Scanner: choose the kind of card → photograph the front → the44/// back → (bank cards) validate the security-code mask → preview the virtual45/// card with the detected proposals → hand a `ScanDraft` to the editor.46///47/// Presented as a full-screen cover. It dismisses itself on cancel, and calls48/// `onFinish` then dismisses when the owner continues from the preview.49struct ScannerFlowView: View {50 private enum Stage: Hashable { case kind, front, back, preview }5152 private let onFinish: (ScanDraft) -> Void53 @State private var stage: Stage54 @State private var kind: CardKind?55 @State private var front: ProcessedSide?56 @State private var back: ProcessedSide?57 @State private var draft: ScanDraft?58 @Environment(\.dismiss) private var dismiss59 @Environment(\.accessibilityReduceMotion) private var reduceMotion6061 init(initialKind: CardKind? = nil, onFinish: @escaping (ScanDraft) -> Void) {62 self.onFinish = onFinish63 _kind = State(initialValue: initialKind)64 _stage = State(initialValue: initialKind == nil ? .kind : .front)65 }6667 var body: some View {68 ZStack {69 Color.black.ignoresSafeArea()70 switch stage {71 case .kind:72 CardKindPicker(onSelect: { selected in73 kind = selected74 stage = .front75 }, onClose: { dismiss() })76 .transition(.opacity)77 case .front:78 if let kind {79 SideCaptureFlow(side: .front, kind: kind, expectedFormat: kind.defaultFormat, step: .front, onResult: { result in80 front = result81 // A passport is a single page: nothing to photograph on the other side.82 if kind == .passport { finishSides() } else { stage = .back }83 }, onClose: { dismiss() })84 .id(Stage.front)85 .transition(.opacity)86 }87 case .back:88 if let kind, let front {89 SideCaptureFlow(side: .back, kind: kind, expectedFormat: front.format, step: .back, allowsSkip: true, onResult: { result in90 back = result91 finishSides()92 }, onClose: { dismiss() })93 .id(Stage.back)94 .transition(.opacity)95 }96 case .preview:97 if let draft {98 ScanPreviewView(draft: draft, onContinue: {99 Haptics.shared.play(.success)100 onFinish(draft)101 dismiss()102 }, onRestart: restart, onClose: { dismiss() })103 .transition(.opacity)104 }105 }106 }107 .animation(reduceMotion ? SP.Motion.reduced : SP.Motion.gentle, value: stage)108 .preferredColorScheme(.dark)109 .tint(SP.Palette.electric)110 }111112 private func finishSides() {113 guard let kind, let front else { return }114 draft = SmartScanEngine.makeDraft(kind: kind, front: front, back: back)115 stage = .preview116 }117118 private func restart() {119 front = nil120 back = nil121 draft = nil122 stage = .front123 }124}125126// MARK: - Kind picker127128/// First screen of the scanner: what is being scanned, grouped by the five129/// built-in categories.130struct CardKindPicker: View {131 var onSelect: (CardKind) -> Void132 var onClose: () -> Void133134 var body: some View {135 ZStack {136 VaultBackground()137 ScrollView {138 VStack(alignment: .leading, spacing: SP.Space.xl) {139 PageHeader(eyebrow: "SmartScan", title: "New Card") {140 GlassIconButton(symbol: "xmark", label: "Cancel scan", action: onClose)141 .accessibilityIdentifier("scanner.close")142 }143 Text("Choose what you are about to photograph. The photo stays on this iPhone, encrypted; nothing is saved to Photos.")144 .font(.spCallout).foregroundStyle(SP.Palette.textSecondary)145 .fixedSize(horizontal: false, vertical: true)146 ForEach(CardCategory.builtIn) { category in147 VStack(alignment: .leading, spacing: SP.Space.s) {148 SectionHeader(category.name)149 VStack(spacing: 0) {150 let kinds = CardKind.kinds(inCategory: category.id)151 ForEach(kinds, id: \.self) { kind in152 Button {153 Haptics.shared.play(.select)154 onSelect(kind)155 } label: {156 HStack(spacing: SP.Space.s) {157 IconBadge(symbol: kind.symbol, tint: Color(category.tint), size: 38)158 VStack(alignment: .leading, spacing: 2) {159 Text(kind.title).font(.spBody.weight(.medium)).foregroundStyle(SP.Palette.textPrimary)160 Text(kind.defaultFormat.label).font(.spCaption).foregroundStyle(SP.Palette.textTertiary)161 }162 Spacer(minLength: SP.Space.xs)163 Image(systemName: "chevron.right").font(.system(size: 13, weight: .semibold)).foregroundStyle(SP.Palette.textTertiary)164 }165 .padding(.vertical, 10)166 .contentShape(Rectangle())167 }168 .buttonStyle(.plain)169 .accessibilityIdentifier("scanner.kind.\(kind.rawValue)")170 if kind != kinds.last { Hairline().padding(.leading, 50) }171 }172 }173 .spPanel(padding: SP.Space.s)174 }175 }176 }177 .padding(.horizontal, SP.Space.page)178 .padding(.top, SP.Space.m)179 .padding(.bottom, SP.Space.xxxl)180 }181 .scrollIndicators(.hidden)182 }183 }184}185186// MARK: - Card preview187188/// Card Preview: the virtual card as it will appear in the wallet (tap to turn189/// it over) and what SmartScan read on it, as proposals.190struct ScanPreviewView: View {191 let draft: ScanDraft192 var onContinue: () -> Void193 var onRestart: () -> Void194 var onClose: () -> Void195196 @State private var showsBack = false197 @State private var appeared = false198 @Environment(\.accessibilityReduceMotion) private var reduceMotion199200 private var maskedNumber: String? {201 guard let number = draft.suggestion.number, !number.isEmpty else { return nil }202 let compact = number.filter { $0.isLetter || $0.isNumber }203 return compact.count > 4 ? "•••• " + compact.suffix(4) : number204 }205206 private var expiryText: String? {207 guard let expiry = draft.suggestion.expiry else { return nil }208 var style = Date.FormatStyle(date: .long, time: .omitted)209 style.timeZone = TimeZone(identifier: "UTC")!210 return expiry.formatted(style)211 }212213 var body: some View {214 ZStack {215 VaultBackground()216 VStack(spacing: 0) {217 ScannerTopBar(step: .review, onClose: onClose) {218 GlassIconButton(symbol: "arrow.counterclockwise", label: "Scan again", action: onRestart)219 .accessibilityIdentifier("scanner.restart")220 }221 ScrollView {222 VStack(spacing: SP.Space.xl) {223 VStack(spacing: 6) {224 Text("Card Preview").font(.spDisplay).foregroundStyle(SP.Palette.textPrimary)225 Text(draft.kind.title).spEyebrow(SP.Palette.electric)226 }227 .accessibilityElement(children: .combine)228 .accessibilityAddTraits(.isHeader)229230 card231 .padding(.horizontal, SP.Space.xs)232 .scaleEffect(appeared || reduceMotion ? 1 : 0.92)233 .opacity(appeared ? 1 : 0)234235 if draft.back != nil {236 Button {237 Haptics.shared.play(.flip)238 showsBack.toggle()239 } label: {240 Label(showsBack ? "Show front" : "Show back", systemImage: "arrow.left.arrow.right")241 .font(.system(size: 14, weight: .semibold)).foregroundStyle(SP.Palette.textPrimary)242 .padding(.horizontal, SP.Space.m).frame(minHeight: 44)243 }244 .buttonStyle(.plain)245 .spGlass()246 .accessibilityIdentifier("scanner.flip")247 }248249 VStack(alignment: .leading, spacing: SP.Space.s) {250 SectionHeader("Detected on the card", subtitle: "Proposals — you can correct everything next")251 VStack(spacing: 0) {252 proposal("Name", draft.suggestion.name ?? draft.kind.title, symbol: "textformat", detected: draft.suggestion.name != nil)253 Hairline()254 proposal("Issuer", draft.suggestion.issuer, symbol: "building.columns")255 Hairline()256 proposal("Holder", draft.suggestion.holderName, symbol: "person")257 Hairline()258 proposal(draft.kind.numberLabel, maskedNumber, symbol: "number", mono: true)259 Hairline()260 proposal("Expiry", expiryText, symbol: "calendar")261 Hairline()262 proposal("Format", draft.format.label, symbol: "ruler", detected: true)263 if draft.kind.isBanking {264 Hairline()265 DetailRow(label: "Security code", symbol: "eye.slash") {266 StatusPill(text: "Never stored", tone: .positive, symbol: "checkmark")267 }268 }269 }270 .spPanel(padding: SP.Space.m)271 }272 }273 .padding(.horizontal, SP.Space.page)274 .padding(.top, SP.Space.l)275 .padding(.bottom, SP.Space.xl)276 }277 .scrollIndicators(.hidden)278279 Button("Continue", action: onContinue)280 .buttonStyle(.spPrimary)281 .padding(.horizontal, SP.Space.page)282 .padding(.vertical, SP.Space.s)283 .accessibilityIdentifier("scanner.continue")284 }285 }286 .onAppear { withAnimation(reduceMotion ? SP.Motion.reduced : SP.Motion.card) { appeared = true } }287 }288289 /// The card, turning over in 3D between the two photographs.290 private var card: some View {291 let angle: Double = showsBack ? 180 : 0292 return ZStack {293 RawCardFace(image: draft.front, format: draft.format)294 .modifier(PreviewFlipFace(angle: angle, isBack: false, reduceMotion: reduceMotion))295 if let back = draft.back {296 RawCardFace(image: back, format: draft.format)297 .modifier(PreviewFlipFace(angle: angle, isBack: true, reduceMotion: reduceMotion))298 }299 }300 .animation(reduceMotion ? SP.Motion.reduced : SP.Motion.flip, value: showsBack)301 .contentShape(Rectangle())302 .onTapGesture {303 guard draft.back != nil else { return }304 Haptics.shared.play(.flip)305 showsBack.toggle()306 }307 .accessibilityElement(children: .ignore)308 .accessibilityLabel("Preview of the \(showsBack ? "back" : "front") of the card")309 .accessibilityAddTraits(.isImage)310 .accessibilityAction(named: "Turn over") { if draft.back != nil { showsBack.toggle() } }311 .accessibilityIdentifier("scanner.preview.card")312 }313314 private func proposal(_ label: String, _ value: String?, symbol: String, mono: Bool = false, detected: Bool? = nil) -> some View {315 DetailRow(label: label, symbol: symbol) {316 if let value, !value.isEmpty {317 Text(value).font(mono ? .spNumber : .spCallout.weight(.medium))318 } else {319 Text("Not detected").font(.spCallout).foregroundStyle(SP.Palette.textTertiary)320 }321 }322 .accessibilityElement(children: .combine)323 }324}325326private struct PreviewFlipFace: ViewModifier, @MainActor Animatable {327 var angle: Double328 var isBack: Bool329 var reduceMotion: Bool330331 var animatableData: Double {332 get { angle }333 set { angle = newValue }334 }335336 func body(content: Content) -> some View {337 let visible = isBack ? angle >= 90 : angle < 90338 if reduceMotion {339 content.opacity(visible ? 1 : 0)340 } else {341 content342 .rotation3DEffect(.degrees(isBack ? angle - 180 : angle), axis: (x: 0, y: 1, z: 0), perspective: 0.55)343 .scaleEffect(1 + 0.05 * sin(angle * .pi / 180))344 .opacity(visible ? 1 : 0)345 }346 }347}348