SPB Git

Repository Public

SearchView.swift 22.1 KB 449 lines swift

1//2//  Food-Ka iOS v23//  File: FoodKa/Features/Search/SearchView.swift4//  Description: résultats de recherche et rayons — liste dense, prix unitaire normalisé toujours visible, tris5//               (pertinence, prix, prix unitaire, plus forte baisse), filtres (rayon, enseigne, marque, en solde,6//               fourchette de prix, mentions), pastilles de filtres actifs, chargement progressif.7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import SwiftUI1314struct SearchView: View {15    @State var filters: SearchFilters16    @Environment(AppModel.self) private var model17    @Environment(\.horizontalSizeClass) private var hSize1819    @State private var products: [Product] = []20    @State private var total = 021    @State private var page = 022    @State private var pages = 123    @State private var approximate = false24    @State private var unitPriceUnit: String?25    @State private var facets: Facets?26    @State private var loading = true27    @State private var loadingMore = false28    @State private var failure: APIError?29    @State private var stale = false30    @State private var showFilters = false31    @State private var queryDraft = ""3233    var body: some View {34        ScrollView {35            LazyVStack(alignment: .leading, spacing: 0) {36                heading.padding(.bottom, 8)37                chips38                if stale { StaleBanner().padding(.vertical, 8) }39                if loading && products.isEmpty {40                    LoadingShelves(rows: 5)41                } else if let failure, products.isEmpty {42                    ErrorState(error: failure) { Task { await reload() } }43                } else if products.isEmpty {44                    empty45                } else {46                    if approximate {47                        HonestNote(text: "Aucun produit ne contient tous les mots. Voici ceux qui en contiennent au moins la moitié.")48                            .padding(.vertical, 8)49                    }50                    if filters.sort == .unitPrice, let u = unitPriceUnit {51                        HonestNote(text: "Tri par prix unitaire : seuls les produits mesurés en $ / \(u) sont classés, pour ne pas mêler les unités.")52                            .padding(.vertical, 8)53                    }54                    if filters.sort == .drop {55                        HonestNote(text: "Seules les baisses vérifiées dans l'historique sont classées, la plus forte d'abord.")56                            .padding(.vertical, 8)57                    }58                    grid59                    if page < pages {60                        HStack { Spacer(); ProgressView(); Spacer() }61                            .frame(height: 60)62                            .onAppear { Task { await loadMore() } }63                    } else if total > 0 {64                        Text("\(Fmt.plural(total, "produit", "produits")) affichés.")65                            .font(.footnote).monospacedDigit().foregroundStyle(Theme.ink3)66                            .frame(maxWidth: .infinity).padding(.vertical, 24)67                    }68                }69            }70            .pageColumn(wide: hSize == .regular)71            .padding(.bottom, 30)72        }73        .paper()74        .navigationTitle(filters.title)75        .navigationBarTitleDisplayMode(.inline)76        .toolbar {77            ToolbarItemGroup(placement: .topBarTrailing) {78                Menu {79                    Picker("Trier", selection: $filters.sort) {80                        ForEach(SortOrder.allCases) { s in Text(s.label).tag(s) }81                    }82                } label: {83                    Image(systemName: "arrow.up.arrow.down")84                }85                .accessibilityLabel("Trier : \(filters.sort.label)")86                .accessibilityIdentifier("sort-menu")87                Button { showFilters = true } label: {88                    Image(systemName: filters.activeCount > 0 ? "line.3.horizontal.decrease.circle.fill" : "line.3.horizontal.decrease.circle")89                }90                .accessibilityLabel(filters.activeCount > 0 ? "Filtres, \(filters.activeCount) actifs" : "Filtres")91                .accessibilityIdentifier("filters-button")92            }93        }94        .sheet(isPresented: $showFilters) {95            FiltersSheet(filters: $filters, facets: facets, total: total)96                .presentationDetents([.large])97        }98        .task(id: filters) { await reload() }99        .onAppear {100            queryDraft = filters.q101            if model.launchSheet == "filters" { showFilters = true }102        }103    }104105    private var heading: some View {106        VStack(alignment: .leading, spacing: 10) {107            HStack(spacing: 10) {108                Image(systemName: "magnifyingglass").foregroundStyle(Theme.ink3)109                TextField(filters.categoryName.map { "Chercher dans \($0)" } ?? "Produit, marque, rayon", text: $queryDraft)110                    .submitLabel(.search).autocorrectionDisabled().textInputAutocapitalization(.never)111                    .onSubmit { filters.q = queryDraft.trimmingCharacters(in: .whitespacesAndNewlines) }112                    .accessibilityIdentifier("results-search-field")113                if !queryDraft.isEmpty {114                    Button { queryDraft = ""; filters.q = "" } label: {115                        Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.ink3).frame(width: 36, height: 44).contentShape(Rectangle())116                    }117                    .buttonStyle(.plain).accessibilityLabel("Effacer la recherche")118                }119            }120            .padding(.horizontal, 12).frame(minHeight: 46)121            .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))122            .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))123            HStack(alignment: .firstTextBaseline) {124                Text(loading && products.isEmpty ? "Recherche…" : Fmt.plural(total, "produit", "produits"))125                    .font(.subheadline.weight(.medium)).monospacedDigit().foregroundStyle(Theme.ink)126                    .accessibilityIdentifier("results-count")127                Spacer()128                Text(filters.sort.label).font(.footnote).foregroundStyle(Theme.ink3)129            }130        }131        .padding(.top, 10)132    }133134    /// Sous-rayons du rayon courant, puis pastilles des filtres actifs, retirables une à une.135    @ViewBuilder private var chips: some View {136        let subs = facets?.categories.first { $0.slug == filters.category }?.subcategories ?? []137        if filters.category != nil, !subs.isEmpty {138            ScrollView(.horizontal, showsIndicators: false) {139                HStack(spacing: 8) {140                    ForEach(subs) { s in141                        Chip(label: s.name, selected: filters.subcategory == s.slug, count: s.n) {142                            if filters.subcategory == s.slug { filters.subcategory = nil; filters.subcategoryName = nil }143                            else { filters.subcategory = s.slug; filters.subcategoryName = s.name }144                        }145                    }146                }147            }148            .scrollClipDisabled()149        }150        if filters.activeCount > 0 {151            FlowLayout(spacing: 8) {152                ForEach(filters.stores, id: \.self) { s in153                    Chip(label: facets?.stores.first { $0.id == s }?.name ?? s, selected: true, removable: true) { filters.stores.removeAll { $0 == s } }154                }155                if let b = filters.brand { Chip(label: b, selected: true, removable: true) { filters.brand = nil } }156                ForEach(filters.tags.sorted(), id: \.self) { t in157                    Chip(label: facets?.tagLabels[t] ?? t, selected: true, removable: true) { filters.tags.remove(t) }158                }159                if filters.onSale { Chip(label: "En solde", selected: true, removable: true) { filters.onSale = false } }160                if filters.dealOnly { Chip(label: "Baisse vérifiée", selected: true, removable: true) { filters.dealOnly = false } }161                if filters.matchedOnly { Chip(label: "Dans plusieurs enseignes", selected: true, removable: true) { filters.matchedOnly = false } }162                if filters.inStockOnly { Chip(label: "En stock", selected: true, removable: true) { filters.inStockOnly = false } }163                if let k = filters.kind { Chip(label: k == "circulaire" ? "Circulaires" : "Catalogue", selected: true, removable: true) { filters.kind = nil } }164                if filters.priceMin != nil || filters.priceMax != nil {165                    Chip(label: FiltersSheet.priceLabel(filters.priceMin, filters.priceMax), selected: true, removable: true) { filters.priceMin = nil; filters.priceMax = nil }166                }167            }168            .padding(.top, 4)169        }170    }171172    @ViewBuilder private var grid: some View {173        if hSize == .regular {174            LazyVGrid(columns: [GridItem(.flexible(), spacing: 28), GridItem(.flexible(), spacing: 28)], alignment: .leading, spacing: 0) {175                ForEach(products) { p in176                    VStack(spacing: 0) { ProductRow(product: p); Hairline() }177                }178            }179        } else {180            ForEach(products) { p in181                ProductRow(product: p)182                Hairline()183            }184        }185    }186187    private var empty: some View {188        let hasFilters = filters.activeCount > 0189        return EmptyShelf(title: "Aucun produit ne correspond",190                          message: hasFilters ? "Essayer sans les filtres ?" : (filters.q.isEmpty ? nil : "Essayer un mot plus court, ou sans la marque ? Certaines enseignes publient leurs noms en anglais."),191                          actionLabel: hasFilters ? "Retirer les filtres" : nil,192                          action: hasFilters ? {193                              filters.clearSheet()194                          } : nil)195            .accessibilityIdentifier("results-empty")196    }197198    private func reload() async {199        loading = true200        failure = nil201        do {202            let r = try await APIClient.shared.search(filters, page: 1, facets: true)203            if Task.isCancelled { return }204            products = r.value.products205            total = r.value.total; page = 1; pages = r.value.pages206            approximate = r.value.approximate; unitPriceUnit = r.value.unitPriceUnit207            if let f = r.value.facets { facets = f }208            stale = r.stale209        } catch is CancellationError {210            return211        } catch {212            products = []213            failure = (error as? APIError) ?? .offline214        }215        loading = false216    }217218    private func loadMore() async {219        guard !loadingMore, page < pages else { return }220        loadingMore = true221        defer { loadingMore = false }222        let current = filters223        guard let r = try? await APIClient.shared.search(current, page: page + 1), current == filters else { return }224        let known = Set(products.map(\.id))225        products.append(contentsOf: r.value.products.filter { !known.contains($0.id) })226        page = r.value.page227        pages = r.value.pages228    }229}230231extension View {232    /// Colonne de page ; large sur iPad pour une grille à deux colonnes.233    func pageColumn(wide: Bool) -> some View {234        self.padding(.horizontal, Theme.margin)235            .frame(maxWidth: wide ? 1040 : Theme.readable)236            .frame(maxWidth: .infinity)237    }238}239240/// Feuille de filtres : les comptes viennent des facettes de la recherche en cours.241struct FiltersSheet: View {242    @Binding var filters: SearchFilters243    let facets: Facets?244    let total: Int245    @Environment(\.dismiss) private var dismiss246    @State private var allStores = false247    @State private var allBrands = false248249    static let presets: [(Double?, Double?)] = [(nil, 2), (2, 5), (5, 10), (10, 20), (20, nil)]250251    static func priceLabel(_ lo: Double?, _ hi: Double?) -> String {252        switch (lo, hi) {253        case let (a?, b?): "\(Fmt.number(a, digits: 0)) à \(Fmt.number(b, digits: 0))\(Fmt.nbsp)$"254        case let (nil, b?): "Moins de \(Fmt.number(b, digits: 0))\(Fmt.nbsp)$"255        case let (a?, nil): "\(Fmt.number(a, digits: 0))\(Fmt.nbsp)$ et plus"256        default: "Tous les prix"257        }258    }259260    var body: some View {261        NavigationStack {262            ScrollView {263                VStack(alignment: .leading, spacing: 26) {264                    group("Comparaison") {265                        Toggle(isOn: $filters.matchedOnly) {266                            label("Dans plusieurs enseignes", facets?.matched, note: "le même produit est suivi dans au moins deux enseignes")267                        }268                        .tint(Theme.brand)269                        .accessibilityIdentifier("filter-matched")270                        Toggle(isOn: $filters.inStockOnly) {271                            label("Sans les ruptures connues", nil, note: "écarte les produits signalés en rupture au dernier relevé")272                        }273                        .tint(Theme.brand)274                    }275                    group("Prix") {276                        Toggle(isOn: $filters.onSale) {277                            label("En solde", facets?.onSale, note: "l'enseigne annonce un solde ou une circulaire")278                        }279                        .tint(Theme.brand)280                        Toggle(isOn: $filters.dealOnly) {281                            label("Baisse vérifiée seulement", facets?.deals, note: "le prix a réellement baissé, d'après l'historique")282                        }283                        .tint(Theme.brand)284                        .accessibilityIdentifier("filter-deal")285                        FlowLayout(spacing: 8) {286                            ForEach(Array(FiltersSheet.presets.enumerated()), id: \.offset) { _, p in287                                let on = filters.priceMin == p.0 && filters.priceMax == p.1288                                Chip(label: FiltersSheet.priceLabel(p.0, p.1), selected: on) {289                                    if on { filters.priceMin = nil; filters.priceMax = nil } else { filters.priceMin = p.0; filters.priceMax = p.1 }290                                }291                            }292                        }293                    }294                    if let f = facets, !f.categories.isEmpty {295                        group("Rayon") {296                            FlowLayout(spacing: 8) {297                                ForEach(f.categories) { c in298                                    Chip(label: c.name, selected: filters.category == c.slug, count: c.n) {299                                        if filters.category == c.slug { filters.category = nil; filters.categoryName = nil }300                                        else { filters.category = c.slug; filters.categoryName = c.name }301                                        filters.subcategory = nil; filters.subcategoryName = nil302                                    }303                                }304                            }305                        }306                    }307                    if let f = facets, !f.stores.isEmpty {308                        let sorted = f.stores.sorted { $0.n > $1.n }309                        group("Enseigne") {310                            FlowLayout(spacing: 8) {311                                ForEach(allStores ? sorted : Array(sorted.prefix(12))) { s in312                                    Chip(label: s.name, selected: filters.stores.contains(s.id), count: s.n) {313                                        if let i = filters.stores.firstIndex(of: s.id) { filters.stores.remove(at: i) } else { filters.stores.append(s.id) }314                                    }315                                }316                            }317                            if sorted.count > 12 {318                                Button(allStores ? "Moins d'enseignes" : "Les \(sorted.count) enseignes") { allStores.toggle() }319                                    .font(.subheadline).foregroundStyle(Theme.brand).frame(minHeight: 44)320                            }321                        }322                    }323                    if let f = facets, !f.brands.isEmpty {324                        group("Marque") {325                            FlowLayout(spacing: 8) {326                                ForEach(allBrands ? f.brands : Array(f.brands.prefix(14))) { b in327                                    Chip(label: b.name + (b.store_brand == true ? " (maison)" : ""), selected: filters.brand?.caseInsensitiveCompare(b.name) == .orderedSame, count: b.n) {328                                        filters.brand = filters.brand?.caseInsensitiveCompare(b.name) == .orderedSame ? nil : b.name329                                    }330                                }331                            }332                            if f.brands.count > 14 {333                                Button(allBrands ? "Moins de marques" : "Les \(f.brands.count) marques les plus présentes") { allBrands.toggle() }334                                    .font(.subheadline).foregroundStyle(Theme.brand).frame(minHeight: 44)335                            }336                        }337                    }338                    if let f = facets, !f.tags.isEmpty {339                        group("Mentions") {340                            FlowLayout(spacing: 8) {341                                ForEach(f.tags.keys.sorted { (f.tags[$0] ?? 0) > (f.tags[$1] ?? 0) }, id: \.self) { t in342                                    Chip(label: f.tagLabels[t] ?? t, selected: filters.tags.contains(t), count: f.tags[t]) {343                                        if filters.tags.contains(t) { filters.tags.remove(t) } else { filters.tags.insert(t) }344                                    }345                                }346                            }347                            HonestNote(text: "Mentions indicatives : elles sont repérées dans le nom, la marque et les étiquettes publiées par l'enseigne. Ce n'est pas une certification.")348                        }349                    }350                    group("Source du prix") {351                        FlowLayout(spacing: 8) {352                            Chip(label: "Catalogue", selected: filters.kind == "catalogue") { filters.kind = filters.kind == "catalogue" ? nil : "catalogue" }353                            Chip(label: "Circulaires", selected: filters.kind == "circulaire") { filters.kind = filters.kind == "circulaire" ? nil : "circulaire" }354                        }355                    }356                }357                .padding(Theme.margin)358                .padding(.bottom, 90)359            }360            .paper()361            .navigationTitle("Filtres")362            .navigationBarTitleDisplayMode(.inline)363            .toolbar {364                ToolbarItem(placement: .topBarLeading) {365                    Button("Réinitialiser") {366                        filters.clearSheet()367                    }368                    .disabled(filters.activeCount == 0)369                }370            }371            .safeAreaInset(edge: .bottom) {372                Button("Voir \(Fmt.plural(total, "produit", "produits"))") { dismiss() }373                    .buttonStyle(PrimaryButtonStyle())374                    .padding(.horizontal, Theme.margin).padding(.vertical, 10)375                    .background(Theme.bg)376                    .accessibilityIdentifier("filters-apply")377            }378        }379    }380381    private func group<Content: View>(_ title: String, @ViewBuilder _ content: () -> Content) -> some View {382        VStack(alignment: .leading, spacing: 10) {383            Text(title).font(.editorial(19)).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)384            content()385        }386    }387388    private func label(_ title: String, _ count: Int?, note: String) -> some View {389        VStack(alignment: .leading, spacing: 2) {390            HStack(spacing: 6) {391                Text(title).font(.body).foregroundStyle(Theme.ink)392                if let count { Text(Fmt.group(count)).font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink3) }393            }394            Text(note).font(.caption).foregroundStyle(Theme.ink3)395        }396    }397}398399/// Tous les rayons et leurs sous-rayons.400struct CategoriesView: View {401    @Environment(AppModel.self) private var model402    @State private var state: Loadable<CategoriesResponse> = .loading403404    var body: some View {405        ScrollView {406            LazyVStack(alignment: .leading, spacing: 0) {407                switch state {408                case .loading: LoadingShelves()409                case .failed(let e): ErrorState(error: e) { Task { await load() } }410                case .loaded(let r, let stale):411                    if stale { StaleBanner().padding(.vertical, 8) }412                    ForEach(r.categories) { c in413                        Button { model.openCategory(name: c.name, slug: c.slug) } label: {414                            HStack(spacing: 12) {415                                Image(c.icon).resizable().scaledToFit().frame(width: 26, height: 26).foregroundStyle(Theme.ink)416                                Text(c.name).font(.editorial(19)).foregroundStyle(Theme.ink)417                                Spacer()418                                Text(Fmt.group(c.n)).font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink3)419                            }420                            .frame(minHeight: 52).contentShape(Rectangle())421                        }422                        .buttonStyle(.plain)423                        .padding(.top, 14)424                        ShelfBar(thickness: 2.5)425                        if !c.subcategories.isEmpty {426                            FlowLayout(spacing: 8) {427                                ForEach(c.subcategories) { s in428                                    Chip(label: s.name, count: s.n) { model.openCategory(name: c.name, slug: c.slug, sub: (s.name, s.slug)) }429                                }430                            }431                            .padding(.top, 10)432                        }433                    }434                }435            }436            .pageColumn()437            .padding(.bottom, 30)438        }439        .paper()440        .navigationTitle("Rayons")441        .navigationBarTitleDisplayMode(.inline)442        .task { await load() }443    }444445    private func load() async {446        if let s = await Loadable.from({ try await APIClient.shared.categories() }) { state = s }447    }448}449
Files main
Menu

Theme