SPB Git

Repository Public

CompareView.swift 8.2 KB 164 lines swift

1//2//  Auto-Ka iOS v23//  File: AutoKa/Features/Saved/CompareView.swift4//  Description: comparateur — jusqu'à quatre véhicules côte à côte, gardés sur l'appareil. Les faits sont alignés5//               ligne à ligne ; aucun véhicule n'est désigné « meilleur ».6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213struct CompareView: View {14    @Environment(AppModel.self) private var model15    @Environment(Library.self) private var library16    @Environment(\.horizontalSizeClass) private var hSize17    @Environment(\.dynamicTypeSize) private var typeSize1819    @State private var vehicles: [String: Vehicle] = [:]20    @State private var missing: Set<String> = []21    @State private var loading = true2223    private var ordered: [Vehicle] { library.compareIDs.compactMap { vehicles[$0] } }2425    var body: some View {26        Group {27            if library.compareIDs.isEmpty {28                ScrollView {29                    EmptyState(title: "Rien à comparer",30                               message: "« Comparer », sur une fiche, ajoute un véhicule ici. Jusqu'à \(Library.compareMax) véhicules, gardés sur cet appareil.",31                               actionLabel: "Chercher un véhicule") { model.search(SearchFilters()) }32                        .padding(.top, 50)33                }34            } else if loading, vehicles.isEmpty {35                VStack { BrandLoader() }.frame(maxWidth: .infinity, maxHeight: .infinity)36            } else {37                table38            }39        }40        .background(Theme.bg)41        .navigationTitle("Comparateur")42        .navigationBarTitleDisplayMode(.inline)43        .toolbar {44            if !library.compareIDs.isEmpty {45                ToolbarItem(placement: .topBarTrailing) { Button("Vider") { library.clearCompare() } }46            }47        }48        .task(id: library.compareIDs) { await load() }49    }5051    private func load() async {52        loading = true53        defer { loading = false }54        for uid in library.compareIDs where vehicles[uid] == nil {55            if let seed = model.seed(for: uid), seed.isDetail { vehicles[uid] = seed; continue }56            do {57                let v = try await APIClient.shared.vehicle(uid)58                vehicles[uid] = v59                model.seed(v)60            } catch {61                missing.insert(uid)62            }63        }64    }6566    private var columnWidth: CGFloat { typeSize.isAccessibilitySize ? 250 : (hSize == .regular ? 220 : 172) }67    private let labelWidth: CGFloat = 06869    private var table: some View {70        ScrollView {71            VStack(alignment: .leading, spacing: 16) {72                if !missing.isEmpty {73                    Text("\(Fmt.plural(missing.intersection(library.compareIDs).count, "annonce n'est plus disponible", "annonces ne sont plus disponibles")) et n'apparaît pas ci-dessous.")74                        .font(.footnote).foregroundStyle(Theme.ink3).padding(.horizontal, 16)75                }76                ScrollView(.horizontal, showsIndicators: false) {77                    VStack(alignment: .leading, spacing: 0) {78                        heads79                        Rule(strong: true)80                        row("Prix demandé") { v in Text(Fmt.money(v.price)).font(.display(18)).num().foregroundStyle(Theme.ink) }81                        row("Prix face au marché") { v in82                            VStack(alignment: .leading, spacing: 8) {83                                VerdictPill(verdict: v.verdict, compact: true)84                                if let pv = v.verdict, let p = v.price { MarketGauge(price: p, verdict: pv, size: .medium) }85                            }86                        }87                        row("Prix de marché") { v in fact(v.verdict.map { Fmt.money($0.marketPrice) }) }88                        row("Écart") { v in fact(v.verdict.flatMap { pv in v.price.map { Fmt.signedMoney(pv.gap(price: $0)) } }) }89                        row("Comparables") { v in fact(v.verdict.map { Fmt.int($0.comparables) }) }90                        row("Kilométrage") { v in fact(Fmt.mileageShort(v.mileageKm)) }91                        row("Année") { v in fact(v.year.map(String.init)) }92                        row("Carrosserie") { v in fact(v.bodyType, inferred: v.isInferred("body_type")) }93                        row("Carburant") { v in fact(v.fuel, inferred: v.isInferred("fuel")) }94                        row("Transmission") { v in fact(v.transmission) }95                        row("Rouage") { v in fact(v.drivetrain) }96                        row("Moteur") { v in fact(v.engine) }97                        row("Couleur") { v in fact(v.exteriorColor) }98                        row("Vendeur") { v in fact(v.privateSeller ? "Particulier" : v.dealerName) }99                        row("Ville") { v in fact(v.city) }100                        row("Mise en ligne") { v in fact(v.daysListed.map { $0 <= 0 ? "Aujourd'hui" : "Il y a \($0) j" }) }101                        row("Dernière variation") { v in fact(v.priceChange?.delta.map { Fmt.signedMoney($0) }) }102                        row("Rappels publiés") { v in fact(v.recalls.flatMap { $0.checked ? String($0.count) : nil }) }103                    }104                    .padding(.horizontal, 16)105                }106                Text("Les faits viennent des annonces ; « — » : la source ne l'indique pas. Le verdict situe le prix parmi des véhicules comparables : il ne dit pas lequel choisir.")107                    .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.horizontal, 16)108            }109            .padding(.top, 8).padding(.bottom, 32)110        }111    }112113    private var heads: some View {114        HStack(alignment: .top, spacing: 14) {115            ForEach(ordered) { v in116                VStack(alignment: .leading, spacing: 8) {117                    Button { model.open(.vehicle(v.uid)) } label: {118                        VStack(alignment: .leading, spacing: 8) {119                            RemoteImage(source: v.photo, width: .small, placeholder: v.bodyIcon)120                                .aspectRatio(4.0 / 3.0, contentMode: .fit)121                                .clipShape(RoundedRectangle(cornerRadius: Theme.radiusCard, style: .continuous))122                            Text(v.fullTitle).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink).lineLimit(3).multilineTextAlignment(.leading)123                                .frame(minHeight: 40, alignment: .topLeading)124                        }125                    }126                    .buttonStyle(CardPressStyle())127                    .accessibilityLabel("\(v.fullTitle). Ouvrir la fiche.")128                    Button { library.toggleCompare(v.uid) } label: {129                        Text("Retirer").font(.footnote.weight(.medium)).foregroundStyle(Theme.ink3).frame(minHeight: 44, alignment: .leading)130                    }131                    .accessibilityLabel("Retirer \(v.fullTitle) de la comparaison")132                }133                .frame(width: columnWidth, alignment: .leading)134            }135        }136        .padding(.bottom, 4)137    }138139    /// Une ligne du tableau : le libellé au-dessus, puis la valeur de chaque véhicule dans sa colonne.140    private func row<C: View>(_ label: String, @ViewBuilder _ cell: @escaping (Vehicle) -> C) -> some View {141        VStack(alignment: .leading, spacing: 0) {142            Text(label).eyebrowStyle().padding(.top, 12)143            HStack(alignment: .top, spacing: 14) {144                ForEach(ordered) { v in145                    cell(v).frame(width: columnWidth, alignment: .leading)146                        .accessibilityElement(children: .combine)147                        .accessibilityLabel(Text("\(v.name), \(label)"))148                }149            }150            .padding(.top, 6).padding(.bottom, 12)151            Rule()152        }153    }154155    private func fact(_ value: String?, inferred: Bool = false) -> some View {156        let empty = value?.isEmpty ?? true157        return VStack(alignment: .leading, spacing: 1) {158            Text(empty ? "—" : value!).font(.subheadline.weight(.medium)).num().foregroundStyle(empty ? Theme.ink3 : Theme.ink)159                .fixedSize(horizontal: false, vertical: true)160            if inferred, !empty { Text("déduit du modèle").font(.caption2).foregroundStyle(Theme.ink3) }161        }162    }163}164
Files main
Menu

Theme