SPB Git

Repository Public

Scaffolding.swift 19.1 KB 442 lines swift

1import MCCCore2import SwiftUI34// Building blocks shared by every iOS screen. Conventions:5//   - a screen is a ScrollView or a List decorated with `.screen(id, title:, load:, reload:)`;6//   - rows that lead somewhere are `RouteRow`s (they call `Navigator.open`);7//   - anything that changes server state goes through `MutationRunner` / `MutationButton`: disabled offline or8//     without the permission, errors (403 included) shown with their correlation id;9//   - every block of data ends with a `DataStamp` (when it was received) or a `FreshnessLabel` (how fresh the10//     telemetry is according to the server).1112extension EnvironmentValues {13    @Entry var appModel: AppModel? = nil14}1516/// Shorthand for the environment objects every screen needs.17@MainActor18@propertyWrapper19struct Session: DynamicProperty {20    @Environment(AppSession.self) private var session21    var wrappedValue: AppSession { session }22}2324private struct ScreenModifier: ViewModifier {25    @Environment(\.mccTheme) private var theme26    @Environment(Navigator.self) private var nav27    let id: String28    let title: String29    let load: () async -> Void30    let reload: () async -> Void3132    func body(content: Content) -> some View {33        content34            .scrollContentBackground(.hidden)35            .background(theme.canvas.ignoresSafeArea())36            .navigationTitle(title)37            .navigationBarTitleDisplayMode(.large)38            .refreshable { await reload() }39            // Cancelled by SwiftUI when the screen disappears.40            .task { await load() }41            .onChange(of: nav.refreshToken) { Task { await reload() } }42            .accessibilityIdentifier("screen-" + id)43    }44}4546extension View {47    /// Standard chrome of a screen: title, themed background, pull to refresh, load when shown, ⌘R.48    func screen(_ id: String, title: String, load: @escaping () async -> Void, reload: (() async -> Void)? = nil) -> some View {49        modifier(ScreenModifier(id: id, title: title, load: load, reload: reload ?? load))50    }5152    /// Loads a keyed resource while the view is shown and cancels the request when it goes away.53    func loads<V: Codable & Sendable>(_ resource: Resource<V>, maxAge: TimeInterval = 20) -> some View {54        task(id: ObjectIdentifier(resource)) { await resource.loadIfNeeded(maxAge: maxAge) }55            .onDisappear { resource.cancelLoad() }56    }5758    /// Minimum 44 pt touch target.59    func touchTarget() -> some View { frame(minWidth: Tokens.Size.touchMin, minHeight: Tokens.Size.touchMin) }60}6162/// Vertical stack of cards with the standard margins, for ScrollView-based screens.63struct ScreenStack<Content: View>: View {64    @ViewBuilder var content: Content65    var body: some View {66        ScrollView {67            LazyVStack(alignment: .leading, spacing: Tokens.Space.s5) { content }68                .padding(.horizontal, Tokens.Space.s5)69                .padding(.vertical, Tokens.Space.s4)70                .frame(maxWidth: Tokens.Size.contentMax, alignment: .leading)71                .frame(maxWidth: .infinity)72        }73    }74}7576/// A titled card. The accessory sits beside the title, or under it at accessibility text sizes (never squeezed out).77struct SectionCard<Content: View, Accessory: View>: View {78    @Environment(\.mccTheme) private var theme79    @Environment(\.dynamicTypeSize) private var size80    let title: String81    @ViewBuilder var accessory: Accessory82    @ViewBuilder var content: Content83    init(_ title: String, @ViewBuilder accessory: () -> Accessory, @ViewBuilder content: () -> Content) {84        self.title = title; self.accessory = accessory(); self.content = content()85    }86    var body: some View {87        let heading = Text(title).font(.headline).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)88        Card {89            VStack(alignment: .leading, spacing: Tokens.Space.s4) {90                if size.isAccessibilitySize {91                    VStack(alignment: .leading, spacing: Tokens.Space.s2) { heading; accessory }92                } else {93                    HStack(alignment: .firstTextBaseline) { heading; Spacer(minLength: Tokens.Space.s3); accessory }94                }95                content96            }97        }98    }99}100101/// Text button used as a card accessory ("See nodes"): the whole 44 pt area is the control.102struct LinkButton: View {103    let title: String104    let identifier: String105    let action: () -> Void106    var body: some View {107        Button(action: action) {108            Text(title).font(.callout.weight(.medium))109                .padding(.horizontal, Tokens.Space.s3)110                .frame(minWidth: Tokens.Size.touchMin, minHeight: Tokens.Size.touchMin)111                .contentShape(Rectangle())112        }113        .buttonStyle(.plain)114        .foregroundStyle(.tint)115        .hoverEffect(.highlight)116        .accessibilityIdentifier(identifier)117    }118}119120/// A count with a tone and a caption. Like the core `CountTile`, without a line limit: the caption wraps at any size.121struct StatTile: View {122    @Environment(\.mccTheme) private var theme123    let value: String124    let caption: String125    var tone: StatusTone = .neutral126    var body: some View {127        VStack(alignment: .leading, spacing: Tokens.Space.s1) {128            HStack(spacing: Tokens.Space.s2) {129                Image(systemName: tone.symbol).foregroundStyle(tone.color(theme)).imageScale(.small).accessibilityHidden(true)130                Text(value).font(.title2.weight(.semibold).monospacedDigit()).foregroundStyle(theme.textPrimary)131            }132            Text(caption).font(.caption).foregroundStyle(theme.textSecondary).fixedSize(horizontal: false, vertical: true)133        }134        .frame(maxWidth: .infinity, alignment: .leading)135        .accessibilityElement(children: .ignore)136        .accessibilityLabel(caption)137        .accessibilityValue(value)138    }139}140141extension SectionCard where Accessory == EmptyView {142    init(_ title: String, @ViewBuilder content: () -> Content) { self.init(title, accessory: { EmptyView() }, content: content) }143}144145/// "Reçu à 14:05:32" — when the data on screen was received from the server (or read from the cache).146struct DataStamp: View {147    @Environment(\.mccTheme) private var theme148    let receivedAt: Date?149    var stale = false150    var body: some View {151        if let receivedAt {152            Label {153                Text(tr(stale ? "stamp.cached_at" : "stamp.received_at", Format.time(receivedAt, seconds: true)))154            } icon: {155                Image(systemName: stale ? "clock.badge.exclamationmark" : "clock")156            }157            .font(.footnote)158            .foregroundStyle(stale ? StatusTone.stale.color(theme) : theme.textSecondary)159            .accessibilityIdentifier("data-stamp")160        }161    }162}163164/// A `Resource` rendered with its explicit states (loading, unavailable, error, stale banner) and its timestamp.165struct ResourceSection<Value: Codable & Sendable, Content: View>: View {166    let resource: Resource<Value>167    var showsStamp = true168    @ViewBuilder var content: (Value) -> Content169    var body: some View {170        VStack(alignment: .leading, spacing: Tokens.Space.s3) {171            ResourceView(resource, content: content)172            if showsStamp, resource.value != nil { DataStamp(receivedAt: resource.receivedAt, stale: resource.isShowingStaleData) }173        }174    }175}176177/// "Label / value" that stacks vertically when the text is large, so that nothing is truncated.178struct InfoRow: View {179    @Environment(\.mccTheme) private var theme180    @Environment(\.dynamicTypeSize) private var size181    let label: String182    let value: String?183    var monospaced = false184    init(_ label: String, _ value: String?, monospaced: Bool = false) { self.label = label; self.value = value; self.monospaced = monospaced }185    var body: some View {186        let shown = value.flatMap { $0.isEmpty ? nil : $0 }187        let v = Text(shown ?? tr("metric.not_reported"))188            .font(monospaced ? .callout.monospaced() : .callout)189            .foregroundStyle(shown == nil ? theme.textTertiary : theme.textPrimary)190            .textSelection(.enabled)191        let k = Text(label).font(.callout).foregroundStyle(theme.textSecondary)192        Group {193            if size.isAccessibilitySize {194                VStack(alignment: .leading, spacing: Tokens.Space.s1) { k; v }195            } else {196                HStack(alignment: .firstTextBaseline) { k; Spacer(minLength: Tokens.Space.s4); v.multilineTextAlignment(.trailing) }197            }198        }199        .frame(maxWidth: .infinity, alignment: .leading)200        .accessibilityElement(children: .ignore)201        .accessibilityLabel(label)202        .accessibilityValue(shown ?? tr("metric.not_reported"))203    }204}205206/// A row that opens a destination. Selected state on iPad, chevron on iPhone, pointer hover, 44 pt minimum.207struct RouteRow<Label: View>: View {208    @Environment(\.mccTheme) private var theme209    @Environment(Navigator.self) private var nav210    let route: Route211    var identifier: String?212    @ViewBuilder var label: Label213    var body: some View {214        let selected = nav.isSelected(route)215        Button { nav.open(route) } label: {216            HStack(spacing: Tokens.Space.s3) {217                label.frame(maxWidth: .infinity, alignment: .leading)218                Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(theme.textTertiary).accessibilityHidden(true)219            }220            .padding(.vertical, Tokens.Space.s3)221            .padding(.horizontal, Tokens.Space.s4)222            .frame(minHeight: Tokens.Size.touchMin)223            .background(selected ? theme.accentMuted : theme.surface, in: RoundedRectangle(cornerRadius: Tokens.Radius.lg, style: .continuous))224            .overlay(RoundedRectangle(cornerRadius: Tokens.Radius.lg, style: .continuous).strokeBorder(selected ? theme.accent : theme.borderSubtle, lineWidth: 1))225            .contentShape(RoundedRectangle(cornerRadius: Tokens.Radius.lg, style: .continuous))226        }227        .buttonStyle(.plain)228        .hoverEffect(.highlight)229        .accessibilityAddTraits(selected ? [.isSelected] : [])230        .accessibilityIdentifier(identifier ?? "row")231    }232}233234/// Runs mutations for a screen: one at a time, with the error kept for display. Step-up is handled by the core235/// (the passkey sheet appears when the server asks for it).236@MainActor237@Observable238final class MutationRunner {239    private(set) var isRunning = false240    var error: APIError?241242    /// Returns the result, or nil when the mutation failed (the error is then in `error`) or was cancelled.243    @discardableResult244    func run<T: Sendable>(_ operation: () async throws -> T) async -> T? {245        guard !isRunning else { return nil }246        isRunning = true247        defer { isRunning = false }248        do {249            let v = try await operation()250            error = nil251            return v252        } catch {253            let e = APIError.from(error)254            if !e.isCancelled && !e.isPasskeyCancelled { self.error = e }255            return nil256        }257    }258}259260extension View {261    /// Shows the error of a failed mutation (message from the server, status, correlation id).262    func mutationError(_ runner: MutationRunner) -> some View {263        alert(tr("error.title"), isPresented: Binding(get: { runner.error != nil }, set: { if !$0 { runner.error = nil } }), presenting: runner.error) { _ in264            Button(tr("common.ok"), role: .cancel) {}265        } message: { e in266            Text(MutationErrorText.describe(e))267        }268    }269}270271enum MutationErrorText {272    static func describe(_ e: APIError) -> String {273        var lines = [e.message]274        if e.isForbidden { lines.append(tr("error.forbidden_hint")) }275        if let s = e.status { lines.append(tr("error.status", s, e.code)) }276        if let c = e.correlationID { lines.append(tr("error.correlation_id") + " : " + c) }277        return lines.joined(separator: "\n")278    }279}280281/// A button that changes server state. Disabled while offline (nothing is queued) or when the session lacks the282/// permission; the reason is exposed to VoiceOver.283struct MutationButton: View {284    @Session private var session285    let title: String286    var systemImage: String?287    var role: ButtonRole?288    var permission: String?289    var identifier: String?290    var prominent = false291    let action: () -> Void292293    var body: some View {294        let offline = !session.canMutate295        let denied = permission.map { !session.can($0) } ?? false296        Group {297            if prominent { button.buttonStyle(.mccProminent) } else { button.buttonStyle(.bordered) }298        }299        .disabled(offline || denied)300        .accessibilityHint(offline ? tr("mutation.offline_hint") : denied ? tr("mutation.denied_hint") : "")301        .accessibilityIdentifier(identifier ?? "mutation")302    }303304    private var button: some View {305        Button(role: role, action: action) {306            if let systemImage { Label(title, systemImage: systemImage) } else { Text(title) }307        }308        .frame(minHeight: Tokens.Size.touchMin)309    }310}311312/// Banner shown above everything while the server is unreachable or the event stream is reconnecting.313struct ConnectionBanner: View {314    @Session private var session315    @Environment(\.mccTheme) private var theme316    var body: some View {317        if session.phase == .signedIn {318            if session.isOffline {319                banner(tone: .offline, symbol: "wifi.slash", id: "offline-banner",320                       text: session.offlineSince.map { tr("connection.offline_since", Format.time($0)) } ?? tr("connection.offline"))321            } else if case .reconnecting = session.streamState {322                banner(tone: .warning, symbol: "arrow.triangle.2.circlepath", id: "reconnecting-banner", text: tr("connection.reconnecting"))323            }324        }325    }326327    private func banner(tone: StatusTone, symbol: String, id: String, text: String) -> some View {328        Label(text, systemImage: symbol)329            .font(.footnote.weight(.medium))330            .foregroundStyle(theme.textPrimary)331            .padding(.vertical, Tokens.Space.s3)332            .padding(.horizontal, Tokens.Space.s5)333            .frame(maxWidth: .infinity, alignment: .leading)334            .background(tone.muted(theme))335            .overlay(alignment: .bottom) { Rectangle().fill(tone.color(theme)).frame(height: 1) }336            .accessibilityElement(children: .combine)337            .accessibilityAddTraits(.isStaticText)338            .accessibilityIdentifier(id)339    }340}341342/// Adaptive grid of tiles: as many columns as fit, one column at accessibility text sizes.343struct TileGrid<Content: View>: View {344    @Environment(\.dynamicTypeSize) private var size345    var minimum: CGFloat = 150346    @ViewBuilder var content: Content347    var body: some View {348        let cols = size.isAccessibilitySize ? [GridItem(.flexible())] : [GridItem(.adaptive(minimum: minimum), spacing: Tokens.Space.s4, alignment: .topLeading)]349        LazyVGrid(columns: cols, alignment: .leading, spacing: Tokens.Space.s4) { content }350    }351}352353/// Segmented period picker for the charts (shared by every chart of the app through `AppModel.range`).354struct RangePicker: View {355    @Binding var range: API.TimeRange356    var body: some View {357        Picker(tr("range.title"), selection: $range) {358            ForEach(API.TimeRange.allCases, id: \.self) { r in Text(r.shortLabel).tag(r).accessibilityLabel(r.label) }359        }360        .pickerStyle(.segmented)361        .accessibilityIdentifier("range-picker")362    }363}364365extension API.TimeRange {366    var shortLabel: String { trDynamic("range.short." + rawValue) }367}368369/// Placeholder of the detail pane on iPad when nothing is selected.370struct DetailPlaceholder: View {371    let section: AppSection372    var body: some View {373        EmptyStateView(tr("detail.placeholder.title"), message: tr("detail.placeholder.message"), systemImage: section.symbol)374    }375}376377/// Localized string for a key built at runtime (enum labels). Literal keys go through `tr`, which the catalog check378/// can verify statically; the keys built here are listed in `DynamicKeys.all` and verified by a unit test.379func trDynamic(_ key: String) -> String { Localization.shared.string(key) }380381enum DynamicKeys {382    static var all: [String] {383        AppSection.allCases.map { "section." + $0.rawValue }384            + AppearancePreference.allCases.map { "appearance." + $0.rawValue }385            + API.TimeRange.allCases.map { "range.short." + $0.rawValue }386            + SettingsPane.allCases.map { "settings.pane." + $0.rawValue }387    }388}389390/// Freshness of telemetry as computed by the server, with the observation time. Same content and VoiceOver output as391/// the core `FreshnessLabel`, but the text wraps instead of being limited to one line: at large Dynamic Type sizes392/// "Hors ligne · il y a 2 min" must stay readable in full.393struct FreshnessLine: View {394    @Environment(\.mccTheme) private var theme395    private let freshness: API.Freshness396    private let observedAt: Date?397    private let showsTime: Bool398    init(_ freshness: API.Freshness, observedAt: Date? = nil, showsTime: Bool = true) {399        self.freshness = freshness; self.observedAt = observedAt; self.showsTime = showsTime400    }401    private var detail: String? {402        guard showsTime else { return nil }403        guard let observedAt else { return freshness == .offline ? tr("freshness.never_seen") : nil }404        return Format.relative(observedAt)405    }406    var body: some View {407        HStack(alignment: .firstTextBaseline, spacing: Tokens.Space.s2) {408            Image(systemName: freshness.tone.symbol).imageScale(.small).foregroundStyle(freshness.tone.color(theme)).accessibilityHidden(true)409            (Text(freshness.label).foregroundStyle(theme.textPrimary) + Text(detail.map { " · " + $0 } ?? "").foregroundStyle(theme.textSecondary))410                .fixedSize(horizontal: false, vertical: true)411        }412        .accessibilityElement(children: .ignore)413        .accessibilityLabel(tr("freshness.title"))414        .accessibilityValue([freshness.label, detail].compactMap { $0 }.joined(separator: ", "))415    }416}417418/// Primary button: accent fill with the token's contrast colour for the label (the system prominent style puts a419/// white label on the light accent of the dark theme, which fails contrast).420struct ProminentButtonStyle: ButtonStyle {421    func makeBody(configuration: Configuration) -> some View { ProminentLabel(configuration: configuration) }422    struct ProminentLabel: View {423        @Environment(\.mccTheme) private var theme424        @Environment(\.isEnabled) private var enabled425        let configuration: Configuration426        var body: some View {427            configuration.label428                .font(.body.weight(.semibold))429                .foregroundStyle(enabled ? theme.accentContrast : theme.textSecondary)430                .padding(.horizontal, Tokens.Space.s5)431                .padding(.vertical, Tokens.Space.s3)432                .background(enabled ? theme.accent : theme.raised, in: RoundedRectangle(cornerRadius: Tokens.Radius.xl, style: .continuous))433                .opacity(configuration.isPressed ? 0.75 : 1)434                .contentShape(RoundedRectangle(cornerRadius: Tokens.Radius.xl, style: .continuous))435                .hoverEffect(.lift)436        }437    }438}439extension ButtonStyle where Self == ProminentButtonStyle {440    static var mccProminent: ProminentButtonStyle { ProminentButtonStyle() }441}442
Files main
Menu

Theme