Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Search/SearchScreen.swift3// Description: Advanced search: the local full-text index (instant, offline) merged with the server's search, with filters (space, tag, period, favourites, archives). Ranking by meaning is an explicit switch because it costs one paid model call per search on the server.4import SwiftUI5import SPNotesCore6import SPNotesStore7import SPNotesSync8import SPNotesDesign910@Observable final class SearchModel {11 var query = ""12 var filters = SearchFilters()13 private(set) var results: [UnifiedSearchResult] = []14 private(set) var usedServer = false15 private(set) var serverNote: String?16 private(set) var isSearching = false17 @ObservationIgnored private var task: Task<Void, Never>?1819 /// The scope a search runs with: local only without a reachable session, free server search otherwise, hybrid only on demand.20 static func scope(signedIn: Bool, reachable: Bool, semantic: Bool) -> SearchScope { !signedIn || !reachable ? .localOnly : semantic ? .hybrid : .serverLexical }2122 /// Typing searches this Mac only (no request). The server is asked on Return.23 func typed(env: AppEnvironment) {24 task?.cancel()25 let q = query, f = filters26 task = Task { [weak self] in27 try? await Task.sleep(for: .milliseconds(120)); guard !Task.isCancelled else { return }28 let local = q.trimmingCharacters(in: .whitespaces).isEmpty ? [] : ((try? await env.repositories.search.local(q, filters: f, limit: 60)) ?? [])29 guard let self, !Task.isCancelled, q == self.query else { return }30 self.results = local; self.usedServer = false; self.serverNote = nil31 }32 }33 func submit(env: AppEnvironment) async {34 task?.cancel()35 let q = query.trimmingCharacters(in: .whitespaces); guard !q.isEmpty else { results = []; return }36 isSearching = true; defer { isSearching = false }37 let scope = Self.scope(signedIn: env.account.isSignedIn, reachable: env.connectivity.reachable, semantic: env.preferences.semanticSearch)38 guard let outcome = try? await env.repositories.search.search(q, scope: scope, filters: filters, limit: 60) else { return }39 guard q == query.trimmingCharacters(in: .whitespaces) else { return }40 results = outcome.results; usedServer = outcome.usedServer41 serverNote = scope == .localOnly ? (env.account.isSignedIn ? "Hors ligne : résultats de ce Mac seulement." : "Sans compte : résultats de ce Mac seulement.") : outcome.serverError != nil ? "Le serveur n'a pas répondu : résultats de ce Mac seulement." : nil42 }43}4445struct SearchScreen: View {46 @Environment(AppEnvironment.self) private var env47 let router: FeatureRouting48 @State private var model = SearchModel()49 @FocusState private var focused: Bool5051 var body: some View {52 @Bindable var p = env.preferences53 VStack(spacing: 0) {54 VStack(alignment: .leading, spacing: NVSpace.md) {55 PanelHeader(title: "Recherche", subtitle: subtitle)56 HStack(spacing: NVSpace.sm) {57 Image(systemName: "magnifyingglass").foregroundStyle(NVColor.fgMuted)58 TextField("Chercher dans toutes les notes…", text: $model.query).textFieldStyle(.plain).nvFont(.body).focused($focused).onSubmit { Task { await model.submit(env: env) } }.accessibilityIdentifier("search-screen-field")59 if model.isSearching { ProgressView().controlSize(.small) }60 Button("Chercher") { Task { await model.submit(env: env) } }.buttonStyle(.borderedProminent).controlSize(.small).disabled(model.query.trimmingCharacters(in: .whitespaces).isEmpty)61 }.fieldSurface(focused: focused)62 HStack(spacing: NVSpace.md) {63 Picker("Espace", selection: $model.filters.section) { Text("Tous les espaces").tag(String?.none); ForEach(LibraryModel.sections, id: \.id) { Text($0.label).tag(String?.some($0.id)) } }.labelsHidden().fixedSize()64 Menu(model.filters.tags.isEmpty ? "Tags" : model.filters.tags.map { "#" + $0 }.joined(separator: " ")) {65 ForEach(env.library.tags) { t in Toggle(t.name, isOn: Binding(get: { model.filters.tags.contains(t.name) }, set: { on in if on { model.filters.tags.append(t.name) } else { model.filters.tags.removeAll { $0 == t.name } } })) }66 }.fixedSize()67 Toggle("Favoris", isOn: $model.filters.favoritesOnly).toggleStyle(.button)68 Toggle("Archives", isOn: $model.filters.includeArchived).toggleStyle(.button)69 Spacer()70 Toggle(isOn: $p.semanticSearch) { Label("Recherche par le sens", systemImage: "sparkles") }.toggleStyle(.switch).controlSize(.small)71 .help("Le serveur classe aussi les résultats par proximité de sens. Chaque recherche lancée avec cette option fait un appel payant à un modèle d'embedding.").accessibilityIdentifier("semantic-toggle")72 }.controlSize(.small)73 if p.semanticSearch { Label("Recherche par le sens activée : un appel payant au modèle d'embedding du serveur à chaque « Chercher ». La saisie, elle, ne cherche que sur ce Mac.", systemImage: "dollarsign.circle").nvFont(.micro).foregroundStyle(NVColor.ai) }74 }75 .padding(.horizontal, NVSpace.xl).padding(.top, NVSpace.xl).padding(.bottom, NVSpace.md)76 Divider().overlay(NVColor.line)77 if model.results.isEmpty {78 NVEmptyState(systemImage: "magnifyingglass", title: model.query.isEmpty ? "Chercher dans toutes les notes" : "Aucun résultat", message: model.query.isEmpty ? "La saisie cherche dans l'index de ce Mac, hors ligne. Retour interroge aussi le serveur." : "Aucune note ne correspond à « \(model.query) ». Retour interroge aussi le serveur.").frame(maxHeight: .infinity)79 } else {80 ScrollView {81 LazyVStack(alignment: .leading, spacing: NVSpace.sm) {82 ForEach(Array(model.results.enumerated()), id: \.element.id) { i, r in83 Button { router.openPage(id: r.pageId, blockId: r.blockId) } label: { resultRow(r) }.buttonStyle(.plain).nvBlockReveal(index: i).accessibilityIdentifier("search-result")84 }85 }.padding(NVSpace.xl).frame(maxWidth: NVSpace.readingMeasure + NVSpace.huge).frame(maxWidth: .infinity)86 }87 }88 }89 .background(NVColor.bg)90 .onChange(of: model.query) { _, _ in model.typed(env: env) }91 .onChange(of: model.filters) { _, _ in model.typed(env: env) }92 .onAppear { focused = !env.options.noActivate }93 .accessibilityIdentifier("search-screen")94 }95 private var subtitle: String {96 if let note = model.serverNote { return note }97 if model.results.isEmpty { return "Index local et serveur" }98 return "\(model.results.count) résultat\(model.results.count > 1 ? "s" : "")" + (model.usedServer ? " · ce Mac et le serveur" : " · ce Mac (Retour pour interroger le serveur)")99 }100 private func resultRow(_ r: UnifiedSearchResult) -> some View {101 VStack(alignment: .leading, spacing: NVSpace.xs) {102 HStack(spacing: NVSpace.sm) {103 if let icon = r.icon, !icon.isEmpty { Text(icon) }104 Text(Format.title(r.title)).font(NVFont.font(.h3, size: NVFont.Style.body.size())).lineLimit(1)105 Spacer()106 NVChip(r.origin == .local ? "ce Mac" : r.origin == .server ? "serveur" : "les deux", tone: r.origin == .local ? .neutral : .accent)107 }108 if let h = r.heading, !h.isEmpty { Text(h).nvFont(.micro).foregroundStyle(NVColor.accent) }109 if !r.snippet.isEmpty { HighlightedText(marked: r.snippet.replacingOccurrences(of: "\n", with: " ")).nvFont(.ui).foregroundStyle(NVColor.fgMuted).lineLimit(3).frame(maxWidth: .infinity, alignment: .leading) }110 }111 .padding(NVSpace.md).nvCard(radius: NVRadius.md).contentShape(Rectangle())112 }113}114