SPB Git

Repository Public

Components.swift 15.4 KB 386 lines swift

1//2//  Food-Ka iOS v23//  File: FoodKa/Design/Components.swift4//  Description: composants communs — titres de section, filets, lignes de faits, boutons, pastilles de filtre,5//               états de chargement, vides, d'erreur et hors ligne. Filets et espace plutôt que boîtes.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SafariServices12import SwiftUI1314struct SectionHeader<Trailing: View>: View {15    let title: String16    var eyebrow: String?17    var note: String?18    @ViewBuilder var trailing: () -> Trailing1920    init(_ title: String, eyebrow: String? = nil, note: String? = nil, @ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() }) {21        self.title = title; self.eyebrow = eyebrow; self.note = note; self.trailing = trailing22    }2324    var body: some View {25        VStack(alignment: .leading, spacing: 5) {26            if let eyebrow { Text(eyebrow).eyebrowStyle() }27            HStack(alignment: .firstTextBaseline, spacing: 12) {28                Text(title).font(.editorial(21)).foregroundStyle(Theme.ink)29                    .fixedSize(horizontal: false, vertical: true)30                    .accessibilityAddTraits(.isHeader)31                Spacer(minLength: 0)32                trailing()33            }34            if let note {35                Text(note).font(.subheadline).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)36            }37        }38        .frame(maxWidth: .infinity, alignment: .leading)39    }40}4142struct MoreLink: View {43    var label = "Tout voir"44    let action: () -> Void45    var body: some View {46        Button(action: action) {47            HStack(spacing: 3) {48                Text(label)49                Image(systemName: "chevron.right").font(.caption2.weight(.bold))50            }51            .font(.subheadline.weight(.medium))52            .foregroundStyle(Theme.brand)53            .frame(minHeight: 44)54            .contentShape(Rectangle())55        }56        .buttonStyle(.plain)57    }58}5960struct Hairline: View {61    var color: Color = Theme.line62    var body: some View { Rectangle().fill(color).frame(height: 1).accessibilityHidden(true) }63}6465/// Ligne « libellé … valeur » ; s'empile en très grand texte.66struct FactRow<Value: View>: View {67    let label: String68    var divider = true69    @ViewBuilder var value: () -> Value70    @Environment(\.dynamicTypeSize) private var typeSize7172    var body: some View {73        VStack(spacing: 0) {74            Group {75                if typeSize.isAccessibilitySize {76                    VStack(alignment: .leading, spacing: 4) { labelView; value() }.frame(maxWidth: .infinity, alignment: .leading)77                } else {78                    HStack(alignment: .firstTextBaseline, spacing: 12) {79                        labelView80                        Spacer(minLength: 8)81                        value().multilineTextAlignment(.trailing)82                    }83                }84            }85            .padding(.vertical, 11)86            if divider { Hairline() }87        }88        .accessibilityElement(children: .combine)89    }9091    private var labelView: some View {92        Text(label).font(.subheadline).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)93    }94}9596extension FactRow where Value == Text {97    init(_ label: String, _ value: String, divider: Bool = true) {98        self.label = label99        self.divider = divider100        self.value = { Text(value).font(.subheadline.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.ink) }101    }102}103104/// Chiffre nommé (marché, enseigne).105struct Figure: View {106    let label: String107    let value: String108    var note: String?109    var body: some View {110        VStack(alignment: .leading, spacing: 3) {111            Text(label).font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)112            Text(value).font(.display(20)).num().foregroundStyle(Theme.ink).lineLimit(1).minimumScaleFactor(0.6)113            if let note { Text(note).font(.caption).num().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true) }114        }115        .frame(maxWidth: .infinity, alignment: .leading)116        .accessibilityElement(children: .combine)117    }118}119120struct FigureGrid<Content: View>: View {121    @ViewBuilder var content: () -> Content122    @Environment(\.dynamicTypeSize) private var typeSize123    var body: some View {124        LazyVGrid(columns: typeSize.isAccessibilitySize ? [GridItem(.flexible())] : [GridItem(.flexible(), spacing: 16), GridItem(.flexible(), spacing: 16)],125                  alignment: .leading, spacing: 18) { content() }126    }127}128129// --- Boutons ------------------------------------------------------------------------------------130131struct PrimaryButtonStyle: ButtonStyle {132    @Environment(\.isEnabled) private var enabled133    func makeBody(configuration: Configuration) -> some View {134        configuration.label135            .font(.body.weight(.semibold))136            .foregroundStyle(Theme.brandInk)137            .padding(.horizontal, 18)138            .frame(maxWidth: .infinity, minHeight: 50)139            .background(Theme.brand.opacity(enabled ? (configuration.isPressed ? 0.82 : 1) : 0.4),140                        in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))141    }142}143144struct SecondaryButtonStyle: ButtonStyle {145    @Environment(\.isEnabled) private var enabled146    func makeBody(configuration: Configuration) -> some View {147        configuration.label148            .font(.body.weight(.medium))149            .foregroundStyle(Theme.ink.opacity(enabled ? 1 : 0.4))150            .padding(.horizontal, 16)151            .frame(maxWidth: .infinity, minHeight: 50)152            .background(configuration.isPressed ? Theme.surface2 : Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))153            .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))154    }155}156157/// Pastille de filtre ou de choix : rectangle aux coins mesurés (pas de capsule).158struct Chip: View {159    let label: String160    var selected = false161    var removable = false162    var count: Int?163    let action: () -> Void164165    var body: some View {166        Button(action: action) {167            HStack(spacing: 6) {168                Text(label).lineLimit(1)169                if let count { Text(Fmt.group(count)).num().foregroundStyle(selected ? Theme.brandStrong.opacity(0.8) : Theme.ink3) }170                if removable { Image(systemName: "xmark").font(.caption2.weight(.bold)) }171            }172            .font(.subheadline.weight(selected ? .semibold : .regular))173            .foregroundStyle(selected ? Theme.brandStrong : Theme.ink)174            .padding(.horizontal, 12)175            .frame(minHeight: 38)176            .background(selected ? Theme.brandSoft : Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))177            .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(selected ? Theme.brand.opacity(0.35) : Theme.line2, lineWidth: 1))178            .frame(minHeight: 44)179            .contentShape(Rectangle())180        }181        .buttonStyle(.plain)182        .accessibilityAddTraits(selected ? .isSelected : [])183        .accessibilityHint(removable ? "Retire ce filtre" : "")184    }185}186187/// Rangée de pastilles qui passe à la ligne.188struct FlowLayout: Layout {189    var spacing: CGFloat = 8190191    private func rows(_ width: CGFloat, _ subviews: Subviews) -> [[(Int, CGSize)]] {192        var rows: [[(Int, CGSize)]] = [[]]193        var x: CGFloat = 0194        for (i, v) in subviews.enumerated() {195            let s = v.sizeThatFits(ProposedViewSize(width: width, height: nil))196            if x + s.width > width, !rows[rows.count - 1].isEmpty { rows.append([]); x = 0 }197            rows[rows.count - 1].append((i, s))198            x += s.width + spacing199        }200        return rows201    }202203    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {204        let w = proposal.width ?? 320205        let r = rows(w, subviews)206        let h = r.map { $0.map(\.1.height).max() ?? 0 }.reduce(0, +) + spacing * CGFloat(max(0, r.count - 1))207        return CGSize(width: w, height: h)208    }209210    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {211        var y = bounds.minY212        for row in rows(bounds.width, subviews) {213            var x = bounds.minX214            let h = row.map(\.1.height).max() ?? 0215            for (i, s) in row {216                subviews[i].place(at: CGPoint(x: x, y: y + (h - s.height) / 2), proposal: ProposedViewSize(width: min(s.width, bounds.width), height: s.height))217                x += s.width + spacing218            }219            y += h + spacing220        }221    }222}223224// --- États --------------------------------------------------------------------------------------225226/// Chargement (attente réelle seulement) : les tablettes sont là, vides ; une étiquette de papier sans chiffre227/// glisse d'un bout à l'autre du premier rail.228struct LoadingShelves: View {229    var rows = 4230    var label = "Chargement"231    let allowed = MotionAllowed()232    @State private var slide = false233234    var body: some View {235        VStack(alignment: .leading, spacing: 34) {236            ForEach(0..<rows, id: \.self) { i in237                VStack(alignment: .leading, spacing: 8) {238                    Capsule().fill(Theme.line2).frame(height: 3)239                    if i == 0 {240                        GeometryReader { geo in241                            RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous)242                                .fill(Theme.tagPaper)243                                .overlay(RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))244                                .frame(width: 62, height: 26)245                                .offset(x: slide && allowed.value ? geo.size.width - 62 : 0)246                        }247                        .frame(height: 26)248                    } else {249                        RoundedRectangle(cornerRadius: 4).fill(Theme.surface2).frame(width: i % 2 == 0 ? 150 : 210, height: 12)250                    }251                }252            }253        }254        .padding(.vertical, 24)255        .frame(maxWidth: .infinity, alignment: .leading)256        .onAppear {257            guard allowed.value else { return }258            withAnimation(.timingCurve(0.3, 0, 0.15, 1, duration: 1.4).repeatForever(autoreverses: true)) { slide = true }259        }260        .accessibilityElement(children: .ignore)261        .accessibilityLabel(label)262    }263}264265/// État vide : la tablette seule, sans produit, l'étiquette portant un tiret. Dit ce qui manque et quoi faire.266struct EmptyShelf: View {267    let title: String268    var message: String?269    var actionLabel: String?270    var action: (() -> Void)?271272    var body: some View {273        VStack(alignment: .leading, spacing: 14) {274            VStack(alignment: .trailing, spacing: 8) {275                Capsule().fill(Theme.shelf).frame(height: 4)276                Text("—")277                    .font(.display(15)).foregroundStyle(Theme.ink3)278                    .frame(width: 62, height: 26)279                    .overlay(RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous)280                        .strokeBorder(Theme.line2, style: StrokeStyle(lineWidth: 1, dash: [4, 3])))281            }282            .frame(maxWidth: 220)283            .padding(.top, 40)284            .accessibilityHidden(true)285            Text(title).font(.editorial(21)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)286            if let message {287                Text(message).font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)288            }289            if let actionLabel, let action {290                Button(actionLabel, action: action).buttonStyle(SecondaryButtonStyle()).frame(maxWidth: 280)291                    .padding(.top, 4)292            }293        }294        .frame(maxWidth: .infinity, alignment: .leading)295        .padding(.vertical, 24)296        .accessibilityElement(children: .contain)297    }298}299300/// Erreur de chargement, avec « Réessayer ». Une panne de réseau ne se confond pas avec un contenu introuvable.301struct ErrorState: View {302    let error: Error303    var retry: (() -> Void)?304305    private var offline: Bool { (error as? APIError)?.isOffline ?? false }306    private var notFound: Bool { (error as? APIError) == .notFound }307308    var body: some View {309        EmptyShelf(title: offline ? "Pas de connexion" : (notFound ? "Introuvable" : "Chargement impossible"),310                   message: offline311                       ? "Les prix ne peuvent pas être relevés sans réseau. Votre liste d'épicerie et vos produits suivis restent disponibles."312                       : (notFound ? "Ce contenu n'existe pas ou n'est plus publié."313                          : ((error as? LocalizedError)?.errorDescription ?? "Une erreur est survenue.")),314                   actionLabel: retry == nil || notFound ? nil : "Réessayer", action: retry)315            .accessibilityIdentifier("error-state")316    }317}318319/// Bandeau discret : les données affichées viennent du cache, faute de réseau.320struct StaleBanner: View {321    var body: some View {322        HStack(spacing: 8) {323            Image(systemName: "wifi.slash").font(.footnote)324            Text("Hors ligne : dernière version consultée.").font(.footnote)325            Spacer(minLength: 0)326        }327        .foregroundStyle(Theme.high)328        .padding(.horizontal, 12).padding(.vertical, 9)329        .background(Theme.highSoft, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))330        .accessibilityElement(children: .combine)331        .accessibilityIdentifier("stale-banner")332    }333}334335/// Note honnête sur une limite des données (appariement, prix hors Québec, mentions indicatives).336struct HonestNote: View {337    let text: String338    var icon = "info.circle"339    var body: some View {340        HStack(alignment: .firstTextBaseline, spacing: 8) {341            Image(systemName: icon).font(.footnote).foregroundStyle(Theme.ink3)342            Text(text).font(.footnote).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)343        }344        .frame(maxWidth: .infinity, alignment: .leading)345        .accessibilityElement(children: .combine)346    }347}348349/// Chargement générique d'une ressource : en cours, valeur (peut-être du cache), erreur.350enum Loadable<T: Sendable>: Sendable {351    case loading352    case loaded(T, stale: Bool)353    case failed(APIError)354355    var value: T? { if case .loaded(let v, _) = self { v } else { nil } }356    var isStale: Bool { if case .loaded(_, let s) = self { s } else { false } }357358    @MainActor static func from(_ work: () async throws -> Fetched<T>) async -> Loadable<T>? {359        do {360            let f = try await work()361            return .loaded(f.value, stale: f.stale)362        } catch is CancellationError {363            return nil364        } catch let e as APIError {365            return .failed(e)366        } catch {367            return .failed(.offline)368        }369    }370}371372struct SafariView: UIViewControllerRepresentable {373    let url: URL374    func makeUIViewController(context: Context) -> SFSafariViewController {375        let c = SFSafariViewController(url: url)376        c.preferredControlTintColor = UIColor(Theme.brand)377        return c378    }379    func updateUIViewController(_ controller: SFSafariViewController, context: Context) {}380}381382struct IdentifiedURL: Identifiable {383    let url: URL384    var id: String { url.absoluteString }385}386
Files main
Menu

Theme