SPB Git

Repository Public

SearchView.swift 11.3 KB 232 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Features/Search/SearchView.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/// Local search. Results come from the in-memory index of the unlocked vault;44/// no query is stored, suggested back or handed to the system.45struct SearchView: View {46    @Environment(Vault.self) private var vault47    @Environment(AppSettings.self) private var settings48    @Environment(AppRouter.self) private var router4950    @State private var query = ""51    @FocusState private var focused: Bool5253    private var trimmed: String { query.trimmingCharacters(in: .whitespacesAndNewlines) }5455    var body: some View {56        let results = trimmed.isEmpty ? [] : vault.search(trimmed)57        NavigationStack {58            ScreenScaffold(eyebrow: "On this iPhone only", title: "Search") {59                field60                if trimmed.isEmpty {61                    suggestions62                } else if results.isEmpty {63                    EmptyStateView(symbol: "magnifyingglass", title: "No card matches",64                                   message: "Try a name, an issuer, a category, an expiry year or the last four digits.")65                        .spPanel(padding: 0)66                        .accessibilityIdentifier("search.empty")67                } else {68                    VStack(alignment: .leading, spacing: SP.Space.s) {69                        SectionHeader(results.count == 1 ? "1 result" : "\(results.count) results")70                        VStack(spacing: 0) {71                            ForEach(Array(results.enumerated()), id: \.element.id) { position, card in72                                Button { router.open(card: card.id) } label: {73                                    let pill = card.expiryPill(soonWithinDays: settings.expiringSoonDays)74                                    CardRowView(card: card, statusText: pill?.tone == .positive ? nil : pill?.text, statusTone: pill?.tone ?? .neutral) {75                                        Image(systemName: "chevron.right").font(.system(size: 13, weight: .semibold)).foregroundStyle(SP.Palette.textTertiary)76                                    }77                                    .padding(SP.Space.m)78                                }79                                .buttonStyle(.plain)80                                .accessibilityIdentifier("search.result.\(card.name)")81                                if position < results.count - 1 { Hairline().padding(.leading, SP.Space.m) }82                            }83                        }84                        .spPanel(padding: 0)85                    }86                }87            }88        }89    }9091    private var field: some View {92        HStack(spacing: SP.Space.xs) {93            Image(systemName: "magnifyingglass").font(.system(size: 16, weight: .semibold))94                .foregroundStyle(focused ? SP.Palette.electric : SP.Palette.titanium)95            TextField("Name, issuer, last four digits…", text: $query)96                .font(.spBody).foregroundStyle(SP.Palette.textPrimary)97                .focused($focused)98                .textInputAutocapitalization(.never).autocorrectionDisabled()99                .submitLabel(.search)100                .accessibilityIdentifier("search.field")101            if !query.isEmpty {102                Button {103                    query = ""104                } label: {105                    Image(systemName: "xmark.circle.fill").font(.system(size: 17)).foregroundStyle(SP.Palette.textTertiary)106                        .frame(width: 32, height: 32).contentShape(Rectangle())107                }108                .buttonStyle(.plain)109                .accessibilityLabel("Clear search")110                .accessibilityIdentifier("search.clear")111            }112        }113        .padding(.leading, SP.Space.m).padding(.trailing, SP.Space.xs)114        .frame(minHeight: 52)115        .background(SP.Palette.surface, in: RoundedRectangle(cornerRadius: SP.Radius.m, style: .continuous))116        .overlay(RoundedRectangle(cornerRadius: SP.Radius.m, style: .continuous)117            .strokeBorder(focused ? SP.Palette.electric.opacity(0.7) : SP.Palette.hairlineStrong, lineWidth: focused ? 1.25 : 0.75))118        .animation(SP.Motion.quick, value: focused)119    }120121    // MARK: Suggestions122123    @ViewBuilder124    private var suggestions: some View {125        if vault.cards.isEmpty {126            EmptyStateView(symbol: "rectangle.stack.badge.plus", title: "Your vault is empty",127                           message: "Scan a first card and it becomes searchable at once.", actionTitle: "Scan a card") { router.startScan() }128                .spPanel(padding: 0)129        } else {130            let categories = vault.categories.filter { category in vault.cards.contains { $0.categoryID == category.id } }131            VStack(alignment: .leading, spacing: SP.Space.s) {132                SectionHeader("Categories")133                LazyVGrid(columns: [GridItem(.flexible(), spacing: SP.Space.s), GridItem(.flexible())], spacing: SP.Space.s) {134                    ForEach(categories) { category in135                        let count = vault.cards.filter { $0.categoryID == category.id }.count136                        Button { run(category.name) } label: {137                            HStack(spacing: SP.Space.s) {138                                IconBadge(symbol: category.symbol, tint: Color(category.tint), size: 34)139                                VStack(alignment: .leading, spacing: 1) {140                                    Text(Self.shortName(category.name)).font(.spCallout.weight(.semibold))141                                        .foregroundStyle(SP.Palette.textPrimary).lineLimit(1).minimumScaleFactor(0.75)142                                    Text(count == 1 ? "1 card" : "\(count) cards").font(.spCaption).monospacedDigit().foregroundStyle(SP.Palette.textSecondary)143                                }144                                Spacer(minLength: 0)145                            }146                            .spPanel(radius: SP.Radius.m, padding: SP.Space.s, raised: false)147                            .contentShape(Rectangle())148                        }149                        .buttonStyle(.plain)150                        .accessibilityIdentifier("search.category.\(category.id)")151                    }152                }153            }154            let kinds = Array(Set(vault.cards.map(\.kind))).sorted { $0.title < $1.title }155            VStack(alignment: .leading, spacing: SP.Space.s) {156                SectionHeader("Card types")157                FlowLayout(spacing: SP.Space.xs) {158                    ForEach(kinds, id: \.self) { kind in159                        Button { run(kind.title) } label: {160                            HStack(spacing: 6) {161                                Image(systemName: kind.symbol).font(.system(size: 11, weight: .semibold)).foregroundStyle(SP.Palette.titanium)162                                Text(kind.title).font(.system(size: 14, weight: .medium)).foregroundStyle(SP.Palette.textPrimary)163                            }164                            .padding(.horizontal, SP.Space.s).frame(minHeight: 36)165                            .background(SP.Palette.surface, in: Capsule())166                            .overlay(Capsule().strokeBorder(SP.Palette.hairlineStrong, lineWidth: 0.75))167                            .contentShape(Capsule())168                        }169                        .buttonStyle(.plain)170                        .accessibilityIdentifier("search.kind.\(kind.rawValue)")171                    }172                }173            }174            Text("Searches names, issuers, categories, notes, expiry dates and the last four digits. Full numbers and sensitive fields are never indexed.")175                .font(.spCaption).foregroundStyle(SP.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)176        }177    }178179    /// "My Professional Cards" becomes "Professional"; custom names are kept.180    nonisolated static func shortName(_ name: String) -> String {181        var short = name182        if short.hasPrefix("My ") { short.removeFirst(3) }183        if short.hasSuffix(" Cards"), short.count > 6 { short.removeLast(6) }184        return short.isEmpty ? name : short185    }186187    private func run(_ text: String) {188        Haptics.shared.play(.select)189        query = text.replacingOccurrences(of: "'", with: " ")190    }191}192193/// Wrapping row layout for chips.194struct FlowLayout: Layout {195    var spacing: CGFloat = 8196197    private func rows(_ subviews: Subviews, width: CGFloat) -> [[(Int, CGSize)]] {198        var rows: [[(Int, CGSize)]] = [[]]199        var x: CGFloat = 0200        for (index, subview) in subviews.enumerated() {201            let size = subview.sizeThatFits(ProposedViewSize(width: width, height: nil))202            if x + size.width > width, !rows[rows.count - 1].isEmpty {203                rows.append([])204                x = 0205            }206            rows[rows.count - 1].append((index, size))207            x += size.width + spacing208        }209        return rows210    }211212    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {213        let width = proposal.width ?? 320214        let rows = rows(subviews, width: width)215        let height = rows.reduce(0) { $0 + ($1.map(\.1.height).max() ?? 0) } + spacing * CGFloat(max(0, rows.count - 1))216        return CGSize(width: width, height: height)217    }218219    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {220        var y = bounds.minY221        for row in rows(subviews, width: bounds.width) {222            var x = bounds.minX223            let rowHeight = row.map(\.1.height).max() ?? 0224            for (index, size) in row {225                subviews[index].place(at: CGPoint(x: x, y: y + (rowHeight - size.height) / 2), proposal: ProposedViewSize(size))226                x += size.width + spacing227            }228            y += rowHeight + spacing229        }230    }231}232
Files main
Menu

Theme