SPB Git

Repository Public

SearchHomeView.swift 10.5 KB 245 lines swift

1//2//  Fabri-Ka iOS v23//  File: FabriKa/Features/Search/SearchHomeView.swift4//  Description: onglet « Chercher » — champ de recherche tolérant aux fautes avec autocomplétion (mots, catégories,5//               boutiques, lieux, produits), recherches récentes gardées sur l'appareil, entrées par catégorie.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213struct SearchHomeView: View {14    @Environment(AppModel.self) private var model15    @Environment(Library.self) private var library16    @State private var query = ""17    @State private var suggestions: Suggestions?18    @State private var suggesting = false19    @State private var categories: Loadable<Categories> = .loading20    @FocusState private var focused: Bool2122    private var trimmed: String { query.trimmingCharacters(in: .whitespacesAndNewlines) }2324    var body: some View {25        ScrollView {26            VStack(alignment: .leading, spacing: 0) {27                field.padding(.top, 8)28                if trimmed.count >= 2 {29                    suggestionList.padding(.top, 10)30                } else {31                    browse32                }33            }34            .pageColumn()35            .padding(.bottom, 40)36        }37        .scrollDismissesKeyboard(.interactively)38        .linen()39        .navigationTitle("Chercher")40        .task(id: trimmed) { await suggest() }41        .task {42            if categories.value == nil, let s = await Loadable.from({ try await APIClient.shared.categories() }) { categories = s }43        }44        .onAppear {45            if query.isEmpty, let q = model.launchQuery { query = q }46        }47    }4849    // --- Champ ----------------------------------------------------------------------------------------5051    private var field: some View {52        HStack(spacing: 10) {53            Image(systemName: "magnifyingglass").foregroundStyle(Theme.ink3)54            TextField("Savon, miel, tuque, bague…", text: $query)55                .focused($focused)56                .submitLabel(.search)57                .autocorrectionDisabled()58                .textInputAutocapitalization(.never)59                .onSubmit { run(trimmed) }60                .accessibilityIdentifier("search-field")61            if !query.isEmpty {62                Button { query = ""; suggestions = nil; focused = true } label: {63                    Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.ink3)64                        .frame(width: 36, height: 44).contentShape(Rectangle())65                }66                .accessibilityLabel("Effacer la recherche")67            }68        }69        .font(.body)70        .padding(.leading, 14).padding(.trailing, 6)71        .frame(minHeight: 48)72        .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))73        .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(focused ? Theme.brand : Theme.line2, lineWidth: focused ? 1.5 : 1))74    }7576    private func run(_ q: String) {77        guard !q.isEmpty else { return }78        library.remember(search: q)79        var f = SearchFilters()80        f.q = q81        focused = false82        model.openSearch(f)83    }8485    private func suggest() async {86        let q = trimmed87        guard q.count >= 2 else { suggestions = nil; return }88        suggesting = true89        defer { suggesting = false }90        try? await Task.sleep(for: .milliseconds(220))91        if Task.isCancelled { return }92        if let s = try? await APIClient.shared.suggest(q), !Task.isCancelled { suggestions = s }93    }9495    // --- Autocomplétion -------------------------------------------------------------------------------9697    @ViewBuilder98    private var suggestionList: some View {99        Button { run(trimmed) } label: {100            VStack(spacing: 0) {101                HStack(spacing: 12) {102                    Image(systemName: "magnifyingglass").foregroundStyle(Theme.brand).frame(width: 24)103                    VStack(alignment: .leading, spacing: 2) {104                        Text("Chercher « \(trimmed) »").font(.body.weight(.medium)).foregroundStyle(Theme.ink)105                        if let n = suggestions?.productsTotal, suggestions?.q == trimmed {106                            Text(n == 0 ? "Aucun produit ne porte ces mots" : Fmt.products(n)).font(.footnote).num().foregroundStyle(Theme.ink3)107                        }108                    }109                    Spacer(minLength: 0)110                }111                .padding(.vertical, 12).frame(minHeight: 52)112                Hairline()113            }114            .contentShape(Rectangle())115        }116        .buttonStyle(.plain)117        .accessibilityIdentifier("search-all")118119        if let s = suggestions {120            if !s.terms.isEmpty {121                FlowLayout(spacing: 8) {122                    ForEach(s.terms.prefix(6), id: \.self) { t in123                        Chip(label: t) { query = t; run(t) }124                    }125                }126                .padding(.top, 10)127            }128            if !s.categories.isEmpty || !s.subcategories.isEmpty {129                group("Catégories") {130                    ForEach(s.categories.prefix(3)) { c in131                        NavRow(icon: CategoryIcon.name(for: c.key), title: c.label, detail: Fmt.products(c.n)) {132                            model.openCategory(key: c.key, label: c.label)133                        }134                    }135                    ForEach(s.subcategories.prefix(4), id: \.slug) { c in136                        NavRow(icon: CategoryIcon.name(for: c.category), title: c.label, detail: Fmt.products(c.n)) {137                            var f = SearchFilters()138                            f.category = c.category; f.subcategory = c.slug; f.subcategoryName = c.label139                            model.openSearch(f)140                        }141                    }142                }143            }144            if !s.stores.isEmpty {145                group("Boutiques") {146                    ForEach(s.stores.prefix(4)) { st in147                        NavRow(icon: "ic-boutique", title: st.name,148                               detail: [st.place, Fmt.products(st.n)].compactMap { $0 }.joined(separator: " · ")) {149                            model.openStore(st.id)150                        }151                        .accessibilityIdentifier("suggest-store-\(st.id)")152                    }153                }154            }155            if !s.regions.isEmpty || !s.cities.isEmpty {156                group("Lieux") {157                    ForEach(s.regions.prefix(2)) { r in158                        NavRow(icon: "ic-region", title: r.name, detail: "Région") { model.open(.region(r.slug)) }159                    }160                    ForEach(s.cities.prefix(3)) { c in161                        NavRow(icon: "ic-region", title: c.name, detail: c.n.map(Fmt.stores)) { model.open(.city(c.slug)) }162                    }163                }164            }165            if !s.products.isEmpty {166                group("Produits") {167                    ForEach(s.products.prefix(5)) { p in168                        Button { model.openProduct(p, trigger: .direct) } label: {169                            VStack(spacing: 0) {170                                HStack(spacing: 12) {171                                    Photo(source: p.img, maxPixel: 160).frame(width: 46, height: 46)172                                    VStack(alignment: .leading, spacing: 2) {173                                        Text(p.title).font(.editorial(16)).foregroundStyle(Theme.ink).lineLimit(1)174                                        Text([p.priceText, p.storeName].filter { !$0.isEmpty }.joined(separator: " · "))175                                            .font(.footnote).num().foregroundStyle(Theme.ink3).lineLimit(1)176                                    }177                                    Spacer(minLength: 0)178                                }179                                .padding(.vertical, 9)180                                Hairline()181                            }182                            .contentShape(Rectangle())183                        }184                        .buttonStyle(.plain)185                    }186                }187            }188        } else if suggesting {189            LoadingSign()190        }191    }192193    private func group<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {194        VStack(alignment: .leading, spacing: 0) {195            Text(title).eyebrowStyle().padding(.top, 22).padding(.bottom, 2)196            content()197        }198    }199200    // --- Sans texte : recherches récentes, catégories -------------------------------------------------201202    @ViewBuilder203    private var browse: some View {204        if !library.searches.isEmpty {205            HStack(alignment: .firstTextBaseline) {206                Text("Recherches récentes").eyebrowStyle()207                Spacer()208                Button("Effacer") { library.clearSearches() }209                    .font(.footnote).foregroundStyle(Theme.brand).frame(minHeight: 44)210            }211            .padding(.top, 14)212            FlowLayout(spacing: 8) {213                ForEach(library.searches, id: \.self) { q in214                    Chip(label: q) { query = q; run(q) }215                }216            }217        }218        VStack(alignment: .leading, spacing: 0) {219            Text("Parcourir").eyebrowStyle().padding(.top, 24).padding(.bottom, 2)220            NavRow(icon: "ic-nouveau", title: "Nouveautés de la semaine", detail: "Vus pour la première fois depuis 7 jours") {221                var f = SearchFilters(); f.new = true; f.daysMax = 7222                model.openSearch(f)223            }224            NavRow(icon: "ic-region", title: "Par région", detail: "Les dix-sept régions du Québec") { model.open(.regions) }225            NavRow(icon: "ic-liste", title: "Tous les produits") { model.openSearch(SearchFilters()) }226        }227        VStack(alignment: .leading, spacing: 0) {228            Text("Catégories").eyebrowStyle().padding(.top, 24).padding(.bottom, 2)229            switch categories {230            case .loading: LoadingSign()231            case .failed(let e):232                Text(e.isOffline ? "Les catégories demandent une connexion." : (e.errorDescription ?? ""))233                    .font(.subheadline).foregroundStyle(Theme.ink3).padding(.vertical, 12)234            case .loaded(let c, _):235                ForEach(c.categories) { cat in236                    NavRow(icon: cat.icon, title: cat.label,237                           detail: Fmt.products(cat.n) + (cat.stores.map { " · " + Fmt.stores($0) } ?? "")) {238                        model.openCategory(key: cat.key, label: cat.label)239                    }240                }241            }242        }243    }244}245
Files main
Menu

Theme