Cotton code
410 lines · 16.1 KB · SwiftRaw
// The four screens that paint OUTSIDE any route, and each one hides the// splash itself.//// This is design P16's rule and it is bought with an incident: before the// splash seam existed, a boot-time error looked exactly like a hang — issue #15// was eleven launches across two TestFlight builds, each one an error screen// nobody could see behind the constellation. `ErrorFallback`,// `ServerRefusalScreen` and `GateScreen` are rendered INSTEAD of the// navigator, so nothing else would ever take the splash down; each calls// `hideSplashOnce()` on appear, and the guard makes "once" survive all three// asking.//// The gate paints NOTHING while the core's gate says `wait`: the splash is// still up, and a spinner between it and the first screen is exactly what the// boot seam exists to prevent. Past its ceiling the core's gate says the step,// its clock, and — past its stall bound — what is safe (`GateScreen`).//// ON PAPER since 2026-09-15 (redesign phase 19). They were the last surfaces// wearing the pre-redesign look — a white ground, a 40pt SF Symbol, settings// pills. Now each is a piece of paper on Home's plaster: a refusal is a TORN// cream slip (the reason in red ink, the title in the serif, the sentence// typed), work on the database and every other wait is a CUT sheet with the// step, its progress and its time (`GateScreen`), and the// last resort is a card PAINTED in the cream dye with no photograph under it.// No glyph: a symbol is not an object. WHAT each prints is `GateSlip`'s pure// table (`Boot/GateSlip.swift`); `OutsideRouteFrame` below lays it out, once.import CottonKitimport SwiftUI// MARK: - The server said no/// The server said no, in words, with a way out of our own.////// The way out is the point of the screen, not a courtesy. Everything below the/// gate reads the file, so a person who cannot open one has no settings screen,/// no account block, nothing — the app they are looking at has exactly the/// surface this view draws. Without a way out they are not stuck on a screen,/// they are stuck in an INSTALL, and the only escape is deleting it. Which way/// out, and Retry beside it, is `GateSlip.refusal`'s decision.public struct ServerRefusalScreen: View {    private let refusal: ServerRefusal    private let onRetry: () -> Void    private let onSignOut: () -> Void    private let onResetKey: () -> Void    private let onErase: () -> Void    /// The one confirmation the erase asks for. A paper slip, like every other    /// question in the app — this screen paints outside every route but it is    /// not outside the product's voice.    @State private var confirmingErase = false    public init(        refusal: ServerRefusal,        onRetry: @escaping () -> Void = {},        onSignOut: @escaping () -> Void = {},        onResetKey: @escaping () -> Void = {},        onErase: @escaping () -> Void = {}    ) {        self.refusal = refusal        self.onRetry = onRetry        self.onSignOut = onSignOut        self.onResetKey = onResetKey        self.onErase = onErase    }    public var body: some View {        OutsideRouteFrame(slip: .refusal(refusal), seed: refusal.code) { action in            switch action {            case .retry: onRetry()            case .resetKey: onResetKey()            case .signOut: onSignOut()            case .erase: confirmingErase = true            case .copyDetails: break            }        }        .confirmDecision(            isPresented: $confirmingErase,            title: CottonStrings.eraseConfirmTitle,            message: CottonStrings.eraseConfirmBody,            confirmLabel: CottonStrings.eraseConfirmVerb,            identifier: "server-refusal-erase-confirm",            onConfirm: onErase        )        .accessibilityIdentifier("server-refusal")    }}// MARK: - The gate the core answered/// Every gate slip the core answers (`shell.home`): a wait past its ceiling,/// with its step, its clock and — past the stall bound — what is safe; a/// move, with its steps; a move that failed, with Try again and the details/// to copy; an open that failed; a refusal's wall. What it prints is/// `GateSlip.of`, the core's words on paper.public struct GateScreen: View {    private let gate: HomeAnswer.Gate    private let onWayOut: (String) -> Void    @State private var copied = false    @State private var confirmingErase = false    public init(gate: HomeAnswer.Gate, onWayOut: @escaping (String) -> Void) {        self.gate = gate        self.onWayOut = onWayOut    }    public var body: some View {        OutsideRouteFrame(slip: .of(gate, copied: copied), seed: gate.code ?? gate.stage) { action in            switch action {            case .retry: onWayOut("retry")            case .resetKey: onWayOut("reset_key")            case .signOut: onWayOut("sign_out")            case .erase: confirmingErase = true            case .copyDetails:                UIPasteboard.general.string = gate.words.detail                copied = true            }        }        .confirmDecision(            isPresented: $confirmingErase,            title: CottonStrings.eraseConfirmTitle,            message: CottonStrings.eraseConfirmBody,            confirmLabel: CottonStrings.eraseConfirmVerb,            identifier: "server-refusal-erase-confirm",            onConfirm: { onWayOut("erase") }        )        .accessibilityIdentifier(Self.identifier(gate.stage))    }    static func identifier(_ stage: String) -> String {        switch stage {        case "refused": return "server-refusal"        case "moving", "move_failed": return "migration-screen"        case "failed": return "error-fallback"        case "stalled": return "stalled"        default: return "wait"        }    }}/// The indicator for progress nobody can count: three marks, one of them/// inked, and it moves ONE MARK PER ANSWER from the core (`beat`). There is no/// animation of its own — a free-running spinner turns over a frozen app, and/// a frozen screen must mean a frozen app.struct BeatIndicator: View {    let beat: Int    @Environment(\.theme) private var theme    var body: some View {        HStack(spacing: 6) {            ForEach(0 ..< 3, id: \.self) { mark in                Circle()                    .fill(mark == beat % 3 ? theme.print(.ink) : theme.print(.pencil).opacity(0.35))                    .frame(width: 7, height: 7)            }        }        .accessibilityHidden(true)    }}// MARK: - The last resort/// Above every model and every provider: something threw that is not a state/// anybody designed for.////// It is deliberately plainer than the refusal screen — it cannot assume the/// design system's environment is intact, so its card is PAINTED in the cream/// dye with no photograph and its ground is the flat plaster colour with no/// tile — but it still hides the splash, which is the whole point of it/// existing rather than a blank window.public struct ErrorFallback: View {    private let message: String    private let onRetry: () -> Void    public init(message: String, onRetry: @escaping () -> Void = {}) {        self.message = message        self.onRetry = onRetry    }    public var body: some View {        OutsideRouteFrame(slip: .fallback(message: message), seed: "error-fallback") { action in            if action == .retry { onRetry() }        }        .accessibilityIdentifier("error-fallback")    }}// MARK: - The frame the four share/// One piece of paper, centred on the plaster, and the splash coming down.////// The four screens differ by what `GateSlip` prints and by nothing else, so/// the hide-the-splash call lives HERE — once, where none of them can forget/// it — and so does the paper./// "Send a report" from a gate card: files the report and answers the/// sentence the link then reads ("Report saved", "Copied — not saved: …")./// Set by whoever holds the core (`RootView`); absent, the link is not drawn.struct GateReport: Sendable {    let send: @Sendable () async -> String}private struct GateReportKey: EnvironmentKey {    static let defaultValue: GateReport? = nil}extension EnvironmentValues {    var gateReport: GateReport? {        get { self[GateReportKey.self] }        set { self[GateReportKey.self] = newValue }    }}struct OutsideRouteFrame: View {    @Environment(\.theme) private var theme    @Environment(\.gateReport) private var gateReport    /// What the report link says once pressed.    @State private var reported: String?    let slip: GateSlip    /// The paper's seed: the same slip tears the same way on every launch.    let seed: String    let onAction: (GateAction) -> Void    var body: some View {        VStack(spacing: 0) {            Spacer(minLength: 24)            paper                .frame(maxWidth: 480)                // A slip is as tall as its writing. Offered the whole screen,                // the paper took it, and a four-line refusal came out as a                // page of empty paper; the spacers centre it instead.                .fixedSize(horizontal: false, vertical: true)            Spacer(minLength: 24)        }        .padding(.horizontal, 24)        .frame(maxWidth: .infinity, maxHeight: .infinity)        .background { ground.ignoresSafeArea() }        .onAppear { hideSplashOnce() }    }    /// Home's plaster — except under the last resort, which paints the flat    /// colour and draws no tile, because a missing resource bundle is one of    /// the things it may be standing in for.    @ViewBuilder private var ground: some View {        if slip.paper == .painted {            Rectangle().fill(CottonColors.groundMuted)        } else {            PlasterGround()        }    }    @ViewBuilder private var paper: some View {        switch slip.paper {        case .tornSlip:            Paper(dye: .cream, edge: .torn, seed: seed, tilt: false, inset: 26) { writing }        case .sheet:            Paper(dye: .cream, edge: .cut, seed: seed, tilt: false, inset: 26) { writing }        case .painted:            writing                .padding(26)                .background(                    PaperShape(edge: .cut, seed: seed, theme: theme).fill(PaperDye.cream.fill)                )                .softShadow()        }    }    /// What is printed on a slip or a sheet, top to bottom.    private var writing: some View {        VStack(alignment: .leading, spacing: 14) {            if let reason = slip.reason {                Text(reason)                    .paperRed(13)                    .textCase(.uppercase)                    .tracking(1.2)            }            Text(slip.title)                .paperTitle(24)                .fixedSize(horizontal: false, vertical: true)                .modifier(OptionalIdentifier(slip.titleIdentifier))            PaperRuleLine(seed: seed, ink: slip.redRule ? .red : .pencil)            Text(slip.sentence)                .paperBody(14)                .fixedSize(horizontal: false, vertical: true)                .modifier(OptionalIdentifier(slip.sentenceIdentifier))            if let figure = slip.figure {                Text(figure)                    .paperHand(22)                    .modifier(OptionalIdentifier(slip.figureIdentifier))            }            if let progress = slip.progress {                progressRow(progress)            }            if let usually = slip.usually {                Text(usually)                    .paperMeta(12)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("wait-usually")            }            if let note = slip.note {                Text(note)                    .paperBody(14)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("wait-note")            }            if let detail = slip.detail {                Text(detail)                    .paperMeta(12)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("error-fallback-detail")            }            if !slip.buttons.isEmpty {                buttons                    .padding(.top, 6)            }        }        .frame(maxWidth: .infinity, alignment: .leading)    }    /// A wait's progress: a bar with its count where the core counted, and    /// otherwise the indicator with the time so far. Neither animates by    /// itself — each redraws when the model does, which is when the core    /// answered.    @ViewBuilder private func progressRow(_ progress: GateProgress) -> some View {        switch progress {        case .bar(let done, let total, let label, let identifier):            VStack(alignment: .leading, spacing: 6) {                ProgressView(value: Double(min(done, total)), total: Double(total))                    .progressViewStyle(.linear)                    .tint(theme.print(.ink))                    .accessibilityIdentifier("wait-bar")                Text(label)                    .paperHand(20)                    .accessibilityIdentifier(identifier)            }        case .activity(let beat, let label, let identifier):            HStack(spacing: 12) {                BeatIndicator(beat: beat)                    .accessibilityIdentifier("wait-indicator")                Text(label)                    .paperHand(20)                    .monospacedDigit()                    .accessibilityIdentifier(identifier)            }        }    }    /// The ink pill first, then the typed lines under one pencil rule.    @ViewBuilder private var buttons: some View {        let pills = slip.buttons.filter { $0.weight == .ink }        let lines = slip.buttons.filter { $0.weight != .ink }        let report = gateReport.flatMap { gateReport in slip.report.map { (gateReport, $0) } }        VStack(alignment: .leading, spacing: 10) {            ForEach(pills, id: \.identifier) { button in                InkPillButton(label: button.label, identifier: button.identifier) {                    onAction(button.action)                }            }            if !lines.isEmpty {                VStack(alignment: .leading, spacing: 0) {                    PaperRuleLine(seed: seed + "-actions")                    ForEach(lines, id: \.identifier) { button in                        TypewriterLine(                            label: button.label,                            identifier: button.identifier,                            ink: button.weight == .red ? .red : .ink                        ) { onAction(button.action) }                    }                }            }            if case let (gateReport, identifier)? = report {                VStack(alignment: .leading, spacing: 0) {                    if lines.isEmpty { PaperRuleLine(seed: seed + "-actions") }                    TypewriterLine(label: reported ?? ShellLines.line("boot", "gate.send_report"), identifier: identifier, ink: .ink) {                        guard reported == nil else { return }                        reported = ShellLines.line("boot", "gate.sending")                        Task { reported = await gateReport.send() }                    }                }            }            // WHICH APP AND BUILD DREW THIS CARD (`ProcessStamp`), on every            // card that shows a problem — with or without a report to send.            if slip.report != nil {                Text(ProcessStamp.of().text)                    .font(.system(size: 10, design: .monospaced))                    .foregroundStyle(theme.colors.inkTertiary.color)                    .lineLimit(2)                    .textSelection(.enabled)                    .accessibilityIdentifier("process-stamp")            }        }    }}/// An identifier where the table names one, and nothing where it does not —/// an empty identifier would still be an identifier.private struct OptionalIdentifier: ViewModifier {    let identifier: String?    init(_ identifier: String?) {        self.identifier = identifier    }    @ViewBuilder func body(content: Content) -> some View {        if let identifier {            content.accessibilityIdentifier(identifier)        } else {            content        }    }}