SPB Git

Repository Public

SearchResultsView.swift 8.5 KB 128 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Next/SearchResultsView.swift3// Description: Search 2.0: the toolbar field asks the server, which looks in names and in the text of documents (PDF, Office, images through OCR) and answers with highlighted passages; a "by meaning" mode when the server has its on-device model. Scores are never shown. Offline, or on a 1.0 server, the browser's local name search takes over.4import SPDriveCore5import SPDriveNext6import SwiftUI78struct SearchResultsView: View {9    let model: AppModel10    let nav: Navigator11    @State private var results: Loadable<SearchResults> = .loading12    @State private var semantic: Loadable<SemanticResults> = .loading13    @State private var asked = ""1415    var body: some View {16        @Bindable var nav = nav17        VStack(spacing: 0) {18            HStack(spacing: SPDTheme.Space.md) {19                Picker("Chercher dans", selection: $nav.searchScope) { Text("Noms et contenu").tag(SearchScope.all); Text("Noms").tag(SearchScope.name); Text("Contenu").tag(SearchScope.content) }20                    .pickerStyle(.segmented).fixedSize().disabled(nav.searchSemantic).labelsHidden()21                if model.has(.semantic) {22                    Toggle(isOn: $nav.searchSemantic) { Label("Par le sens", systemImage: "sparkle.magnifyingglass") }.toggleStyle(.button)23                        .help("Rapproche votre phrase des passages qui veulent dire la même chose, même sans les mêmes mots. Calculé sur le serveur, sans service externe.")24                }25                Spacer()26                Text(summary).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)27            }28            .padding(.horizontal, SPDTheme.Space.md).frame(height: 36).background(.bar)29            .overlay(alignment: .bottom) { Rectangle().fill(SPDTheme.hairline).frame(height: 1) }30            content.frame(maxWidth: .infinity, maxHeight: .infinity).background(SPDTheme.canvas)31        }32        .task(id: "\(nav.searchText)|\(nav.searchScope.rawValue)|\(nav.searchSemantic)") { await run() }33        .accessibilityIdentifier("search-results")34    }35    private var summary: String {36        if nav.searchSemantic { return semantic.value.map { "\($0.hits.count) passage\($0.hits.count > 1 ? "s" : "") proche\($0.hits.count > 1 ? "s" : ""), du plus au moins proche" } ?? "" }37        guard let r = results.value else { return "" }38        let n = r.files.count + r.folders.count, inContent = r.files.filter { $0.match?.where != "name" }.count39        return "\(n) résultat\(n > 1 ? "s" : "")" + (inContent > 0 ? " · \(inContent) dans le contenu" : "")40    }41    @ViewBuilder private var content: some View {42        if nav.searchSemantic {43            switch semantic {44            case .loading: ProgressView()45            case .failed(let m): SPDEmptyState(symbol: "wifi.slash", title: "Recherche indisponible", message: m) { Button("Réessayer") { Task { await run() } } }46            case .ready(let r):47                if !r.available { SPDEmptyState(symbol: "sparkle.magnifyingglass", title: "Recherche par le sens indisponible", message: "Le modèle du serveur ne répond pas en ce moment. La recherche par mots fonctionne.") { Button("Chercher par mots") { nav.searchSemantic = false } } }48                else if r.hits.isEmpty { SPDEmptyState(symbol: "sparkle.magnifyingglass", title: "Aucun passage proche", message: "Aucun document indexé ne contient de passage proche de cette phrase.") }49                else {50                    List(selection: selection) {51                        ForEach(r.hits) { h in52                            VStack(alignment: .leading, spacing: 3) {53                                NextFileRow(model: model, file: h.file) { if let p = h.passage.page { SPDPill(text: "p. \(p)") } }54                                Text(h.passage.text).font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary).lineLimit(3).padding(.leading, 32)55                            }56                            .padding(.vertical, 3).tag(h.file.id).contextMenu { menu(h.file) }57                        }58                    }59                    .listStyle(.inset).contextMenu(forSelectionType: String.self) { _ in } primaryAction: { ids in open(ids) }60                }61            }62        } else {63            switch results {64            case .loading: ProgressView()65            case .failed(let m): SPDEmptyState(symbol: "wifi.slash", title: "Recherche indisponible", message: m) { Button("Réessayer") { Task { await run() } } }66            case .ready(let r):67                if r.files.isEmpty && r.folders.isEmpty {68                    SPDEmptyState(symbol: "magnifyingglass", title: "Aucun résultat", message: "Ni un nom ni le contenu d’un document ne correspond à « \(asked) ». Essayez d’autres mots" + (model.has(.semantic) ? ", ou la recherche par le sens." : ".")) {69                        if model.has(.semantic) { Button("Chercher par le sens") { nav.searchSemantic = true }.buttonStyle(.borderedProminent) }70                        Button("Effacer la recherche") { nav.searchText = "" }71                    }72                } else {73                    List(selection: selection) {74                        if !r.folders.isEmpty {75                            Section("Dossiers") {76                                ForEach(r.folders) { f in77                                    Label(f.name, systemImage: "folder").tag(f.id)78                                        .contextMenu { Button("Ouvrir", systemImage: "folder") { nav.searchText = ""; nav.go(to: f.id) } }79                                }80                            }81                        }82                        Section("Fichiers") {83                            ForEach(r.files) { f in84                                VStack(alignment: .leading, spacing: 3) {85                                    NextFileRow(model: model, file: f) {86                                        HStack(spacing: 4) {87                                            if let p = f.match?.page { SPDPill(text: "p. \(p)") }88                                            if f.match?.where == "content" { SPDPill(text: "Dans le contenu", symbol: "text.magnifyingglass", tint: SPDTheme.brand) }89                                            else if f.match?.where == "both" { SPDPill(text: "Nom et contenu", symbol: "text.magnifyingglass", tint: SPDTheme.brand) }90                                        }91                                    }92                                    if let m = f.match, m.snippet != nil { SnippetText(match: m).padding(.leading, 32) }93                                }94                                .padding(.vertical, 3).tag(f.id).contextMenu { menu(f) }95                            }96                        }97                    }98                    .listStyle(.inset).contextMenu(forSelectionType: String.self) { _ in } primaryAction: { ids in open(ids) }99                }100            }101        }102    }103    private var selection: Binding<Set<String>> { Binding(get: { nav.selection }, set: { nav.selection = $0 }) }104    @ViewBuilder private func menu(_ f: NextFile) -> some View {105        Button("Afficher dans son dossier", systemImage: "folder") { model.show(f, in: nav) }106        Button("Ouvrir", systemImage: "arrow.up.forward.app") { Task { await model.open(f.item(model)) } }107        if model.has(.ai) { Button("Demander à ce document…", systemImage: "sparkles") { nav.sheet = .ask(f.item(model)) } }108        Button("Télécharger", systemImage: "arrow.down.circle") { Task { await model.download([f.item(model)]) } }109    }110    private func open(_ ids: Set<String>) {111        guard let id = ids.first else { return }112        if let f = results.value?.files.first(where: { $0.id == id }) ?? semantic.value?.hits.first(where: { $0.file.id == id })?.file { model.show(f, in: nav) }113        else if results.value?.folders.contains(where: { $0.id == id }) == true { nav.searchText = ""; nav.go(to: id) }114    }115    private func run() async {116        let q = nav.searchText.trimmingCharacters(in: .whitespacesAndNewlines)117        guard !q.isEmpty, let next = model.next else { return }118        try? await Task.sleep(nanoseconds: 280_000_000) // let the person finish the word119        if Task.isCancelled { return }120        asked = q121        if nav.searchSemantic {122            do { semantic = .ready(try await next.semanticSearch(q, limit: 20)) } catch { if !Task.isCancelled { semantic = .failed(NextText.error(error)) } }123        } else {124            do { results = .ready(try await next.search(q, in: nav.searchScope)) } catch { if !Task.isCancelled { results = .failed(NextText.error(error)) } }125        }126    }127}128
Files main
Menu

Theme