Cotton code
407 lines · 17.4 KB · SwiftRaw
// The receipt, and the undo it owes.//// Before the rewrite the receipt and the undo strip were two components that// never met. Here they are one object with two shapes, because the mic's receipt (design P10) is both: a sentence// AND an Undo, above the FAB, for three seconds.//// TWO WINDOWS, and they are not the same rule:////   • The RECEIPT is ≤3 s (the "Layout" section: a routed thought's receipt//     with Undo). Short, because it sits over the screen you are already//     reading.//   • A verb that takes a row OUT OF VIEW owes a 5-second undo that restores//     the whole prior row (the app-wide grammar). Longer, because what it//     undoes is gone from the screen.//// THE TIMER IS INJECTED. `ToastCenter` never touches `Task.sleep` or a// `Timer`, so a test advances the window rather than waiting out three real// seconds — and the FAILURE that shape prevents is the one this component is// most likely to have: a re-armed window that silently kept the first timer.//// RE-ARMING IS THE RULE, not queueing: a second receipt replaces the first and// restarts the FULL window, so the strip always undoes the LATEST act. Two// stacked undos would ask a person which of two things they meant.import SwiftUI/// Something scheduled that can be called off.public protocol ToastTicket: Sendable {    func cancel()}/// The seam the window is measured through.public protocol ToastScheduler: Sendable {    func schedule(after seconds: TimeInterval, _ work: @escaping @MainActor () -> Void) -> any ToastTicket}struct TaskTicket: ToastTicket {    let task: Task<Void, Never>    func cancel() { task.cancel() }}/// The real one.public struct SystemToastScheduler: ToastScheduler {    public init() {}    public func schedule(        after seconds: TimeInterval,        _ work: @escaping @MainActor () -> Void    ) -> any ToastTicket {        TaskTicket(            task: Task { @MainActor in                try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))                guard !Task.isCancelled else { return }                work()            }        )    }}public struct CottonToast: Identifiable, Equatable {    public enum Tone: String, CaseIterable, Sendable { case notice, success, error, warning }    public let id: Int    public let message: String    public let tone: Tone    /// Present when the act can be taken back. The strip draws the word only    /// then; a receipt with no undo is a sentence and nothing else.    public let undo: (() -> Void)?    /// It stands until the next tap (`ToastWindow.untilTap`), not a window.    public var untilTap = false    public static func == (lhs: CottonToast, rhs: CottonToast) -> Bool {        lhs.id == rhs.id && lhs.message == rhs.message && lhs.tone == rhs.tone    }}/// How long a receipt stands.public enum ToastWindow {    /// A routed thought's receipt, over a screen you are already reading.    public static let receipt: TimeInterval = 3    /// A verb that took a row out of view.    public static let rowUndo: TimeInterval = 5    /// A line that stands until the next tap anywhere (Find a book before    /// sign-in): no timer clears it.    public static let untilTap: TimeInterval = .infinity}@MainActor@Observablepublic final class ToastCenter {    public private(set) var current: CottonToast?    private let scheduler: any ToastScheduler    private var ticket: (any ToastTicket)?    private var nextId = 0    /// `nonisolated` so the environment's default value can be built where a    /// nonisolated `EnvironmentKey` has to build it. Nothing here touches the    /// main-actor state — it stores a scheduler and nothing else — and every    /// method that DOES is still isolated.    public nonisolated init(scheduler: any ToastScheduler = SystemToastScheduler()) {        self.scheduler = scheduler    }    /// Show a receipt. A second one REPLACES the first and restarts the full    /// window — the strip always undoes the latest act.    ///    /// THE WINDOW FOLLOWS THE UNDO. A verb that takes a row out of view owes    /// five seconds, not three: the person has to notice the row went, read    /// what happened and reach the word. So `window` is not given a constant    /// default — a receipt carrying an undo gets `rowUndo`, one without gets    /// `receipt`, and a caller who knows better still passes its own.    @discardableResult    public func show(        _ message: String,        tone: CottonToast.Tone = .notice,        window: TimeInterval? = nil,        undo: (() -> Void)? = nil    ) -> Int {        let window = window ?? (undo == nil ? ToastWindow.receipt : ToastWindow.rowUndo)        ticket?.cancel()        nextId += 1        let id = nextId        current = CottonToast(id: id, message: message, tone: tone, undo: undo, untilTap: !window.isFinite)        guard window.isFinite else {            ticket = nil            return id        }        ticket = scheduler.schedule(after: window) { [weak self] in            // Only the receipt this flight armed may clear itself: a straggler            // must never clear its replacement.            guard let self, self.current?.id == id else { return }            self.current = nil            self.ticket = nil        }        return id    }    /// Take the act back and drop the receipt. The window is over either way.    public func undo() {        guard let undo = current?.undo else { return }        ticket?.cancel()        ticket = nil        current = nil        undo()    }    public func dismiss() {        ticket?.cancel()        ticket = nil        current = nil    }    /// A tap anywhere: a line standing until the next tap goes.    public func tapped() {        guard current?.untilTap == true else { return }        dismiss()    }}/// The strip itself: at the top of the screen, under the status bar, never/// over the fan, its hub or the mic (the owner, 17 Nov 2026: every toast/// comes at the top; only the edge changed — the look, the words, the Undo/// and the windows are as they were).////// ## The dress (phase 20, 2026-09-14)////// A receipt IS a receipt: a narrow cream stub with a perforated bottom edge,/// lifted off the screen, the sentence typed on it and "Undo" in red ink — the/// one word on the stub a person might want to reach for. A failure is typed in/// red too, and is given more lines; the paper never changes colour for a/// tone, because a coloured slab over a page is somebody else's design/// language.struct ToastStrip: View {    private let toast: CottonToast    private let onUndo: () -> Void    private let onDismiss: () -> Void    @Environment(\.theme) private var theme    public init(toast: CottonToast, onUndo: @escaping () -> Void, onDismiss: @escaping () -> Void) {        self.toast = toast        self.onUndo = onUndo        self.onDismiss = onDismiss    }    /// The ink a tone types its sentence in. A failure has to be READ; the    /// rest are receipts.    static func ink(for tone: CottonToast.Tone) -> PaperInk {        switch tone {        case .error: return .red        case .notice, .success, .warning: return .ink        }    }    /// How many lines a tone may take. A failure and a warning explain; a    /// confirmation stays terse.    static func lineLimit(for tone: CottonToast.Tone) -> Int {        switch tone {        case .error, .warning: return 6        case .notice, .success: return 3        }    }    /// The ink the undo verb is typed in.    static let undoInk: PaperInk = .red    /// The stub's type sizes.    static let messageSize: CGFloat = 14    static let undoSize: CGFloat = 15    public var body: some View {        Paper(dye: .cream, edge: .receipt, seed: "toast-\(toast.id)", shadow: .lifted, inset: 0) {            HStack(spacing: 12) {                Text(toast.message)                    .paperBody(ToastStrip.messageSize, ink: ToastStrip.ink(for: toast.tone))                    .lineSpacing(2)                    .lineLimit(ToastStrip.lineLimit(for: toast.tone))                    .frame(maxWidth: .infinity, alignment: .leading)                if toast.undo != nil {                    Button(action: onUndo) {                        Text(CottonStrings.undo)                            .paperBody(ToastStrip.undoSize, ink: ToastStrip.undoInk)                            .underline(true, color: theme.print(ToastStrip.undoInk).opacity(0.5))                            // Four letters and three to five seconds of life:                            // the word needs the whole 44pt target around it,                            // not its own glyph box.                            .padding(.horizontal, 6)                            .frame(minWidth: 44, minHeight: 44)                            .contentShape(Rectangle())                    }                    .buttonStyle(OpacityButtonStyle())                }            }            .padding(.leading, 16)            .padding(.trailing, toast.undo == nil ? 16 : 8)            .padding(.top, 8)            // The perforation takes the bottom few points; the sentence sits            // clear of it.            .padding(.bottom, 12)        }        // The stub is as tall as its sentence. `Paper` fills a height it is        // PROPOSED, and the frame below proposes the whole screen.        .fixedSize(horizontal: false, vertical: true)        .padding(.horizontal, ContentMarginKnobs.chromeContentMargin)        .atToastEdge()        // A receipt goes on its own after a few seconds, and a person who has        // read it should not have to wait. There is no × — the strip itself is        // the control, and a screen-reader user is told so.        .accessibilityElement(children: .contain)        .accessibilityIdentifier(ToastStrip.identifier)        .accessibilityAction(named: "Dismiss", onDismiss)        .onTapGesture(perform: onDismiss)    }    /// The paper strip's name to a test: it never stands in an app with a look of its own.    static let identifier = "toast-paper"}/// The centre a screen speaks into, handed down from the host that draws it.////// **One host above the router, and every screen speaks into it.** A receipt is/// often spoken on the WAY OUT of a screen — a note saved, a todo dropped, a/// day switched — and a centre owned by that screen dies with the view that/// owns it, so the sentence is delivered to something being torn down. So the/// host publishes ONE centre, and it publishes it on ONE channel: the/// Observation environment, read as `@Environment(ToastCenter.self)`.////// **One channel, on purpose.** There used to be two — this one, and a custom/// `EnvironmentKey` with a default centre nothing hung. A host that published/// only the key left every `@Environment(ToastCenter.self)` reader under it/// with NO centre at all (SwiftUI traps on a type-keyed read with no value),/// and a host that published only the type left every key reader speaking/// into the default, where a toast drew nothing and raised nothing. The/// gallery did the first and half the screens did the second. The type-keyed/// read is the one kept because it has no silent default: a screen mounted/// without a host above it fails at once, in a preview, rather than dropping/// its receipts in production. `SourceGuardTests` holds the shape — a fresh/// `ToastCenter()` nowhere under `Screens/`, and this modifier the only/// publisher.extension View {    /// Hang a centre's receipt over a screen, and hand it to everything below.    ///    /// The two halves are ONE call on purpose: a host that drew the strip    /// without publishing the centre would leave the screens under it speaking    /// into a different one, and the toast would simply never appear.    public func cottonToasts(_ center: ToastCenter) -> some View {        modifier(ReceiptOverlay(center: center, cover: false))        .environment(center)    }    /// The same, over a whole-screen cover: a presentation of its own, which the window's overlay stands under    /// and cannot be seen through. It draws whatever stands above it in the window, and quiets the ones inside it.    func cottonToastsOverCover(_ center: ToastCenter) -> some View {        modifier(ReceiptOverlay(center: center, cover: true))        .environment(center)    }    /// A cover's receipts, from the centre the presenter hands down (none in a preview: nothing to draw).    func receiptsOverCover() -> some View { modifier(CoverReceipts()) }}private struct CoverReceipts: ViewModifier {    @Environment(ToastCenter.self) private var toasts: ToastCenter?    func body(content: Content) -> some View {        if let toasts { content.cottonToastsOverCover(toasts) } else { content }    }}// One overlay per presentation draws the centre's receipt: the window's (`RootView`), and a whole-screen cover's// over that cover. Any other overlay inside the same presentation (the stack's, a card's) stays quiet// (`receiptsHungAbove`): no new centre or timer is created, and Undo is the same action wherever the receipt came from.//// WHO DRAWS IT (22 Nov 2026): an app with a toast of its own (Words, Days, Story, Comms:// `AppToast`) is handed the words and draws them in that toast; Vault and Health draw theirs in their look; only// the apps still on paper draw the paper strip. The strip is never built in a redesigned app.private struct ReceiptOverlay: ViewModifier {    let center: ToastCenter    /// A whole-screen cover's overlay: it draws though the window's hangs above it, under the cover.    let cover: Bool    @Environment(\.vaultLook) private var vaultLook    @Environment(\.appToast) private var appToast    /// A receipt overlay already hangs over this one in the same presentation: it draws, this one does not. The    /// window's and the stack's overlays both drew every passing line, one in the paper strip and one in the app's    /// look (seen on the iPhone deleting an account, launch-ios walk, 22 Nov 2026, and approving a device in Comms).    @Environment(\.receiptsHungAbove) private var hungAbove    func body(content: Content) -> some View {        content            .environment(\.receiptsHungAbove, true)            // A line standing until the next tap goes with it, wherever it lands.            .simultaneousGesture(TapGesture().onEnded { center.tapped() },                                 including: center.current?.untilTap == true ? .all : .subviews)            .overlay(alignment: ToastKnobs.edge) {                if ToastKnobs.draws(cover: cover, hungAbove: hungAbove), let toast = center.current {                    receipt(toast).transition(.opacity)                }            }        .animation(.easeOut(duration: 0.18), value: center.current?.id)    }    @ViewBuilder private func receipt(_ toast: CottonToast) -> some View {        #if os(iOS)        if let appToast {            // The app's own toast, handed the words (`AppToast`).            AppToastView(app: appToast, toast: toast, onUndo: { center.undo() }, onDismiss: { center.dismiss() })        } else {            standing(toast)        }        #else        standing(toast)        #endif    }    @ViewBuilder private func standing(_ toast: CottonToast) -> some View {        if let look = vaultLook {            // Cotton Vault's and Cotton Health's receipt, in their own look.            VaultToastView(toast: toast, look: look, onUndo: { center.undo() }, onDismiss: { center.dismiss() })        } else {            ToastStrip(toast: toast, onUndo: { center.undo() }, onDismiss: { center.dismiss() })        }    }}/// The sizes, counts and timings the toast draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum ToastKnobs {    /// The one edge every toast stands at, in every Cotton app: the top, so    /// none covers the fan, the hub or the mic at the foot.    static let edge: Alignment = .top    /// The gap under the status bar (the safe area's top) to the stub.    static let topGap: CGFloat = 8    /// Whether an overlay draws the receipt: the first in its presentation does, a cover's over the cover does, and    /// one beneath another in the same presentation stays quiet, so a line is drawn once.    static func draws(cover: Bool, hungAbove: Bool) -> Bool { cover || !hungAbove }}extension View {    /// Hang a passing receipt card (a change's receipt with Undo, a kept    /// thought's) over this screen at the toast edge, under the safe area's    /// top: the one place a receipt stands in every Cotton app.    func receiptAtToastEdge<Receipt: View>(@ViewBuilder _ receipt: () -> Receipt) -> some View {        overlay(alignment: ToastKnobs.edge) {            receipt().padding(.top, ToastKnobs.topGap)        }    }    /// Stand a transient line at the toast edge: the top of the space it is    /// given, under the safe area's top. The receipt strip and the record    /// button's line both stand here, so no toast is drawn at the foot.    func atToastEdge() -> some View {        padding(.top, ToastKnobs.topGap)            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: ToastKnobs.edge)    }}private struct ReceiptsHungAboveKey: EnvironmentKey {    static let defaultValue = false}extension EnvironmentValues {    /// A window-wide receipt overlay hangs above (`cottonToasts`): one beneath it in the same presentation stays quiet.    var receiptsHungAbove: Bool {        get { self[ReceiptsHungAboveKey.self] }        set { self[ReceiptsHungAboveKey.self] = newValue }    }}