SPB Git

Repository Public

SearchView.swift 14.3 KB 243 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Search/SearchView.swift4//  Description: Global search across messages (server full-text + semantic), with an offline fallback over downloaded conversations.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import SwiftUI1112struct SearchView: View {13    let onOpen: () -> Void14    @Environment(AppEnvironment.self) private var env15    @Environment(\.dismiss) private var dismiss16    @Environment(\.accessibilityReduceMotion) private var reduceMotion17    @State private var query = ""18    @State private var filters = SearchFilters()19    @State private var showFilters = false20    @State private var hits: [SearchHit] = []21    @State private var localHits: [Conversation] = []22    @State private var isSearching = false23    @State private var usedLocal = false24    @State private var error: String?2526    var body: some View {27        NavigationStack {28            List {29                Section {30                    filterBar.listRowInsets(EdgeInsets()).listRowBackground(Color.clear).listRowSeparator(.hidden)31                }32                if usedLocal && !localHits.isEmpty {33                    Section("Conversations téléchargées") {34                        ForEach(localHits) { c in35                            Button { open(c.id) } label: {36                                VStack(alignment: .leading, spacing: 2) { Text(c.title).foregroundStyle(Color.textPrimary); Text(Format.relative(c.sortDate)).font(.caption).foregroundStyle(Color.muted) }37                            }38                        }39                    }40                }41                ForEach(hits) { h in42                    Button { open(h.conversationId) } label: {43                        VStack(alignment: .leading, spacing: 5) {44                            HStack { Text(h.title).font(.subheadline.weight(.semibold)).foregroundStyle(Color.textPrimary).lineLimit(1); Spacer(minLength: 4); Text(Format.relative(h.createdAt)).font(.caption).foregroundStyle(Color.muted) }45                            Text(Self.snippet(h.snippet)).font(.footnote).foregroundStyle(Color.textSecondary).lineLimit(3)46                            if h.role == "user" {47                                Label("Toi", systemImage: "person").font(.caption2).foregroundStyle(Color.muted)48                            } else {49                                let who = ModelIdentity(model: env.catalog.model(h.modelId), modelId: h.modelId, provider: nil)50                                ModelChip(logo: who.logo, creatorName: who.creatorName, name: who.name, route: who.route, markSize: 12, font: .caption2.weight(.medium))51                            }52                        }53                        .contentShape(.rect)54                    }55                    .buttonStyle(.plain)56                    .accessibilityIdentifier("search.hit")57                }58            }59            .listStyle(.plain)60            .scrollContentBackground(.hidden)61            .background(Color.appBackground)62            .overlay {63                if isSearching && hits.isEmpty && localHits.isEmpty { ProgressView() }64                else if query.trimmingCharacters(in: .whitespaces).count < 2 { ContentUnavailableView { Label("Rechercher", systemImage: "magnifyingglass") } description: { Text("Cherche dans le texte de tous tes messages. La recherche comprend aussi le sens, pas seulement les mots exacts.") } }65                else if let error, hits.isEmpty, localHits.isEmpty { ContentUnavailableView { Label("Recherche indisponible", systemImage: "wifi.slash") } description: { Text(error) } }66                else if !isSearching && hits.isEmpty && localHits.isEmpty {67                    if filters.isActive {68                        ContentUnavailableView { Label("Aucun résultat avec ces filtres", systemImage: "line.3.horizontal.decrease.circle") } description: { Text("Aucun message ne correspond à « \(query) » avec les filtres actifs.") } actions: { Button("Effacer les filtres") { withAnimation(Motion.snappy(reduceMotion)) { filters = SearchFilters() } } }69                    } else { ContentUnavailableView.search(text: query) }70                }71            }72            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Messages, idées, mots-clés"))73            .navigationTitle("Recherche").navigationBarTitleDisplayMode(.inline)74            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }75            .sheet(isPresented: $showFilters) { SearchFilterSheet(filters: $filters).presentationDetents([.large]) }76            // debounce: one request after the typing pauses, cancelled when the query or a filter changes again77            .task(id: SearchKey(query: query, filters: filters)) {78                let q = query.trimmingCharacters(in: .whitespacesAndNewlines)79                guard q.count >= 2 else { hits = []; localHits = []; error = nil; return }80                try? await Task.sleep(for: .milliseconds(350))81                guard !Task.isCancelled else { return }82                await run(q)83            }84        }85    }8687    private struct SearchKey: Equatable { var query: String; var filters: SearchFilters }8889    // MARK: filters9091    /// « Filtres » then one removable chip per active filter.92    private var filterBar: some View {93        ScrollView(.horizontal, showsIndicators: false) {94            HStack(spacing: 8) {95                Button { showFilters = true } label: {96                    ChipLabel(text: filters.isActive ? String(localized: "Filtres · \(filters.activeCount)") : String(localized: "Filtres"), systemImage: "line.3.horizontal.decrease", selected: filters.isActive).frame(minHeight: 44)97                }98                .buttonStyle(PressScale())99                .accessibilityIdentifier("search.filters")100                ForEach(activeChips, id: \.title) { chip in101                    Button { env.haptics.selection(); withAnimation(Motion.snappy(reduceMotion)) { chip.clear() } } label: { ChipLabel(text: chip.title, systemImage: "xmark", selected: true).frame(minHeight: 44) }102                        .buttonStyle(PressScale())103                        .accessibilityLabel(String(localized: "Retirer le filtre \(chip.title)"))104                        .accessibilityIdentifier("search.filterChip")105                }106            }107            .padding(.horizontal, 16)108        }109    }110111    private var activeChips: [(title: String, clear: () -> Void)] {112        var out: [(String, () -> Void)] = []113        if let id = filters.modelId { out.append((env.catalog.model(id)?.displayName ?? id, { filters.modelId = nil })) }114        if let p = filters.provider { out.append((SearchFilterSheet.providerLabel(p), { filters.provider = nil })) }115        if let id = filters.projectId { out.append((env.catalog.project(id)?.name ?? String(localized: "Projet"), { filters.projectId = nil })) }116        if let d = filters.from { out.append((String(localized: "depuis le \(d.formatted(date: .abbreviated, time: .omitted))"), { filters.from = nil })) }117        if let d = filters.to { out.append((String(localized: "jusqu’au \(d.formatted(date: .abbreviated, time: .omitted))"), { filters.to = nil })) }118        if let t = filters.fileType { out.append((SearchFilterSheet.fileTypeLabel(t), { filters.fileType = nil })) }119        if filters.favoritesOnly { out.append((String(localized: "Favoris"), { filters.favoritesOnly = false })) }120        if let r = filters.role { out.append((r == "user" ? String(localized: "Mes messages") : String(localized: "Réponses"), { filters.role = nil })) }121        if !filters.semantic { out.append((String(localized: "Mots exacts"), { filters.semantic = true })) }122        return out123    }124125    private func run(_ q: String) async {126        isSearching = true; defer { isSearching = false }127        do {128            let r = try await env.api.search(q, filters: filters)129            guard !Task.isCancelled else { return }130            hits = r; localHits = []; usedLocal = false; error = nil131        } catch let e as APIError {132            guard e.kind != .cancelled, !Task.isCancelled else { return }133            hits = []; usedLocal = true134            localHits = await env.store.searchCached(q)135            error = e.kind == .network ? String(localized: "Hors ligne : recherche limitée aux conversations déjà téléchargées.") : e.message136        } catch { }137    }138139    private func open(_ id: String) { env.open(id); onOpen(); dismiss() }140141    /// The server marks matches with <b>…</b> (PostgreSQL ts_headline): shown in bold.142    static func snippet(_ s: String) -> AttributedString {143        var out = AttributedString()144        var rest = Substring(s.replacingOccurrences(of: "\n", with: " "))145        while let open = rest.range(of: "<b>") {146            out.append(AttributedString(String(rest[..<open.lowerBound])))147            let after = rest[open.upperBound...]148            guard let close = after.range(of: "</b>") else { rest = after; break }149            var bold = AttributedString(String(after[..<close.lowerBound])); bold.inlinePresentationIntent = .stronglyEmphasized; bold.foregroundColor = .accentColor150            out.append(bold)151            rest = after[close.upperBound...]152        }153        out.append(AttributedString(String(rest)))154        return out155    }156}157158/// Every filter of the message search (`GET /api/search`): model, route, project, dates, file type, favourites, role, semantic.159struct SearchFilterSheet: View {160    @Binding var filters: SearchFilters161    @Environment(AppEnvironment.self) private var env162    @Environment(\.dismiss) private var dismiss163    @State private var pickModel = false164165    var body: some View {166        NavigationStack {167            Form {168                Section {169                    Button { pickModel = true } label: {170                        HStack {171                            Text("Modèle").foregroundStyle(Color.textPrimary)172                            Spacer(minLength: 12)173                            if let id = filters.modelId { ModelChip(model: env.catalog.model(id), fallback: id) } else { Text("Tous").foregroundStyle(Color.muted) }174                            Image(systemName: "chevron.right").font(.caption2.weight(.bold)).foregroundStyle(Color.muted)175                        }176                        .contentShape(.rect)177                    }178                    .buttonStyle(.plain)179                    .accessibilityIdentifier("search.filter.model")180                    if filters.modelId != nil { Button("Tous les modèles") { filters.modelId = nil } }181                    Picker("Route d’exécution", selection: $filters.provider) {182                        Text("Toutes").tag(String?.none)183                        ForEach(["anthropic", "openai", "xai", "local", "openrouter"], id: \.self) { p in Text(Self.providerLabel(p)).tag(String?.some(p)) }184                    }185                    Picker("Auteur", selection: $filters.role) {186                        Text("Tous les messages").tag(String?.none); Text("Mes messages").tag(String?.some("user")); Text("Réponses des modèles").tag(String?.some("assistant"))187                    }188                } header: { Text("Qui") } footer: { Text("La route est l’API qui a exécuté la réponse : celle du créateur du modèle, ou OpenRouter.") }189190                Section("Où") {191                    Picker("Projet", selection: $filters.projectId) {192                        Text("Tous").tag(String?.none)193                        ForEach(env.catalog.projects) { p in Text(p.name).tag(String?.some(p.id)) }194                    }195                    Toggle("Conversations favorites seulement", isOn: $filters.favoritesOnly)196                    Picker("Conversations avec fichier", selection: $filters.fileType) {197                        Text("Peu importe").tag(String?.none)198                        ForEach(["any", "image", "pdf", "document"], id: \.self) { t in Text(Self.fileTypeLabel(t)).tag(String?.some(t)) }199                    }200                }201202                Section("Quand") {203                    dateRow(String(localized: "Depuis le"), $filters.from, startOfDay: true)204                    dateRow(String(localized: "Jusqu’au"), $filters.to, startOfDay: false)205                }206207                Section {208                    Toggle("Recherche par le sens", isOn: $filters.semantic)209                } footer: { Text("Désactivée, la recherche ne retient que les messages contenant les mots tapés.") }210            }211            .navigationTitle("Filtres").navigationBarTitleDisplayMode(.inline)212            .toolbar {213                ToolbarItem(placement: .cancellationAction) { Button("Effacer") { filters = SearchFilters() }.disabled(!filters.isActive) }214                ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() }.fontWeight(.semibold).accessibilityIdentifier("search.filters.done") }215            }216            .sheet(isPresented: $pickModel) {217                ModelSheet(purpose: .pick(title: String(localized: "Filtrer par modèle"), current: filters.modelId) { m in filters.modelId = m.id }).presentationDetents([.large])218            }219        }220    }221222    private func dateRow(_ title: String, _ value: Binding<Date?>, startOfDay: Bool) -> some View {223        let calendar = Calendar.current224        func normalise(_ d: Date) -> Date {225            let start = calendar.startOfDay(for: d)226            return startOfDay ? start : (calendar.date(byAdding: DateComponents(day: 1, second: -1), to: start) ?? d)227        }228        return Group {229            Toggle(title, isOn: Binding(get: { value.wrappedValue != nil }, set: { on in value.wrappedValue = on ? normalise(Date()) : nil }))230            if let d = value.wrappedValue {231                DatePicker(title, selection: Binding(get: { d }, set: { value.wrappedValue = normalise($0) }), in: ...Date(), displayedComponents: .date).labelsHidden()232                    .frame(maxWidth: .infinity, alignment: .trailing)233                    .accessibilityLabel(title)234            }235        }236    }237238    static func providerLabel(_ p: String) -> String { p == "openrouter" ? "OpenRouter" : p == "local" ? AIModel.providerLabel(p) : String(localized: "\(AIModel.providerLabel(p)) · direct") }239    static func fileTypeLabel(_ t: String) -> String {240        switch t { case "image": String(localized: "Images"); case "pdf": String(localized: "PDF"); case "document": String(localized: "Documents"); default: String(localized: "Tout fichier") }241    }242}243
Files main
Menu

Theme