SPB Git

Repository Public

Components.swift 17.3 KB 446 lines swift

1//2//  Fabri-Ka iOS v23//  File: FabriKa/Design/Components.swift4//  Description: composants communs — titres de section, filets, lignes de faits, boutons, pastilles de filtre et5//               d'état (un mot et une forme, jamais la couleur seule), états d'erreur et hors ligne. Filets et6//               espace plutôt que boîtes.7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import SafariServices13import SwiftUI1415/// Titre de section éditorial (New York), avec sur-titre et note facultatifs.16struct SectionHeader<Trailing: View>: View {17    let title: String18    var eyebrow: String?19    var note: String?20    @ViewBuilder var trailing: () -> Trailing2122    init(_ title: String, eyebrow: String? = nil, note: String? = nil, @ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() }) {23        self.title = title; self.eyebrow = eyebrow; self.note = note; self.trailing = trailing24    }2526    var body: some View {27        VStack(alignment: .leading, spacing: 5) {28            if let eyebrow { Text(eyebrow).eyebrowStyle() }29            HStack(alignment: .firstTextBaseline, spacing: 12) {30                Text(title).font(.editorial(22)).foregroundStyle(Theme.ink)31                    .fixedSize(horizontal: false, vertical: true)32                    .accessibilityAddTraits(.isHeader)33                Spacer(minLength: 0)34                trailing()35            }36            if let note {37                Text(note).font(.subheadline).num().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)38            }39        }40        .frame(maxWidth: .infinity, alignment: .leading)41    }42}4344struct MoreLink: View {45    var label = "Tout voir"46    let action: () -> Void4748    var body: some View {49        Button(action: action) {50            HStack(spacing: 3) {51                Text(label)52                Image(systemName: "chevron.right").font(.caption2.weight(.bold))53            }54            .font(.subheadline.weight(.medium))55            .foregroundStyle(Theme.brand)56            .frame(minHeight: 44)57            .contentShape(Rectangle())58        }59        .buttonStyle(.plain)60    }61}6263struct Hairline: View {64    var color: Color = Theme.line65    var body: some View { Rectangle().fill(color).frame(height: 1).accessibilityHidden(true) }66}6768/// Ligne de fait : libellé à gauche, valeur à droite, filet dessous. Empilée en très grand texte.69struct FactRow<Value: View>: View {70    let label: String71    var divider = true72    @ViewBuilder var value: () -> Value73    @Environment(\.dynamicTypeSize) private var typeSize7475    var body: some View {76        VStack(spacing: 0) {77            Group {78                if typeSize.isAccessibilitySize {79                    VStack(alignment: .leading, spacing: 4) { labelView; value() }.frame(maxWidth: .infinity, alignment: .leading)80                } else {81                    HStack(alignment: .firstTextBaseline, spacing: 12) {82                        labelView83                        Spacer(minLength: 8)84                        value().multilineTextAlignment(.trailing)85                    }86                }87            }88            .padding(.vertical, 11)89            if divider { Hairline() }90        }91        .accessibilityElement(children: .combine)92    }9394    private var labelView: some View {95        Text(label).font(.subheadline).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)96    }97}9899extension FactRow where Value == Text {100    init(_ label: String, _ value: String, divider: Bool = true) {101        self.label = label102        self.divider = divider103        self.value = { Text(value).font(.subheadline.weight(.medium)).monospacedDigit().foregroundStyle(Theme.ink) }104    }105}106107/// Ligne de navigation sobre : icône de la marque, titre, précision, chevron ; filet dessous.108struct NavRow: View {109    var icon: String?110    let title: String111    var detail: String?112    var divider = true113    let action: () -> Void114115    var body: some View {116        Button(action: action) {117            VStack(spacing: 0) {118                HStack(spacing: 12) {119                    if let icon {120                        Image(icon).resizable().scaledToFit().frame(width: 24, height: 24).foregroundStyle(Theme.ink2)121                    }122                    VStack(alignment: .leading, spacing: 2) {123                        Text(title).font(.body).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)124                        if let detail {125                            Text(detail).font(.footnote).num().foregroundStyle(Theme.ink3).multilineTextAlignment(.leading)126                        }127                    }128                    Spacer(minLength: 8)129                    Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)130                }131                .padding(.vertical, 12)132                .frame(minHeight: 52)133                if divider { Hairline() }134            }135            .contentShape(Rectangle())136        }137        .buttonStyle(.plain)138    }139}140141// --- Boutons ------------------------------------------------------------------------------------142143struct PrimaryButtonStyle: ButtonStyle {144    @Environment(\.isEnabled) private var enabled145146    func makeBody(configuration: Configuration) -> some View {147        configuration.label148            .font(.body.weight(.semibold))149            .foregroundStyle(Theme.brandInk)150            .multilineTextAlignment(.center)151            .padding(.horizontal, 18).padding(.vertical, 8)152            .frame(maxWidth: .infinity, minHeight: 50)153            .background(Theme.brand.opacity(enabled ? (configuration.isPressed ? 0.82 : 1) : 0.4),154                        in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))155    }156}157158struct SecondaryButtonStyle: ButtonStyle {159    @Environment(\.isEnabled) private var enabled160161    func makeBody(configuration: Configuration) -> some View {162        configuration.label163            .font(.body.weight(.medium))164            .foregroundStyle(Theme.ink.opacity(enabled ? 1 : 0.4))165            .multilineTextAlignment(.center)166            .padding(.horizontal, 16).padding(.vertical, 8)167            .frame(maxWidth: .infinity, minHeight: 50)168            .background(configuration.isPressed ? Theme.surface2 : Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))169            .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))170    }171}172173/// Pastille de filtre (rectangle arrondi, jamais une capsule).174struct Chip: View {175    let label: String176    var selected = false177    var removable = false178    var count: Int?179    let action: () -> Void180181    var body: some View {182        Button(action: action) {183            HStack(spacing: 6) {184                Text(label).lineLimit(1)185                if let count { Text(Fmt.group(count)).num().foregroundStyle(selected ? Theme.brandStrong.opacity(0.8) : Theme.ink3) }186                if removable { Image(systemName: "xmark").font(.caption2.weight(.bold)) }187            }188            .font(.subheadline.weight(selected ? .semibold : .regular))189            .foregroundStyle(selected ? Theme.brandStrong : Theme.ink)190            .padding(.horizontal, 12)191            .frame(minHeight: 38)192            .background(selected ? Theme.brandSoft : Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))193            .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(selected ? Theme.brand.opacity(0.35) : Theme.line2, lineWidth: 1))194            .frame(minHeight: 44)195            .contentShape(Rectangle())196        }197        .buttonStyle(.plain)198        .accessibilityAddTraits(selected ? .isSelected : [])199        .accessibilityHint(removable ? "Retire ce filtre" : "")200    }201}202203/// Disposition en lignes qui passent à la ligne (pastilles).204struct FlowLayout: Layout {205    var spacing: CGFloat = 8206207    private func rows(_ width: CGFloat, _ subviews: Subviews) -> [[(Int, CGSize)]] {208        var rows: [[(Int, CGSize)]] = [[]]209        var x: CGFloat = 0210        for (i, v) in subviews.enumerated() {211            let s = v.sizeThatFits(ProposedViewSize(width: width, height: nil))212            if x + s.width > width, !rows[rows.count - 1].isEmpty { rows.append([]); x = 0 }213            rows[rows.count - 1].append((i, s))214            x += s.width + spacing215        }216        return rows217    }218219    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {220        let w = proposal.width ?? 320221        let r = rows(w, subviews)222        let h = r.map { $0.map(\.1.height).max() ?? 0 }.reduce(0, +) + spacing * CGFloat(max(0, r.count - 1))223        return CGSize(width: w, height: h)224    }225226    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {227        var y = bounds.minY228        for row in rows(bounds.width, subviews) {229            var x = bounds.minX230            let h = row.map(\.1.height).max() ?? 0231            for (i, s) in row {232                subviews[i].place(at: CGPoint(x: x, y: y + (h - s.height) / 2), proposal: ProposedViewSize(width: min(s.width, bounds.width), height: s.height))233                x += s.width + spacing234            }235            y += h + spacing236        }237    }238}239240// --- États de fait ------------------------------------------------------------------------------241242/// Pastille d'état : une forme, un mot (et une date pour « Nouveau »), la couleur d'état sur son fond doux.243struct StatusPill: View {244    enum Kind: Equatable {245        case inStock, soldOut, new(String?), verified, unreachable246247        var word: String {248            switch self {249            case .inStock: "En stock"250            case .soldOut: "Épuisé"251            case .new(let date): date.map { "Nouveau · vu le \($0)" } ?? "Nouveau"252            case .verified: "Lieu vérifié"253            case .unreachable: "Injoignable"254            }255        }256        var color: Color {257            switch self {258            case .inStock, .verified: Theme.good259            case .soldOut: Theme.fair260            case .new: Theme.high261            case .unreachable: Theme.bad262            }263        }264        var soft: Color {265            switch self {266            case .inStock, .verified: Theme.goodSoft267            case .soldOut: Theme.fairSoft268            case .new: Theme.highSoft269            case .unreachable: Theme.badSoft270            }271        }272    }273274    let kind: Kind275    var compact = false276    /// la forme seule (le mot reste lu par VoiceOver)277    var wordless = false278279    var body: some View {280        // faute de place (carte étroite, prix en fourchette), la forme reste et le mot passe à VoiceOver281        Group {282            if wordless { pill(word: false) } else {283                ViewThatFits(in: .horizontal) {284                    pill(word: true)285                    pill(word: false)286                }287            }288        }289        .accessibilityElement(children: .ignore)290        .accessibilityLabel(kind.word)291    }292293    private func pill(word: Bool) -> some View {294        HStack(spacing: 5) {295            StatusGlyph(kind: kind).frame(width: 9, height: 9)296            if word {297                Text(kind.word).font(.system(size: Font.scaled(compact ? 11.5 : 12.5, max: 18), weight: .semibold)).lineLimit(1)298                    .fixedSize()299            }300        }301        .foregroundStyle(kind.color)302        .padding(.horizontal, compact ? 6 : 8).padding(.vertical, compact ? 3 : 4)303        .background(kind.soft, in: RoundedRectangle(cornerRadius: Theme.radiusPill, style: .continuous))304    }305}306307/// La forme d'un état : rond plein (en stock), rond barré (épuisé), losange (nouveau), coche (lieu vérifié), croix.308struct StatusGlyph: View {309    let kind: StatusPill.Kind310311    var body: some View {312        Canvas { ctx, size in313            let r = CGRect(origin: .zero, size: size).insetBy(dx: 0.8, dy: 0.8)314            let color = GraphicsContext.Shading.color(kind.color)315            let stroke = StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round)316            switch kind {317            case .inStock:318                ctx.fill(Path(ellipseIn: r.insetBy(dx: 0.6, dy: 0.6)), with: color)319            case .soldOut:320                ctx.stroke(Path(ellipseIn: r), with: color, style: stroke)321                var p = Path(); p.move(to: CGPoint(x: r.minX + 1.2, y: r.maxY - 1.2)); p.addLine(to: CGPoint(x: r.maxX - 1.2, y: r.minY + 1.2))322                ctx.stroke(p, with: color, style: stroke)323            case .new:324                var p = Path()325                p.move(to: CGPoint(x: r.midX, y: r.minY)); p.addLine(to: CGPoint(x: r.maxX, y: r.midY))326                p.addLine(to: CGPoint(x: r.midX, y: r.maxY)); p.addLine(to: CGPoint(x: r.minX, y: r.midY)); p.closeSubpath()327                ctx.fill(p, with: color)328            case .verified:329                var p = Path()330                p.move(to: CGPoint(x: r.minX, y: r.midY + 0.5)); p.addLine(to: CGPoint(x: r.minX + r.width * 0.36, y: r.maxY - 1))331                p.addLine(to: CGPoint(x: r.maxX, y: r.minY + 1))332                ctx.stroke(p, with: color, style: stroke)333            case .unreachable:334                var p = Path()335                p.move(to: CGPoint(x: r.minX + 1, y: r.minY + 1)); p.addLine(to: CGPoint(x: r.maxX - 1, y: r.maxY - 1))336                p.move(to: CGPoint(x: r.maxX - 1, y: r.minY + 1)); p.addLine(to: CGPoint(x: r.minX + 1, y: r.maxY - 1))337                ctx.stroke(p, with: color, style: stroke)338            }339        }340        .accessibilityHidden(true)341    }342}343344// --- États de page ------------------------------------------------------------------------------345346/// Erreur : dire ce qui s'est passé, proposer de réessayer.347struct ErrorState: View {348    let error: Error349    var retry: (() -> Void)?350351    private var offline: Bool { (error as? APIError)?.isOffline ?? false }352    private var notFound: Bool { (error as? APIError) == .notFound }353354    var body: some View {355        EmptyBracket(title: offline ? "Pas de connexion" : (notFound ? "Introuvable" : "Chargement impossible"),356                     message: offline357                         ? "Le répertoire ne peut pas être lu sans réseau. Vos favoris, vos boutiques suivies et les fiches déjà consultées restent disponibles."358                         : (notFound ? "Cette page n'existe pas ou n'est plus publiée."359                            : ((error as? LocalizedError)?.errorDescription ?? "Une erreur est survenue.")),360                     actionLabel: retry == nil || notFound ? nil : "Réessayer", action: retry)361            .accessibilityIdentifier("error-state")362    }363}364365/// Bandeau discret quand une réponse vient du cache faute de réseau.366struct StaleBanner: View {367    var body: some View {368        HStack(spacing: 8) {369            Image(systemName: "wifi.slash").font(.footnote)370            Text("Hors ligne : dernière version consultée.").font(.footnote)371            Spacer(minLength: 0)372        }373        .foregroundStyle(Theme.fair)374        .padding(.horizontal, 12).padding(.vertical, 9)375        .background(Theme.fairSoft, in: RoundedRectangle(cornerRadius: Theme.radiusPill, style: .continuous))376        .accessibilityElement(children: .combine)377        .accessibilityIdentifier("stale-banner")378    }379}380381/// Précision honnête en petit : ce qu'on sait, ce qu'on ne sait pas.382struct HonestNote: View {383    let text: String384    var icon: String?385386    var body: some View {387        HStack(alignment: .firstTextBaseline, spacing: 8) {388            if let icon {389                Image(icon).resizable().scaledToFit().frame(width: 16, height: 16).foregroundStyle(Theme.ink3)390                    .alignmentGuide(.firstTextBaseline) { d in d[.bottom] - 3 }391            }392            Text(text).font(.footnote).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)393        }394        .frame(maxWidth: .infinity, alignment: .leading)395        .accessibilityElement(children: .combine)396    }397}398399/// État d'un chargement de page.400enum Loadable<T: Sendable>: Sendable {401    case loading402    case loaded(T, stale: Bool)403    case failed(APIError)404405    var value: T? { if case .loaded(let v, _) = self { v } else { nil } }406    var isStale: Bool { if case .loaded(_, let s) = self { s } else { false } }407    var error: APIError? { if case .failed(let e) = self { e } else { nil } }408409    @MainActor static func from(_ work: () async throws -> Fetched<T>) async -> Loadable<T>? {410        do {411            let f = try await work()412            return .loaded(f.value, stale: f.stale)413        } catch is CancellationError {414            return nil415        } catch let e as APIError {416            return .failed(e)417        } catch {418            return .failed(.offline)419        }420    }421}422423/// Page web de la boutique, dans l'app (SFSafariViewController) : on quitte Fabri-Ka, on le voit.424struct SafariView: UIViewControllerRepresentable {425    let url: URL426427    func makeUIViewController(context: Context) -> SFSafariViewController {428        let c = SFSafariViewController(url: url)429        c.preferredControlTintColor = UIColor(Theme.brand)430        return c431    }432433    func updateUIViewController(_ controller: SFSafariViewController, context: Context) {}434}435436struct IdentifiedURL: Identifiable {437    let url: URL438    var id: String { url.absoluteString }439440    /// Adresse web ouvrable (http ou https seulement).441    init?(_ string: String?) {442        guard let string, let u = URL(string: string), let s = u.scheme?.lowercased(), s == "https" || s == "http" else { return nil }443        url = u444    }445}446
Files main
Menu

Theme