Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Features/Search/FiltersSheet.swift4// Description: filtres de la recherche — marque, modèle, version, année, prix, kilométrage, carrosserie,5// carburant, transmission, rouage, couleur, lieu (région, ville, rayon autour de soi),6// concessionnaire, verdict, vendeur. Les valeurs et leurs comptes viennent de `/api/facets` et7// suivent les choix en cours ; le bouton dit le nombre de résultats.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11//1213import SwiftUI1415struct FiltersSheet: View {16 let sort: SearchSort17 let locator: Locator18 let apply: (SearchFilters) -> Void1920 @Environment(\.dismiss) private var dismiss21 @Environment(AppModel.self) private var model22 @State private var f: SearchFilters23 @State private var facets: Facets?24 @State private var failed = false2526 init(initial: SearchFilters, sort: SearchSort, locator: Locator, apply: @escaping (SearchFilters) -> Void) {27 self.sort = sort; self.locator = locator; self.apply = apply28 _f = State(initialValue: initial)29 }3031 private static let prices = [2500, 5000, 7500, 10_000, 15_000, 20_000, 25_000, 30_000, 35_000, 40_000, 50_000, 60_000, 75_000, 100_000, 150_000]32 private static let mileages = [10_000, 25_000, 50_000, 75_000, 100_000, 125_000, 150_000, 200_000, 250_000]33 private static let radii = [10, 25, 50, 100, 200]34 private static let ages = [1, 3, 7, 14, 30]3536 var body: some View {37 NavigationStack {38 ScrollView {39 VStack(alignment: .leading, spacing: 30) {40 kindSection41 vehicleSection42 rangeSection43 chips("Carrosserie", values: facets?.bodyTypes, selection: $f.bodyTypes, unknownKey: "body_type", icon: { BodyType.icon(for: $0) })44 chips("Carburant", values: facets?.fuels, selection: $f.fuels, unknownKey: "fuel", icon: { Fuel.icon(for: $0) })45 chips("Transmission", values: facets?.transmissions, selection: $f.transmissions, unknownKey: "transmission")46 chips("Rouage", values: facets?.drivetrains, selection: $f.drivetrains, unknownKey: "drivetrain")47 chips("Couleur", values: facets?.colors, selection: $f.colors, unknownKey: "color")48 placeSection49 verdictSection50 sellerSection51 moreSection52 }53 .padding(.horizontal, 16).padding(.top, 12).padding(.bottom, 24)54 .frame(maxWidth: 720, alignment: .leading)55 .frame(maxWidth: .infinity)56 }57 .background(Theme.bg)58 .navigationTitle("Filtres")59 .navigationBarTitleDisplayMode(.inline)60 .toolbar {61 ToolbarItem(placement: .topBarLeading) { Button("Fermer") { dismiss() } }62 ToolbarItem(placement: .topBarTrailing) {63 Button("Tout effacer") { f = SearchFilters() }.disabled(f.isEmpty)64 }65 }66 .safeAreaInset(edge: .bottom) {67 VStack(spacing: 0) {68 Rule()69 Button {70 apply(f)71 dismiss()72 } label: { Text(buttonLabel) }73 .buttonStyle(PrimaryButtonStyle())74 .padding(.horizontal, 16).padding(.vertical, 10)75 .accessibilityIdentifier("appliquer-filtres")76 }77 .background(Theme.bg)78 }79 .task(id: f) {80 // les comptes suivent les choix (court délai pendant la saisie)81 if facets != nil { try? await Task.sleep(for: .milliseconds(250)) }82 if Task.isCancelled { return }83 do {84 let r = try await APIClient.shared.facets(f)85 if !Task.isCancelled { facets = r; failed = false }86 } catch is CancellationError {87 } catch { failed = facets == nil }88 }89 }90 }9192 private var buttonLabel: String {93 guard let t = facets?.total else { return failed ? "Appliquer" : "Voir les véhicules" }94 return t == 0 ? "Aucun véhicule : élargir les critères" : "Voir \(t == 1 ? "le véhicule" : "les \(Fmt.int(t)) véhicules")"95 }9697 // MARK: Sections9899 private func header(_ title: String, note: String? = nil) -> some View {100 VStack(alignment: .leading, spacing: 3) {101 Text(title).font(.editorial(19)).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)102 if let note { Text(note).font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true) }103 }104 }105106 private var kindSection: some View {107 VStack(alignment: .leading, spacing: 12) {108 header("Type")109 FlowLayout(spacing: 8) {110 ForEach([("auto", "Voitures et camions"), ("moto", "Motos"), ("scooter", "Scooters")], id: \.0) { k in111 ChoiceChip(label: k.1, count: facets?.kinds?.first { $0.value == k.0 }?.n, selected: f.kind == k.0) {112 if f.kind != k.0 { f.kind = k.0; f.makes = []; f.models = []; f.verdicts = [] }113 }114 }115 }116 }117 }118119 private var vehicleSection: some View {120 VStack(alignment: .leading, spacing: 0) {121 header("Véhicule").padding(.bottom, 8)122 Rule()123 NavigationLink {124 FacetPicker(title: "Marque", values: facets?.makes ?? [], selection: Binding(get: { f.makes }, set: { f.makes = $0; f.models = [] }), single: true)125 } label: { pickerRow("Marque", f.makes.isEmpty ? "Toutes" : f.makes.joined(separator: ", ")) }126 if !f.makes.isEmpty {127 NavigationLink {128 FacetPicker(title: "Modèle", values: facets?.models ?? [], selection: $f.models)129 } label: { pickerRow("Modèle", f.models.isEmpty ? "Tous" : f.models.joined(separator: ", ")) }130 }131 HStack(spacing: 12) {132 Text("Version").font(.subheadline).foregroundStyle(Theme.ink3)133 TextField("XLE, Sport, Limited…", text: $f.trim)134 .multilineTextAlignment(.trailing).textInputAutocapitalization(.never).autocorrectionDisabled()135 .font(.subheadline.weight(.medium))136 }137 .frame(minHeight: 48)138 Rule()139 HStack(spacing: 12) {140 Text("Mots-clés").font(.subheadline).foregroundStyle(Theme.ink3)141 TextField("Ville, concessionnaire, NIV…", text: $f.q)142 .multilineTextAlignment(.trailing).textInputAutocapitalization(.never).autocorrectionDisabled()143 .font(.subheadline.weight(.medium))144 }145 .frame(minHeight: 48)146 Rule()147 }148 }149150 private var rangeSection: some View {151 let years: [Int] = {152 let lo = Int(facets?.ranges?.year?.min ?? 1990), hi = Int(facets?.ranges?.year?.max ?? Double(Calendar.current.component(.year, from: Date()) + 1))153 return Array((max(1980, lo)...max(lo, hi)).reversed())154 }()155 return VStack(alignment: .leading, spacing: 0) {156 header("Année, prix, kilométrage", note: facets?.ranges?.price?.median.map { "Prix médian des résultats : \(Fmt.money($0)). Kilométrage médian : \(Fmt.int(facets?.ranges?.mileageKm?.median)) km." }).padding(.bottom, 8)157 Rule()158 rangeRow("Année", min: $f.yearMin, max: $f.yearMax, options: years) { String($0) }159 rangeRow("Prix", min: $f.priceMin, max: $f.priceMax, options: FiltersSheet.prices) { Fmt.money(Double($0)) }160 rangeRow("Kilométrage", min: $f.kmMin, max: $f.kmMax, options: FiltersSheet.mileages) { "\(Fmt.int($0)) km" }161 if f.kmMin != nil || f.kmMax != nil {162 Text("Un filtre de kilométrage écarte les annonces qui ne l'indiquent pas.").font(.caption).foregroundStyle(Theme.ink3).padding(.top, 8)163 }164 }165 }166167 private func rangeRow(_ title: String, min: Binding<Int?>, max: Binding<Int?>, options: [Int], label: @escaping (Int) -> String) -> some View {168 VStack(spacing: 0) {169 HStack(spacing: 10) {170 Text(title).font(.subheadline).foregroundStyle(Theme.ink3)171 Spacer(minLength: 6)172 bound("De", value: min, options: options.sorted(), label: label)173 bound("À", value: max, options: options.sorted(), label: label)174 }175 .frame(minHeight: 52)176 Rule()177 }178 }179180 private func bound(_ prefix: String, value: Binding<Int?>, options: [Int], label: @escaping (Int) -> String) -> some View {181 Menu {182 Button("Sans limite") { value.wrappedValue = nil }183 ForEach(options, id: \.self) { o in Button(label(o)) { value.wrappedValue = o } }184 } label: {185 HStack(spacing: 5) {186 Text(value.wrappedValue.map(label) ?? (prefix == "De" ? "Min." : "Max.")).font(.subheadline.weight(.medium)).num()187 .foregroundStyle(value.wrappedValue == nil ? Theme.ink3 : Theme.ink).lineLimit(1)188 Image(systemName: "chevron.up.chevron.down").font(.caption2.weight(.semibold)).foregroundStyle(Theme.ink3)189 }190 .padding(.horizontal, 10).frame(minHeight: 40)191 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous))192 .overlay(RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))193 }194 .accessibilityLabel("\(prefix == "De" ? "Minimum" : "Maximum") : \(value.wrappedValue.map(label) ?? "sans limite")")195 }196197 @ViewBuilder198 private func chips(_ title: String, values: [FacetValue]?, selection: Binding<[String]>, unknownKey: String, icon: ((String) -> String)? = nil) -> some View {199 // les valeurs déjà choisies restent visibles même si leur compte tombe à zéro200 let all = (values ?? []) + selection.wrappedValue.filter { s in !(values ?? []).contains { $0.value == s } }.map { FacetValue(value: $0, n: 0) }201 if !all.isEmpty {202 VStack(alignment: .leading, spacing: 12) {203 let unknown = facets?.unknown?[unknownKey] ?? 0204 header(title, note: unknown > 0 ? "\(Fmt.plural(unknown, "annonce ne l'indique pas", "annonces ne l'indiquent pas")) : ce filtre les écarte." : nil)205 FlowLayout(spacing: 8) {206 ForEach(all) { v in207 ChoiceChip(label: SearchFilters.fuelLabel(v.value), count: v.n, icon: icon?(v.value), selected: selection.wrappedValue.contains(v.value)) {208 toggle(v.value, in: selection)209 }210 }211 }212 }213 }214 }215216 private func toggle(_ value: String, in selection: Binding<[String]>) {217 if let i = selection.wrappedValue.firstIndex(of: value) { selection.wrappedValue.remove(at: i) } else { selection.wrappedValue.append(value) }218 }219220 private var placeSection: some View {221 VStack(alignment: .leading, spacing: 0) {222 header("Lieu").padding(.bottom, 8)223 Rule()224 HStack(spacing: 10) {225 Image(systemName: "location").foregroundStyle(Theme.ink2).frame(width: 22)226 Toggle(isOn: Binding(get: { f.near != nil }, set: { on in227 if on {228 locator.locate { c in f.near = NearPoint(lat: c.latitude, lng: c.longitude, label: "ma position") }229 } else { f.near = nil }230 })) {231 VStack(alignment: .leading, spacing: 2) {232 Text("Autour de moi").font(.subheadline).foregroundStyle(Theme.ink)233 if locator.status == .denied {234 Text("Position refusée : l'autoriser dans Réglages.").font(.caption).foregroundStyle(Theme.bad)235 } else if locator.status == .failed {236 Text("Position introuvable pour le moment.").font(.caption).foregroundStyle(Theme.bad)237 } else {238 Text("Votre position ne sert qu'à cette recherche.").font(.caption).foregroundStyle(Theme.ink3)239 }240 }241 }242 .tint(Theme.brand)243 }244 .frame(minHeight: 56)245 Rule()246 if f.near != nil {247 HStack {248 Text("Rayon").font(.subheadline).foregroundStyle(Theme.ink3)249 Spacer()250 Picker("Rayon", selection: $f.radiusKm) {251 ForEach(FiltersSheet.radii, id: \.self) { r in Text(Fmt.distance(km: Double(r), unit: model.units)).tag(r) }252 }253 .pickerStyle(.menu).tint(Theme.ink)254 }255 .frame(minHeight: 48)256 Rule()257 }258 NavigationLink {259 FacetPicker(title: "Région", values: facets?.regions ?? [], selection: $f.regions)260 } label: { pickerRow("Région", f.regions.isEmpty ? "Toutes" : f.regions.joined(separator: ", ")) }261 NavigationLink {262 FacetPicker(title: "Ville", values: facets?.cities ?? [], selection: $f.cities)263 } label: { pickerRow("Ville", f.cities.isEmpty ? "Toutes" : f.cities.joined(separator: ", ")) }264 NavigationLink {265 FacetPicker(title: "Concessionnaire", values: facets?.dealers ?? [], selection: Binding(get: { f.dealers }, set: { ids in266 f.dealers = ids267 f.dealerNames = ids.map { id in facets?.dealers?.first { $0.value == id }?.title ?? id }268 }), note: "Les 60 commerces qui ont le plus de résultats. L'annuaire complet est dans l'onglet Plus.")269 } label: { pickerRow("Concessionnaire", f.dealerNames.isEmpty ? "Tous" : f.dealerNames.joined(separator: ", ")) }270 }271 }272273 @ViewBuilder274 private var verdictSection: some View {275 if f.kind == "auto", let positions = facets?.positions ?? facets?.verdicts, !positions.isEmpty {276 VStack(alignment: .leading, spacing: 12) {277 header("Prix face au marché", note: "Le verdict situe le prix demandé parmi ceux de véhicules comparables. Les libellés et la règle viennent d'Auto-Ka ; la méthode est décrite dans l'onglet Plus.")278 FlowLayout(spacing: 8) {279 // dans l'ordre de l'échelle, avec les libellés du service280 ForEach(VerdictRules.order, id: \.self) { code in281 let n = code == "aucun" ? facets?.verdicts?.first { $0.value == "aucun" }?.n : positions.first { $0.value == code }?.n282 if let n {283 ChoiceChip(label: positions.first { $0.value == code }?.label ?? VerdictRules.label(for: code), count: n,284 icon: code == "aucun" ? nil : Theme.icon(for: VerdictRules.position(forCode: code)),285 selected: f.verdicts.contains(code)) { toggle(code, in: $f.verdicts) }286 }287 }288 }289 }290 }291 }292293 private var sellerSection: some View {294 VStack(alignment: .leading, spacing: 12) {295 header("Vendeur")296 FlowLayout(spacing: 8) {297 ChoiceChip(label: "Tous", selected: f.seller == nil) { f.seller = nil }298 ChoiceChip(label: "Concessionnaires", selected: f.seller == "concessionnaire") { f.seller = "concessionnaire" }299 ChoiceChip(label: "Particuliers", selected: f.seller == "particulier") { f.seller = "particulier" }300 }301 if let statuses = facets?.statuses, statuses.count > 1 {302 FlowLayout(spacing: 8) {303 ForEach(statuses) { s in304 ChoiceChip(label: s.value == "certifie" ? "Certifiés" : (s.value == "demo" ? "Démonstrateurs" : "Occasion"), count: s.n,305 selected: f.statuses.contains(s.value)) { toggle(s.value, in: $f.statuses) }306 }307 }308 }309 }310 }311312 private var moreSection: some View {313 VStack(alignment: .leading, spacing: 0) {314 header("Annonce").padding(.bottom, 8)315 Rule()316 Toggle(isOn: $f.priceDrop) { Text("Prix baissé").font(.subheadline).foregroundStyle(Theme.ink) }.tint(Theme.brand).frame(minHeight: 48)317 Rule()318 Toggle(isOn: $f.withPhoto) { Text("Avec de vraies photos").font(.subheadline).foregroundStyle(Theme.ink) }.tint(Theme.brand).frame(minHeight: 48)319 Rule()320 HStack {321 Text("En ligne depuis").font(.subheadline).foregroundStyle(Theme.ink3)322 Spacer()323 Picker("En ligne depuis", selection: $f.daysMax) {324 Text("Peu importe").tag(Int?.none)325 ForEach(FiltersSheet.ages, id: \.self) { d in Text(d == 1 ? "24 heures" : "\(d) jours ou moins").tag(Int?.some(d)) }326 }327 .pickerStyle(.menu).tint(Theme.ink)328 }329 .frame(minHeight: 48)330 Rule()331 }332 }333334 private func pickerRow(_ title: String, _ value: String) -> some View {335 VStack(spacing: 0) {336 HStack(spacing: 12) {337 Text(title).font(.subheadline).foregroundStyle(Theme.ink3)338 Spacer(minLength: 8)339 Text(value).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink).lineLimit(1)340 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3)341 }342 .frame(minHeight: 48).contentShape(Rectangle())343 Rule()344 }345 .accessibilityElement(children: .combine)346 }347}348349/// Choix dans une facette : liste cherchable, comptes à droite, sélection simple ou multiple.350struct FacetPicker: View {351 let title: String352 let values: [FacetValue]353 @Binding var selection: [String]354 var single = false355 var note: String?356357 @Environment(\.dismiss) private var dismiss358 @State private var query = ""359360 private var shown: [FacetValue] {361 let q = Fmt.slug(query)362 return q.isEmpty ? values : values.filter { Fmt.slug($0.title).contains(q) }363 }364365 var body: some View {366 ScrollView {367 LazyVStack(alignment: .leading, spacing: 0) {368 if let note { Text(note).font(.caption).foregroundStyle(Theme.ink3).padding(.bottom, 10) }369 Rule()370 if !selection.isEmpty {371 Button { selection = []; if single { dismiss() } } label: { row(single ? "Toutes" : "Effacer la sélection", n: nil, on: false) }.buttonStyle(.plain)372 }373 ForEach(shown) { v in374 let on = selection.contains(v.value)375 Button {376 Haptics.select()377 if single { selection = on ? [] : [v.value]; dismiss() }378 else if on { selection.removeAll { $0 == v.value } } else { selection.append(v.value) }379 } label: { row(v.title, n: v.n, on: on) }380 .buttonStyle(.plain)381 .accessibilityAddTraits(on ? .isSelected : [])382 }383 if shown.isEmpty {384 Text(values.isEmpty ? "Aucune valeur pour les critères en cours." : "Rien ne correspond à « \(query) ».")385 .font(.subheadline).foregroundStyle(Theme.ink3).padding(.vertical, 24)386 }387 }388 .padding(.horizontal, 16).padding(.top, 8).padding(.bottom, 24)389 }390 .background(Theme.bg)391 .navigationTitle(title)392 .navigationBarTitleDisplayMode(.inline)393 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Chercher")394 }395396 private func row(_ label: String, n: Int?, on: Bool) -> some View {397 VStack(spacing: 0) {398 HStack(spacing: 10) {399 Text(label).font(.body.weight(on ? .semibold : .regular)).foregroundStyle(on ? Theme.brandStrong : Theme.ink)400 Spacer(minLength: 8)401 if let n { Text(Fmt.int(n)).font(.subheadline).num().foregroundStyle(Theme.ink3) }402 Image(systemName: "checkmark").font(.footnote.weight(.bold)).foregroundStyle(Theme.brand).opacity(on ? 1 : 0)403 }404 .frame(minHeight: 48).contentShape(Rectangle())405 Rule()406 }407 .accessibilityElement(children: .combine)408 }409}410411/// Mise en page en lignes qui passent à la suivante quand la largeur manque (options de filtre).412struct FlowLayout: Layout {413 var spacing: CGFloat = 8414415 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {416 let width = proposal.width ?? .infinity417 var x: CGFloat = 0, y: CGFloat = 0, rowH: CGFloat = 0, maxX: CGFloat = 0418 for s in subviews {419 let size = s.sizeThatFits(ProposedViewSize(width: width, height: nil))420 if x > 0, x + size.width > width { x = 0; y += rowH + spacing; rowH = 0 }421 x += size.width + spacing422 rowH = max(rowH, size.height)423 maxX = max(maxX, x - spacing)424 }425 return CGSize(width: width.isFinite ? width : maxX, height: y + rowH)426 }427428 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {429 var x = bounds.minX, y = bounds.minY, rowH: CGFloat = 0430 for s in subviews {431 let size = s.sizeThatFits(ProposedViewSize(width: bounds.width, height: nil))432 if x > bounds.minX, x + size.width > bounds.maxX { x = bounds.minX; y += rowH + spacing; rowH = 0 }433 s.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size))434 x += size.width + spacing435 rowH = max(rowH, size.height)436 }437 }438}439