SPB Git

Repository Public

UnifiedSearchScreen.swift 12.1 KB 250 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Work/Search/UnifiedSearchScreen.swift3// Description: The unified search screen: field, the explicit (paid) semantic switch, filters (a side column on regular,4//              a horizontal strip on compact), and results with their origin, heading and highlighted snippet.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesAPI9import SPNotesDesign10import SPNotesSync11import SwiftUI1213public struct UnifiedSearchScreen: View {14    @State private var model: UnifiedSearchModel1516    public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil) {17        _model = State(initialValue: UnifiedSearchModel(repositories: repositories, router: router))18    }1920    public init(model: UnifiedSearchModel) { _model = State(initialValue: model) }2122    public var body: some View {23        FeatureScaffold(title: L("Recherche"), subtitle: L("Dans toutes vos notes, sur l'appareil et sur le serveur"), phase: model.phase) { sizeClass in24            UnifiedSearchContent(model: model, compact: sizeClass.isCompact)25        }26        .task { if model.phase == .idle { await model.load() } }27    }28}2930struct UnifiedSearchContent: View {31    @Bindable var model: UnifiedSearchModel32    let compact: Bool3334    var body: some View {35        VStack(alignment: .leading, spacing: 0) {36            VStack(alignment: .leading, spacing: NVSpace.sm) {37                field38                semanticRow39                if compact { filterStrip }40                if let status = model.statusText {41                    Text(status).nvFont(.micro).foregroundStyle(NVColor.fgMuted).accessibilityAddTraits(.updatesFrequently)42                }43                if let failure = model.serverFailure {44                    Label(failure.isOffline ? L("Serveur injoignable : résultats de l'appareil seulement.") : LF("Le serveur n'a pas répondu (%@) : résultats de l'appareil seulement.", failure.message),45                          systemImage: "wifi.slash")46                        .nvFont(.ui).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)47                }48            }49            .padding(.horizontal, compact ? NVSpace.lg : NVSpace.xl)50            .padding(.bottom, NVSpace.md)51            HStack(alignment: .top, spacing: 0) {52                if !compact {53                    filterColumn.frame(width: 232).padding(.leading, NVSpace.xl)54                }55                results56            }57        }58        .onChange(of: model.query) { _, _ in model.queryChanged() }59    }6061    private var field: some View {62        HStack(spacing: NVSpace.sm) {63            HStack(spacing: NVSpace.sm) {64                Image(systemName: "magnifyingglass").foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)65                TextField(L("Rechercher…"), text: $model.query)66                    .textFieldStyle(.plain)67                    .nvFont(.body)68                    .foregroundStyle(NVColor.fg)69                    .onSubmit { Task { await model.submit() } }70                    .accessibilityLabel(L("Texte recherché"))71                if !model.query.isEmpty {72                    Button { model.query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(NVColor.fgMuted) }73                        .buttonStyle(.plain)74                        .accessibilityLabel(L("Effacer la recherche"))75                }76            }77            .padding(.horizontal, NVSpace.md)78            .frame(minHeight: 40)79            .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.md))80            .overlay(NVRadius.shape(NVRadius.md).strokeBorder(NVColor.lineStrong, lineWidth: 1))81            FeatureButton(L("Rechercher"), kind: .primary) { Task { await model.submit() } }82                .disabled(model.trimmedQuery.isEmpty)83                .opacity(model.trimmedQuery.isEmpty ? 0.5 : 1)84        }85    }8687    private var semanticRow: some View {88        VStack(alignment: .leading, spacing: NVSpace.xxs) {89            Toggle(isOn: $model.semantic) {90                Label(L("Recherche par le sens"), systemImage: "sparkles").nvFont(.ui).foregroundStyle(NVColor.ai)91            }92            .toggleStyle(.switch)93            .fixedSize()94            if model.semantic {95                Text(L("Payant : le serveur appelle un modèle d'embeddings à chaque recherche. Lancée seulement quand vous appuyez sur « Rechercher »."))96                    .nvFont(.micro).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)97            }98        }99    }100101    // MARK: filters102103    private var filterStrip: some View {104        ScrollView(.horizontal, showsIndicators: false) {105            HStack(spacing: NVSpace.sm) {106                Menu {107                    Button(L("Toutes les sections")) { model.section = nil; model.queryChanged() }108                    ForEach(PageSection.allCases, id: \.self) { section in109                        Button(InboxModel.sectionLabel(section.rawValue)) { model.section = section; model.queryChanged() }110                    }111                } label: {112                    NVChip(model.section.map { InboxModel.sectionLabel($0.rawValue) } ?? L("Section"), systemImage: "folder", tone: .accent, isSelected: model.section != nil)113                }114                .menuStyle(.borderlessButton).fixedSize()115                Menu {116                    ForEach(UnifiedSearchModel.Period.allCases) { period in117                        Button(period.title) { model.period = period; model.queryChanged() }118                    }119                } label: {120                    NVChip(model.period == .any ? L("Date") : model.period.title, systemImage: "calendar", tone: .accent, isSelected: model.period != .any)121                }122                .menuStyle(.borderlessButton).fixedSize()123                toggleChip(L("Favoris"), "star", $model.favoritesOnly)124                toggleChip(L("Épinglées"), "pin", $model.pinnedOnly)125                toggleChip(L("Archives"), "archivebox", $model.includeArchived)126            }127        }128    }129130    private var filterColumn: some View {131        VStack(alignment: .leading, spacing: NVSpace.lg) {132            VStack(alignment: .leading, spacing: NVSpace.xs) {133                Text(L("Section")).nvFont(.micro).foregroundStyle(NVColor.fgMuted).textCase(.uppercase)134                filterOption(L("Toutes les sections"), selected: model.section == nil) { model.section = nil; model.queryChanged() }135                ForEach(PageSection.allCases, id: \.self) { section in136                    filterOption(InboxModel.sectionLabel(section.rawValue), selected: model.section == section) { model.section = section; model.queryChanged() }137                }138            }139            VStack(alignment: .leading, spacing: NVSpace.xs) {140                Text(L("Modifiée")).nvFont(.micro).foregroundStyle(NVColor.fgMuted).textCase(.uppercase)141                ForEach(UnifiedSearchModel.Period.allCases) { period in142                    filterOption(period.title, selected: model.period == period) { model.period = period; model.queryChanged() }143                }144            }145            VStack(alignment: .leading, spacing: NVSpace.sm) {146                Text(L("Limiter à")).nvFont(.micro).foregroundStyle(NVColor.fgMuted).textCase(.uppercase)147                WorkFlow(spacing: NVSpace.sm) {148                    toggleChip(L("Favoris"), "star", $model.favoritesOnly)149                    toggleChip(L("Épinglées"), "pin", $model.pinnedOnly)150                    toggleChip(L("Archives"), "archivebox", $model.includeArchived)151                }152            }153            if model.activeFilterCount > 0 {154                FeatureButton(L("Effacer les filtres"), systemImage: "xmark") { model.clearFilters() }155            }156            Spacer(minLength: 0)157        }158    }159160    private func filterOption(_ title: String, selected: Bool, action: @escaping () -> Void) -> some View {161        Button(action: action) {162            HStack(spacing: NVSpace.sm) {163                Image(systemName: selected ? "largecircle.fill.circle" : "circle").foregroundStyle(selected ? NVColor.accent : NVColor.fgMuted).accessibilityHidden(true)164                Text(title).nvFont(.ui).foregroundStyle(NVColor.fg)165                Spacer(minLength: 0)166            }167            .frame(minHeight: 28)168            .contentShape(Rectangle())169        }170        .buttonStyle(.plain)171        .accessibilityAddTraits(selected ? .isSelected : [])172    }173174    private func toggleChip(_ title: String, _ symbol: String, _ value: Binding<Bool>) -> some View {175        NVChip(title, systemImage: symbol, tone: .accent, isSelected: value.wrappedValue) {176            value.wrappedValue.toggle()177            model.queryChanged()178        }179        .accessibilityAddTraits(value.wrappedValue ? .isSelected : [])180    }181182    // MARK: results183184    @ViewBuilder185    private var results: some View {186        if model.answeredQuery.isEmpty {187            NVEmptyState(systemImage: "magnifyingglass", title: L("Cherchez dans vos notes"),188                         message: L("Les résultats de l'appareil apparaissent pendant la frappe ; ceux du serveur les complètent ensuite."))189                .frame(maxWidth: .infinity, maxHeight: .infinity)190        } else if model.results.isEmpty {191            if model.isAskingServer {192                FeatureLoadingView(L("Interrogation du serveur…"))193            } else {194                NVEmptyState(systemImage: "text.magnifyingglass", title: LF("Aucun résultat pour « %@ »", model.answeredQuery),195                             message: model.activeFilterCount > 0 ? L("Essayez sans les filtres.") : L("Essayez d'autres mots, ou la recherche par le sens."))196                    .frame(maxWidth: .infinity, maxHeight: .infinity)197            }198        } else {199            ScrollView {200                LazyVStack(spacing: NVSpace.sm) {201                    ForEach(Array(model.results.enumerated()), id: \.element.id) { index, result in202                        SearchResultRow(result: result) { model.open(result) }.nvBlockReveal(index: index)203                    }204                }205                .padding(.horizontal, compact ? NVSpace.lg : NVSpace.xl)206                .padding(.bottom, NVSpace.xl)207                .frame(maxWidth: 820, alignment: .leading)208                .frame(maxWidth: .infinity, alignment: .leading)209            }210        }211    }212}213214struct SearchResultRow: View {215    let result: UnifiedSearchResult216    let open: () -> Void217218    var body: some View {219        Button(action: open) {220            VStack(alignment: .leading, spacing: NVSpace.xs) {221                HStack(alignment: .firstTextBaseline, spacing: NVSpace.sm) {222                    if let icon = result.icon, !icon.isEmpty { Text(icon).accessibilityHidden(true) } else {223                        Image(systemName: "doc.text").foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)224                    }225                    Text(result.title.isEmpty ? L("Sans titre") : result.title).nvFont(.uiStrong).foregroundStyle(NVColor.fg).lineLimit(2).multilineTextAlignment(.leading)226                    Spacer(minLength: NVSpace.sm)227                    Label(UnifiedSearchModel.originLabel(result.origin), systemImage: UnifiedSearchModel.originSymbol(result.origin))228                        .nvFont(.micro).foregroundStyle(NVColor.fgMuted).lineLimit(1).fixedSize()229                }230                if let heading = result.heading, !heading.isEmpty {231                    Label(heading, systemImage: "text.alignleft").nvFont(.micro).foregroundStyle(NVColor.accent).lineLimit(1)232                }233                if !result.snippet.isEmpty {234                    WorkHighlightedText(snippet: result.snippet).lineLimit(3).multilineTextAlignment(.leading)235                }236                if let section = result.section {237                    Text(InboxModel.sectionLabel(section)).nvFont(.micro).foregroundStyle(NVColor.fgMuted)238                }239            }240            .padding(NVSpace.md)241            .frame(maxWidth: .infinity, alignment: .leading)242            .nvCard(radius: NVRadius.md)243            .contentShape(Rectangle())244        }245        .buttonStyle(.plain)246        .accessibilityElement(children: .combine)247        .accessibilityHint(result.blockId == nil ? L("Ouvre la page") : L("Ouvre la page au passage trouvé"))248    }249}250
Files main
Menu

Theme