SPB Git

Repository Public

SearchViews.swift 20.3 KB 335 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Next/SearchViews.swift3// Description: Search with the operator language — a chip field fed by the SERVER's parse of the query, suggestions (operators, contacts,4// labels, folders, recent searches), scope switch, optional « par le sens » toggle, inline parse errors, results in the shared list5// component with pagination and bulk actions, the visible offline fallback, and saved searches (smart folders).6import SPMailCore7import SwiftUI89extension QueryOperator {10    /// The operator as the chip shows it (the query itself keeps the canonical English operators the three clients share).11    var chipTitle: String {12        switch self {13        case .text: ""; case .from: L("de"); case .to: L("à"); case .cc: L("cc"); case .bcc: L("cci"); case .subject: L("objet"); case .body: L("contenu"); case .filename: L("fichier")14        case .label: L("libellé"); case .in: L("dans"); case .has: L("avec"); case .is: L("état"); case .before: L("avant"); case .after: L("après"); case .larger: L("plus de"); case .smaller: L("moins de")15        }16    }17    var hint: String {18        switch self {19        case .text: ""; case .from: L("expéditeur"); case .to: L("destinataire"); case .cc: L("en copie"); case .bcc: L("en copie cachée"); case .subject: L("mots de l’objet")20        case .body: L("mots du contenu"); case .filename: L("nom d’une pièce jointe"); case .label: L("libellé"); case .in: L("dossier"); case .has: L("pièce jointe")21        case .is: L("non lu, avec drapeau, épinglé…"); case .before: L("avant une date (AAAA-MM-JJ)"); case .after: L("après une date (AAAA-MM-JJ)")22        case .larger: L("plus grand que (5m, 300k)"); case .smaller: L("plus petit que (5m, 300k)")23        }24    }25}2627/// One proposal under the search field. `token` replaces the token being typed.28struct SearchSuggestion: Identifiable, Hashable {29    enum Kind { case op, value, contact, label, recent }30    var kind: Kind31    var title: String32    var subtitle: String?33    var icon: String34    /// The text that replaces the typed token; ends with a space when the term is complete.35    var token: String36    /// A whole query (recent search) instead of one token.37    var replacesAll = false38    var id: String { "\(kind)|\(token)" }39}4041@MainActor42enum SearchSuggestions {43    static func value(_ op: QueryOperator, _ v: String) -> String { QueryChip(op: op, value: v).token + " " }4445    /// Proposals for the token being typed: operators, their values, contacts, labels, folders — and recent searches for an empty field.46    static func make(draft: String, hasChips: Bool, app: AppModel, contacts: [ContactSuggestion]) -> [SearchSuggestion] {47        let token = draft.split(separator: " ", omittingEmptySubsequences: false).last.map(String.init) ?? ""48        let next = app.next49        if draft.trimmingCharacters(in: .whitespaces).isEmpty {50            guard !hasChips else { return [] }51            return RemoteSearchState.recents.prefix(5).map { SearchSuggestion(kind: .recent, title: $0, icon: "clock.arrow.circlepath", token: $0 + " ", replacesAll: true) }52        }53        guard !token.isEmpty else { return [] }54        let negated = token.hasPrefix("-"), bare = negated ? String(token.dropFirst()) : token, sign = negated ? "-" : ""55        if let colon = bare.firstIndex(of: ":"), let op = QueryOperator(rawValue: String(bare[..<colon]).lowercased()) {56            let typed = String(bare[bare.index(after: colon)...]).replacingOccurrences(of: "\"", with: "").lowercased()57            func hit(_ s: String) -> Bool { typed.isEmpty || s.lowercased().hasPrefix(typed) || s.folding(options: .diacriticInsensitive, locale: nil).lowercased().contains(typed) }58            switch op {59            case .from, .to, .cc, .bcc:60                return contacts.prefix(6).map { SearchSuggestion(kind: .contact, title: $0.name.isEmpty ? $0.email : $0.name, subtitle: $0.name.isEmpty ? nil : $0.email, icon: "person.crop.circle", token: sign + value(op, $0.email)) }61            case .label:62                return next.labels.filter { hit($0.name) }.prefix(8).map { SearchSuggestion(kind: .label, title: $0.name, icon: "tag", token: sign + value(.label, $0.name)) }63            case .in, .is, .has:64                return (op.suggestedValues ?? []).filter(hit).map { SearchSuggestion(kind: .value, title: "\(op.rawValue):\($0)", subtitle: stateTitle(op, $0), icon: op == .in ? "folder" : op == .has ? "paperclip" : "circle.lefthalf.filled", token: sign + value(op, $0)) }65            default: return []66            }67        }68        var out: [SearchSuggestion] = []69        let lower = bare.lowercased()70        for op in QueryOperator.allCases where op != .text && op.rawValue.hasPrefix(lower) {71            out.append(SearchSuggestion(kind: .op, title: op.prefix, subtitle: op.hint, icon: "chevron.right.circle", token: sign + op.prefix))72        }73        out += contacts.prefix(3).map { SearchSuggestion(kind: .contact, title: $0.name.isEmpty ? $0.email : $0.name, subtitle: L("de : \($0.email)"), icon: "person.crop.circle", token: value(.from, $0.email)) }74        out += next.labels.filter { $0.name.lowercased().hasPrefix(lower) }.prefix(3).map { SearchSuggestion(kind: .label, title: $0.name, subtitle: L("libellé"), icon: "tag", token: value(.label, $0.name)) }75        return Array(out.prefix(8))76    }7778    static func stateTitle(_ op: QueryOperator, _ v: String) -> String? {79        switch (op, v) {80        case (.is, "unread"): L("non lu"); case (.is, "read"): L("lu"); case (.is, "starred"): L("avec drapeau"); case (.is, "pinned"): L("épinglé"); case (.is, "snoozed"): L("en veille")81        case (.is, "followup"): L("suivi à faire"); case (.is, "answered"): L("répondu"); case (.is, "forwarded"): L("transféré"); case (.is, "draft"): L("brouillon")82        case (.in, "inbox"): L("Boîte de réception"); case (.in, "sent"): L("Envoyés"); case (.in, "drafts"): L("Brouillons"); case (.in, "trash"): L("Corbeille"); case (.in, "junk"): L("Indésirables")83        case (.in, "archive"): L("Archives"); case (.in, "all"): L("tous les dossiers"); case (.in, "snoozed"): L("En veille"); case (.has, "attachment"): L("pièce jointe")84        default: nil85        }86    }87}8889/// A parsed term as a removable chip.90struct QueryChipView: View {91    let chip: QueryChip92    var remove: () -> Void93    var body: some View {94        HStack(spacing: 4) {95            if chip.negated { Text("sauf").foregroundStyle(SPColor.danger) }96            if let op = chip.op, op != .text { Text(op.chipTitle).foregroundStyle(SPColor.text3) } else if chip.op == nil { Text(chip.rawOp).foregroundStyle(SPColor.text3) }97            Text(chip.phrase ? "« \(chip.value) »" : (chip.op.flatMap { SearchSuggestions.stateTitle($0, chip.value) } ?? chip.value)).foregroundStyle(SPColor.text).lineLimit(1)98            Button(action: remove) { Image(systemName: "xmark").font(.system(size: 8, weight: .bold)).foregroundStyle(SPColor.text3).frame(width: 14, height: 14).contentShape(Rectangle()) }99                .buttonStyle(.plain).accessibilityLabel(Text("Retirer ce terme"))100        }101        .font(SPFont.caption)102        .padding(.leading, 7).padding(.trailing, 3).padding(.vertical, 3)103        .background(SPColor.surface3, in: RoundedRectangle(cornerRadius: SPRadius.chip, style: .continuous))104        .accessibilityElement(children: .combine)105        .accessibilityLabel(Text(chip.token))106        .accessibilityAction(named: Text("Retirer ce terme"), remove)107    }108}109110struct SearchView: View {111    @Bindable var scene: MailScene112    let composeSpace: Namespace.ID113    let compactWindow: Bool114    var onOpen: () -> Void115    @FocusState private var focused: Bool116    @State private var contacts: [ContactSuggestion] = []117    @State private var saveName = ""118119    private var app: AppModel { scene.app }120    private var state: RemoteSearchState { scene.next.search }121    private var isList: Bool { scene.selection != .search }122123    private var suggestions: [SearchSuggestion] {124        guard focused else { return [] }125        return SearchSuggestions.make(draft: state.draft, hasChips: !state.chips.isEmpty, app: app, contacts: contacts)126    }127128    var body: some View {129        @Bindable var s = scene.next.search130        @Bindable var next = scene.next131        let suggestions = suggestions132        VStack(spacing: 0) {133            field(suggestions)134            if !suggestions.isEmpty { suggestionList(suggestions) }135            RemoteListView(scene: scene, rows: s.rows, isLoading: s.isSearching, isLoadingMore: s.isLoadingMore, openId: next.openRowId,136                           emptyIcon: s.failure != nil ? "exclamationmark.triangle" : "magnifyingglass",137                           emptyTitle: s.failure ?? (s.isEmpty ? L("Recherchez dans tout votre courrier") : s.errors.isEmpty ? L("Aucun résultat") : L("Corrigez la recherche pour voir des résultats")),138                           emptyMessage: s.isEmpty ? L("Combinez des mots et des opérateurs : from: to: subject: has:attachment is:unread label: in: before: after: filename:") : nil,139                           compactWindow: compactWindow, composeSpace: isList ? composeSpace : nil,140                           open: { row in Task { await scene.openRemote(row) }; RemoteSearchState.remember(s.query); onOpen() },141                           perform: { action, rows in await scene.performRemote(action, on: rows) },142                           loadMore: { row in await scene.loadMoreRemoteSearch(after: row) }) {143                if s.isOffline { OfflineNote(text: L("Hors ligne — résultats locaux : seuls les messages déjà sur cet appareil sont cherchés.")) }144                if let provider = s.provider, !s.rows.isEmpty {145                    Label("Recherche par le sens — traitée par \(provider)", systemImage: "sparkles").font(.footnote).foregroundStyle(SPColor.info).listRowBackground(Color.clear).listRowSeparator(.hidden)146                        #if os(macOS)147                        .selectionDisabled()148                        #endif149                }150            }151        }152        .background(SPColor.bg)153        .navigationTitle(scene.nextTitle)154        #if os(iOS)155        .navigationBarTitleDisplayMode(.inline)156        #endif157        .task(id: "\(s.draft)|\(s.chips.map(\.id))|\(s.allMailboxes)|\(s.semantic)") {158            try? await Task.sleep(for: .milliseconds(320))159            guard !Task.isCancelled, s.lastKey != s.runKey else { return }160            await scene.runRemoteSearch()161        }162        .task(id: s.draft) {163            // contacts for from: / to: and for a bare word — cached suggestions offline, the server's ranking online164            let token = s.draft.split(separator: " ").last.map(String.init) ?? ""165            let word = token.split(separator: ":").last.map(String.init) ?? ""166            guard word.count >= 2, app.next.has(.contacts), token.last != ":" else { contacts = []; return }167            let cached = await app.next.store?.suggest(word, limit: 6) ?? []168            contacts = cached169            try? await Task.sleep(for: .milliseconds(200))170            if !Task.isCancelled, let fresh = try? await app.next.api.suggestContacts(word, limit: 6), !Task.isCancelled { contacts = fresh }171        }172        .onChange(of: next.focusToken) { _, _ in focused = true }173        .onAppear { if scene.selection == .search, s.isEmpty { focused = true } }174        .refreshable { await scene.runRemoteSearch() }175        .toolbar { toolbar }176        #if os(macOS)177        .onExitCommand { if scene.selection == .search { scene.closeSearch() } }178        #endif179        .alert("Enregistrer la recherche", isPresented: $next.saveSearchRequest) {180            TextField("Nom", text: $saveName)181            Button("Enregistrer") { let name = saveName.trimmingCharacters(in: .whitespaces); Task { await save(name) } }.disabled(saveName.trimmingCharacters(in: .whitespaces).isEmpty)182            Button("Annuler", role: .cancel) {}183        } message: { Text("Elle apparaîtra dans la barre latérale et s’ouvrira comme un dossier.") }184    }185186    // MARK: field187188    private func field(_ suggestions: [SearchSuggestion]) -> some View {189        @Bindable var s = scene.next.search190        return VStack(alignment: .leading, spacing: SPSpacing.m) {191            HStack(alignment: .top, spacing: SPSpacing.m) {192              Image(systemName: "magnifyingglass").foregroundStyle(SPColor.text3).frame(height: 24).accessibilityHidden(true)193              WrapLayout(spacing: 6) {194                ForEach(Array(s.chips.enumerated()), id: \.offset) { n, chip in195                    if n > 0, s.chips[n - 1].group == chip.group { Text("ou").font(SPFont.caption).foregroundStyle(SPColor.text3) }196                    QueryChipView(chip: chip) { s.chips.remove(at: n) }197                }198                TextField(s.chips.isEmpty ? L("Rechercher — mots, from:, label:, is:unread…") : L("Affiner…"), text: $s.draft)199                    .textFieldStyle(.plain).focused($focused).autocorrectionDisabled()200                    #if os(iOS)201                    .textInputAutocapitalization(.never).submitLabel(.search)202                    #endif203                    .frame(minWidth: 110, idealWidth: 150, maxWidth: .infinity, minHeight: 24)204                    .onSubmit { if let first = suggestions.first, first.kind == .op || state.draft.hasSuffix(":") { pick(first) } else { Task { await scene.runRemoteSearch(commit: true) } } }205                    .onKeyPress(.delete) {206                        guard s.draft.isEmpty, !s.chips.isEmpty else { return .ignored }207                        s.chips.removeLast()208                        return .handled209                    }210                    .accessibilityLabel(Text("Recherche"))211              }212              .frame(maxWidth: .infinity, alignment: .leading)213                if s.isSearching { ProgressView().controlSize(.small).frame(height: 24) } else if !s.isEmpty {214                    Button { s.chips = []; s.draft = ""; focused = true } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(SPColor.text3).frame(width: 24, height: 24) }215                        .buttonStyle(.plain).accessibilityLabel(Text("Effacer la recherche"))216                }217            }218            .padding(.horizontal, SPSpacing.m).padding(.vertical, SPSpacing.s)219            .background(SPColor.surface, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))220            .overlay(RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).stroke(focused ? SPColor.accent : SPColor.borderStrong, lineWidth: focused ? 1.5 : 0.5))221            .contentShape(Rectangle())222            .onTapGesture { focused = true }223224            ForEach(Array(s.errors.enumerated()), id: \.offset) { _, issue in225                Label(issue.token.isEmpty ? issue.message : "« \(issue.token) » — \(issue.message)", systemImage: "exclamationmark.circle").font(SPFont.callout).foregroundStyle(SPColor.danger)226                    .fixedSize(horizontal: false, vertical: true)227            }228229            if app.accounts.count > 1 || app.next.aiEnabled(.semantic) {230                HStack(spacing: SPSpacing.m) {231                    if app.accounts.count > 1, s.savedSearchId == nil {232                        Picker("Étendue", selection: $s.allMailboxes) { Text("Cette boîte").tag(false); Text("Toutes les boîtes").tag(true) }233                            .pickerStyle(.segmented).labelsHidden().fixedSize()234                            .accessibilityLabel(Text("Étendue de la recherche"))235                    }236                    Spacer(minLength: 0)237                    if app.next.aiEnabled(.semantic) {238                        Toggle(isOn: $s.semantic) { Label("Par le sens", systemImage: "sparkles") }.toggleStyle(.button).controlSize(.small)239                            .help("Recherche hybride : mots-clés et proximité de sens, calculée par le fournisseur d’intelligence choisi")240                    }241                }242            }243        }244        .padding(.horizontal, SPSpacing.xl).padding(.top, SPSpacing.m).padding(.bottom, SPSpacing.m)245    }246247    private func suggestionList(_ suggestions: [SearchSuggestion]) -> some View {248        VStack(spacing: 0) {249            ForEach(suggestions) { item in250                Button { pick(item) } label: {251                    HStack(spacing: SPSpacing.l) {252                        Image(systemName: item.icon).frame(width: 20).foregroundStyle(SPColor.text3)253                        Text(item.title).font(item.kind == .op || item.kind == .value ? SPFont.mono : .body).foregroundStyle(SPColor.text).lineLimit(1)254                        if let sub = item.subtitle { Text(sub).font(SPFont.callout).foregroundStyle(SPColor.text3).lineLimit(1) }255                        Spacer(minLength: 0)256                    }257                    .padding(.horizontal, SPSpacing.xl).padding(.vertical, SPSpacing.s)258                    #if os(iOS)259                    .frame(minHeight: 44)260                    #endif261                    .contentShape(Rectangle())262                }263                .buttonStyle(.plain)264                #if os(iOS)265                .hoverEffect(.highlight)266                #endif267            }268            if suggestions.first?.kind == .recent {269                Button("Effacer les recherches récentes") { RemoteSearchState.forgetRecents(); focused = false }.buttonStyle(.borderless).font(SPFont.caption).foregroundStyle(SPColor.text3)270                    .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, SPSpacing.xl).padding(.vertical, SPSpacing.s)271            }272            Divider().overlay(SPColor.border)273        }274        .background(SPColor.bg)275    }276277    private func pick(_ item: SearchSuggestion) {278        let s = state279        if item.replacesAll { s.chips = []; s.draft = item.token; return }280        var parts = s.draft.split(separator: " ", omittingEmptySubsequences: false).map(String.init)281        if parts.isEmpty { parts = [""] }282        parts[parts.count - 1] = item.token283        s.draft = parts.joined(separator: " ")284        focused = true285    }286287    private func save(_ name: String) async {288        let s = state289        guard !name.isEmpty, !s.query.isEmpty else { return }290        let scope: MailboxScope = s.allMailboxes ? .all : scene.currentAccount.map { .only([$0]) } ?? .all291        if let saved = await app.next.saveSearch(name: name, query: s.query, scope: scope) {292            app.toast = Toast(message: L("Recherche enregistrée"), kind: .success)293            if !NextStore.isLocal(saved.id) { scene.next.previousSelection = nil; scene.selection = .savedSearch(saved.id) }294        }295    }296297    @ToolbarContentBuilder private var toolbar: some ToolbarContent {298        if scene.selection == .search {299            ToolbarItem(placement: .cancellationAction) { Button("Fermer") { scene.closeSearch() }.help("Fermer la recherche (esc)") }300        }301        if app.next.has(.savedSearches), state.savedSearchId == nil, state.title == nil {302            ToolbarItem(placement: .primaryAction) {303                Button { saveName = ""; scene.next.saveSearchRequest = true } label: { Label("Enregistrer la recherche", systemImage: "bookmark") }304                    .disabled(state.isEmpty || !state.errors.isEmpty || state.isOffline).help("Enregistrer la recherche comme dossier intelligent")305            }306        }307    }308}309310extension RemoteSearchState {311    /// What the last run answered for; the field does not ask the server twice for the same thing.312    var runKey: String { "\(query)|\(allMailboxes)|\(semantic)" }313}314315/// Compose and search buttons of the lists that span mailboxes (and of the folder list).316struct NextListToolbar: ToolbarContent {317    let scene: MailScene318    let compactWindow: Bool319    var body: some ToolbarContent {320        #if os(macOS)321        ToolbarItem(placement: .primaryAction) {322            Button { Task { await scene.compose(.new) } } label: { Label("Nouveau message", systemImage: "square.and.pencil") }.help("Nouveau message (⌘N)")323        }324        ToolbarItem(placement: .primaryAction) {325            Button { scene.openSearch() } label: { Label("Rechercher", systemImage: "magnifyingglass") }.help("Rechercher dans le courrier (⌘F)")326        }327        #else328        if !compactWindow {329            ToolbarItem(placement: .primaryAction) { Button { Task { await scene.compose(.new) } } label: { Label("Nouveau message", systemImage: "square.and.pencil") } }330        }331        ToolbarItem(placement: .topBarTrailing) { Button { scene.openSearch() } label: { Label("Rechercher", systemImage: "magnifyingglass") } }332        #endif333    }334}335
Files main
Menu

Theme