SPB Git

Repository Public

SidebarView.swift 17.8 KB 294 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Components/SidebarView.swift3// Description: Window sidebar: search (titles + message text, offline fallback), conversation history grouped by date, library sections, connection state.4import SwiftUI5import SPChatCore67struct SidebarView: View {8    @Bindable var window: WindowModel9    @Environment(AppEnvironment.self) private var env10    @State private var search = SearchModel()11    @State private var renaming: Conversation?12    @State private var renameText = ""13    @State private var deleting: Conversation?14    @FocusState private var searchFocused: Bool15    @State private var showFilters = false1617    private var selection: Binding<String?> {18        Binding(get: { switch window.destination { case .chat(let id): id; case .library(let s): "lib:" + s.rawValue } },19                set: { v in20                    guard let v else { return }21                    if v.hasPrefix("lib:"), let s = LibrarySection(rawValue: String(v.dropFirst(4))) { window.destination = .library(s) } else { window.open(v) }22                })23    }2425    var body: some View {26        @Bindable var store = env.conversations27        VStack(spacing: 0) {28            HStack(spacing: 6) {29                Image(systemName: "magnifyingglass").foregroundStyle(.secondary)30                TextField("Rechercher", text: $window.searchText).textFieldStyle(.plain).focused($searchFocused).accessibilityIdentifier("sidebar-search")31                    .onSubmit { if let first = search.hits.first { open(first) } }32                if !window.searchText.isEmpty { IconButton(systemImage: "xmark.circle.fill", label: "Effacer la recherche") { window.searchText = "" }.foregroundStyle(.secondary) }33                Button { showFilters.toggle() } label: {34                    Image(systemName: search.filters.isDefault ? "line.3.horizontal.decrease" : "line.3.horizontal.decrease.circle.fill").font(.system(size: 12.5))35                        .foregroundStyle(search.filters.isDefault ? DS.C.muted : DS.C.accent).frame(width: 20, height: 20).contentShape(Rectangle())36                }37                .buttonStyle(.plain).help("Filtres de recherche avancée").accessibilityLabel("Filtres de recherche" + (search.filters.isDefault ? "" : " (\(search.filters.activeCount) actifs)")).accessibilityIdentifier("search-filters")38                .popover(isPresented: $showFilters, arrowEdge: .bottom) { SearchFiltersPopover(search: search) { search.update(query: window.searchText, env: env) } }39            }40            .padding(.horizontal, 8).padding(.vertical, 6)41            .background(DS.C.surface2.opacity(0.7), in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))42            .overlay(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).strokeBorder(searchFocused ? DS.C.accent.opacity(0.6) : DS.C.border, lineWidth: 1))43            .padding(.horizontal, 10).padding(.bottom, 8)4445            List(selection: selection) {46                if window.searchText.trimmingCharacters(in: .whitespaces).count >= 2 { searchResults } else { history(store) }47            }48            .listStyle(.sidebar)49            .accessibilityIdentifier("sidebar-list")5051            footer52        }53        .onChange(of: window.searchFocus) { searchFocused = true }54        .onChange(of: window.searchText) { _, q in search.update(query: q, env: env) }55        .task { await env.conversations.refresh() }56        .alert("Renommer la conversation", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {57            TextField("Titre", text: $renameText)58            Button("Renommer") { if let c = renaming { perform { try await env.conversations.update(c.id, ConversationPatch(title: renameText.trimmingCharacters(in: .whitespaces))) } } }59            Button("Annuler", role: .cancel) {}60        }61        .confirmationDialog("Supprimer « \(deleting?.title ?? "") » ?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {62            Button("Supprimer définitivement", role: .destructive) {63                if let c = deleting {64                    perform { try await env.conversations.delete(c.id); env.forget(conversationId: c.id) }65                    if window.currentConversationId == c.id { window.newConversation() }66                }67            }68        } message: { Text("Les messages, fichiers et vecteurs de cette conversation seront effacés du serveur. Cette action est irréversible.") }69    }7071    private func perform(_ work: @escaping () async throws -> Void) { Task { do { try await work() } catch { env.toasts.error(error) } } }7273    // MARK: History7475    @ViewBuilder private func history(_ store: ConversationStore) -> some View {76        Section {77            ForEach(LibrarySection.allCases) { s in Label(s.title, systemImage: s.systemImage).tag("lib:" + s.rawValue) }78        } header: { Text("Espace de travail") }79        .collapsible(true)8081        let sections = store.sections()82        if sections.isEmpty {83            Section { Text(store.isLoading ? "Chargement…" : store.filter == .all ? "Aucune conversation pour l'instant." : "Aucune conversation dans ce filtre.").font(.callout).foregroundStyle(.secondary) }84        }85        ForEach(sections) { section in86            Section(section.title) {87                ForEach(section.items) { c in row(c).tag(c.id) }88            }89        }90    }9192    private func row(_ c: Conversation) -> some View {93        HStack(spacing: 6) {94            VStack(alignment: .leading, spacing: 1) {95                Text(c.title).lineLimit(1)96                HStack(spacing: 4) {97                    if let id = c.modelId { ModelMark(env.catalog.identity(for: id), size: 10).opacity(0.75) }98                    if let p = c.projectName { Text(p).foregroundStyle(Palette.hex(c.projectColor) ?? .secondary) }99                    Text(Format.relative(c.sortDate)).foregroundStyle(.tertiary)100                }101                .font(.caption2)102            }103            Spacer(minLength: 2)104            if c.streaming || env.streamingConversationIds.contains(c.id) { StreamingDot().accessibilityLabel("Réponse en cours") }105            if c.parentId != nil { Image(systemName: "arrow.triangle.branch").font(.caption2).foregroundStyle(.secondary).help(c.branchLabel.map { "Branche « \($0) »" } ?? "Branche").accessibilityLabel("Branche") }106            if c.hasDraft { Image(systemName: "pencil.line").font(.caption2).foregroundStyle(.secondary).accessibilityLabel("Brouillon") }107            if c.favorite { Image(systemName: "star.fill").font(.caption2).foregroundStyle(DS.C.accent).accessibilityLabel("Favori") }108            if c.pinned { Image(systemName: "pin.fill").font(.caption2).foregroundStyle(.secondary).accessibilityLabel("Épinglée") }109        }110        .contextMenu {111            Button("Ouvrir dans une nouvelle fenêtre") { NewWindowOpener.shared.open?(c.id) }112            Divider()113            Button("Renommer…") { renameText = c.title; renaming = c }114            Button(c.pinned ? "Désépingler" : "Épingler") { perform { try await env.conversations.update(c.id, ConversationPatch(pinned: !c.pinned)) } }115            Button(c.favorite ? "Retirer des favoris" : "Ajouter aux favoris") { perform { try await env.conversations.update(c.id, ConversationPatch(favorite: !c.favorite)) } }116            Menu("Déplacer vers un projet") {117                Button("Aucun projet") { perform { try await env.conversations.update(c.id, ConversationPatch(projectId: .some(nil))); await env.conversations.refresh() } }118                ForEach(env.catalog.projects) { p in Button(p.name) { perform { try await env.conversations.update(c.id, ConversationPatch(projectId: .some(p.id))); await env.conversations.refresh() } } }119            }120            Button(c.isArchived ? "Désarchiver" : "Archiver") { perform { try await env.conversations.update(c.id, ConversationPatch(archived: !c.isArchived)) } }121            Divider()122            Button("Supprimer…", role: .destructive) { deleting = c }123        }124        .accessibilityElement(children: .combine).accessibilityIdentifier("conversation-row")125    }126127    // MARK: Search128129    @ViewBuilder private var searchResults: some View {130        if search.isSearching && search.hits.isEmpty { Section { HStack { ProgressView().controlSize(.small); Text("Recherche…").foregroundStyle(.secondary) } } }131        else if search.hits.isEmpty { Section { Text("Aucun résultat pour « \(window.searchText) ».").foregroundStyle(.secondary).font(.callout) } }132        if search.offline { Section { Label("Hors ligne : recherche dans le cache local", systemImage: "wifi.slash").font(.caption).foregroundStyle(.secondary) } }133        let titles = search.hits.filter { $0.role == "title" }, messages = search.hits.filter { $0.role != "title" }134        if !titles.isEmpty { Section("Conversations") { ForEach(titles) { h in Button { open(h) } label: { Text(h.title).lineLimit(1) }.buttonStyle(.plain) } } }135        if !messages.isEmpty {136            Section("Messages") {137                ForEach(messages) { h in138                    Button { open(h) } label: {139                        VStack(alignment: .leading, spacing: 2) {140                            HStack(spacing: 5) {141                                if let id = h.modelId { ModelMark(env.catalog.identity(for: id), size: 11) }142                                Text(h.title).font(.caption.weight(.semibold)).lineLimit(1)143                            }144                            h.snippetSegments.reduce(Text("")) { acc, seg in Text("\(acc)\(seg.highlighted ? Text(seg.text).bold().foregroundStyle(Palette.iris) : Text(seg.text))") }145                                .font(.caption).foregroundStyle(.secondary).lineLimit(3)146                        }147                        .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())148                    }149                    .buttonStyle(.plain).accessibilityIdentifier("search-hit")150                }151            }152        }153    }154155    private func open(_ hit: SearchHit) {156        window.open(hit.conversationId)157        if hit.role != "title" { env.open(conversationId: hit.conversationId, messageId: hit.id) }158    }159160    // MARK: Footer161162    private var footer: some View {163        @Bindable var store = env.conversations164        return VStack(spacing: 6) {165            Divider()166            if !env.connectivity.isOnline || store.isStale {167                Label(env.connectivity.isOnline ? "Serveur injoignable — cache local" : "Hors ligne — cache local", systemImage: "wifi.slash")168                    .font(.caption).foregroundStyle(Palette.warning).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 12)169                    .accessibilityIdentifier("offline-indicator")170            }171            HStack {172                Picker("Filtre", selection: $store.filter) { ForEach(ConversationFilter.allCases, id: \.self) { Text($0.label).tag($0) } }173                    .labelsHidden().pickerStyle(.menu).fixedSize().controlSize(.small).accessibilityLabel("Filtrer les conversations")174                Spacer()175                IconButton(systemImage: "arrow.clockwise", label: "Actualiser la liste") { Task { await env.conversations.refresh() } }176            }177            .padding(.horizontal, 10).padding(.bottom, 8)178        }179    }180}181182/// Lets non-view code open a conversation in a new window (set by the app scene).183final class NewWindowOpener { static let shared = NewWindowOpener(); var open: ((String) -> Void)? }184185/// Debounced search: server full-text + semantic search, local cache when offline.186@Observable final class SearchModel {187    private(set) var hits: [SearchHit] = []188    private(set) var isSearching = false189    private(set) var offline = false190    /// Advanced search filters, applied by the server (`GET /api/search`).191    var filters = SearchFilters()192    @ObservationIgnored private var task: Task<Void, Never>?193194    func update(query: String, env: AppEnvironment) {195        task?.cancel()196        let q = query.trimmingCharacters(in: .whitespaces)197        guard q.count >= 2 else { hits = []; isSearching = false; return }198        isSearching = true199        task = Task {200            try? await Task.sleep(for: .milliseconds(280))201            guard !Task.isCancelled else { return }202            do {203                async let titles = env.api.conversations(filter: .all, query: q, limit: 20)204                var f = filters; f.semantic = f.semantic && env.preferences.semanticSearch205                async let messages = env.api.search(q, filters: f)206                let (t, m) = try await (titles, messages)207                guard !Task.isCancelled else { return }208                // title matches are not narrowed by message-level filters: they are listed only for an unfiltered search209                hits = (filters.isDefault ? t.map { SearchHit(id: "title:" + $0.id, conversationId: $0.id, role: "title", title: $0.title, snippet: $0.title, createdAt: $0.sortDate) } : []) + m210                offline = false211            } catch {212                guard !Task.isCancelled else { return }213                hits = (try? await env.cache?.search(q)) ?? []; offline = true214            }215            isSearching = false216        }217    }218}219220/// Small iris dot that breathes while a conversation generates (no spinner).221struct StreamingDot: View {222    @Environment(\.accessibilityReduceMotion) private var reduceMotion223    @State private var dim = false224    var body: some View {225        Circle().fill(DS.C.accent).frame(width: 6, height: 6).opacity(dim ? 0.35 : 1)226            .onAppear { if !reduceMotion { withAnimation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true)) { dim = true } } }227    }228}229230/// Advanced search: model, provider, dates, project, role, file type, favourites, semantic toggle — all applied by the server.231struct SearchFiltersPopover: View {232    @Bindable var search: SearchModel233    let apply: () -> Void234    @Environment(AppEnvironment.self) private var env235    @State private var useFrom = false236    @State private var useTo = false237238    var body: some View {239        VStack(alignment: .leading, spacing: 11) {240            HStack { Text("Recherche avancée").font(DS.F.heading); Spacer(); if !search.filters.isDefault { Button("Réinitialiser") { let s = search.filters.semantic; search.filters = SearchFilters(semantic: s); useFrom = false; useTo = false }.buttonStyle(.link).font(DS.F.caption) } }241            Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 9) {242                GridRow {243                    Text("Modèle").foregroundStyle(DS.C.text2)244                    Picker("Modèle", selection: $search.filters.modelId) {245                        Text("Tous").tag(String?.none)246                        ForEach(env.catalog.menuModels) { m in Text(m.isOpenRouter ? "\(m.shortName) · OpenRouter" : m.shortName).tag(String?.some(m.id)) }247                    }.labelsHidden().frame(maxWidth: 220)248                }249                GridRow {250                    Text("Fournisseur").foregroundStyle(DS.C.text2)251                    Picker("Fournisseur", selection: $search.filters.provider) {252                        Text("Tous").tag(String?.none)253                        ForEach(Provider.known, id: \.self) { Text(Provider.label($0)).tag(String?.some($0)) }254                    }.labelsHidden().fixedSize()255                }256                GridRow {257                    Text("Projet").foregroundStyle(DS.C.text2)258                    Picker("Projet", selection: $search.filters.projectId) {259                        Text("Tous").tag(String?.none)260                        ForEach(env.catalog.projects) { Text($0.name).tag(String?.some($0.id)) }261                    }.labelsHidden().frame(maxWidth: 220)262                }263                GridRow {264                    Text("Auteur").foregroundStyle(DS.C.text2)265                    Picker("Auteur", selection: $search.filters.role) { Text("Tous").tag(String?.none); Text("Mes messages").tag(String?.some("user")); Text("Réponses").tag(String?.some("assistant")) }.pickerStyle(.segmented).labelsHidden().fixedSize()266                }267                GridRow {268                    Text("Fichiers").foregroundStyle(DS.C.text2)269                    Picker("Fichiers", selection: $search.filters.fileType) {270                        Text("Indifférent").tag(SearchFilters.FileType?.none)271                        ForEach(SearchFilters.FileType.allCases, id: \.self) { Text($0.label).tag(SearchFilters.FileType?.some($0)) }272                    }.labelsHidden().fixedSize()273                }274                GridRow {275                    Toggle("Depuis", isOn: $useFrom).toggleStyle(.checkbox).foregroundStyle(DS.C.text2)276                    DatePicker("Depuis", selection: Binding(get: { search.filters.from ?? Calendar.current.date(byAdding: .month, value: -1, to: Date())! }, set: { search.filters.from = $0 }), displayedComponents: .date).labelsHidden().disabled(!useFrom)277                }278                GridRow {279                    Toggle("Jusqu'au", isOn: $useTo).toggleStyle(.checkbox).foregroundStyle(DS.C.text2)280                    DatePicker("Jusqu'au", selection: Binding(get: { search.filters.to ?? Date() }, set: { search.filters.to = $0 }), displayedComponents: .date).labelsHidden().disabled(!useTo)281                }282            }283            .font(DS.F.uiRegular)284            Toggle("Conversations favorites seulement", isOn: $search.filters.favoritesOnly).toggleStyle(.checkbox).font(DS.F.uiRegular)285            Toggle("Recherche sémantique (en plus du plein texte)", isOn: $search.filters.semantic).toggleStyle(.checkbox).font(DS.F.uiRegular)286        }287        .padding(16).frame(width: 360)288        .onAppear { useFrom = search.filters.from != nil; useTo = search.filters.to != nil }289        .onChange(of: useFrom) { _, on in search.filters.from = on ? (search.filters.from ?? Calendar.current.date(byAdding: .month, value: -1, to: Date())) : nil }290        .onChange(of: useTo) { _, on in search.filters.to = on ? (search.filters.to ?? Date()) : nil }291        .onChange(of: search.filters) { apply() }292    }293}294
Files main
Menu

Theme