SPB Git

Repository Public

CardDetailView.swift 22.3 KB 492 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Features/Cards/CardDetailView.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 Detail — one card, full size, with everything known about it. Sensitive44/// values stay masked until a fresh Face ID check, and mask themselves again.45struct CardDetailView: View {46    let cardID: UUID4748    @Environment(Vault.self) private var vault49    @Environment(AppSettings.self) private var settings50    @Environment(AppEnvironment.self) private var environment51    @Environment(\.dismiss) private var dismiss52    @Environment(\.accessibilityReduceMotion) private var reduceMotion5354    @State private var showsBack = false55    @State private var dragTilt: CGSize = .zero56    @State private var privacy = false57    @State private var revealed = false58    @State private var revealTask: Task<Void, Never>?59    @State private var showsFullScreen = false60    @State private var showsEditor = false61    @State private var retakeSide: CardSide?62    @State private var confirmsDelete = false63    @State private var copied = false64    @State private var errorMessage: String?6566    /// Seconds a revealed number stays visible.67    static let revealDuration: Duration = .seconds(30)6869    private var card: Card? { vault.cards.first { $0.id == cardID } }7071    var body: some View {72        ZStack {73            if let card {74                background(card)75                ScrollView {76                    VStack(spacing: SP.Space.xl) {77                        hero(card)78                        controls(card)79                        numberPanel(card)80                        detailsPanel(card)81                        if !card.fields.isEmpty { fieldsPanel(card) }82                        if !card.notes.isEmpty { notesPanel(card) }83                        recordPanel(card)84                    }85                    .padding(.horizontal, SP.Space.page)86                    .padding(.top, 76)87                    .padding(.bottom, SP.Space.xxxl)88                }89                .scrollIndicators(.hidden)90                topBar(card)91            } else {92                VaultBackground().onAppear { dismiss() }93            }94        }95        .tracksDeviceTilt()96        .onAppear {97            privacy = settings.privacyMode98            #if DEBUG99            switch environment.launch.screen {100            case "back": showsBack = true101            case "fullscreen": showsFullScreen = true102            case "editor": showsEditor = true103            case "reveal": revealed = true104            default: break105            }106            #endif107        }108        .onDisappear { revealTask?.cancel() }109        .fullScreenCover(isPresented: $showsFullScreen) {110            if let card { FullScreenCardView(card: card, startsOnBack: showsBack) }111        }112        .sheet(isPresented: $showsEditor) {113            if let card { CardEditorView(mode: .edit(card)) }114        }115        .fullScreenCover(item: $retakeSide) { side in116            if let card {117                SingleSideCaptureView(side: side, kind: card.kind, format: card.format) { image in replaceImage(image, side: side) }118            }119        }120        .confirmationDialog("Delete this card?", isPresented: $confirmsDelete, titleVisibility: .visible) {121            Button("Delete card", role: .destructive) { delete() }122        } message: {123            Text("Its photographs and its encryption key are erased from this iPhone. This cannot be undone.")124        }125        .alert("Something went wrong", isPresented: Binding(get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } })) {126            Button("OK", role: .cancel) {}127        } message: { Text(errorMessage ?? "") }128    }129130    // MARK: Pieces131132    private func background(_ card: Card) -> some View {133        ZStack {134            VaultBackground(emphasis: 0)135            // The room takes a little of the card's colour.136            RadialGradient(colors: [Color(card.dominantColor, opacity: 0.30), .clear], center: UnitPoint(x: 0.5, y: 0.16),137                           startRadius: 10, endRadius: 440)138                .ignoresSafeArea()139        }140    }141142    private func topBar(_ card: Card) -> some View {143        VStack {144            HStack(spacing: SP.Space.xs) {145                GlassIconButton(symbol: "chevron.down", label: "Close") { dismiss() }146                    .accessibilityIdentifier("detail.close")147                Spacer()148                GlassIconButton(symbol: card.isFavorite ? "star.fill" : "star", label: card.isFavorite ? "Remove from favourites" : "Add to favourites") {149                    Haptics.shared.play(.select)150                    vault.toggleFavorite(card.id)151                }152                .accessibilityIdentifier("detail.favorite")153                Menu {154                    Button { showsEditor = true } label: { Label("Edit details", systemImage: "pencil") }155                    Button { retakeSide = .front } label: { Label("Retake front", systemImage: "camera") }156                    Button { retakeSide = .back } label: { Label(card.hasBack ? "Retake back" : "Add back", systemImage: "camera.rotate") }157                    if card.hasBack {158                        Button(role: .destructive) { removeBack() } label: { Label("Remove back", systemImage: "rectangle.slash") }159                    }160                    Divider()161                    Button(role: .destructive) { confirmsDelete = true } label: { Label("Delete card", systemImage: "trash") }162                } label: {163                    Image(systemName: "ellipsis").font(.system(size: 17, weight: .semibold)).foregroundStyle(SP.Palette.textPrimary)164                        .frame(width: 44, height: 44).contentShape(Circle())165                }166                .spGlass(in: Circle())167                .accessibilityLabel("More actions")168                .accessibilityIdentifier("detail.more")169            }170            .padding(.horizontal, SP.Space.page)171            .padding(.top, SP.Space.xs)172            Spacer()173        }174    }175176    private func hero(_ card: Card) -> some View {177        FlippableCardView(card: card, showsBack: $showsBack, thumbnail: false, mode: settings.renderMode, privacy: privacy,178                          manualTilt: dragTilt)179            .rotation3DEffect(.degrees(reduceMotion ? 0 : Double(dragTilt.width) * 14), axis: (x: 0, y: 1, z: 0), perspective: 0.5)180            .rotation3DEffect(.degrees(reduceMotion ? 0 : Double(-dragTilt.height) * 10), axis: (x: 1, y: 0, z: 0), perspective: 0.5)181            .gesture(182                DragGesture(minimumDistance: 6)183                    .onChanged { value in184                        dragTilt = CGSize(width: max(-1, min(1, value.translation.width / 140)), height: max(-1, min(1, value.translation.height / 140)))185                    }186                    .onEnded { _ in withAnimation(.spring(response: 0.5, dampingFraction: 0.6)) { dragTilt = .zero } }187            )188            .onTapGesture { flip(card) }189            .simultaneousGesture(MagnifyGesture().onEnded { value in if value.magnification > 1.15 { showsFullScreen = true } })190            .padding(.top, SP.Space.xs)191            .accessibilityIdentifier("detail.card")192            .accessibilityHint(card.hasBack ? "Double tap to turn the card over" : "")193    }194195    private func controls(_ card: Card) -> some View {196        HStack(spacing: SP.Space.s) {197            control("arrow.left.arrow.right", "Flip", id: "flip", disabled: !card.hasBack) { flip(card) }198            control("arrow.up.left.and.arrow.down.right", "Full screen", id: "fullscreen") { showsFullScreen = true }199            control(privacy ? "eye.slash.fill" : "eye.fill", privacy ? "Hidden" : "Visible", id: "privacy", active: privacy) {200                Haptics.shared.play(.select)201                withAnimation(SP.Motion.gentle) { privacy.toggle() }202            }203            control(settings.renderMode == .premium ? "sparkles" : "photo", settings.renderMode.title, id: "mode") {204                Haptics.shared.play(.select)205                settings.renderMode = settings.renderMode == .premium ? .original : .premium206            }207        }208    }209210    private func control(_ symbol: String, _ title: String, id: String, active: Bool = false, disabled: Bool = false, action: @escaping () -> Void) -> some View {211        Button(action: action) {212            VStack(spacing: 6) {213                Image(systemName: symbol).font(.system(size: 17, weight: .semibold)).frame(height: 22)214                Text(title).font(.system(size: 11, weight: .semibold)).lineLimit(1).minimumScaleFactor(0.8)215            }216            .foregroundStyle(active ? SP.Palette.electric : SP.Palette.textPrimary)217            .frame(maxWidth: .infinity).frame(height: 62)218            .contentShape(RoundedRectangle(cornerRadius: SP.Radius.m, style: .continuous))219        }220        .buttonStyle(.plain)221        .spGlass(in: RoundedRectangle(cornerRadius: SP.Radius.m, style: .continuous))222        .opacity(disabled ? 0.35 : 1)223        .disabled(disabled)224        .accessibilityIdentifier("detail.\(id)")225    }226227    @ViewBuilder228    private func numberPanel(_ card: Card) -> some View {229        if !card.number.isEmpty {230            VStack(alignment: .leading, spacing: SP.Space.s) {231                SectionHeader(card.kind.numberLabel) {232                    if revealed { StatusPill(text: "Visible for 30 s", tone: .warning, symbol: "timer") }233                    else { StatusPill(text: "Protected", tone: .positive, symbol: "lock.fill") }234                }235                Text(revealed ? card.formattedNumber : card.maskedNumber)236                    .font(.system(size: 22, weight: .medium, design: .monospaced))237                    .foregroundStyle(SP.Palette.textPrimary)238                    .lineLimit(1).minimumScaleFactor(0.6)239                    .contentTransition(.numericText())240                    .privacySensitive()241                    .accessibilityIdentifier("detail.number")242                    .accessibilityLabel(revealed ? card.formattedNumber : "Hidden, ending in \(card.last4)")243                HStack(spacing: SP.Space.s) {244                    Button {245                        revealed ? hide() : reveal()246                    } label: {247                        Label(revealed ? "Hide" : "Reveal with \(vault.biometry.name)", systemImage: revealed ? "eye.slash" : "faceid")248                    }249                    .buttonStyle(SPButtonStyle(kind: revealed ? .secondary : .primary))250                    .accessibilityIdentifier("detail.reveal")251                    if revealed {252                        Button { copyNumber(card) } label: { Label(copied ? "Copied" : "Copy", systemImage: copied ? "checkmark" : "doc.on.doc") }253                            .buttonStyle(.spSecondary)254                            .accessibilityHint("Copies the number for 60 seconds, on this device only")255                    }256                }257                if card.kind.isBanking {258                    Text("The security code and the PIN are never stored in SP Vault.")259                        .font(.spCaption).foregroundStyle(SP.Palette.textTertiary)260                }261            }262            .spPanel()263        }264    }265266    private func detailsPanel(_ card: Card) -> some View {267        let category = vault.category(id: card.categoryID)268        return VStack(alignment: .leading, spacing: 0) {269            SectionHeader("Details").padding(.bottom, SP.Space.xs)270            DetailRow("Name", card.name, symbol: "textformat")271            Hairline()272            DetailRow("Type", card.kind.title, symbol: card.kind.symbol)273            if !card.issuer.isEmpty { Hairline(); DetailRow("Issuer", card.issuer, symbol: "building.columns") }274            if !card.holderName.isEmpty { Hairline(); DetailRow("Holder", card.holderName, symbol: "person") }275            Hairline()276            DetailRow(label: "Expiry", symbol: "calendar") { ExpiryLabel(card: card, soonDays: settings.expiringSoonDays) }277            Hairline()278            DetailRow(label: "Category", symbol: "folder") {279                HStack(spacing: 6) {280                    Circle().fill(Color(category.tint)).frame(width: 8, height: 8)281                    Text(category.name)282                }283            }284            Hairline()285            DetailRow("Format", card.format.label, symbol: "ruler")286        }287        .spPanel()288    }289290    private func fieldsPanel(_ card: Card) -> some View {291        VStack(alignment: .leading, spacing: 0) {292            SectionHeader("More information").padding(.bottom, SP.Space.xs)293            ForEach(Array(card.fields.enumerated()), id: \.element.id) { index, field in294                if index > 0 { Hairline() }295                DetailRow(label: field.label, symbol: field.isSensitive ? "lock" : nil) {296                    Text(field.isSensitive && !revealed ? "••••••" : field.value).privacySensitive(field.isSensitive)297                }298            }299            if card.fields.contains(where: \.isSensitive), !revealed, card.number.isEmpty {300                Button { reveal() } label: { Label("Reveal with \(vault.biometry.name)", systemImage: "faceid") }301                    .buttonStyle(.spSecondary).padding(.top, SP.Space.s)302            }303        }304        .spPanel()305    }306307    private func notesPanel(_ card: Card) -> some View {308        VStack(alignment: .leading, spacing: SP.Space.xs) {309            SectionHeader("Notes")310            Text(card.notes).font(.spCallout).foregroundStyle(SP.Palette.textPrimary).frame(maxWidth: .infinity, alignment: .leading)311        }312        .spPanel()313    }314315    private func recordPanel(_ card: Card) -> some View {316        VStack(alignment: .leading, spacing: 0) {317            SectionHeader("Record").padding(.bottom, SP.Space.xs)318            DetailRow("Added", card.createdAt.formatted(date: .abbreviated, time: .shortened))319            Hairline()320            DetailRow("Modified", card.modifiedAt.formatted(date: .abbreviated, time: .shortened))321            Hairline()322            DetailRow("Sides", card.hasBack ? "Front and back" : "Front only")323            Hairline()324            DetailRow(label: "Storage") { Label("AES-256-GCM, own key", systemImage: "lock.shield").labelStyle(.titleAndIcon) }325        }326        .spPanel(raised: false)327    }328329    // MARK: Actions330331    private func flip(_ card: Card) {332        guard card.hasBack else { return }333        Haptics.shared.play(.flip)334        showsBack.toggle()335    }336337    private func reveal() {338        Task {339            guard await vault.reauthenticate(reason: "Reveal the full number") else {340                Haptics.shared.play(.error)341                return342            }343            Haptics.shared.play(.success)344            withAnimation(SP.Motion.gentle) { revealed = true }345            revealTask?.cancel()346            revealTask = Task {347                try? await Task.sleep(for: Self.revealDuration)348                if !Task.isCancelled { hide() }349            }350        }351    }352353    private func hide() {354        revealTask?.cancel()355        withAnimation(SP.Motion.gentle) { revealed = false; copied = false }356    }357358    /// Explicit copy only, never automatic: local to this device, expires in 60 s.359    private func copyNumber(_ card: Card) {360        UIPasteboard.general.setItems([[UIPasteboard.typeAutomatic: card.number]],361                                      options: [.localOnly: true, .expirationDate: Date().addingTimeInterval(60)])362        Haptics.shared.play(.success)363        copied = true364    }365366    private func replaceImage(_ image: CGImage, side: CardSide) {367        do {368            let full = try CardImageCodec.encode(CardImageCodec.resized(image, longEdge: CardImageCodec.fullLongEdge))369            let thumb = try CardImageCodec.encode(CardImageCodec.resized(image, longEdge: CardImageCodec.thumbnailLongEdge), quality: 0.82)370            try vault.setImage(full, thumbnail: thumb, side: side, for: cardID)371            if side == .front, var card {372                card.dominantColor = CardImageCodec.dominantColor(of: image)373                try vault.update(card)374            }375            Haptics.shared.play(.success)376        } catch {377            errorMessage = "The photograph could not be saved."378        }379    }380381    private func removeBack() {382        do {383            try vault.setImage(nil, thumbnail: nil, side: .back, for: cardID)384            showsBack = false385        } catch { errorMessage = "The back could not be removed." }386    }387388    private func delete() {389        do {390            try vault.delete(cardID)391            Haptics.shared.play(.drop)392            dismiss()393        } catch { errorMessage = "The card could not be deleted." }394    }395}396397extension CardSide: Identifiable {398    var id: String { rawValue }399}400401/// Full Screen Card Viewer — the card alone on black, as large as the screen402/// allows (landscape cards are turned a quarter turn), with pinch and pan.403struct FullScreenCardView: View {404    let card: Card405    var startsOnBack = false406407    @Environment(AppSettings.self) private var settings408    @Environment(\.dismiss) private var dismiss409    @State private var showsBack = false410    @State private var zoom: CGFloat = 1411    @State private var steadyZoom: CGFloat = 1412    @State private var offset: CGSize = .zero413    @State private var steadyOffset: CGSize = .zero414    @State private var chromeVisible = true415416    var body: some View {417        GeometryReader { proxy in418            let landscape = card.format.aspectRatio > 1419            // A landscape card rotated 90° is as wide as the screen is tall.420            let length = landscape ? min(proxy.size.height - 150, (proxy.size.width - 32) * card.format.aspectRatio)421                                   : proxy.size.width - 32422            ZStack {423                Color.black.ignoresSafeArea()424                FlippableCardView(card: card, showsBack: $showsBack, thumbnail: false, mode: settings.renderMode, privacy: false)425                    .frame(width: length)426                    .rotationEffect(.degrees(landscape ? 90 : 0))427                    .scaleEffect(zoom)428                    .offset(offset)429                    .gesture(430                        MagnifyGesture()431                            .onChanged { zoom = max(1, min(5, steadyZoom * $0.magnification)) }432                            .onEnded { _ in433                                steadyZoom = zoom434                                if zoom <= 1.02 { reset() }435                            }436                            .simultaneously(with: DragGesture()437                                .onChanged { value in438                                    guard zoom > 1 else { return }439                                    offset = CGSize(width: steadyOffset.width + value.translation.width, height: steadyOffset.height + value.translation.height)440                                }441                                .onEnded { _ in steadyOffset = offset })442                    )443                    .onTapGesture(count: 2) {444                        withAnimation(SP.Motion.card) {445                            if zoom > 1 { reset() } else { zoom = 2.5; steadyZoom = 2.5 }446                        }447                    }448                    .onTapGesture { withAnimation(SP.Motion.gentle) { chromeVisible.toggle() } }449                    .frame(width: proxy.size.width, height: proxy.size.height)450                    .contentShape(Rectangle())451                    .accessibilityIdentifier("fullscreen.card")452453                if chromeVisible {454                    VStack {455                        HStack {456                            GlassIconButton(symbol: "xmark", label: "Close full screen") { dismiss() }457                                .accessibilityIdentifier("fullscreen.close")458                            Spacer()459                            if zoom > 1 {460                                Text("\(Int((zoom * 100).rounded())) %").font(.spNumber).foregroundStyle(.white.opacity(0.8))461                                    .padding(.horizontal, 12).frame(height: 36).spGlass(interactive: false)462                            }463                            if card.hasBack {464                                GlassIconButton(symbol: "arrow.left.arrow.right", label: showsBack ? "Show front" : "Show back") {465                                    Haptics.shared.play(.flip)466                                    showsBack.toggle()467                                }468                                .accessibilityIdentifier("fullscreen.flip")469                            }470                        }471                        Spacer()472                        Text(showsBack ? "Back" : "Front").spEyebrow(.white.opacity(0.55))473                    }474                    .padding(.horizontal, SP.Space.page).padding(.vertical, SP.Space.xs)475                    .transition(.opacity)476                }477            }478            .frame(width: proxy.size.width, height: proxy.size.height)479        }480        .preferredColorScheme(.dark)481        .statusBarHidden(!chromeVisible)482        .persistentSystemOverlays(.hidden)483        .onAppear { showsBack = startsOnBack && card.hasBack }484    }485486    private func reset() {487        withAnimation(SP.Motion.card) {488            zoom = 1; steadyZoom = 1; offset = .zero; steadyOffset = .zero489        }490    }491}492
Files main
Menu

Theme