# Toast

Brief news at the corner on the locked float: a delete that waits while its red rim runs out, the agent asking one question, a run that stopped, money moved, and the everyday note, done, info, warning, error and save, in a stack that fans out.

Tier: free. Type: component. Category: feedback. Tags: agent, undo, motion.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/toast.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/toast.tsx`.

## Preview

Live preview: https://pixilui.com/components/toast

Knobs:

- `type`: `delete with undo`, `note`, `done`, `info`, `warning`, `error`, `saving`, `agent asks`, `run stopped`, `money moved`

Signature: A deleted run waits while the disc's red rim drains; Undo winds the rim back to full and the disc turns green as the words blur to Run restored.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/toast.tsx, quiet https://pixilui.com/r/standalone/toast.quiet.tsx.

## Code

`components/pixilui/toast.tsx`

```tsx
"use client";

/*
  Toast (B13, locked 2 Dec 2026) with the everyday set (locked the same day): brief news at the corner, on the locked float. A
  port of the locked toast.js and toast-everyday.js: the stack that collapses to the newest and fans out while you point at
  it, one timer per toast that pauses with the others, the Undo rim that drains and winds back, ⌘Z, swipe with Sonner's
  numbers, the corner close, a toast that turns into its next state through the blur, and the money moved payoff on the
  locked Aurora light (aurora-light). Every value is a token in foundation.css section 8 (--pixilui-toast-*), read here as the
  lock reads toast.css.

  What the library adds: each toast's inside is rendered by React (Toast, the same markup Toasts.markup gives), so a
  picture, a title and an action are React nodes, and a picture kept through a turn keeps its element (an avatar keeps
  moving). A type picks the everyday or AI preset (tone, glyph, how long it stays); every word is an option or config.
*/

import { cloneElement, createElement, forwardRef, isValidElement, useLayoutEffect, useRef, useState, type ComponentPropsWithoutRef, type ReactElement, type ReactNode, type RefObject } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { cn } from "./lib/utils";
import { close as surfaceClose, open as surfaceOpen } from "./lib/motion/surface";
import { prefersReducedMotion } from "./lib/motion/reduced-motion";
import { IconDone } from "./icons/done";
import { IconFailed } from "./icons/failed";
import { IconInfo } from "./icons/info";
import { IconLoading } from "./icons/loading";
import { IconWarning } from "./icons/warning";
import { Button } from "./button";
import { relayHold, relayPop } from "./aurora-light";

/** The locked status colors; they color only the picture. */
export type ToastTone = "neutral" | "done" | "warn" | "fail" | "wait";
/** The everyday set and the AI toasts (page-map, 4 Dec): each a preset of tone, glyph and time. */
export type ToastType = "note" | "done" | "info" | "warning" | "error" | "saving" | "agent-asks" | "run-stopped" | "money-moved";
/** A step of a run, for ToastSteps. */
export type ToastStepState = "done" | "fail" | "now" | "todo";

/** A toast's next state (morph): leave icon and picture out to keep the picture as it is. */
export type ToastState = {
  tone?: ToastTone;
  /** A glyph: it sits in a disc of the tone. A new glyph on a kept disc crosses in place. */
  icon?: ReactNode;
  /** Any other picture (an agent avatar, a person's coin, ToastSteps, a toast figure): it stands in the slot. */
  picture?: ReactNode;
  title: ReactNode;
  /** The line under the title (up to two lines). */
  sub?: ReactNode;
  /** The title shimmers, aria-busy, the timer waits. */
  working?: boolean;
  /** Money moved: the locked Aurora pop and glass light, once. */
  moment?: boolean;
  actions?: ToastAction[];
};
/** An action: go is the one that matters (the locked primary), soft the other. Return true from run to keep the toast. */
export type ToastAction = { label: string; kind?: "go" | "soft"; run?: (t: ToastHandle) => boolean | void };
/** A held action: run happens only when the rim runs out; Undo (or ⌘Z) calls restore instead and turns the toast into after. */
export type ToastUndo = { label?: string; run?: () => void; restore?: () => void; after?: ToastState };
export type ToastOptions = ToastState & {
  /** A preset: tone, glyph and time for the everyday and AI toasts. Anything set here wins over it. */
  type?: ToastType;
  undo?: ToastUndo;
  /** ms before it leaves; Infinity waits for an answer. Default: --pixilui-toast-hold with Undo or an action, else --pixilui-toast-brief. */
  hold?: number;
};
/** A live toast. */
export type ToastHandle = {
  el: HTMLElement;
  /** Turns the toast into its next state through the locked blur. */
  morph(state: ToastState & { picDo?: (pic: HTMLElement | null) => void }): Promise<void>;
  /** Starts its time again (ms; Infinity waits); done runs when it is up (default: it leaves). */
  arm(ms: number, done?: () => void): void;
  dismiss(): void;
};
/** The words and the close glyph every toast shares (for translation). */
export type ToastConfig = { close: ReactNode; closeLabel: string; undoLabel: string; regionLabel: string; retryLabel: string };

const CLOSE_GLYPH = (
  // the lock's own close: the static Hugeicons cancel-01 (MIT)
  <svg className="pixilui-i" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" aria-hidden="true">
    <path d="M18 6L6 18m12 0L6 6" />
  </svg>
);
const cfg: ToastConfig = { close: CLOSE_GLYPH, closeLabel: "Dismiss", undoLabel: "Undo", regionLabel: "Notifications", retryLabel: "Retry" };

const PRESETS: Record<ToastType, () => Partial<ToastOptions>> = {
  note: () => ({ tone: "neutral" }),
  done: () => ({ tone: "done", icon: <IconDone /> }),
  info: () => ({ tone: "neutral", icon: <IconInfo /> }),
  warning: () => ({ tone: "warn", icon: <IconWarning /> }),
  error: () => ({ tone: "fail", icon: <IconFailed />, hold: Infinity }),
  saving: () => ({ tone: "neutral", icon: <IconLoading />, working: true, hold: Infinity }),
  "agent-asks": () => ({ tone: "wait", hold: Infinity }),
  "run-stopped": () => ({ tone: "fail", hold: Infinity }),
  "money-moved": () => ({ tone: "done", moment: true }),
};

const isMac = () => typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
const two = (o: { actions?: ToastAction[]; undo?: ToastUndo | null }) => (o.actions || []).length + (o.undo ? 1 : 0) > 1;

/** A run's steps as a picture: dots on thin links filling the slot, each link in the state of the step it reaches; now breathes. */
export function ToastSteps({ steps }: { steps: ToastStepState[] }) {
  return (
    <span className="pixilui-toast-steps" aria-hidden="true">
      {steps.map((s, i) => [i ? <i key={`l${i}`} className="pixilui-toast-step-link" data-s={s} /> : null, <i key={`s${i}`} className="pixilui-toast-step" data-s={s} />])}
    </span>
  );
}

// the time ring: the disc's own rim, the time left in the tone's hue; pathLength 100, so any slot size works
const C = 100;
function Ring({ left }: { left: number }) {
  return (
    <svg className="pixilui-toast-ring" aria-hidden="true">
      <circle className="pixilui-toast-ring-left" cx="50%" cy="50%" pathLength={100} style={{ strokeDasharray: C, strokeDashoffset: (C * (1 - left)).toFixed(2) }} />
    </svg>
  );
}

type Glyph = { gen: number; node: ReactNode };
/** A disc's glyphs: a new one crosses in place (the old shrinks into a blur, the new one grows out of one), as the lock's turn. */
function DiscGlyphs({ glyph, pic }: { glyph: Glyph; pic: RefObject<HTMLSpanElement | null> }) {
  const [items, setItems] = useState<(Glyph & { out?: boolean })[]>([glyph]);
  if (items[items.length - 1]!.gen !== glyph.gen) setItems((list) => [...list.map((g) => ({ ...g, out: true })), glyph]);
  useLayoutEffect(() => {
    const p = pic.current;
    if (!p || items.length < 2) return;
    const reduce = prefersReducedMotion();
    const from = css(p, `--pixilui-toast-everyday-glyph-from`) || ".6";
    let live = true;
    const drop = () => { if (live) setItems((list) => list.filter((g) => !g.out)); };
    if (reduce) drop();
    else p.querySelectorAll<HTMLElement>(":scope > [data-glyph]").forEach((n) => {
      if (n.dataset.glyph === "out") n.animate([{ opacity: 1, filter: "blur(0)", scale: 1 }, { opacity: 0, filter: `blur(${css(p, "--pixilui-blur-in")})`, scale: from }], { duration: ms(p, "--pixilui-dur-exit"), easing: css(p, EASE_EXIT) || "ease", fill: "forwards" }).finished.then(drop, drop);
      else n.animate([{ opacity: 0, filter: `blur(${css(p, "--pixilui-blur-swap")})`, scale: from }, { opacity: 1, filter: "blur(0)", scale: 1 }], { duration: ms(p, "--pixilui-toast-swap"), easing: css(p, "--pixilui-ease-out") || "ease" });
    });
    playIcon(p);
    return () => { live = false; };
  }, [items, pic]);
  // each glyph is the disc's own child (the lock's `> svg` rule) in the icon slot (.pixilui-i, as the lock's .i), marked so a cross can find it
  return (
    <>
      {items.map((g) =>
        isValidElement(g.node)
          ? cloneElement(g.node as ReactElement<{ className?: string }>, { key: g.gen, className: cn("pixilui-i", (g.node as ReactElement<{ className?: string }>).props.className), "data-glyph": items.length > 1 ? (g.out ? "out" : "in") : undefined } as Record<string, unknown>)
          : g.node,
      )}
    </>
  );
}

export type ToastProps = Omit<ComponentPropsWithoutRef<"div">, "title"> & {
  /** What the toast says and shows: the same options toast() takes (type, tone, icon or picture, title, sub, undo, actions). */
  state: ToastOptions;
  /** With Undo: the ring's share of time left (1 full). */
  left?: number | null;
  /** The ring is fading out (Undo turned it). */
  ringOut?: boolean;
  /** Increments when a kept disc's glyph changes. */
  glyphGen?: number;
};

/**
 * A toast's markup without its behavior: a still copy for a states sheet or a preview (the same markup the live toast
 * renders). To show one at the corner, call toast().
 */
export const Toast = forwardRef<HTMLDivElement, ToastProps>(function Toast({ state, left, ringOut, glyphGen = 0, className, ...rest }, ref) {
  const o = resolve(state);
  return (
    <div
      ref={ref}
      className={cn("pixilui-toast font-body", className)}
      data-tone={o.tone ?? "neutral"}
      data-two={two(o) ? "" : undefined}
      data-working={o.working ? "" : undefined}
      aria-busy={o.working ? true : undefined}
      {...rest}
    >
      <ToastInner o={o} left={left ?? null} ringOut={ringOut} glyphGen={glyphGen} />
    </div>
  );
});

function ToastInner({ o, left, ringOut, glyphGen, gen = 0, keepPic }: { o: ToastOptions; left: number | null; ringOut?: boolean; glyphGen: number; gen?: number; keepPic?: boolean }) {
  const disc = o.icon != null && o.picture == null;
  const pic = useRef<HTMLSpanElement>(null);
  const keys = isMac() ? ["⌘", "Z"] : ["Ctrl", "Z"];
  return (
    <>
      <span ref={pic} key={keepPic ? "pic" : `pic${gen}`} className="pixilui-toast-pic" data-disc={disc ? "" : undefined} data-ring={left != null && !ringOut ? "" : undefined}>
        {disc ? <DiscGlyphs glyph={{ gen: glyphGen, node: o.icon }} pic={pic} /> : o.picture}
        {left != null ? <Ring left={left} /> : null}
      </span>
      <span key={`text${gen}`} className="pixilui-toast-text">
        <b className={o.working ? "pixilui-text-shimmer" : undefined}>{o.title}</b>
        {o.sub ? <small>{o.sub}</small> : null}
      </span>
      <span key={`acts${gen}`} className="pixilui-toast-actions">
        {o.undo ? (
          <Button variant="soft" data-act="undo" aria-keyshortcuts={isMac() ? "Meta+Z" : "Control+Z"} shortcut={keys}>
            {o.undo.label || cfg.undoLabel}
          </Button>
        ) : null}
        {(o.actions || []).map((a, i) => (
          <Button key={i} variant={a.kind === "go" ? "primary" : "soft"} data-act={i}>
            {a.label}
          </Button>
        ))}
      </span>
      <Button key={keepPic ? "close" : `close${gen}`} variant="secondary" size="xs" icon={cfg.close} aria-label={cfg.closeLabel} className="pixilui-toast-close" data-act="close" />
    </>
  );
}

function resolve(o: ToastOptions): ToastOptions {
  if (!o.type) return o;
  return { ...PRESETS[o.type](), ...Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) } as ToastOptions;
}

// -------------------------------------------------------------------------------------------------------------------
// the engine: a line-for-line port of the locked toast.js

/** The lock's exit curve, a token read by name (--pixilui-ease-in). */
const EASE_EXIT = "--pixilui-ease-in"; // check-registry-ignore: a token name, not a class
const P_ = "--pixilui-";
const rootStyle = () => getComputedStyle(region ?? document.documentElement);
// a system name as the library calls it (scripts/lib/locked-tokens.ts: --ease-in-out is --pixilui-ease-move)
const tokName = (n: string) => (n.startsWith(P_) ? n : n.replace(/^--/, P_));
const css = (el: Element | null, n: string) => getComputedStyle(el ?? region ?? document.documentElement).getPropertyValue(tokName(n)).trim();
const ms = (el: Element | null, n: string) => { const v = css(el, n); return v.endsWith("ms") ? parseFloat(v) : parseFloat(v) * 1000 || 0; };
const px = (n: string) => parseFloat(rootStyle().getPropertyValue(tokName(n))) || 0;
const reduce = () => prefersReducedMotion();
function playIcon(pic: HTMLElement | null, wait = 0) {
  if (!pic) return;
  setTimeout(() => { pic.setAttribute("data-pxi-play", ""); setTimeout(() => pic.removeAttribute("data-pxi-play"), ms(pic, "--pixilui-toast-pic-play")); }, wait);
}

type View = { o: ToastOptions; left: number | null; ringOut?: boolean; glyphGen: number; gen: number; keepPic?: boolean };
type T = {
  el: HTMLDivElement; slot: HTMLDivElement; root: Root; view: View; timer: Animation | null; h: number; leaving?: boolean;
  undo?: ToastUndo | null; restored?: boolean; working?: boolean; actions: ToastAction[]; dragging?: boolean; spring?: Animation | null; api: ToastHandle;
};
let region: HTMLElement | null = null;
let hovered = false;
const stack: T[] = []; // oldest first

function render(t: T) { flushSync(() => t.root.render(createElement(ToastInner, t.view))); }

function ensure() {
  if (region) return region;
  region = document.createElement("section"); region.className = "pixilui-toasts"; region.setAttribute("aria-label", cfg.regionLabel); region.setAttribute("aria-live", "polite");
  region.dataset.aurora = "full"; // the payoff at full strength (the locked Aurora light)
  region.dataset.look = "aurora";
  // a one-file build scopes its rules and tokens to `[data-pixilui]` // brand-allow
  region.setAttribute("data-pixilui", ""); // brand-allow
  document.body.appendChild(region);
  region.addEventListener("pointerenter", () => { hovered = true; layout(); pauseAll(); });
  region.addEventListener("pointerleave", () => { hovered = false; layout(); if (!document.hidden) playAll(); });
  document.addEventListener("visibilitychange", () => { if (document.hidden) pauseAll(); else if (!hovered) playAll(); });
  document.addEventListener("keydown", onKey);
  return region;
}
const pauseAll = () => stack.forEach((t) => t.timer?.pause());
const playAll = () => stack.forEach((t) => { if (!t.working) t.timer?.play(); });

// collapsed: the newest in front, older ones as edges behind it; fanned out: a list, newest at the bottom
function layout() {
  if (!region) return;
  const live = stack.filter((t) => !t.leaving), n = live.length, peek = px("--pixilui-toast-peek"), recede = parseFloat(rootStyle().getPropertyValue(tokName("--pixilui-toast-recede"))) || 0,
    show = parseInt(rootStyle().getPropertyValue(tokName("--pixilui-toast-show"))) || 3, gap = px("--pixilui-toast-stack-gap");
  const frontH = n ? live[n - 1]!.h : 0;
  let y = 0;
  live.slice().reverse().forEach((t, k) => {
    const s = t.slot.style;
    s.setProperty(`${P_}slot-z`, String(100 - k));
    if (hovered) { s.setProperty(`${P_}slot-y`, `${-y}px`); s.setProperty(`${P_}slot-s`, "1"); s.setProperty(`${P_}slot-o`, "1"); t.slot.removeAttribute("data-behind"); y += t.h + gap; }
    else {
      s.setProperty(`${P_}slot-y`, `${-k * peek}px`); s.setProperty(`${P_}slot-s`, String(1 - k * recede)); s.setProperty(`${P_}slot-o`, k < show ? "1" : "0");
      s.setProperty(`${P_}slot-h`, `${frontH}px`); t.slot.toggleAttribute("data-behind", k > 0);
    }
  });
  region.style.setProperty(`${P_}toasts-h`, `${hovered ? Math.max(0, y - gap) : frontH + peek * Math.min(Math.max(n - 1, 0), show - 1)}px`);
}
const measure = (t: T) => { t.slot.removeAttribute("data-behind"); t.h = t.el.offsetHeight; };

const gone = (t: T) => { t.root.unmount(); t.slot.remove(); const i = stack.indexOf(t); if (i >= 0) stack.splice(i, 1); };
// closing a toast early, by its close, a swipe or overflow, lets an action it was holding run now
const settle = (t: T) => { if (t.undo && !t.restored && t.timer?.playState !== "finished") t.undo.run?.(); };
function dismiss(t: T) {
  if (t.leaving) return; t.leaving = true;
  t.timer?.cancel();
  layout(); // the others glide into place while this one sinks away where it is
  void surfaceClose(t.el).then(() => gone(t));
}
// swiped away: it keeps going the way the finger threw it, at least as fast as the finger, and fades as it goes
function fling(t: T, x: number, v: number) {
  if (t.leaving) return; t.leaving = true;
  t.timer?.cancel(); layout();
  const el = t.el, to = el.offsetWidth + px("--pixilui-toast-edge"), dur = reduce() ? 0 : Math.min(ms(null, "--pixilui-toast-fling-max"), Math.max(ms(null, "--pixilui-toast-fling-min"), (to - x) / Math.max(v, parseFloat(css(null, "--pixilui-toast-fling-v")))));
  el.animate([{ translate: `${x}px 0`, opacity: getComputedStyle(el).opacity }, { translate: `${to}px 0`, opacity: 0 }], { duration: dur, easing: css(null, "--pixilui-ease-out") || "ease", fill: "forwards" })
    .finished.then(() => gone(t), () => gone(t));
}

// the time: one Animation per toast, so it pauses and plays with the others. With Undo it is the ring draining.
function arm(t: T, span: number, done?: (() => void) | null) {
  t.timer?.cancel(); t.timer = null;
  if (!Number.isFinite(span)) return; // a question waits for its answer
  const c = t.el.querySelector(".pixilui-toast-ring-left");
  t.timer = c ? c.animate([{ strokeDashoffset: 0 }, { strokeDashoffset: C }], { duration: span, easing: "linear", fill: "forwards" })
    : new Animation(new KeyframeEffect(null, [], { duration: span }), document.timeline);
  if (!c) t.timer.play();
  if (hovered || document.hidden || t.dragging) t.timer.pause();
  t.timer.finished.then(() => { if (!t.leaving) (done || (() => dismiss(t)))(); }, () => {});
}

// an action, or Undo, turns the toast itself into its next state: the words (and the picture, unless kept) swap through a blur
async function morph(t: T, next: ToastState & { picDo?: (p: HTMLElement | null) => void }) {
  const el = t.el, keepPic = !("icon" in next) && !("picture" in next);
  const prev = t.view.o;
  // a new glyph on a kept disc crosses in place (the everyday turn and Undo's turn); a new picture replaces the slot
  const cross = !keepPic && next.icon != null && next.picture == null && prev.icon != null && prev.picture == null;
  const keep = (keepPic || cross) && el.querySelector<HTMLElement>(".pixilui-toast-pic");
  const parts = () => [...el.children].filter((x) => !x.classList.contains("pixilui-toast-close") && !(keep && x === keep)) as HTMLElement[];
  if (!reduce()) await Promise.all(parts().map((p) => p.animate([{ opacity: 1, filter: "blur(0)" }, { opacity: 0, filter: `blur(${css(null, "--pixilui-blur-in")})` }],
    { duration: ms(null, "--pixilui-dur-exit"), easing: css(null, EASE_EXIT) || "ease", fill: "forwards" }).finished.catch(() => {})));
  const { picDo, ...rest } = next;
  const o: ToastOptions = { ...rest };
  if (keepPic) { o.icon = prev.icon; o.picture = prev.picture; }
  t.working = !!o.working;
  if (o.tone) el.dataset.tone = o.tone;
  el.toggleAttribute("data-working", t.working); el.setAttribute("aria-busy", String(t.working));
  t.view = { ...t.view, o, gen: t.view.gen + 1, keepPic: !!keep, glyphGen: cross ? t.view.glyphGen + 1 : t.view.glyphGen };
  render(t);
  picDo?.(el.querySelector(".pixilui-toast-pic"));
  t.actions = o.actions || []; el.toggleAttribute("data-two", two(o));
  if (!reduce()) parts().forEach((p) => p.animate([{ opacity: 0, filter: `blur(${css(null, "--pixilui-blur-swap")})` }, { opacity: 1, filter: "blur(0)" }],
    { duration: ms(null, "--pixilui-toast-swap"), easing: css(null, "--pixilui-ease-out") || "ease" }));
  measure(t); layout();
  if (t.working) t.timer?.pause();
  if (o.moment) moment(el);
}

// swipe to dismiss: follows the finger 1:1 to the right, friction to the left, a flick or a long drag sends it off
function swipe(t: T) {
  const el = t.el;
  let g: { id: number; x0: number; y0: number; base: number; x: number; at: number; on: boolean } | null = null;
  el.addEventListener("pointerdown", (e) => {
    if (g || t.leaving || e.button !== 0 || (e.target as Element).closest("button, a")) return; // one finger; never from a button
    let base = 0;
    if (t.spring?.playState === "running") { base = parseFloat(getComputedStyle(el).translate) || 0; t.spring.cancel(); t.spring = null; el.style.translate = `${base}px 0`; }
    g = { id: e.pointerId, x0: e.clientX, y0: e.clientY, base, x: base, at: 0, on: false };
  });
  el.addEventListener("pointermove", (e) => {
    if (!g || e.pointerId !== g.id) return;
    const dx = e.clientX - g.x0, dy = e.clientY - g.y0, start = px("--pixilui-toast-swipe-start");
    if (!g.on) {
      if (Math.abs(dx) < start && Math.abs(dy) < start) return;
      if (Math.abs(dy) > Math.abs(dx)) { g = null; return; } // a vertical move belongs to the page
      g.on = true; g.x0 += Math.sign(dx) * start; g.at = performance.now(); t.dragging = true;
      el.setPointerCapture(g.id); el.dataset.dragging = ""; t.timer?.pause();
    }
    const raw = g.base + e.clientX - g.x0, reach = px("--pixilui-toast-swipe-friction");
    g.x = raw >= 0 ? raw : -reach * (1 - Math.exp(raw / (reach * 2.5))); // left: it gives a little, then less and less
    el.style.translate = `${g.x}px 0`;
    el.style.opacity = String(1 - Math.min(1, Math.max(0, g.x) / el.offsetWidth) * (parseFloat(css(el, "--pixilui-toast-swipe-fade")) || 0));
  });
  const end = (e: PointerEvent) => {
    if (!g || e.pointerId !== g.id) return;
    const was = g; g = null; if (!was.on) return;
    t.dragging = false; delete el.dataset.dragging;
    const v = Math.abs(was.x - was.base) / Math.max(1, performance.now() - was.at);
    if (e.type === "pointerup" && (was.x >= px("--pixilui-toast-swipe-dismiss") || (was.x > was.base && v > parseFloat(css(null, "--pixilui-toast-swipe-flick"))))) {
      settle(t); el.style.translate = ""; el.style.opacity = "";
      fling(t, was.x, v); return;
    }
    const from = { translate: `${was.x}px 0`, opacity: el.style.opacity || 1 };
    el.style.translate = ""; el.style.opacity = "";
    if (!reduce()) t.spring = el.animate([from, { translate: "0px 0", opacity: 1 }], { duration: parseFloat(css(el, "--pixilui-spring-snappy-duration")) || 300, easing: css(el, "--pixilui-spring-snappy") || css(null, "--pixilui-ease-out") });
    if (!hovered && !document.hidden && !t.working) t.timer?.play();
  };
  el.addEventListener("pointerup", end); el.addEventListener("pointercancel", end);
}

// Undo is a rewind: the ring winds back up to full, the time given back; then the disc turns to the result's tone and grows
// back to the slot as the ring fades, the glyph blurs across to the new one and plays its move, and the words swap
async function undoNow(t: T) {
  const after = t.undo?.after, left = t.el.querySelector<SVGElement>(".pixilui-toast-ring-left");
  const from = left ? getComputedStyle(left).strokeDashoffset : null; // read before the timer is cancelled, or the ring jumps full
  t.restored = true; t.undo?.restore?.(); t.timer?.cancel(); t.undo = null;
  if (!after) { dismiss(t); return; }
  // the parts that leave keep their own color as they fade (red into green passes through olive on the way)
  const glyph = t.el.querySelector<HTMLElement>(".pixilui-toast-pic svg.pxi, .pixilui-toast-pic .pixilui-i");
  if (left) left.style.stroke = getComputedStyle(left).stroke;
  if (glyph) glyph.style.color = getComputedStyle(glyph).color;
  if (left && !reduce()) { // on-screen motion: the travel time on the move curve; the words start turning halfway through
    const d = ms(null, "--pixilui-toast-move");
    left.animate([{ strokeDashoffset: from! }, { strokeDashoffset: 0 }], { duration: d, easing: css(null, "--pixilui-ease-move") || "ease", fill: "forwards" });
    await new Promise((r) => setTimeout(r, d / 2));
  }
  // the ring fades out as the disc glides back to the slot
  const ring = t.el.querySelector<SVGElement>(".pixilui-toast-ring");
  t.view = { ...t.view, ringOut: true };
  render(t);
  const ringGone = () => { t.view = { ...t.view, left: null, ringOut: false }; render(t); };
  if (ring && !reduce()) ring.animate([{ opacity: 1 }, { opacity: 0 }], { duration: ms(null, "--pixilui-dur-exit"), easing: css(null, EASE_EXIT) || "ease", fill: "forwards" }).finished.then(ringGone, ringGone);
  else ringGone();
  await morph(t, after);
  arm(t, ms(null, "--pixilui-toast-brief"));
}

// as the toast arrives, its picture springs in a beat later and its icon plays its locked move once
function arrive(p: HTMLElement | null) {
  if (!p || reduce()) return;
  p.animate([{ scale: parseFloat(css(p, "--pixilui-toast-pic-in")) || .6, opacity: 0 }, { scale: 1, opacity: 1 }],
    { duration: parseFloat(css(p, "--pixilui-spring-snappy-duration")) || 300, delay: parseFloat(css(p, "--pixilui-toast-pic-delay")) || 0, easing: css(p, "--pixilui-spring-snappy") || css(null, "--pixilui-ease-out"), fill: "backwards" });
  playIcon(p, parseFloat(css(p, "--pixilui-toast-pic-delay")) || 0);
}
// a payoff (money moved, a merge): the locked Aurora pop and the glass light rising, holding a moment and letting go
function moment(el: HTMLElement) {
  if (reduce()) return;
  const fam = el.dataset.tone === "fail" ? "fail" : "done";
  relayPop(el);
  relayHold(el, true, fam);
  setTimeout(() => { if (el.isConnected) relayHold(el, false); }, parseFloat(css(el, "--pixilui-toast-moment")) || 1200);
}

/** Shows a toast at the corner. Returns the live toast: morph, arm and dismiss it. */
export function toast(input: ToastOptions): ToastHandle {
  ensure();
  const o = resolve(input);
  const { tone = "neutral", undo, actions, hold } = o;
  const slot = document.createElement("div"); slot.className = "pixilui-toast-slot";
  const el = document.createElement("div"); el.className = "pixilui-toast font-body"; el.dataset.tone = tone; el.dataset.surface = "edge"; el.setAttribute("role", "status");
  el.toggleAttribute("data-two", two(o));
  if (o.working) { el.setAttribute("data-working", ""); el.setAttribute("aria-busy", "true"); } // working from its first frame (the everyday fix)
  slot.appendChild(el); region!.appendChild(slot);
  const t = { el, slot, root: createRoot(el), view: { o, left: undo ? 1 : null, glyphGen: 0, gen: 0 }, timer: null, h: 0, actions: actions || [], undo, working: !!o.working } as unknown as T;
  t.api = { el, morph: (s) => morph(t, s), arm: (span, done) => arm(t, span, done), dismiss: () => dismiss(t) };
  render(t);
  stack.push(t); measure(t); layout();
  surfaceOpen(el);
  arrive(el.querySelector(".pixilui-toast-pic"));
  arm(t, hold ?? ms(null, undo || o.actions?.length ? "--pixilui-toast-hold" : "--pixilui-toast-brief"), undo ? () => { undo.run?.(); dismiss(t); } : null);
  swipe(t);
  el.addEventListener("click", (e) => {
    const b = (e.target as Element).closest<HTMLElement>("[data-act]"); if (!b || t.leaving) return;
    const a = b.dataset.act!;
    if (a === "close") { settle(t); dismiss(t); return; }
    if (a === "undo") { void undoNow(t); return; }
    const act = t.actions[+a]; if (!act) return;
    const keep = act.run?.(t.api); if (!keep) dismiss(t);
  });
  if (o.moment) moment(el);
  // too many: the oldest leaves, and if it was holding an action, the action runs now
  const live = stack.filter((x) => !x.leaving), max = parseInt(rootStyle().getPropertyValue(tokName("--pixilui-toast-max"))) || 4;
  if (live.length > max) { const old = live[0]!; settle(old); dismiss(old); }
  return t.api;
}

// ⌘Z / Ctrl+Z undoes the newest toast still holding an action (not while typing)
function onKey(e: KeyboardEvent) {
  const mac = isMac();
  if (!(mac ? e.metaKey : e.ctrlKey) || e.shiftKey || e.altKey || e.key.toLowerCase() !== "z") return;
  if ((e.target as Element | null)?.closest?.("input, textarea, [contenteditable=\"\"], [contenteditable=\"true\"]")) return;
  const t = stack.filter((x) => !x.leaving && x.undo && !x.restored).at(-1); if (!t) return;
  e.preventDefault(); void undoNow(t);
}

/**
 * One toast that waits for a task (the everyday save): working from its first frame (the loading glyph's rays, the title's
 * shimmer, no timer); success or error turns the same toast; an error waits with Retry, which runs the task again in place.
 */
toast.promise = function promise(task: () => unknown, s: { loading: ToastOptions; success: ToastOptions; error: ToastOptions }, t?: ToastHandle): ToastHandle {
  const loading = resolve({ type: "saving", ...s.loading }), success = resolve({ type: "done", ...s.success }), error = resolve({ type: "error", ...s.error });
  const handle = t ?? toast({ ...loading, working: true, hold: Infinity });
  const words = ({ type: _type, hold: _hold, undo: _undo, ...rest }: ToastOptions): ToastState => rest;
  Promise.resolve().then(task).then(
    () => handle.morph(words(success)).then(() => handle.arm(ms(null, "--pixilui-toast-brief"))),
    () => handle.morph({ ...words(error), actions: [{ label: cfg.retryLabel, kind: "go", run: () => {
      void handle.morph({ ...words(loading), working: true }).then(() => toast.promise(task, s, handle));
      return true; } }] }));
  return handle;
};
/** Sets the words and the close glyph every toast shares. */
toast.config = (o: Partial<ToastConfig>) => { Object.assign(cfg, o); if (region) region.setAttribute("aria-label", cfg.regionLabel); };
/** Dismisses every toast. */
toast.dismissAll = () => stack.slice().forEach(dismiss);
```

## Usage

When to use:

- A delete or an archive you can still undo: undo holds the action until the rim runs out, and Undo or ⌘Z restores it in place.
- The agent asking one quick question (agent-asks): the answer that matters is the primary, and the toast turns into the work, then the result.
- A run that stopped (run-stopped, with ToastSteps) waiting for Retry, or money moved (money-moved) with the Aurora pop and glass light.
- The everyday set: note, done, info with one action, a warning that lasts, an error that waits, and saving that resolves in the same toast (toast.promise).

When not to use:

- Something tied to one place on the page: use a notice in that place.
- Something that affects the whole app (a limit, an outage): use a banner.
- A decision that cannot wait or must not be missed: use a dialog.

```tsx
import { useState } from "react";
import { IconDelete } from "@/components/pixilui/icons/delete";
import { IconUndo } from "@/components/pixilui/icons/undo";
import { AgentAvatar, type AgentAvatarState } from "@/components/pixilui/agent-avatar";
import { Button } from "@/components/pixilui/button";
import { toast, ToastSteps, Toast, type ToastHandle, type ToastOptions } from "@/components/pixilui/toast";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  type: ["delete with undo", "note", "done", "info", "warning", "error", "saving", "agent asks", "run stopped", "money moved"],
} as const;

const agent = (state: AgentAvatarState) => <AgentAvatar family="2d" color="blue" name="Support agent" size={60} state={state} />;
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));

// the locked pages' toasts, in the support agent's world
const ASK = { title: "Refund Lena Ortiz $214.00?", sub: "Charged twice on Nov 14 for the same order." };
const SEEN: Record<(typeof knobs.type)[number], ToastOptions> = {
  "delete with undo": { tone: "fail", icon: <IconDelete />, title: "Run deleted", sub: "Seat audit for Hana Ito", undo: { after: { tone: "done", icon: <IconUndo />, title: "Run restored", sub: "Seat audit for Hana Ito" } } },
  note: { type: "note", title: "Lena's chat moved to Done" },
  done: { type: "done", title: "Invite sent to Hana Ito", sub: "She'll get an email in a minute" },
  info: { type: "info", title: "New agent version ready", sub: "Reload to use v13", actions: [{ label: "Reload", kind: "soft" }] },
  warning: { type: "warning", title: "You're offline", sub: "Replies will send when you're back" },
  error: { type: "error", title: "Couldn't save the instructions", sub: "Your edits are kept", actions: [{ label: "Retry", kind: "go" }] },
  saving: { type: "saving", title: "Saving the instructions", sub: "v13 for the support agent" },
  "agent asks": { type: "agent-asks", picture: agent("waiting"), ...ASK, actions: [{ label: "Keep charge", kind: "soft" }, { label: "Refund $214.00", kind: "go" }] },
  "run stopped": { type: "run-stopped", picture: <ToastSteps steps={["done", "done", "done", "fail"]} />, title: "Couldn't reach Stripe", sub: "The refund wasn't sent.", actions: [{ label: "Retry", kind: "go" }] },
  "money moved": { type: "money-moved", picture: agent("done"), title: "Refunded $214.00", sub: "Back on Lena's Visa in 5 to 10 days" },
};

// what Show does: the same toast, live, with its story where it has one
function play(type: (typeof knobs.type)[number]) {
  const o = SEEN[type];
  if (type === "saving") return toast.promise(() => wait(1800), { loading: o, success: { title: "Instructions saved", sub: "Live for every agent now" }, error: SEEN.error });
  if (type === "agent asks") return toast({ ...o, picture: agent("waiting"), actions: [
    { label: "Keep charge", kind: "soft", run: (t) => { void t.morph({ tone: "neutral", title: "Charge kept", sub: "The agent won't ask about this one again" }).then(() => t.arm(2400)); return true; } },
    { label: "Refund $214.00", kind: "go", run: (t) => { void refund(t); return true; } },
  ] });
  if (type === "run stopped") return toast({ ...o, actions: [{ label: "Retry", kind: "go", run: (t) => { void retry(t); return true; } }] });
  return toast(o);
}
async function refund(t: ToastHandle) {
  await t.morph({ tone: "neutral", picture: agent("running"), title: "Refunding Lena Ortiz", sub: "$214.00 to Visa ending 4242", working: true });
  await wait(1900);
  await t.morph({ tone: "done", picture: agent("done"), title: "Refunded $214.00", sub: "Back on Lena's Visa in 5 to 10 days", moment: true });
  t.arm(3600);
}
async function retry(t: ToastHandle) {
  await t.morph({ tone: "neutral", picture: <ToastSteps steps={["done", "done", "done", "now"]} />, title: "Retrying the refund", sub: "$214.00 to Visa ending 4242", working: true });
  await wait(1900);
  await t.morph({ tone: "done", picture: <ToastSteps steps={["done", "done", "done", "done"]} />, title: "Refunded $214.00", sub: "Paid on the second try", moment: true });
  t.arm(3600);
}

/** The chosen toast as it looks at rest (the Undo rim at 62% left), and Show to play it live at the corner. */
export default function ToastDemo({ type = "delete with undo" }: KnobValues<typeof knobs>) {
  const [n, setN] = useState(0);
  return (
    <div className="flex w-full max-w-md flex-col items-center gap-6">
      <Toast key={type} state={SEEN[type]} left={type === "delete with undo" ? 0.62 : null} className="w-full" />
      <Button variant="soft" size="sm" onClick={() => { play(type); setN(n + 1); }}>
        Show it
      </Button>
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `state` (required) | `ToastOptions` |  | What the toast says and shows: the same options toast() takes (type, tone, icon or picture, title, sub, undo, actions). |
| `left` | `number \| null` |  | With Undo: the ring's share of time left (1 full). |
| `ringOut` | `boolean` |  | The ring is fading out (Undo turned it). |
| `glyphGen` | `number` | `0` | Increments when a kept disc's glyph changes. |

Also accepts every native `<div>` attribute except `title`, and a ref to it.

## Keyboard

- `⌘` + `Z`: Undoes the newest toast still holding an action (Ctrl+Z off a Mac), not while typing in a field.
- `Tab`: Reaches the actions and the close, which shows on focus.
- `Enter` + `Space`: Runs the focused action.

## Accessibility

- The region is a polite live region named Notifications; each toast is role status, so a screen reader hears its title and the line under it.
- Undo announces its keys (aria-keyshortcuts). A working toast sets aria-busy from its first frame.
- Pointing at the toasts, a drag, or leaving the tab pauses every timer, so nothing runs out while it is being read; an error never times out.
- The close has a 36px target around its 24px button. Touch swipes instead.

## Motion

- It rises from the edge out of a blur; the picture springs in 60ms later and its icon plays its move once.
- Undo: the red rim winds back to full over 420ms, then fades as the disc turns green and the words blur across (200ms).
- A turn swaps the words through the locked blur (out 140ms ease-in, in 200ms ease-out); a kept disc crosses its glyph in place.
- The stack fans out while you point at it and glides back on the locked 420ms travel; a swipe flies off at the finger's speed or springs back.
- Money moved: the locked Aurora pop and glass light, held 1200ms. Reduced motion: everything swaps at once, but the rim still runs: it is the time.

## Responsive

- 400 wide in lively and 360 in quiet, never wider than the window less 24px each side; the words take what is left and the line under the title clamps at two lines.

## Performance

- One Web Animation per toast is its timer, so pausing is free; the payoff light runs on Aurora light's one shared clock.

## Notes for AI

- toast({ type: "done", title: "Reply sent to Lena" }) shows one; it returns { el, morph(state), arm(ms), dismiss() }. No provider to mount: the region is made on first use.
- Types: note, done, info, warning, error, saving, agent-asks, run-stopped, money-moved. A type is a preset (tone, glyph, time); anything you pass wins.
- undo: { run, restore, after } holds run until the rim runs out; Undo or ⌘Z calls restore and turns the toast into after.
- actions: [{ label, kind: "go" | "soft", run(t) }]; return true from run to keep the toast, then t.morph(next) and t.arm(ms).
- icon goes in a disc of the tone; picture stands alone (an AgentAvatar, a user avatar, <ToastSteps steps={[...]} />, a toast figure). Leave both out of a morph to keep the picture.
- toast.promise(task, { loading, success, error }) is one toast from working to its result; an error waits with Retry. toast.config({ closeLabel, undoLabel, regionLabel, retryLabel, close }) sets the shared words.
- Toast renders the same markup still, for a states sheet or a preview.

## Related

- [Toast figures](https://pixilui.com/components/toast-figures/markdown): Ten small figures for the toast's picture slot that show an AI moment's own data in flat marks: a run, an approval gate, agents in parallel, a handoff, context, accuracy, a retry, latency, spend and a voice call.
- [Banner](https://pixilui.com/components/banner/markdown): One line across the top of the app or a panel for something that affects all of it: a runs limit, a paused agent, news. A bare icon or the agent, the lead in ink and the rest in grey, one action, a close only when it can go.
- [Notice](https://pixilui.com/components/notice/markdown): A tinted panel in the content about the thing beside it: a bare icon in the tone or the agent as the subject, the title and its line, one action, and a close only when it can go, lit with a still glim at the mark.
- [Aurora light](https://pixilui.com/components/aurora-light/markdown): Soft light for an element's moment, in our glass colors: the glim crosses a card when work arrives, the rim blooms out of what you pressed and holds while the agent works, the ring pops for a moment that matters.
