SPB Git

Repository Public

Components.swift 10.3 KB 257 lines swift

1//2//  VQuant iOS3//  File: VQuant/DesignSystem/Components.swift4//  Description: Reusable interface pieces: freshness badge, change label, cards, quote rows, load / error / offline states.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import SwiftUI1112/// Says where a displayed value comes from: live, delayed, last close, device copy, or unavailable.13struct FreshnessBadge: View {14    let freshness: DataFreshness15    var compact = false1617    private var spec: (text: String, detail: String, color: Color, symbol: String) {18        switch freshness {19        // "Interrogé", never "en direct": VQuant has no streaming feed; a quote is fetched on request (CONTRACT §3).20        case .live: ("Interrogé", "Cours demandé au fournisseur à l’instant", Theme.up, "arrow.triangle.2.circlepath")21        case .delayed(let t): ("Différé", "Dernière transaction \(Fmt.relative(t))", Theme.warning, "clock")22        case .historical(let t): ("Clôture", t.map { "Dernière valeur officielle, \(Fmt.dateTime($0))" } ?? "Dernière valeur officielle", Theme.textSecondary, "calendar")23        case .cached(let t): ("Copie locale", "Enregistrée \(Fmt.relative(t)) — réseau indisponible", Theme.warning, "internaldrive")24        case .unavailable: ("Indisponible", "Aucune donnée n’a pu être obtenue", Theme.down, "exclamationmark.triangle")25        }26    }2728    var body: some View {29        let s = spec30        HStack(spacing: 4) {31            Image(systemName: s.symbol).imageScale(.small)32            Text(compact ? s.text : "\(s.text) · \(shortDetail)")33        }34        .font(.caption2.weight(.semibold))35        .foregroundStyle(s.color)36        .padding(.horizontal, 7).padding(.vertical, 3)37        .background(s.color.opacity(0.12), in: Capsule())38        .accessibilityElement(children: .ignore)39        .accessibilityAddTraits(.isStaticText)40        .accessibilityLabel("\(s.text). \(s.detail)")41    }4243    private var shortDetail: String {44        switch freshness {45        case .live: "à l’instant"46        case .delayed(let t): Fmt.time(t)47        case .historical(let t): t.map(Fmt.dateTime) ?? "—"48        case .cached(let t): Fmt.relative(t)49        case .unavailable: "—"50        }51    }52}5354/// A change with its sign, an arrow and a colour: direction is never conveyed by colour alone.55struct ChangeLabel: View {56    var percent: Double?57    var absolute: Double?58    var font: Font = .subheadline59    var body: some View {60        let v = percent ?? absolute61        HStack(spacing: 3) {62            if let v, v != 0 { Image(systemName: v > 0 ? "arrow.up.right" : "arrow.down.right").imageScale(.small) }63            if let absolute { Text(Fmt.signed(absolute)) }64            if let percent { Text(absolute == nil ? Fmt.percent(percent) : "(\(Fmt.percent(percent)))") }65            if percent == nil && absolute == nil { Text("—") }66        }67        .font(font.monospacedDigit())68        .foregroundStyle(Theme.direction(v))69        .accessibilityElement(children: .ignore)70        .accessibilityAddTraits(.isStaticText)71        .accessibilityLabel(accessibility)72    }73    private var accessibility: String {74        guard let v = percent ?? absolute else { return "Variation inconnue" }75        let dir = v > 0 ? "en hausse de" : v < 0 ? "en baisse de" : "inchangé"76        if let percent { return v == 0 ? dir : "\(dir) \(Fmt.percent(abs(percent)).replacingOccurrences(of: "+", with: ""))" }77        return "\(dir) \(Fmt.price(abs(v)))"78    }79}8081struct Card<Content: View>: View {82    var title: String?83    var systemImage: String?84    @ViewBuilder var content: Content85    var trailing: AnyView?8687    init(_ title: String? = nil, systemImage: String? = nil, trailing: AnyView? = nil, @ViewBuilder content: () -> Content) {88        self.title = title; self.systemImage = systemImage; self.trailing = trailing; self.content = content()89    }9091    var body: some View {92        VStack(alignment: .leading, spacing: 10) {93            if let title {94                HStack {95                    Label { Text(title.uppercased()).tracking(0.9) } icon: { if let systemImage { Image(systemName: systemImage) } }96                        .font(.caption.weight(.semibold)).foregroundStyle(Theme.textSecondary)97                        .accessibilityLabel(title)98                        .accessibilityAddTraits(.isHeader)99                    Spacer()100                    trailing101                }102            }103            content104        }105        .padding(14)106        .frame(maxWidth: .infinity, alignment: .leading)107        .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.corner, style: .continuous))108        .overlay(RoundedRectangle(cornerRadius: Theme.corner, style: .continuous).strokeBorder(Theme.border, lineWidth: 1))109    }110}111112/// One line of a quote list: symbol, name, price, change.113struct QuoteRow: View {114    let symbol: String115    var name: String?116    var quote: Quote?117    var failed = false118119    var body: some View {120        HStack(spacing: 12) {121            VStack(alignment: .leading, spacing: 2) {122                Text(symbol.replacingOccurrences(of: "^", with: "")).font(.body.weight(.semibold))123                if let n = name ?? quote?.name { Text(n).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(2) }124            }125            Spacer(minLength: 8)126            if let quote {127                VStack(alignment: .trailing, spacing: 2) {128                    Text(Fmt.price(quote.price)).font(.mono(.callout, weight: .medium)).lineLimit(1).fixedSize()129                    ChangeLabel(percent: quote.changePercent, font: .caption)130                }131            } else if failed {132                Label("Indisponible", systemImage: "exclamationmark.triangle").font(.caption).foregroundStyle(Theme.textSecondary).labelStyle(.titleAndIcon)133            } else {134                ProgressView().controlSize(.small)135            }136        }137        .contentShape(Rectangle())138        .accessibilityElement(children: .combine)139    }140}141142/// Banner shown at the top of a screen while the device is offline.143struct OfflineBanner: View {144    @Environment(AppModel.self) private var model145    var body: some View {146        if !model.network.isOnline {147            Label("Hors ligne — données enregistrées sur l’appareil, actions en direct désactivées", systemImage: "wifi.slash")148                .font(.footnote.weight(.medium))149                .foregroundStyle(Theme.warning)150                .frame(maxWidth: .infinity, alignment: .leading)151                .padding(.horizontal, 14).padding(.vertical, 8)152                .background(Theme.warning.opacity(0.12))153                .accessibilityIdentifier("offline-banner")154        }155    }156}157158/// Full-area state for a list that has nothing to show: loading, failed, or empty.159struct StateView: View {160    enum Kind { case loading, empty, failed }161    var kind: Kind162    var title: String163    var message: String?164    var systemImage = "tray"165    var retry: (() -> Void)?166167    var body: some View {168        switch kind {169        case .loading:170            VStack(spacing: 10) { ProgressView(); Text(title).font(.footnote).foregroundStyle(Theme.textSecondary) }171                .frame(maxWidth: .infinity, minHeight: 120)172        case .empty, .failed:173            ContentUnavailableView {174                Label(title, systemImage: kind == .failed ? "exclamationmark.triangle" : systemImage)175            } description: {176                if let message { Text(message) }177            } actions: {178                if let retry { Button("Réessayer", action: retry).buttonStyle(.bordered) }179            }180        }181    }182}183184extension View {185    /// Shows `error` in an alert and clears it when dismissed.186    func errorAlert(_ error: Binding<String?>) -> some View {187        alert("Action impossible", isPresented: Binding(get: { error.wrappedValue != nil }, set: { if !$0 { error.wrappedValue = nil } })) {188            Button("OK", role: .cancel) {}189        } message: { Text(error.wrappedValue ?? "") }190    }191192    /// Disabled, with the reason readable by VoiceOver, while the device is offline.193    func requiresNetwork(_ online: Bool) -> some View {194        disabled(!online).accessibilityHint(online ? "" : "Indisponible hors ligne")195    }196}197198/// Label–value line used in detail screens.199struct KeyValueRow: View {200    var key: String201    var value: String202    var body: some View {203        HStack(alignment: .firstTextBaseline) {204            Text(key).foregroundStyle(Theme.textSecondary)205            Spacer(minLength: 12)206            Text(value).monospacedDigit().multilineTextAlignment(.trailing)207        }208        .font(.subheadline)209        .accessibilityElement(children: .combine)210    }211}212213struct SectionHeader: View {214    var title: String215    var action: (title: String, run: () -> Void)?216    var body: some View {217        HStack {218            Text(title).font(.serif(.title3)).accessibilityAddTraits(.isHeader)219            Spacer()220            if let action { Button(action.title, action: action.run).font(.subheadline) }221        }222    }223}224225/// Status pill of a server job.226struct JobStatusBadge: View {227    var text: String228    var color: Color229    var running = false230    var body: some View {231        HStack(spacing: 5) {232            if running { ProgressView().controlSize(.mini) }233            Text(text)234        }235        .font(.caption2.weight(.semibold)).foregroundStyle(color)236        .padding(.horizontal, 7).padding(.vertical, 3).background(color.opacity(0.12), in: Capsule())237    }238    static func generation(_ s: GenerationStatus) -> JobStatusBadge {239        switch s {240        case .running: JobStatusBadge(text: "En cours", color: Theme.orange, running: true)241        case .done: JobStatusBadge(text: "Terminée", color: Theme.up)242        case .cancelled: JobStatusBadge(text: "Arrêtée", color: Theme.textSecondary)243        case .error: JobStatusBadge(text: "Interrompue", color: Theme.down)244        case .unknown: JobStatusBadge(text: "État inconnu", color: Theme.textSecondary)245        }246    }247    static func quant(_ s: QuantStatus) -> JobStatusBadge {248        switch s {249        case .running: JobStatusBadge(text: "En cours", color: Theme.orange, running: true)250        case .done: JobStatusBadge(text: "Terminé", color: Theme.up)251        case .error: JobStatusBadge(text: "Échec", color: Theme.down)252        case .interrupted: JobStatusBadge(text: "Interrompu", color: Theme.warning)253        case .unknown: JobStatusBadge(text: "État inconnu", color: Theme.textSecondary)254        }255    }256}257
Files main
Menu

Theme