SPB Git

Repository Public

Components.swift 17.1 KB 433 lines swift

1//2//  Auto-Ka iOS v23//  File: AutoKa/Design/Components.swift4//  Description: composants de base — chargement d'un écran, états vides et d'erreur, en-têtes de section, filets,5//               boutons, lignes de faits, barres de répartition, icônes de la marque.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213// MARK: - Icône de la marque1415/// Icône du système de marque (grille 24, trait 1,6, bouts ronds) prise dans le catalogue d'images.16struct BrandIcon: View {17    let name: String18    var size: CGFloat = 201920    init(_ name: String, size: CGFloat = 20) { self.name = name; self.size = size }2122    var body: some View {23        Image(name).resizable().scaledToFit().frame(width: size, height: size).accessibilityHidden(true)24    }25}2627// MARK: - Filets et en-têtes2829/// Filet horizontal : la séparation par défaut, plutôt qu'une boîte.30struct Rule: View {31    var strong = false32    var body: some View { Rectangle().fill(strong ? Theme.line2 : Theme.line).frame(height: 1).accessibilityHidden(true) }33}3435/// En-tête de section : titre serif mesuré, et une action à droite si besoin.36struct SectionHeader<Trailing: View>: View {37    let title: String38    var subtitle: String?39    @ViewBuilder var trailing: () -> Trailing4041    init(_ title: String, subtitle: String? = nil, @ViewBuilder trailing: @escaping () -> Trailing) {42        self.title = title; self.subtitle = subtitle; self.trailing = trailing43    }4445    var body: some View {46        HStack(alignment: .firstTextBaseline, spacing: 12) {47            VStack(alignment: .leading, spacing: 3) {48                Text(title).font(.editorial(21)).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)49                if let subtitle { Text(subtitle).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true) }50            }51            Spacer(minLength: 8)52            trailing()53        }54    }55}5657extension SectionHeader where Trailing == EmptyView {58    init(_ title: String, subtitle: String? = nil) { self.init(title, subtitle: subtitle) { EmptyView() } }59}6061/// Lien discret « Tout voir » d'un en-tête.62struct MoreLink: View {63    var label = "Tout voir"64    let action: () -> Void65    var body: some View {66        Button(action: action) {67            HStack(spacing: 3) {68                Text(label)69                Image(systemName: "chevron.right").font(.caption2.weight(.semibold))70            }71            .font(.subheadline.weight(.medium)).foregroundStyle(Theme.brand)72            .frame(minHeight: 44)73            .contentShape(Rectangle())74        }75        .buttonStyle(.plain)76    }77}7879// MARK: - Boutons8081/// Bouton principal : aplat pétrole, coins de 8, texte de la couleur `brand-ink`.82struct PrimaryButtonStyle: ButtonStyle {83    func makeBody(configuration: Configuration) -> some View {84        configuration.label85            .font(.body.weight(.semibold))86            .foregroundStyle(Theme.brandInk)87            .frame(maxWidth: .infinity, minHeight: 48)88            .padding(.horizontal, 16)89            .background(configuration.isPressed ? Theme.brandStrong : Theme.brand, in: RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous))90    }91}9293/// Bouton secondaire : filet, texte asphalte.94struct SecondaryButtonStyle: ButtonStyle {95    func makeBody(configuration: Configuration) -> some View {96        configuration.label97            .font(.subheadline.weight(.medium))98            .foregroundStyle(Theme.ink)99            .frame(minHeight: 44)100            .padding(.horizontal, 14)101            .background(configuration.isPressed ? Theme.surface2 : Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous))102            .overlay(RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))103    }104}105106/// Option à cocher d'un filtre : rectangle aux coins de 8, sélection en pétrole doux.107struct ChoiceChip: View {108    let label: String109    var count: Int?110    var icon: String?111    let selected: Bool112    let action: () -> Void113114    var body: some View {115        Button {116            Haptics.select()117            action()118        } label: {119            HStack(spacing: 6) {120                if let icon { BrandIcon(icon, size: 18) }121                Text(label).font(.subheadline.weight(selected ? .semibold : .regular))122                if let count { Text(Fmt.int(count)).font(.caption).num().foregroundStyle(selected ? Theme.brandStrong.opacity(0.8) : Theme.ink3) }123            }124            .foregroundStyle(selected ? Theme.brandStrong : Theme.ink)125            .padding(.horizontal, 12)126            .frame(minHeight: 44)127            .background(selected ? Theme.brandSoft : Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous))128            .overlay(RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous).strokeBorder(selected ? Theme.brand : Theme.line2, lineWidth: 1))129        }130        .buttonStyle(.plain)131        .accessibilityAddTraits(selected ? .isSelected : [])132        .accessibilityLabel(count.map { "\(label), \(Fmt.int($0))" } ?? label)133    }134}135136// MARK: - États137138/// État vide : la portière fermée, ce qui manque, et quoi faire.139struct EmptyState: View {140    let title: String141    var message: String?142    var actionLabel: String?143    var action: (() -> Void)?144145    var body: some View {146        VStack(spacing: 14) {147            BrandIllustration(kind: .closed, size: 76)148            Text(title).font(.editorial(20)).foregroundStyle(Theme.ink).multilineTextAlignment(.center)149            if let message {150                Text(message).font(.subheadline).foregroundStyle(Theme.ink3).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true)151            }152            if let actionLabel, let action {153                Button(actionLabel, action: action).buttonStyle(SecondaryButtonStyle()).padding(.top, 4)154            }155        }156        .padding(.horizontal, 32).padding(.vertical, 36)157        .frame(maxWidth: .infinity)158    }159}160161/// État d'erreur : dire ce qui s'est passé, proposer de réessayer.162struct ErrorState: View {163    let error: Error164    var retry: (() -> Void)?165166    private var offline: Bool { (error as? APIError)?.isOffline ?? false }167168    var body: some View {169        VStack(spacing: 14) {170            BrandIllustration(kind: .ajar, size: 76)171            Text(offline ? "Hors ligne" : "Le chargement a échoué").font(.editorial(20)).foregroundStyle(Theme.ink)172            Text(offline ? "Aucune copie de cet écran n'est gardée sur l'appareil. Vérifiez votre connexion, puis réessayez."173                         : ((error as? LocalizedError)?.errorDescription ?? "Une erreur est survenue."))174                .font(.subheadline).foregroundStyle(Theme.ink3).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true)175            if let retry { Button("Réessayer", action: retry).buttonStyle(SecondaryButtonStyle()).padding(.top, 4) }176        }177        .padding(.horizontal, 32).padding(.vertical, 36)178        .frame(maxWidth: .infinity)179    }180}181182/// Bandeau discret : la dernière copie connue est affichée faute de réseau.183struct OfflineNote: View {184    var body: some View {185        HStack(spacing: 8) {186            Image(systemName: "wifi.slash").font(.footnote)187            Text("Hors ligne : dernière copie gardée sur l'appareil.").font(.footnote)188        }189        .foregroundStyle(Theme.ink2)190        .padding(.horizontal, 12).padding(.vertical, 9)191        .frame(maxWidth: .infinity, alignment: .leading)192        .background(Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radiusControl, style: .continuous))193        .accessibilityElement(children: .combine)194    }195}196197/// Chargement d'un écran : indicateur de la marque, erreur avec reprise, puis le contenu. Tirer pour rafraîchir.198struct Loadable<T: Sendable, Content: View>: View {199    /// change quand la requête change (relance le chargement)200    let id: String201    let load: @Sendable () async throws -> T202    @ViewBuilder let content: (T) -> Content203204    @State private var value: T?205    @State private var error: Error?206    @State private var attempt = 0207    @State private var offline = false208209    var body: some View {210        Group {211            if let value {212                VStack(spacing: 0) {213                    if offline { OfflineNote().padding(.horizontal, 16).padding(.top, 8) }214                    content(value)215                }216            } else if let error {217                ScrollView { ErrorState(error: error) { self.error = nil; attempt += 1 }.padding(.top, 60) }218            } else {219                VStack { BrandLoader() }.frame(maxWidth: .infinity, maxHeight: .infinity)220            }221        }222        .background(Theme.bg)223        .task(id: "\(id)#\(attempt)") {224            do {225                let v = try await load()226                offline = await APIClient.shared.servedFromCache227                value = v228                error = nil229            } catch is CancellationError {230            } catch {231                if value == nil { self.error = error }232            }233        }234    }235}236237// MARK: - Faits et chiffres238239/// Chiffre clé : grand nombre tabulaire, libellé dessous. Sans boîte.240struct StatFigure: View {241    let value: String242    let label: String243    var detail: String?244245    var body: some View {246        VStack(alignment: .leading, spacing: 3) {247            Text(value).font(.display(22)).num().foregroundStyle(Theme.ink).lineLimit(1).minimumScaleFactor(0.7)248            Text(label).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)249            if let detail { Text(detail).font(.caption).foregroundStyle(Theme.ink3) }250        }251        .frame(maxWidth: .infinity, alignment: .leading)252        .accessibilityElement(children: .combine)253    }254}255256/// Grille de chiffres clés : deux colonnes (une seule aux très grandes tailles de texte).257struct StatGrid<Content: View>: View {258    @Environment(\.dynamicTypeSize) private var typeSize259    @ViewBuilder var content: () -> Content260    var body: some View {261        LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 16, alignment: .topLeading), count: typeSize.isAccessibilitySize ? 1 : 2),262                  alignment: .leading, spacing: 18, content: content)263    }264}265266/// Ligne libellé → valeur, séparée par un filet.267struct FactRow: View {268    let label: String269    let value: String270    /// note discrète sous la valeur (« déduit du modèle »)271    var note: String?272    var icon: String?273    @Environment(\.dynamicTypeSize) private var typeSize274275    var body: some View {276        VStack(spacing: 0) {277            Group {278                if typeSize.isAccessibilitySize {279                    VStack(alignment: .leading, spacing: 3) { labelView; valueView(.leading) }.frame(maxWidth: .infinity, alignment: .leading)280                } else {281                    HStack(alignment: .firstTextBaseline, spacing: 12) { labelView; Spacer(minLength: 8); valueView(.trailing) }282                }283            }284            .padding(.vertical, 11)285            Rule()286        }287        .accessibilityElement(children: .combine)288    }289290    private var labelView: some View {291        HStack(spacing: 8) {292            if let icon { BrandIcon(icon, size: 18).foregroundStyle(Theme.ink3) }293            Text(label).font(.subheadline).foregroundStyle(Theme.ink3)294        }295    }296297    private func valueView(_ align: HorizontalAlignment) -> some View {298        VStack(alignment: align, spacing: 2) {299            Text(value).font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink)300                .multilineTextAlignment(align == .trailing ? .trailing : .leading)301            if let note { Text(note).font(.caption2).foregroundStyle(Theme.ink3) }302        }303    }304}305306/// Barre de répartition horizontale : libellé, barre à plat proportionnelle, compte.307struct BarRow: View {308    let label: String309    let value: Double310    let max: Double311    var valueLabel: String?312    var color: Color = Theme.brand313    var icon: String?314    @State private var shown = 0.0315316    var body: some View {317        VStack(alignment: .leading, spacing: 5) {318            HStack(alignment: .firstTextBaseline) {319                if let icon { BrandIcon(icon, size: 18).foregroundStyle(Theme.ink2) }320                Text(label).font(.subheadline).foregroundStyle(Theme.ink).lineLimit(1)321                Spacer(minLength: 8)322                Text(valueLabel ?? Fmt.int(value)).font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink2)323            }324            GeometryReader { geo in325                ZStack(alignment: .leading) {326                    Rectangle().fill(Theme.surface3)327                    Rectangle().fill(color).frame(width: geo.size.width * CGFloat(max > 0 ? min(1, value / max) : 0) * shown)328                }329                .clipShape(RoundedRectangle(cornerRadius: 2))330            }331            .frame(height: 5)332        }333        .drawOnAppear($shown, duration: 0.6)334        .accessibilityElement(children: .ignore)335        .accessibilityLabel("\(label) : \(valueLabel ?? Fmt.int(value))")336    }337}338339/// Répartition des verdicts d'un ensemble (marque, modèle, ville, commerce) : une barre segmentée à plat et sa340/// légende chiffrée. Les libellés viennent du service.341struct VerdictBreakdown: View {342    /// code ou position du service → nombre de véhicules343    let counts: [String: Int]344345    /// regroupés par position, dans l'ordre de l'échelle346    private var rows: [(code: String, n: Int)] {347        let grouped = VerdictRules.byPosition(counts)348        return VerdictRules.order.compactMap { c in grouped[c].flatMap { $0 > 0 ? (c, $0) : nil } }349    }350351    var body: some View {352        let total = max(1, rows.reduce(0) { $0 + $1.n })353        VStack(alignment: .leading, spacing: 12) {354            GeometryReader { geo in355                HStack(spacing: 2) {356                    ForEach(rows, id: \.code) { r in357                        Rectangle().fill(shade(r.code)).frame(width: max(2, (geo.size.width - CGFloat(rows.count - 1) * 2) * CGFloat(r.n) / CGFloat(total)))358                    }359                }360            }361            .frame(height: 10)362            .clipShape(RoundedRectangle(cornerRadius: 3))363            .accessibilityHidden(true)364            VStack(spacing: 0) {365                ForEach(rows, id: \.code) { r in366                    HStack(spacing: 10) {367                        RoundedRectangle(cornerRadius: 2).fill(shade(r.code)).frame(width: 10, height: 10)368                        Text(VerdictRules.label(for: r.code)).font(.subheadline).foregroundStyle(Theme.ink)369                        Spacer()370                        Text(Fmt.int(r.n)).font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink)371                        Text(Fmt.pct(Double(r.n) * 100 / Double(total), digits: 0)).font(.footnote).num().foregroundStyle(Theme.ink3).frame(minWidth: 44, alignment: .trailing)372                    }373                    .padding(.vertical, 7)374                    .accessibilityElement(children: .combine)375                }376            }377        }378    }379380    /// Cobalt, gris, ocre, brique ; gravier clair pour « sans verdict ».381    private func shade(_ code: String) -> Color {382        code == "aucun" ? Theme.line2 : Theme.color(forCode: code).opacity(code == "dans" ? 0.75 : 1)383    }384}385386/// Mise en page d'un écran défilant : fond givre, colonne de lecture bornée sur iPad, marges de 16.387struct Page<Content: View>: View {388    var spacing: CGFloat = 28389    @ViewBuilder var content: () -> Content390391    var body: some View {392        ScrollView {393            VStack(alignment: .leading, spacing: spacing, content: content)394                .padding(.horizontal, HeroLayout.margin)395                .padding(.top, 8).padding(.bottom, 32)396                .frame(maxWidth: HeroLayout.maxColumn + 2 * HeroLayout.margin, alignment: .leading)397                .frame(maxWidth: .infinity)398        }399        .background(Theme.bg)400    }401}402403/// Ligne de navigation d'un index (marques, villes, outils) : titre, détail, chevron, filet.404struct IndexRow: View {405    let title: String406    var detail: String?407    var value: String?408    var icon: String?409    var systemIcon: String?410411    var body: some View {412        VStack(spacing: 0) {413            HStack(spacing: 12) {414                if let icon { BrandIcon(icon, size: 22).foregroundStyle(Theme.ink2).frame(width: 26) }415                if let systemIcon { Image(systemName: systemIcon).font(.body).foregroundStyle(Theme.ink2).frame(width: 26) }416                VStack(alignment: .leading, spacing: 2) {417                    Text(title).font(.body).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)418                    if let detail { Text(detail).font(.footnote).foregroundStyle(Theme.ink3).multilineTextAlignment(.leading) }419                }420                Spacer(minLength: 8)421                if let value { Text(value).font(.subheadline).num().foregroundStyle(Theme.ink2) }422                Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3.opacity(0.7))423            }424            .padding(.vertical, 12)425            .frame(minHeight: 48)426            .contentShape(Rectangle())427            Rule()428        }429        .accessibilityElement(children: .combine)430        .accessibilityAddTraits(.isButton)431    }432}433
Files main
Menu

Theme