SPB Git

Repository Public

SuggestionsPanel.swift 12.1 KB 278 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Search iOS9// File             : Features/Search/SuggestionsPanel.swift10// Description      : While typing: completions, sites and spelling proposals11//                    from /v2/autocomplete, each drawn in its own way; recent12//                    searches and operators.13// Module           : Features14// Repository       : https://git.spboucher.ai/sp-search-ios15// Project Website  : https://search.spboucher.ai16// Created          : 2026-12-0117// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SPSearchKit92import SwiftUI9394struct SuggestionsPanel: View {95    @Environment(SearchModel.self) private var model96    /// Runs a search.97    var onPick: (String) -> Void98    /// Puts a text in the field without searching.99    var onFill: (String) -> Void100    /// Opens a site suggested by name.101    var onOpen: (URL) -> Void102103    private static let operators: [(label: String, insert: String, hint: LocalizedStringKey)] = [104        ("site:", "site:", "Limiter à un site"),105        ("intitle:", "intitle:", "Mot dans le titre"),106        ("\"…\"", "\"", "Phrase exacte"),107        ("-", "-", "Exclure un terme"),108        ("lang:", "lang:", "Limiter à une langue"),109    ]110111    var body: some View {112        VStack(spacing: 0) {113            ScrollView(.horizontal, showsIndicators: false) {114                HStack(spacing: 8) {115                    ForEach(Self.operators, id: \.label) { op in116                        Button { onFill(QuerySyntax.appending(op.insert, to: model.text)) } label: { Text(verbatim: op.label) }117                            .buttonStyle(ChipStyle(mono: true))118                            .accessibilityLabel(Text(op.hint))119                            .accessibilityHint("Ajoute l’opérateur au texte")120                    }121                }122                .padding(.horizontal, 16).padding(.vertical, 10)123            }124            Rule()125            List {126                if model.text.trimmingCharacters(in: .whitespaces).isEmpty {127                    recent128                } else {129                    typed130                }131            }132            .listStyle(.plain)133            .scrollContentBackground(.hidden)134            .scrollDismissesKeyboard(.interactively)135            .frame(maxWidth: Theme.column)136        }137        .frame(maxWidth: .infinity)138        .background(Theme.paper)139    }140141    @ViewBuilder private var typed: some View {142        row(icon: "magnifyingglass", strong: true, fill: nil, label: Text(verbatim: model.text)) { onPick(model.text) }143            .accessibilityLabel(Text("Rechercher « \(model.text) »"))144        ForEach(model.suggestions) { s in145            switch s.kind {146            case .completion:147                row(icon: "magnifyingglass", strong: false, fill: s.text, label: Text(Self.completion(s.text, typed: model.text))) { onPick(s.text) }148            case .site:149                siteRow(s)150            case .correction:151                correctionRow(s)152            }153        }154    }155156    /// What the reader typed stays regular; what the completion adds is set in semibold.157    static func completion(_ text: String, typed: String) -> AttributedString {158        var a = AttributedString(text)159        let t = SearchRequest.normalise(typed)160        if !t.isEmpty, let r = text.range(of: t, options: [.caseInsensitive, .diacriticInsensitive, .anchored]), r.upperBound < text.endIndex,161           let lo = AttributedString.Index(r.upperBound, within: a) {162            a[lo...].font = .body.weight(.semibold)163        }164        return a165    }166167    /// A site: its name, its address, and a tap that goes straight to it.168    private func siteRow(_ s: Suggestion) -> some View {169        HStack(spacing: 12) {170            Button {171                if let url = s.link { onOpen(url) } else { onPick(s.text) }172            } label: {173                HStack(spacing: 12) {174                    Monogram(name: s.title ?? s.text, size: 26).accessibilityHidden(true)175                    VStack(alignment: .leading, spacing: 1) {176                        Text(verbatim: s.title ?? s.text).font(.body.weight(.medium)).foregroundStyle(Theme.ink).lineLimit(1)177                        // The server often names a site by its address alone: it is then said once.178                        if let title = s.title, title.caseInsensitiveCompare(s.text) != .orderedSame {179                            Text(verbatim: s.text).font(.data(.caption)).foregroundStyle(Theme.muted).lineLimit(1)180                        }181                    }182                    .frame(maxWidth: .infinity, alignment: .leading)183                    Text("Site").font(.eyebrow).textCase(.uppercase).tracking(0.8).foregroundStyle(Theme.muted)184                    Image(systemName: "arrow.up.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.muted)185                }186                .contentShape(Rectangle())187            }188            .buttonStyle(.plain)189            .accessibilityElement(children: .ignore)190            .accessibilityLabel(s.title.map { Text("Site : \($0), \(s.text)") } ?? Text("Site : \(s.text)"))191            .accessibilityHint(s.link != nil ? "Ouvre le site" : "Lance cette recherche")192            .accessibilityAddTraits(.isLink)193        }194        .frame(minHeight: 40)195        .listRowBackground(Color.clear)196        .listRowSeparatorTint(Theme.rule)197    }198199    /// A spelling proposal: said as such, in the display face.200    private func correctionRow(_ s: Suggestion) -> some View {201        Button { onPick(s.text) } label: {202            HStack(spacing: 12) {203                Image(systemName: "character.cursor.ibeam").foregroundStyle(Theme.accent).frame(minWidth: 26).accessibilityHidden(true)204                VStack(alignment: .leading, spacing: 1) {205                    Text("Orthographe proposée").font(.eyebrow).textCase(.uppercase).tracking(0.8).foregroundStyle(Theme.muted)206                    Text(verbatim: s.text).font(.display(.body, weight: .semibold)).italic().foregroundStyle(Theme.ink).lineLimit(2)207                }208                .frame(maxWidth: .infinity, alignment: .leading)209            }210            .contentShape(Rectangle())211        }212        .buttonStyle(.plain)213        .frame(minHeight: 40)214        .accessibilityElement(children: .ignore)215        .accessibilityLabel(Text("Orthographe proposée : \(s.text)"))216        .accessibilityHint("Lance cette recherche")217        .listRowBackground(Color.clear)218        .listRowSeparatorTint(Theme.rule)219    }220221    @ViewBuilder private var recent: some View {222        if !model.history.isEmpty {223            Section {224                ForEach(model.history.prefix(8)) { entry in225                    row(icon: "clock", strong: false, fill: entry.query, label: Text(verbatim: entry.query)) { onPick(entry.query) }226                        .swipeActions { Button("Retirer", role: .destructive) { model.removeFromHistory(entry.query) } }227                }228                Text("Conservées sur cet appareil seulement.").font(.caption).foregroundStyle(Theme.muted)229                    .listRowBackground(Color.clear)230                    .listRowSeparator(.hidden)231            } header: {232                Eyebrow("Recherches récentes")233            }234        } else {235            VStack(alignment: .leading, spacing: 8) {236                Eyebrow("Syntaxe")237                Text(verbatim: "\"phrase exacte\"   -exclu   site:exemple.org   intitle:mot   lang:fr")238                    .font(.data(.footnote)).foregroundStyle(Theme.muted)239                    .fixedSize(horizontal: false, vertical: true)240                if !model.historyEnabled {241                    Text("L’historique est désactivé : aucune recherche n’est conservée.")242                        .font(.footnote).foregroundStyle(Theme.muted)243                }244            }245            .padding(.vertical, 8)246            .listRowBackground(Color.clear)247            .listRowSeparator(.hidden)248        }249    }250251    private func row(icon: String, strong: Bool, fill: String?, label: Text, pick: @escaping () -> Void) -> some View {252        HStack(spacing: 12) {253            Button(action: pick) {254                HStack(spacing: 12) {255                    Image(systemName: icon).foregroundStyle(Theme.muted).frame(minWidth: 26).accessibilityHidden(true)256                    label257                        .font(strong ? .body.weight(.semibold) : .body)258                        .foregroundStyle(Theme.ink)259                        .lineLimit(2)260                        .frame(maxWidth: .infinity, alignment: .leading)261                }262                .contentShape(Rectangle())263            }264            .buttonStyle(.plain)265            if let fill {266                Button { onFill(fill + " ") } label: {267                    Image(systemName: "arrow.up.left").foregroundStyle(Theme.muted).frame(minWidth: 36, minHeight: 36)268                }269                .buttonStyle(.plain)270                .accessibilityLabel(Text("Reprendre « \(fill) » dans le champ"))271            }272        }273        .frame(minHeight: 36)274        .listRowBackground(Color.clear)275        .listRowSeparatorTint(Theme.rule)276    }277}278
Files main
Menu

Theme