SPB Git

Repository Public

CardEditorView.swift 16.1 KB 338 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Features/Cards/CardEditorView.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/// Card Editor — corrects what the scanner proposed, or edits an existing card.44/// Saving encrypts the record (and, for a new card, its photographs).45struct CardEditorView: View {46    enum Mode {47        case new(ScanDraft)48        case edit(Card)49    }5051    let mode: Mode52    var onSaved: ((UUID) -> Void)?5354    @Environment(Vault.self) private var vault55    @Environment(AppSettings.self) private var settings56    @Environment(\.dismiss) private var dismiss5758    @State private var card: Card59    @State private var hasExpiry: Bool60    @State private var expiry: Date61    @State private var isSaving = false62    @State private var errorMessage: String?63    @State private var confirmsDiscard = false6465    init(mode: Mode, onSaved: ((UUID) -> Void)? = nil) {66        self.mode = mode67        self.onSaved = onSaved68        let initial: Card69        switch mode {70        case .new(let draft): initial = draft.makeCard(reminderOffsets: [30, 7, 0])71        case .edit(let card): initial = card72        }73        _card = State(initialValue: initial)74        _hasExpiry = State(initialValue: initial.expiry != nil)75        _expiry = State(initialValue: initial.expiry ?? Calendar.current.date(byAdding: .year, value: 3, to: Date())!)76    }7778    private var isNew: Bool { if case .new = mode { true } else { false } }7980    private var forbiddenField: CardField? { card.fields.first { SensitiveDataPolicy.isForbiddenLabel($0.label) } }8182    private var canSave: Bool {83        !card.name.trimmingCharacters(in: .whitespaces).isEmpty && forbiddenField == nil && !isSaving84    }8586    var body: some View {87        NavigationStack {88            ZStack {89                VaultBackground()90                ScrollView {91                    VStack(alignment: .leading, spacing: SP.Space.xl) {92                        preview93                        identityPanel94                        numberPanel95                        expiryPanel96                        fieldsPanel97                        notesPanel98                    }99                    .padding(.horizontal, SP.Space.page)100                    .padding(.vertical, SP.Space.m)101                }102                .scrollDismissesKeyboard(.interactively)103            }104            .navigationTitle(isNew ? "New card" : "Edit card")105            .navigationBarTitleDisplayMode(.inline)106            .toolbar {107                ToolbarItem(placement: .cancellationAction) {108                    Button("Cancel") { if isNew { confirmsDiscard = true } else { dismiss() } }109                        .accessibilityIdentifier("editor.cancel")110                }111                ToolbarItem(placement: .confirmationAction) {112                    Button(isSaving ? "Saving…" : "Save") { save() }113                        .fontWeight(.semibold)114                        .disabled(!canSave)115                        .accessibilityIdentifier("editor.save")116                }117            }118            .confirmationDialog("Discard this scan?", isPresented: $confirmsDiscard, titleVisibility: .visible) {119                Button("Discard photographs", role: .destructive) { dismiss() }120            } message: { Text("The photographs were never written to disk; they are simply dropped.") }121            .alert("The card was not saved", isPresented: Binding(get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } })) {122                Button("OK", role: .cancel) {}123            } message: { Text(errorMessage ?? "") }124            .onAppear {125                if isNew { card.reminderOffsets = settings.defaultReminderOffsets }126            }127        }128        .interactiveDismissDisabled(isNew)129    }130131    // MARK: Panels132133    @ViewBuilder134    private var preview: some View {135        Group {136            switch mode {137            case .new(let draft): RawCardFace(image: draft.front, format: card.format)138            case .edit(let existing): VirtualCardView(card: existing, thumbnail: false, mode: .premium)139            }140        }141        .padding(.horizontal, SP.Space.xxl)142        .padding(.vertical, SP.Space.xs)143        .frame(maxWidth: .infinity)144    }145146    private var identityPanel: some View {147        VStack(alignment: .leading, spacing: SP.Space.m) {148            SectionHeader("Card")149            SPTextField(title: "Name", text: $card.name, prompt: "Name shown in your wallet", capitalization: .words)150                .accessibilityIdentifier("editor.name")151            menuField("Type", value: card.kind.title, symbol: card.kind.symbol) {152                ForEach(vault.categories) { category in153                    let kinds = CardKind.kinds(inCategory: category.id)154                    if !kinds.isEmpty {155                        Section(category.name) {156                            ForEach(kinds, id: \.self) { kind in157                                Button { setKind(kind) } label: { Label(kind.title, systemImage: kind.symbol) }158                            }159                        }160                    }161                }162            }163            menuField("Category", value: vault.category(id: card.categoryID).name, symbol: vault.category(id: card.categoryID).symbol) {164                ForEach(vault.categories) { category in165                    Button { card.categoryID = category.id } label: { Label(category.name, systemImage: category.symbol) }166                }167            }168            SPTextField(title: "Issuer", text: $card.issuer, prompt: "Bank, authority or company", capitalization: .words)169            SPTextField(title: "Holder", text: $card.holderName, prompt: "Name on the card", capitalization: .words)170            Toggle(isOn: $card.isFavorite) {171                Label("Favourite", systemImage: "star.fill").font(.spBody).foregroundStyle(SP.Palette.textPrimary)172            }173            .tint(SP.Palette.electric)174        }175        .spPanel()176    }177178    private var numberPanel: some View {179        VStack(alignment: .leading, spacing: SP.Space.s) {180            SectionHeader(card.kind.numberLabel) {181                if card.kind.isBanking, !card.digitsOfNumber.isEmpty {182                    if PaymentCard.isValidNumber(card.number) {183                        StatusPill(text: PaymentCard.network(for: card.number) ?? "Valid number", tone: .positive, symbol: "checkmark")184                    } else {185                        StatusPill(text: "Check the digits", tone: .warning, symbol: "exclamationmark")186                    }187                }188            }189            SPTextField(title: "Number", text: $card.number, prompt: card.kind.isBanking ? "0000 0000 0000 0000" : "As printed on the card",190                        mono: true, keyboard: card.kind.isBanking ? .numberPad : .asciiCapable, capitalization: .characters)191                .accessibilityIdentifier("editor.number")192            Text(card.kind.isBanking193                 ? "Stored encrypted and shown masked. Only the last four digits appear in the wallet. The security code (CVV/CVC) and the PIN are never stored."194                 : "Stored encrypted and shown masked until you reveal it with Face ID.")195                .font(.spCaption).foregroundStyle(SP.Palette.textTertiary)196        }197        .spPanel()198    }199200    private var expiryPanel: some View {201        VStack(alignment: .leading, spacing: SP.Space.s) {202            SectionHeader("Expiry and reminders")203            Toggle(isOn: $hasExpiry.animation(SP.Motion.quick)) {204                Text("This card expires").font(.spBody).foregroundStyle(SP.Palette.textPrimary)205            }206            .tint(SP.Palette.electric)207            .accessibilityIdentifier("editor.hasExpiry")208            if hasExpiry {209                DatePicker("Expiry date", selection: $expiry, displayedComponents: .date)210                    .font(.spBody).foregroundStyle(SP.Palette.textPrimary)211                Hairline()212                Text("Remind me").spEyebrow()213                ReminderOffsetChips(offsets: $card.reminderOffsets, identifierPrefix: "editor.offset")214                Text("Reminders are local notifications with generic text: they never name the card.")215                    .font(.spCaption).foregroundStyle(SP.Palette.textTertiary)216            }217        }218        .spPanel()219    }220221    private var fieldsPanel: some View {222        VStack(alignment: .leading, spacing: SP.Space.s) {223            SectionHeader("More information", subtitle: "Class, group number, phone line…")224            ForEach($card.fields) { $field in225                VStack(spacing: SP.Space.xs) {226                    HStack(spacing: SP.Space.xs) {227                        TextField("Label", text: $field.label)228                            .font(.spCallout.weight(.semibold)).textInputAutocapitalization(.words)229                            .frame(maxWidth: 130)230                        Rectangle().fill(SP.Palette.hairline).frame(width: 0.5, height: 22)231                        TextField("Value", text: $field.value).font(.spCallout).autocorrectionDisabled()232                        Button { field.isSensitive.toggle() } label: {233                            Image(systemName: field.isSensitive ? "lock.fill" : "lock.open")234                                .foregroundStyle(field.isSensitive ? SP.Palette.electric : SP.Palette.textTertiary)235                        }236                        .buttonStyle(.plain)237                        .accessibilityLabel(field.isSensitive ? "Sensitive: hidden until revealed" : "Not sensitive")238                        Button { card.fields.removeAll { $0.id == field.id } } label: {239                            Image(systemName: "minus.circle.fill").foregroundStyle(SP.Palette.critical)240                        }241                        .buttonStyle(.plain)242                        .accessibilityLabel("Remove \(field.label)")243                    }244                    .foregroundStyle(SP.Palette.textPrimary)245                    .padding(.horizontal, SP.Space.s).frame(minHeight: 46)246                    .background(SP.Palette.surface, in: RoundedRectangle(cornerRadius: SP.Radius.s, style: .continuous))247                    .overlay(RoundedRectangle(cornerRadius: SP.Radius.s, style: .continuous)248                        .strokeBorder(SensitiveDataPolicy.isForbiddenLabel(field.label) ? SP.Palette.critical : SP.Palette.hairlineStrong, lineWidth: 0.75))249                }250            }251            if let forbiddenField {252                Label("“\(forbiddenField.label)” cannot be stored. SP Vault never keeps a security code, a PIN or magnetic-stripe data.", systemImage: "hand.raised.fill")253                    .font(.spCaption).foregroundStyle(SP.Palette.critical)254                    .accessibilityIdentifier("editor.forbidden")255            }256            Button {257                card.fields.append(CardField(label: "", value: ""))258            } label: { Label("Add a field", systemImage: "plus") }259                .buttonStyle(SPButtonStyle(kind: .quiet, fullWidth: false))260                .accessibilityIdentifier("editor.addField")261        }262        .spPanel()263    }264265    private var notesPanel: some View {266        VStack(alignment: .leading, spacing: SP.Space.xs) {267            SectionHeader("Notes")268            TextField("Personal notes", text: $card.notes, axis: .vertical)269                .lineLimit(3...8).font(.spBody).foregroundStyle(SP.Palette.textPrimary)270                .padding(SP.Space.s)271                .background(SP.Palette.surface, in: RoundedRectangle(cornerRadius: SP.Radius.s, style: .continuous))272                .overlay(RoundedRectangle(cornerRadius: SP.Radius.s, style: .continuous).strokeBorder(SP.Palette.hairlineStrong, lineWidth: 0.75))273        }274        .spPanel()275    }276277    private func menuField(_ title: String, value: String, symbol: String, @ViewBuilder content: () -> some View) -> some View {278        VStack(alignment: .leading, spacing: 6) {279            Text(title).spEyebrow()280            Menu(content: content) {281                HStack(spacing: SP.Space.xs) {282                    Image(systemName: symbol).foregroundStyle(SP.Palette.titanium).frame(width: 22)283                    Text(value).font(.spBody).foregroundStyle(SP.Palette.textPrimary)284                    Spacer()285                    Image(systemName: "chevron.up.chevron.down").font(.system(size: 12, weight: .semibold)).foregroundStyle(SP.Palette.textTertiary)286                }287                .padding(.horizontal, SP.Space.s).frame(minHeight: 48)288                .background(SP.Palette.surface, in: RoundedRectangle(cornerRadius: SP.Radius.s, style: .continuous))289                .overlay(RoundedRectangle(cornerRadius: SP.Radius.s, style: .continuous).strokeBorder(SP.Palette.hairlineStrong, lineWidth: 0.75))290            }291        }292        .accessibilityElement(children: .combine)293        .accessibilityLabel("\(title): \(value)")294    }295296    // MARK: Actions297298    private func setKind(_ kind: CardKind) {299        let followedKind = card.categoryID == card.kind.categoryID300        if card.name == card.kind.title { card.name = kind.title }301        card.kind = kind302        if followedKind { card.categoryID = kind.categoryID }303    }304305    private func save() {306        var record = card307        record.name = record.name.trimmingCharacters(in: .whitespacesAndNewlines)308        record.number = record.number.trimmingCharacters(in: .whitespacesAndNewlines)309        if record.kind.isBanking { record.number = record.digitsOfNumber }310        record.fields.removeAll { $0.label.trimmingCharacters(in: .whitespaces).isEmpty && $0.value.trimmingCharacters(in: .whitespaces).isEmpty }311        record.expiry = hasExpiry ? expiry : nil312        isSaving = true313        Task {314            defer { isSaving = false }315            do {316                switch mode {317                case .new(let draft):318                    let front = draft.front, back = draft.back319                    let images = try await Task.detached(priority: .userInitiated) { try CardImageCodec.images(front: front, back: back) }.value320                    try await vault.add(record, images: images)321                case .edit:322                    try vault.update(record)323                }324                Haptics.shared.play(.success)325                onSaved?(record.id)326                dismiss()327            } catch let error as CocoaError where error.code == .fileWriteOutOfSpace {328                errorMessage = "This iPhone is out of storage. Free some space and try again; nothing was partially saved."329            } catch SensitiveDataPolicy.Violation.magneticStripeData {330                errorMessage = "Magnetic-stripe data cannot be stored."331            } catch {332                Haptics.shared.play(.error)333                errorMessage = "The card could not be encrypted and saved. Nothing was partially written."334            }335        }336    }337}338
Files main
Menu

Theme