SPB Git

Repository Public

VehicleView.swift 16.9 KB 375 lines swift

1//2//  Auto-Ka iOS v23//  File: AutoKa/Features/Vehicle/VehicleView.swift4//  Description: fiche d'un véhicule. Ordre standard, identique sur iPhone et iPad : galerie → prix, verdict et5//               fourchette de marché, titre, compteur, caractéristiques → description → équipement → historique6//               de prix, NIV, rappels → vendeur, annonce d'origine → similaires.7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import QuickLook13import SwiftUI1415struct VehicleView: View {16    let uid: String1718    @Environment(AppModel.self) private var model19    @Environment(Library.self) private var library20    @Environment(BoardingCenter.self) private var boarding21    @Environment(\.accessibilityReduceMotion) private var reduceMotion2223    @State private var vehicle: Vehicle?24    @State private var error: Error?25    @State private var offline = false26    @State private var attempt = 027    @State private var photoIndex = 028    @State private var showGallery = false29    @State private var link: ExternalLink?30    @State private var pdf: URL?31    @State private var pdfBusy = false32    @State private var traced = false3334    var body: some View {35        Group {36            if let v = vehicle ?? model.seed(for: uid) {37                content(v)38            } else if let error {39                missing(error)40            } else {41                VStack { BrandLoader() }.frame(maxWidth: .infinity, maxHeight: .infinity)42            }43        }44        .background(Theme.bg)45        .navigationBarTitleDisplayMode(.inline)46        .toolbar { toolbar }47        .safariSheet($link)48        .quickLookPreview($pdf)49        .task(id: attempt) { await load() }50    }5152    // MARK: Chargement5354    private func load() async {55        do {56            let v = try await APIClient.shared.vehicle(uid)57            offline = await APIClient.shared.servedFromCache58            vehicle = v59            model.seed(v)60            error = nil61            library.markSeen(v)62            library.refreshFavorite(v)63            // le NIV n'avait jamais été décodé : le service le fait à la demande64            if v.vinInfoPending, Fmt.isValidVIN(v.vin), let r = try? await APIClient.shared.vin(v.vin), r.decoded {65                vehicle?.vinInfo = r.info66                vehicle?.vinInfoPending = false67            }68        } catch is CancellationError {69        } catch {70            self.error = error71            if let e = error as? APIError, e == .gone || e == .notFound { library.markFavoriteGone(uid) }72        }73    }7475    @ViewBuilder76    private func missing(_ error: Error) -> some View {77        if let e = error as? APIError, e == .gone || e == .notFound {78            ScrollView {79                EmptyState(title: "Annonce retirée", message: "Ce véhicule n'est plus affiché par sa source : il a été vendu ou retiré.",80                           actionLabel: "Chercher un véhicule") { model.search(SearchFilters()) }81                    .padding(.top, 60)82            }83        } else {84            ScrollView { ErrorState(error: error) { self.error = nil; attempt += 1 }.padding(.top, 60) }85        }86    }8788    // MARK: Barre8990    @ToolbarContentBuilder91    private var toolbar: some ToolbarContent {92        if let v = vehicle ?? model.seed(for: uid) {93            ToolbarItemGroup(placement: .topBarTrailing) {94                if let url = v.shareURL {95                    ShareLink(item: url, subject: Text(v.fullTitle), message: Text("\(v.fullTitle), \(Fmt.money(v.price))")) {96                        Image(systemName: "square.and.arrow.up")97                    }98                    .accessibilityLabel("Partager")99                }100                let fav = library.isFavorite(uid)101                Button { toggleFavorite(v) } label: {102                    Image(systemName: fav ? "heart.fill" : "heart").heartBurst(fav)103                }104                .accessibilityLabel(fav ? "Retirer des favoris" : "Ajouter aux favoris")105                .accessibilityIdentifier("favori")106            }107        }108    }109110    private func toggleFavorite(_ v: Vehicle) {111        let now = library.toggleFavorite(v)112        Haptics.tap()113        model.showToast(now ? "Ajouté aux favoris" : "Retiré des favoris")114    }115116    private func openPDF(_ v: Vehicle) {117        guard !pdfBusy else { return }118        pdfBusy = true119        Task {120            defer { pdfBusy = false }121            guard let url = await APIClient.shared.pdfURL(uid: v.uid),122                  let file = try? await APIClient.shared.download(url, as: "Auto-Ka \(Fmt.slug(v.fullTitle)).pdf") else {123                model.showToast("La fiche PDF n'a pas pu être produite")124                return125            }126            pdf = file127        }128    }129130    // MARK: Contenu131132    private func content(_ v: Vehicle) -> some View {133        GeometryReader { geo in134            let hero = HeroLayout.size(container: geo.size.width)135            ScrollViewReader { proxy in136                ScrollView {137                    VStack(alignment: .leading, spacing: 0) {138                        // 1. galerie139                        GalleryCarousel(images: v.images.isEmpty ? (v.photo.map { [$0] } ?? []) : v.images, title: v.fullTitle,140                                        placeholder: v.bodyIcon, index: $photoIndex) { showGallery = true }141                            .frame(width: hero.width, height: hero.height)142                            .clipShape(RoundedRectangle(cornerRadius: Theme.radiusPhoto, style: .continuous))143                            .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { boarding.setHero($0, for: uid) }144                            // pendant le geste, la photo est dessinée par le calque, au même endroit145                            .opacity(boarding.isBoarding(uid) ? 0 : 1)146                            .frame(maxWidth: .infinity)147                            .padding(.top, 8)148149                        VStack(alignment: .leading, spacing: 0) {150                            if offline { OfflineNote().padding(.top, 14) }151                            if v.isDetail, !v.active { notice("Cette annonce n'est plus affichée par sa source. Les renseignements ci-dessous sont ceux de sa dernière vue, le \(Fmt.date(v.lastSeen)).") }152                            else if v.isDetail, !v.isPublic, let label = v.exclusion?.label { notice("Annonce hors du catalogue public : \(label).") }153154                            // 2. prix, verdict, fourchette, titre, compteur155                            Group {156                                if boarding.isAnimatingDetails(uid) {157                                    TimelineView(.animation) { tl in158                                        VehicleHeader(vehicle: v, details: boarding.details(for: uid, now: tl.date))159                                    }160                                } else {161                                    VehicleHeader(vehicle: v, details: .final)162                                }163                            }164                            .padding(.top, 16)165                            .id("resume")166167                            actions(v).padding(.top, 20)168169                            if v.isDetail {170                                VehicleSections(vehicle: v, link: $link)171                            } else {172                                // la carte a déjà donné l'essentiel ; le reste arrive173                                HStack { Spacer(); BrandLoader(size: 36); Spacer() }.padding(.vertical, 40)174                            }175                        }176                        .frame(maxWidth: HeroLayout.maxColumn, alignment: .leading)177                        .padding(.horizontal, HeroLayout.margin)178                        .frame(maxWidth: .infinity)179                    }180                    .padding(.bottom, 36)181                }182                .onChange(of: v.isDetail, initial: true) { _, detail in183                    // captures : -AKAnchor <section> fait défiler jusqu'à une section184                    if detail, let a = UserDefaults.standard.string(forKey: "AKAnchor") {185                        Task { @MainActor in186                            try? await Task.sleep(for: .milliseconds(700))187                            proxy.scrollTo(a, anchor: .top)188                        }189                    }190                }191            }192        }193        .navigationTitle(v.name)194        .fullScreenCover(isPresented: $showGallery) {195            GalleryViewer(images: v.images.isEmpty ? (v.photo.map { [$0] } ?? []) : v.images, index: $photoIndex)196        }197        .onAppear {198            // ouverte sans le geste : seule la fourchette se trace, une fois199            if !traced, v.verdict != nil { traced = true; boarding.traceVerdict(for: uid, reduceMotion: reduceMotion) }200        }201    }202203    private func notice(_ text: String) -> some View {204        HStack(alignment: .top, spacing: 8) {205            Image(systemName: "info.circle").font(.footnote)206            Text(text).font(.footnote).fixedSize(horizontal: false, vertical: true)207        }208        .foregroundStyle(Theme.bad)209        .padding(12)210        .frame(maxWidth: .infinity, alignment: .leading)211        .background(Theme.badSoft, in: RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous))212        .padding(.top, 14)213        .accessibilityElement(children: .combine)214    }215216    /// Favori, comparer, partager, PDF : quatre actions égales séparées par des filets.217    private func actions(_ v: Vehicle) -> some View {218        let fav = library.isFavorite(uid), cmp = library.isCompared(uid)219        return VStack(spacing: 0) {220            Rule()221            HStack(spacing: 0) {222                ActionCell(icon: fav ? "heart.fill" : "heart", label: fav ? "Favori" : "Garder", active: fav) { toggleFavorite(v) }223                    .accessibilityLabel(fav ? "Retirer des favoris" : "Ajouter aux favoris")224                divider225                ActionCell(brandIcon: "ic-comparer", label: cmp ? "Comparé" : "Comparer", active: cmp) { model.toggleCompare(v, library: library) }226                    .accessibilityLabel(cmp ? "Retirer de la comparaison" : "Ajouter à la comparaison")227                divider228                if let url = v.shareURL {229                    ShareLink(item: url, subject: Text(v.fullTitle), message: Text("\(v.fullTitle), \(Fmt.money(v.price))")) {230                        ActionCell.face(icon: "square.and.arrow.up", brandIcon: nil, label: "Partager", active: false)231                    }232                    .buttonStyle(.plain)233                    divider234                }235                ActionCell(icon: pdfBusy ? "hourglass" : "doc.text", label: "Fiche PDF", active: false) { openPDF(v) }236                    .accessibilityIdentifier("pdf")237            }238            Rule()239        }240    }241242    private var divider: some View { Rectangle().fill(Theme.line).frame(width: 1, height: 36) }243}244245/// Une action de la fiche : icône au-dessus du libellé, cible d'au moins 44 pt.246struct ActionCell: View {247    var icon: String?248    var brandIcon: String?249    let label: String250    let active: Bool251    let action: () -> Void252253    var body: some View {254        Button(action: action) { ActionCell.face(icon: icon, brandIcon: brandIcon, label: label, active: active) }255            .buttonStyle(.plain)256    }257258    static func face(icon: String?, brandIcon: String?, label: String, active: Bool) -> some View {259        VStack(spacing: 5) {260            Group {261                if let brandIcon { BrandIcon(brandIcon, size: 21) } else if let icon { Image(systemName: icon).font(.system(size: 17, weight: .medium)) }262            }263            .frame(height: 22)264            Text(label).font(.caption.weight(.medium)).lineLimit(1).minimumScaleFactor(0.8)265        }266        .foregroundStyle(active ? Theme.brand : Theme.ink)267        .frame(maxWidth: .infinity, minHeight: 60)268        .contentShape(Rectangle())269    }270}271272/// Tête de la fiche : prix et verdict, titre, compteur, caractéristiques en une ligne, fourchette de marché.273/// `details` vient de l'horloge du geste : le compteur roule, le prix se pose, la fourchette se trace.274struct VehicleHeader: View {275    let vehicle: Vehicle276    let details: BoardingDetails277278    @Environment(\.dynamicTypeSize) private var typeSize279280    var body: some View {281        let v = vehicle282        let g = GaugeChoreo.at(details.gauge)283        VStack(alignment: .leading, spacing: 0) {284            // prix demandé : le plus gros chiffre de la page ; il ne défile pas, il se pose285            ViewThatFits(in: .horizontal) {286                HStack(alignment: .center, spacing: 12) { price; Spacer(minLength: 8); pill(g) }287                VStack(alignment: .leading, spacing: 8) { price; pill(g) }288            }289            .opacity(details.price).offset(y: (1 - details.price) * 6)290291            VStack(alignment: .leading, spacing: 5) {292                Text(v.fullTitle).font(.editorial(24)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)293                    .accessibilityAddTraits(.isHeader)294                if !v.sellerLine.isEmpty { Text(v.sellerLine).font(.subheadline).foregroundStyle(Theme.ink3) }295                if let line = v.priceChangeLine {296                    HStack(spacing: 5) {297                        BrandIcon(v.priceChange?.isDrop == true ? "ic-baisse-prix" : "ic-historique-prix", size: 15)298                        Text(line).font(.footnote.weight(.medium)).num()299                    }300                    .foregroundStyle(Theme.ink2).padding(.top, 2)301                }302            }303            .padding(.top, 10)304            .opacity(details.title).offset(y: (1 - details.title) * 6)305306            Rule().padding(.top, 16)307308            // compteur à rouleaux et caractéristiques309            VStack(alignment: .leading, spacing: 10) {310                OdometerView(km: v.mileageKm, progress: details.odometer, short: details.short)311                if !v.specLine.isEmpty { Text(v.specLine).font(.subheadline).foregroundStyle(Theme.ink2) }312            }313            .padding(.vertical, 16)314315            if v.isCar {316                Rule()317                market(g).padding(.top, 16)318            }319        }320    }321322    private var price: some View {323        Text(Fmt.money(vehicle.price)).font(.display(32, weight: .semibold)).num().foregroundStyle(Theme.ink)324            .lineLimit(1).minimumScaleFactor(0.7)325            .accessibilityLabel("Prix demandé : \(Fmt.money(vehicle.price))")326            .accessibilityIdentifier("prix")327    }328329    private func pill(_ g: GaugeChoreo) -> some View {330        Group {331            if vehicle.verdict != nil {332                VerdictPill(verdict: vehicle.verdict, roll: g.deviation, emphasis: g.legend)333            } else if vehicle.isCar {334                VerdictPill(verdict: nil)335            }336        }337    }338339    @ViewBuilder340    private func market(_ g: GaugeChoreo) -> some View {341        VStack(alignment: .leading, spacing: 10) {342            Text("Prix du marché").eyebrowStyle()343            if let verdict = vehicle.verdict, let p = vehicle.price {344                MarketGauge(price: p, verdict: verdict, size: .hero, choreo: g)345                Text(legend(verdict)).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)346                    .opacity(g.legend)347                if verdict.unusual, let note = verdict.note ?? VerdictRules.current?.noteInhabituel {348                    // écart très bas : la note du service, telle quelle349                    HStack(alignment: .top, spacing: 7) {350                        BrandIcon("ic-rappel", size: 16).foregroundStyle(Theme.ink2).padding(.top, 1)351                        Text(note).font(.footnote.weight(.medium)).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)352                    }353                    .opacity(g.legend)354                    .accessibilityElement(children: .combine)355                }356            } else {357                NoVerdictGauge(reason: vehicle.mileageKm == nil358                               ? "Le kilométrage n'est pas indiqué : le prix ne peut pas être comparé à celui de véhicules semblables. Aucun verdict n'est donné."359                               : "Pas assez de véhicules comparables en vente, ou des prix trop dispersés pour situer celui-ci. Aucun verdict n'est donné.")360            }361        }362        .id("marche")363    }364365    /// « 61 Nissan Kicks comparables (2017 à 2019) en vente au Québec, ramenés au kilométrage et à l'année de ce366    /// véhicule. Médiane : 11 690 $. Du 10e au 90e centile : 9 900 $ à 13 400 $. »367    private func legend(_ pv: PriceVerdict) -> String {368        var years = ""369        if let y = vehicle.year { years = " (\(y - pv.yearSpan) à \(y + pv.yearSpan))" }370        let range = if let a = pv.marketP10, let b = pv.marketP90 { "Du 10ᵉ au 90ᵉ centile : \(Fmt.money(a)) à \(Fmt.money(b))." }371                    else { "La moitié se situent entre \(Fmt.money(pv.marketLow)) et \(Fmt.money(pv.marketHigh))." }372        return "\(Fmt.int(pv.comparables)) \(vehicle.name) comparables\(years) en vente au Québec, ramenés au kilométrage et à l'année de ce véhicule. Médiane : \(Fmt.money(pv.marketPrice)). \(range)"373    }374}375
Files main
Menu

Theme