// 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.importSwiftUI/// Something scheduled that can be called off.publicprotocolToastTicket: Sendable {func cancel()}/// The seam the window is measured through.publicprotocolToastScheduler: Sendable {func schedule(after seconds: TimeInterval, _ work: @escaping @MainActor () -> Void) -> any ToastTicket}structTaskTicket: ToastTicket {let task: Task<Void, Never>func cancel() { task.cancel() }}/// The real one.publicstructSystemToastScheduler: ToastScheduler {publicinit() {}publicfunc schedule( after seconds: TimeInterval, _ work: @escaping @MainActor () -> Void ) -> any ToastTicket {TaskTicket( task: Task { @MainActor intry? awaitTask.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))guard !Task.isCancelled else { return } work() } ) }}publicstructCottonToast: Identifiable, Equatable {publicenumTone: String, CaseIterable, Sendable { case notice, success, error, warning }publiclet id: Intpubliclet message: Stringpubliclet 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.publiclet undo: (() -> Void)?/// It stands until the next tap (`ToastWindow.untilTap`), not a window.publicvar untilTap = falsepublicstaticfunc == (lhs: CottonToast, rhs: CottonToast) -> Bool { lhs.id == rhs.id && lhs.message == rhs.message && lhs.tone == rhs.tone }}/// How long a receipt stands.publicenumToastWindow {/// A routed thought's receipt, over a screen you are already reading.publicstaticlet receipt: TimeInterval = 3/// A verb that took a row out of view.publicstaticlet rowUndo: TimeInterval = 5/// A line that stands until the next tap anywhere (Find a book before/// sign-in): no timer clears it.publicstaticlet untilTap: TimeInterval = .infinity}@MainActor@ObservablepublicfinalclassToastCenter {publicprivate(set) var current: CottonToast?privatelet scheduler: any ToastSchedulerprivatevar ticket: (any ToastTicket)?privatevar 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. @discardableResultpublicfunc 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 += 1let id = nextId current = CottonToast(id: id, message: message, tone: tone, undo: undo, untilTap: !window.isFinite)guard window.isFinite else { ticket = nilreturn id } ticket = scheduler.schedule(after: window) { [weakself] in// Only the receipt this flight armed may clear itself: a straggler// must never clear its replacement.guardletself, self.current?.id == id else { return }self.current = nilself.ticket = nil }return id }/// Take the act back and drop the receipt. The window is over either way.publicfunc undo() {guardlet undo = current?.undo else { return } ticket?.cancel() ticket = nil current = nil undo() }publicfunc dismiss() { ticket?.cancel() ticket = nil current = nil }/// A tap anywhere: a line standing until the next tap goes.publicfunc tapped() {guard current?.untilTap == trueelse { 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.structToastStrip: View {privatelet toast: CottonToastprivatelet onUndo: () -> Voidprivatelet onDismiss: () -> Void @Environment(\.theme) privatevar themepublicinit(toast: CottonToast, onUndo: @escaping () -> Void, onDismiss: @escaping () -> Void) {self.toast = toastself.onUndo = onUndoself.onDismiss = onDismiss }/// The ink a tone types its sentence in. A failure has to be READ; the/// rest are receipts.staticfunc ink(for tone: CottonToast.Tone) -> PaperInk {switch tone {case .error: return .redcase .notice, .success, .warning: return .ink } }/// How many lines a tone may take. A failure and a warning explain; a/// confirmation stays terse.staticfunc lineLimit(for tone: CottonToast.Tone) -> Int {switch tone {case .error, .warning: return6case .notice, .success: return3 } }/// The ink the undo verb is typed in.staticlet undoInk: PaperInk = .red/// The stub's type sizes.staticlet messageSize: CGFloat = 14staticlet undoSize: CGFloat = 15publicvar body: someView {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.staticlet 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.extensionView {/// 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.publicfunc cottonToasts(_ center: ToastCenter) -> someView { 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) -> someView { 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() -> someView { modifier(CoverReceipts()) }}privatestructCoverReceipts: ViewModifier { @Environment(ToastCenter.self) privatevar toasts: ToastCenter?func body(content: Content) -> someView {iflet 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.privatestructReceiptOverlay: 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) privatevar vaultLook @Environment(\.appToast) privatevar 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) privatevar hungAbovefunc body(content: Content) -> someView { 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) {ifToastKnobs.draws(cover: cover, hungAbove: hungAbove), let toast = center.current { receipt(toast).transition(.opacity) } } .animation(.easeOut(duration: 0.18), value: center.current?.id) } @ViewBuilder privatefunc receipt(_ toast: CottonToast) -> someView { #if os(iOS)iflet 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 privatefunc standing(_ toast: CottonToast) -> someView {iflet 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`).enumToastKnobs {/// 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.staticlet edge: Alignment = .top/// The gap under the status bar (the safe area's top) to the stub.staticlet 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.staticfunc draws(cover: Bool, hungAbove: Bool) -> Bool { cover || !hungAbove }}extensionView {/// 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) -> someView { 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() -> someView { padding(.top, ToastKnobs.topGap) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: ToastKnobs.edge) }}privatestructReceiptsHungAboveKey: EnvironmentKey {staticlet defaultValue = false}extensionEnvironmentValues {/// 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 } }}