SPB Git

Repository Public

StatusViews.swift 15.6 KB 333 lines swift

1import SwiftUI23/// Icon + text badge. The text is always present; the icon shape differs per tone.4public struct StatusBadge: View {5    @Environment(\.mccTheme) private var theme6    private let tone: StatusTone7    private let label: String8    private let compact: Bool9    public init(_ label: String, tone: StatusTone, compact: Bool = false) {10        self.label = label; self.tone = tone; self.compact = compact11    }12    public var body: some View {13        HStack(spacing: Tokens.Space.s2) {14            Image(systemName: tone.symbol).imageScale(.small).accessibilityHidden(true)15            Text(label).fixedSize(horizontal: false, vertical: true)16        }17        .font(compact ? .caption : .callout)18        .fontWeight(.medium)19        .foregroundStyle(tone.color(theme))20        .padding(.horizontal, compact ? Tokens.Space.s3 - 2 : Tokens.Space.s3)21        .padding(.vertical, compact ? 1 : Tokens.Space.s1)22        .background(tone.muted(theme), in: Capsule())23        .overlay(Capsule().strokeBorder(tone.color(theme).opacity(theme.highContrast ? 0.9 : 0.35), lineWidth: 1))24        .accessibilityElement(children: .ignore)25        .accessibilityLabel(label)26    }27}2829/// Icon + text, without the pill: for dense tables.30public struct StatusLabel: View {31    @Environment(\.mccTheme) private var theme32    private let tone: StatusTone33    private let label: String34    public init(_ label: String, tone: StatusTone) { self.label = label; self.tone = tone }35    public var body: some View {36        HStack(spacing: Tokens.Space.s2) {37            Image(systemName: tone.symbol).imageScale(.small).foregroundStyle(tone.color(theme)).accessibilityHidden(true)38            Text(label).foregroundStyle(theme.textPrimary).fixedSize(horizontal: false, vertical: true)39        }40        .accessibilityElement(children: .ignore)41        .accessibilityLabel(label)42    }43}4445/// A count with a tone and a caption ("3 critiques").46public struct CountTile: View {47    @Environment(\.mccTheme) private var theme48    private let value: String49    private let caption: String50    private let tone: StatusTone51    public init(value: String, caption: String, tone: StatusTone = .neutral) {52        self.value = value; self.caption = caption; self.tone = tone53    }54    public var body: some View {55        VStack(alignment: .leading, spacing: Tokens.Space.s1) {56            HStack(spacing: Tokens.Space.s2) {57                Image(systemName: tone.symbol).foregroundStyle(tone.color(theme)).imageScale(.small).accessibilityHidden(true)58                Text(value).font(.title2.weight(.semibold).monospacedDigit()).foregroundStyle(theme.textPrimary)59            }60            Text(caption).font(.caption).foregroundStyle(theme.textSecondary).lineLimit(2)61        }62        .frame(maxWidth: .infinity, alignment: .leading)63        .accessibilityElement(children: .ignore)64        .accessibilityLabel(caption)65        .accessibilityValue(value)66    }67}6869/// Usage bar with its numeric value; when `ratio` is nil the meter says so instead of drawing an empty bar.70public struct UsageMeter: View {71    @Environment(\.mccTheme) private var theme72    private let ratio: Double?73    private let label: String74    private let detail: String?75    private let unavailableText: String76    public init(label: String, ratio: Double?, detail: String? = nil, unavailableText: String? = nil) {77        self.label = label; self.ratio = ratio; self.detail = detail78        self.unavailableText = unavailableText ?? tr("metric.not_measured")79    }80    private var tone: StatusTone {81        guard let r = ratio else { return .neutral }82        return r >= 0.9 ? .critical : r >= 0.75 ? .warning : .ok83    }84    public var body: some View {85        VStack(alignment: .leading, spacing: Tokens.Space.s2) {86            HStack(alignment: .firstTextBaseline) {87                Text(label).font(.callout).foregroundStyle(theme.textSecondary)88                Spacer()89                if let r = ratio {90                    Text(Format.percent(ratio: r)).font(.callout.weight(.semibold).monospacedDigit()).foregroundStyle(theme.textPrimary)91                } else {92                    Text(unavailableText).font(.callout).foregroundStyle(theme.textTertiary)93                }94            }95            GeometryReader { geo in96                ZStack(alignment: .leading) {97                    Capsule().fill(theme.inset)98                    if let r = ratio {99                        Capsule().fill(tone.color(theme)).frame(width: max(2, geo.size.width * min(1, max(0, r))))100                    }101                }102                .overlay(Capsule().strokeBorder(theme.borderSubtle, lineWidth: 1))103            }104            .frame(height: 8)105            if let detail { Text(detail).font(.caption).foregroundStyle(theme.textTertiary) }106        }107        .accessibilityElement(children: .ignore)108        .accessibilityLabel(label)109        .accessibilityValue(ratio.map { Format.percent(ratio: $0) + (detail.map { ", \($0)" } ?? "") } ?? unavailableText)110    }111}112113/// Banner shown above read-only, possibly outdated data.114public struct InfoBanner: View {115    @Environment(\.mccTheme) private var theme116    private let tone: StatusTone117    private let title: String118    private let message: String?119    public init(tone: StatusTone, title: String, message: String? = nil) {120        self.tone = tone; self.title = title; self.message = message121    }122    public var body: some View {123        HStack(alignment: .firstTextBaseline, spacing: Tokens.Space.s3) {124            Image(systemName: tone.symbol).foregroundStyle(tone.color(theme)).accessibilityHidden(true)125            VStack(alignment: .leading, spacing: 2) {126                Text(title).font(.callout.weight(.semibold)).foregroundStyle(theme.textPrimary)127                if let message { Text(message).font(.caption).foregroundStyle(theme.textSecondary) }128            }129            Spacer(minLength: 0)130        }131        .padding(.horizontal, Tokens.Space.s4)132        .padding(.vertical, Tokens.Space.s3)133        .frame(maxWidth: .infinity, alignment: .leading)134        .background(tone.muted(theme), in: RoundedRectangle(cornerRadius: Tokens.Radius.md, style: .continuous))135        .overlay(RoundedRectangle(cornerRadius: Tokens.Radius.md, style: .continuous).strokeBorder(tone.color(theme).opacity(0.4), lineWidth: 1))136        .accessibilityElement(children: .combine)137    }138}139140/// Empty list / nothing to show.141public struct EmptyStateView: View {142    @Environment(\.mccTheme) private var theme143    private let title: String144    private let message: String?145    private let systemImage: String146    public init(_ title: String, message: String? = nil, systemImage: String = "tray") {147        self.title = title; self.message = message; self.systemImage = systemImage148    }149    public var body: some View {150        VStack(spacing: Tokens.Space.s3) {151            Image(systemName: systemImage).font(.largeTitle).foregroundStyle(theme.textTertiary).accessibilityHidden(true)152            Text(title).font(.headline).foregroundStyle(theme.textPrimary)153            if let message {154                Text(message).font(.callout).foregroundStyle(theme.textSecondary).multilineTextAlignment(.center).frame(maxWidth: 460)155            }156        }157        .padding(Tokens.Space.s8)158        .frame(maxWidth: .infinity, maxHeight: .infinity)159        .accessibilityElement(children: .combine)160    }161}162163/// The correlation id of a failed request, selectable, so that it can be quoted when asking for help.164public struct CorrelationIDView: View {165    @Environment(\.mccTheme) private var theme166    private let id: String167    public init(_ id: String) { self.id = id }168    public var body: some View {169        HStack(spacing: Tokens.Space.s2) {170            Text(tr("error.correlation_id")).font(.caption).foregroundStyle(theme.textTertiary)171            Text(id).font(.caption.monospaced()).foregroundStyle(theme.textSecondary).textSelection(.enabled)172        }173        .accessibilityElement(children: .ignore)174        .accessibilityLabel(tr("error.correlation_id"))175        .accessibilityValue(id)176        .accessibilityIdentifier("correlation-id")177    }178}179180/// A feature that cannot be shown: endpoint not implemented yet, dependency down, permission missing, offline.181/// It states the reason honestly and never substitutes placeholder data.182public struct UnavailableStateView: View {183    @Environment(\.mccTheme) private var theme184    private let reason: UnavailableReason185    private let error: APIError?186    private let retry: (() -> Void)?187    public init(reason: UnavailableReason, error: APIError? = nil, retry: (() -> Void)? = nil) {188        self.reason = reason; self.error = error; self.retry = retry189    }190    private var title: String {191        switch reason {192        case .notImplemented: tr("unavailable.not_implemented.title")193        case .serviceUnavailable(let code): code == "orchestrator_frozen" ? tr("unavailable.frozen.title") : tr("unavailable.service.title")194        case .forbidden: tr("unavailable.forbidden.title")195        case .offline: tr("unavailable.offline.title")196        }197    }198    private var message: String {199        switch reason {200        case .notImplemented: tr("unavailable.not_implemented.message")201        case .serviceUnavailable(let code): code == "orchestrator_frozen" ? tr("unavailable.frozen.message") : tr("unavailable.service.message")202        case .forbidden: tr("unavailable.forbidden.message")203        case .offline: tr("unavailable.offline.message")204        }205    }206    private var symbol: String {207        switch reason {208        case .notImplemented: "hammer"209        case .serviceUnavailable: "exclamationmark.icloud"210        case .forbidden: "lock"211        case .offline: "wifi.slash"212        }213    }214    public var body: some View {215        VStack(spacing: Tokens.Space.s3) {216            Image(systemName: symbol).font(.largeTitle).foregroundStyle(theme.textTertiary).accessibilityHidden(true)217            Text(title).font(.headline).foregroundStyle(theme.textPrimary)218            Text(message).font(.callout).foregroundStyle(theme.textSecondary).multilineTextAlignment(.center).frame(maxWidth: 480)219            if let e = error, let status = e.status {220                Text("HTTP \(status) · \(e.code)").font(.caption.monospaced()).foregroundStyle(theme.textTertiary).textSelection(.enabled)221            }222            if let c = error?.correlationID { CorrelationIDView(c) }223            if let retry { Button(tr("action.retry"), action: retry).keyboardShortcut("r", modifiers: .command) }224        }225        .padding(Tokens.Space.s8)226        .frame(maxWidth: .infinity, maxHeight: .infinity)227        .accessibilityElement(children: .contain)228        .accessibilityIdentifier("state-unavailable")229    }230}231232/// A request failed for a reason the user may act on.233public struct ErrorStateView: View {234    @Environment(\.mccTheme) private var theme235    private let error: APIError236    private let retry: (() -> Void)?237    public init(error: APIError, retry: (() -> Void)? = nil) { self.error = error; self.retry = retry }238    public var body: some View {239        VStack(spacing: Tokens.Space.s3) {240            Image(systemName: "exclamationmark.triangle").font(.largeTitle).foregroundStyle(StatusTone.warning.color(theme)).accessibilityHidden(true)241            Text(tr("error.title")).font(.headline).foregroundStyle(theme.textPrimary)242            Text(error.message).font(.callout).foregroundStyle(theme.textSecondary).multilineTextAlignment(.center).frame(maxWidth: 480).textSelection(.enabled)243            Text(error.status.map { "HTTP \($0) · \(error.code)" } ?? error.code).font(.caption.monospaced()).foregroundStyle(theme.textTertiary)244            if let c = error.correlationID { CorrelationIDView(c) }245            if let retry { Button(tr("action.retry"), action: retry) }246        }247        .padding(Tokens.Space.s8)248        .frame(maxWidth: .infinity, maxHeight: .infinity)249        .accessibilityElement(children: .contain)250        .accessibilityIdentifier("state-error")251    }252}253254/// Inline, single-line rendering of an error (forms, sheets), with the correlation id.255public struct InlineErrorView: View {256    @Environment(\.mccTheme) private var theme257    private let error: APIError258    public init(_ error: APIError) { self.error = error }259    public var body: some View {260        VStack(alignment: .leading, spacing: Tokens.Space.s1) {261            HStack(alignment: .firstTextBaseline, spacing: Tokens.Space.s2) {262                Image(systemName: StatusTone.critical.symbol).foregroundStyle(StatusTone.critical.color(theme)).accessibilityHidden(true)263                Text(error.message).font(.callout).foregroundStyle(theme.textPrimary).textSelection(.enabled)264            }265            HStack(spacing: Tokens.Space.s3) {266                Text(error.status.map { "HTTP \($0) · \(error.code)" } ?? error.code).font(.caption.monospaced()).foregroundStyle(theme.textTertiary)267                if let c = error.correlationID { CorrelationIDView(c) }268            }269        }270        .padding(Tokens.Space.s3)271        .frame(maxWidth: .infinity, alignment: .leading)272        .background(StatusTone.critical.muted(theme), in: RoundedRectangle(cornerRadius: Tokens.Radius.md))273        .accessibilityElement(children: .combine)274        .accessibilityIdentifier("inline-error")275    }276}277278/// Standard container for a `Resource`: content when a value exists (live or cached, with a banner when it is not279/// current), otherwise the explicit loading / unavailable / error state.280public struct ResourceView<Value: Codable & Sendable, Content: View>: View {281    @Environment(\.mccTheme) private var theme282    private let resource: Resource<Value>283    private let content: (Value) -> Content284    public init(_ resource: Resource<Value>, @ViewBuilder content: @escaping (Value) -> Content) {285        self.resource = resource286        self.content = content287    }288    public var body: some View {289        if let value = resource.value {290            VStack(alignment: .leading, spacing: Tokens.Space.s3) {291                if resource.isShowingStaleData, let at = resource.receivedAt {292                    StaleDataBanner(receivedAt: at, state: resource.state)293                }294                content(value)295            }296        } else {297            switch resource.state {298            case .idle, .loading, .loaded:299                ProgressView(tr("state.loading"))300                    .frame(maxWidth: .infinity, maxHeight: .infinity)301                    .padding(Tokens.Space.s8)302            case .unavailable(let reason, let error):303                UnavailableStateView(reason: reason, error: error) { Task { await resource.load() } }304            case .failed(let error):305                ErrorStateView(error: error) { Task { await resource.load() } }306            }307        }308    }309}310311/// "Data from 14:05" — shown when a screen displays a value that the server did not just confirm.312public struct StaleDataBanner<Value: Sendable>: View {313    private let receivedAt: Date314    private let state: Loadable<Value>315    public init(receivedAt: Date, state: Loadable<Value>) { self.receivedAt = receivedAt; self.state = state }316    public var body: some View {317        banner.accessibilityIdentifier("stale-banner")318    }319320    @ViewBuilder private var banner: some View {321        let when = Format.dateTime(receivedAt)322        switch state {323        case .unavailable(.offline, _):324            InfoBanner(tone: .offline, title: tr("stale.offline.title"), message: tr("stale.data_from", when))325        case .unavailable(_, let e), .failed(let e as APIError?):326            InfoBanner(tone: .warning, title: tr("stale.refresh_failed.title"),327                       message: tr("stale.data_from", when) + (e?.correlationID.map { " · \($0)" } ?? ""))328        default:329            InfoBanner(tone: .stale, title: tr("stale.cached.title"), message: tr("stale.data_from", when))330        }331    }332}333
Files main
Menu

Theme