SPB Git

Repository Public

SearchResultsView.swift 16.7 KB 340 lines swift

1//2//  Fabri-Ka iOS v23//  File: FabriKa/Features/Search/SearchResultsView.swift4//  Description: résultats d'une recherche — compte (« 386 produits dans 77 boutiques »), ce que le service a5//               compris d'une faute, tri, filtres actifs, sous-catégories, grille paginée ; état vide qui dit quoi6//               faire. La diversité par boutique est appliquée par le service.7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import SwiftUI1314struct SearchResultsView: View {15    @Environment(AppModel.self) private var model16    @State private var filters: SearchFilters17    @State private var state: Loadable<SearchPage> = .loading18    @State private var products: [Product] = []19    @State private var page = 120    @State private var pages = 121    @State private var loadingMore = false22    @State private var showFilters = false23    @State private var applied = false2425    init(filters: SearchFilters) { _filters = State(initialValue: filters) }2627    var body: some View {28        ScrollView {29            VStack(alignment: .leading, spacing: 0) {30                switch state {31                case .loading:32                    LoadingSign(label: "Recherche en cours")33                case .failed(let e):34                    ErrorState(error: e) { Task { await load() } }35                case .loaded(let r, let stale):36                    if stale { StaleBanner().padding(.bottom, 12) }37                    summary(r)38                    chips(r)39                    if products.isEmpty {40                        empty41                    } else {42                        ProductGrid(products: products, onEnd: { Task { await more() } }) {43                            if loadingMore { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 20) }44                            if page >= pages, products.count > 12 {45                                Text("Fin des résultats : \(Fmt.products(r.total)).")46                                    .font(.footnote).num().foregroundStyle(Theme.ink3).padding(.top, 24)47                            }48                        }49                        .padding(.top, 18)50                    }51                }52            }53            .pageColumn(920)54            .padding(.top, 6).padding(.bottom, 40)55        }56        .linen()57        .navigationTitle(filters.title)58        .navigationBarTitleDisplayMode(.inline)59        .toolbar {60            ToolbarItemGroup(placement: .topBarTrailing) {61                Menu {62                    Picker("Trier", selection: Binding(get: { filters.effectiveSort }, set: { filters.sort = $0 })) {63                        ForEach(sorts) { Text($0.label).tag($0) }64                    }65                } label: {66                    Image(systemName: "arrow.up.arrow.down")67                }68                .accessibilityLabel("Trier : \(filters.effectiveSort.label)")69                .accessibilityIdentifier("sort-menu")70                Button { showFilters = true } label: {71                    Image(systemName: filters.activeCount > 0 ? "line.3.horizontal.decrease.circle.fill" : "line.3.horizontal.decrease.circle")72                }73                .accessibilityLabel(filters.activeCount > 0 ? "Filtres, \(filters.activeCount) actifs" : "Filtres")74                .accessibilityIdentifier("open-filters")75            }76        }77        .sheet(isPresented: $showFilters) {78            FiltersSheet(filters: $filters, facets: state.value?.facets)79                .environment(model)80        }81        .task(id: filters) { await load() }82        .onAppear {83            if !applied, model.launchSheet == "filters" { applied = true; showFilters = true }84        }85    }8687    private var sorts: [SortOrder] {88        filters.trimmedQuery.isEmpty ? [.recent, .priceAsc, .priceDesc, .discount, .title] : [.relevance, .recent, .priceAsc, .priceDesc, .discount, .title]89    }9091    private func load() async {92        if state.value == nil { state = .loading }93        let f = filters94        guard let s = await Loadable.from({ try await APIClient.shared.search(f, facets: true) }) else { return }95        state = s96        if let r = s.value {97            products = r.products; page = r.page; pages = r.pages98        }99    }100101    private func more() async {102        guard !loadingMore, page < pages, state.value != nil else { return }103        loadingMore = true104        defer { loadingMore = false }105        let f = filters, next = page + 1106        guard let r = try? await APIClient.shared.search(f, page: next).value, f == filters else { return }107        let known = Set(products.map(\.uid))108        products.append(contentsOf: r.products.filter { !known.contains($0.uid) })109        page = r.page; pages = r.pages110    }111112    // --- Compte et précisions -------------------------------------------------------------------------113114    @ViewBuilder115    private func summary(_ r: SearchPage) -> some View {116        VStack(alignment: .leading, spacing: 4) {117            Text(countLine(r))118                .font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink)119                .accessibilityIdentifier("results-count")120            if let u = r.understood {121                Text("Compris : \(u).").font(.footnote).foregroundStyle(Theme.ink2)122                    .accessibilityIdentifier("results-understood")123            }124            if r.relaxed, r.total > 0 {125                Text("Aucun produit ne porte tous ces mots : voici ceux qui en portent la plupart.")126                    .font(.footnote).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)127            }128            if r.total > 0 {129                        Text("Trié par : \(filters.effectiveSort.short.lowercased())" + ((r.diversity ?? 0) > 0 ? " · \(r.diversity ?? 3) produits par boutique à la fois" : ""))130                .font(.footnote).foregroundStyle(Theme.ink3)131            }132        }133        .frame(maxWidth: .infinity, alignment: .leading)134    }135136    private func countLine(_ r: SearchPage) -> String {137        var s = Fmt.products(r.total)138        if let n = r.storesTotal, n > 0, filters.store == nil { s += " dans " + Fmt.stores(n) }139        return s140    }141142    @ViewBuilder143    private func chips(_ r: SearchPage) -> some View {144        let active = activeChips145        let subs = filters.subcategory == nil ? (r.facets?.subcategories ?? []).filter { $0.n > 0 }.prefix(14) : []146        if !active.isEmpty || !subs.isEmpty {147            ScrollView(.horizontal, showsIndicators: false) {148                HStack(spacing: 8) {149                    ForEach(active, id: \.label) { c in150                        Chip(label: c.label, selected: true, removable: true, action: c.remove)151                    }152                    ForEach(Array(subs), id: \.slug) { s in153                        Chip(label: s.label, count: s.n) {154                            filters.subcategory = s.slug; filters.subcategoryName = s.label155                            if filters.category == nil { filters.category = s.category }156                        }157                    }158                }159                .padding(.horizontal, Theme.margin)160            }161            .padding(.horizontal, -Theme.margin)162            .padding(.top, 10)163        }164    }165166    private struct ActiveChip { let label: String; let remove: () -> Void }167168    private var activeChips: [ActiveChip] {169        var out: [ActiveChip] = []170        if !filters.trimmedQuery.isEmpty, let c = filters.categoryName {171            out.append(ActiveChip(label: c) { filters.category = nil; filters.categoryName = nil; filters.subcategory = nil; filters.subcategoryName = nil })172        }173        if let s = filters.subcategoryName, filters.subcategory != nil {174            out.append(ActiveChip(label: s) { filters.subcategory = nil; filters.subcategoryName = nil })175        }176        if let r = filters.regionName, filters.region != nil { out.append(ActiveChip(label: r) { filters.region = nil; filters.regionName = nil }) }177        if let c = filters.cityName, filters.city != nil { out.append(ActiveChip(label: c) { filters.city = nil; filters.cityName = nil }) }178        if let p = filters.priceLabel { out.append(ActiveChip(label: p) { filters.priceMin = nil; filters.priceMax = nil }) }179        if filters.inStock { out.append(ActiveChip(label: "En stock") { filters.inStock = false }) }180        if filters.new || filters.daysMax != nil {181            out.append(ActiveChip(label: filters.daysMax.map { "Vus depuis \($0) jours" } ?? "Nouveautés") { filters.new = false; filters.daysMax = nil })182        }183        if filters.onSale { out.append(ActiveChip(label: "Prix réduit") { filters.onSale = false }) }184        if filters.madeInQuebec { out.append(ActiveChip(label: "Sans les revendeurs") { filters.madeInQuebec = false }) }185        return out186    }187188    private var empty: some View {189        EmptyBracket(190            title: filters.trimmedQuery.isEmpty ? "Aucun produit avec ces filtres" : "Aucun produit pour « \(filters.trimmedQuery) »",191            message: filters.activeCount > 0192                ? "Les filtres actifs écartent tout. En retirer un élargit la recherche à tout le Québec."193                : "Essayez un mot plus court ou un synonyme : la recherche tolère les fautes, pas les mots absents des catalogues.",194            actionLabel: filters.activeCount > 0 ? "Retirer les filtres" : nil,195            action: {196                var f = SearchFilters()197                f.q = filters.q; f.category = filters.category; f.categoryName = filters.categoryName; f.sort = filters.sort198                filters = f199            })200            .accessibilityIdentifier("results-empty")201    }202}203204/// Feuille des filtres : un brouillon, le compte en direct, « Voir N produits ».205struct FiltersSheet: View {206    @Binding var filters: SearchFilters207    let facets: Facets?208    @Environment(\.dismiss) private var dismiss209    @State private var draft = SearchFilters()210    @State private var live: Facets?211    @State private var count: Int?212213    private var shown: Facets? { live ?? facets }214215    var body: some View {216        NavigationStack {217            ScrollView {218                VStack(alignment: .leading, spacing: 0) {219                    section("Disponibilité") {220                        toggle("En stock seulement", "Écarte les produits épuisés et ceux dont l'état est inconnu.", $draft.inStock, count: shown?.inStock)221                        toggle("Nouveautés", "Vus pour la première fois depuis 14 jours au plus.", Binding(get: { draft.new }, set: { draft.new = $0; if !$0 { draft.daysMax = nil } }), count: shown?.new)222                        toggle("Prix réduit", "La boutique affiche un prix d'avant plausible.", $draft.onSale, count: shown?.onSale)223                    }224                    section("Origine de la boutique") {225                        toggle("Écarter les revendeurs", "Garde les fabricants, artisans et collectifs établis au Québec. Ce n'est pas une preuve de fabrication, produit par produit.", $draft.madeInQuebec, count: shown?.madeInQuebec)226                    }227                    if let b = shown?.buckets.filter({ $0.n > 0 }), !b.isEmpty {228                        section("Prix") {229                            FlowLayout(spacing: 8) {230                                ForEach(b) { bucket in231                                    let on = draft.priceMin == (bucket.min <= 0 ? nil : bucket.min) && draft.priceMax == bucket.max && (draft.priceMin != nil || draft.priceMax != nil)232                                    Chip(label: bucket.label, selected: on, count: bucket.n) {233                                        if on { draft.priceMin = nil; draft.priceMax = nil } else {234                                            draft.priceMin = bucket.min <= 0 ? nil : bucket.min; draft.priceMax = bucket.max235                                        }236                                    }237                                }238                            }239                            .padding(.top, 6)240                        }241                    }242                    if let cats = shown?.categories.filter({ $0.n > 0 }), cats.count > 1 {243                        section("Catégorie") {244                            FlowLayout(spacing: 8) {245                                ForEach(cats.prefix(21)) { c in246                                    let on = draft.category == c.key || draft.category == c.slug247                                    Chip(label: c.label, selected: on, count: c.n) {248                                        draft.subcategory = nil; draft.subcategoryName = nil249                                        if on { draft.category = nil; draft.categoryName = nil } else { draft.category = c.key; draft.categoryName = c.label }250                                    }251                                }252                            }253                            .padding(.top, 6)254                        }255                    }256                    if let regions = shown?.regions.filter({ $0.n > 0 }), !regions.isEmpty {257                        section("Région de la boutique") {258                            FlowLayout(spacing: 8) {259                                ForEach(regions) { r in260                                    let on = draft.region == r.slug261                                    Chip(label: r.label, selected: on, count: r.n) {262                                        draft.city = nil; draft.cityName = nil263                                        if on { draft.region = nil; draft.regionName = nil } else { draft.region = r.slug; draft.regionName = r.label }264                                    }265                                }266                            }267                            .padding(.top, 6)268                            if let u = shown?.regionUnknown, u > 0 {269                                Text("\(Fmt.products(u)) viennent de boutiques dont la région n'est pas connue : un filtre de région les écarte.")270                                    .font(.footnote).num().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 10)271                            }272                        }273                    }274                }275                .padding(.horizontal, Theme.margin)276                .padding(.bottom, 24)277            }278            .linen()279            .navigationTitle("Filtres")280            .navigationBarTitleDisplayMode(.inline)281            .toolbar {282                ToolbarItem(placement: .topBarLeading) {283                    Button("Tout retirer") {284                        var f = SearchFilters()285                        f.q = draft.q; f.sort = draft.sort; f.store = draft.store; f.storeName = draft.storeName286                        draft = f287                    }288                    .disabled(draft.activeCount == 0 && draft.category == nil)289                }290                ToolbarItem(placement: .topBarTrailing) { Button("Fermer") { dismiss() } }291            }292            .safeAreaInset(edge: .bottom) {293                Button(count.map { $0 == 0 ? "Aucun produit" : "Voir " + Fmt.products($0) } ?? "Voir les produits") {294                    filters = draft295                    dismiss()296                }297                .buttonStyle(PrimaryButtonStyle())298                .num()299                .padding(.horizontal, Theme.margin).padding(.vertical, 10)300                .background(Theme.bg)301                .accessibilityIdentifier("apply-filters")302            }303        }304        .presentationDetents([.large])305        .onAppear { draft = filters; count = facets?.total }306        .onChange(of: facets?.total) { _, v in if live == nil { count = v } }307        .task(id: draft) {308            guard draft != filters || live != nil else { return }309            try? await Task.sleep(for: .milliseconds(180))310            if Task.isCancelled { return }311            if let f = try? await APIClient.shared.facets(draft), !Task.isCancelled { live = f; count = f.total }312        }313    }314315    private func section<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {316        VStack(alignment: .leading, spacing: 0) {317            Text(title).font(.editorial(19)).foregroundStyle(Theme.ink).padding(.top, 24).padding(.bottom, 4)318                .accessibilityAddTraits(.isHeader)319            content()320        }321    }322323    private func toggle(_ title: String, _ note: String, _ on: Binding<Bool>, count: Int?) -> some View {324        VStack(spacing: 0) {325            Toggle(isOn: on) {326                VStack(alignment: .leading, spacing: 2) {327                    HStack(alignment: .firstTextBaseline, spacing: 6) {328                        Text(title).font(.body).foregroundStyle(Theme.ink)329                        if let count { Text(Fmt.group(count)).font(.footnote).num().foregroundStyle(Theme.ink3) }330                    }331                    Text(note).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)332                }333            }334            .tint(Theme.brand)335            .padding(.vertical, 10)336            Hairline()337        }338    }339}340
Files main
Menu

Theme