# Aurora toast

> A dark toast at the top of a billing page, heralded by a wash of colour that falls through the page and leaves a soft glow behind it.

A quiet billing page with its figures and recent invoices. Mark an invoice paid, send a payout or let a payment fail, and a wide crescent of colour falls through the page, green and cyan at the top, violet and magenta lower down, blurring the page as it passes. The dark toast slides in at the top centre while it falls, and the wash settles into a faint blue glow with a fine dot screen that stays behind it; a failed payment turns it all warm. Toasts stack, leave on their own, wait while you hover or focus them, and close with the cross or Escape.

A React component by Bruno Delorence: https://brunodelorence.com/components/aurora-toast. MIT License, Copyright (c) 2026 Bruno Delorence.

Category: Feedback.

## Anatomy

1. **Stage**: The billing page the toast arrives over: header, title row with the event buttons, four figures and the recent invoices.
2. **Halo**: The glow the wash leaves behind the toast: a soft ellipse of the kind’s tint with an 8 px dot screen, over a 1 px blur of the page.
3. **Toast**: A dark slate card at the top centre, 420 px wide at most, 72 px tall, 30 px from the top on a wide stage.
4. **Glyph**: A pale drawing of what happened, fading toward its bottom: a sheet for an invoice, a card for a payout, a sheet with a warning for a failure.
5. **Title**: What happened, in a sentence without a full stop.
6. **Detail**: The figure that matters, its parts joined by a middle dot.
7. **Close**: A 24 px round button named after the toast: “Dismiss: Your invoice has been paid”.

## Properties

### Mode (`mode`)

1. **Stack (default)**: Earlier toasts slide down under the new one, up to `max` (3).
2. **Replace**: The new toast sends the last one away: one at a time.

Stack when events can arrive close together and each one matters (two invoices paid). Replace when only the latest state counts.

### Wash (`wash`)

1. **On (default)**: The colour falls through the page first, and the toast arrives 420 ms after the event.
2. **Off**: The toast arrives at once and its halo fades in: the same as with reduced motion.

Keep the wash for the events worth celebrating. Turn it off where toasts are frequent, and let reduced motion turn it off for the reader.

## When to use

- Good news that arrives on its own while the person works: an invoice paid, a payout sent, a large import finished.
- A rare event worth a moment of ceremony, a few times a session at most, on a page that is otherwise quiet.
- A short message of two lines, a title and a detail with the figure that matters: `Invoice #0042 · $3,240.00`.
- A product tour or a landing page, where the wash shows what a notification can feel like.

## When not to use

- Frequent or routine events, like each saved field or each new message. The wash every few seconds becomes noise; use a plain toast.
- Errors that block the work or need an answer. Put them inline, by the field or the action, or in a dialog.
- Anything the person must read before it goes: a toast leaves on its own. Keep it on the page.
- Busy, colourful pages. The wash needs a pale, quiet page under it to read as a sweep of light.
- More than a line of detail or any form. Toasts take one action at most: here, closing it.

### Timing

- **5 seconds** by default, set with `duration`; `0` keeps the toast until it is closed.
- **Paused while held**: the pointer over the toasts or the focus inside them stops every timer, and each picks up with what it had left.
- **Escape** anywhere on the stage closes the newest toast; the × closes one.
- **The wash takes 1.5 s**, the colour falling through in about 1.2 s; the toast is in place before it ends.

### Choosing a kind

- **Invoice paid** for money received: the full aurora, green at the top to peach at the bottom, and a blue halo.
- **Payout sent** for money leaving to the bank: a cool wash, cyan to indigo.
- **Payment failed** for a charge that did not go through: amber to rose, a warmer slate and an amber halo. Say what failed and leave the fix on the page.

## Do’s and don’ts

- **Do**: Lead with what happened and put the figure that matters in the detail: the invoice and its amount.
- **Don’t**: Raise one toast per item of a batch. Three invoices paid at once are one toast that gives the count and the total.
- **Do**: Match the kind to the event: a failed payment takes the warm slate and the warning glyph, and says what failed.
- **Don’t**: Raise a wash for every small event. Keep it for the ones worth a moment, and turn it off with `wash={false}` where toasts come often.

## Content

Two lines: the title says what happened, the detail gives the figure.

- **Title in sentence case**, no full stop: `Your invoice has been paid`, `Payout sent to your bank`, `A payment failed`.
- **Detail as fragments** joined by a middle dot: `Invoice #0042 · $3,240.00`, `$12,460.00 · arrives Thursday`.
- **Name the thing**: the invoice number, the amount, the day. Not “Something happened”.
- **For a failure, say what failed** (`card declined`), not whose fault it was.

## Installation

Install it with the shadcn CLI, into components/aurora-toast of any React project:

```sh
npx shadcn@latest add https://brunodelorence.com/r/aurora-toast.json
```

Or add the registry to components.json once, as a namespace that coding agents and the shadcn MCP server search by name:

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

```sh
npx shadcn@latest add @brunodelorence/aurora-toast
```

Or copy all the source files below into one folder of your project. Either way it needs React 19 and a bundler with CSS Modules (Next.js, Vite).

It has a dark colour scheme. Its colours are CSS light-dark() pairs, kept inside @supports so that builds which rewrite light-dark() for older browsers leave them alone: it follows your page’s color-scheme (light unless the page sets one) or its colorScheme prop, with nothing to configure. Browsers without light-dark() show it light.

## Usage

```tsx
import { AuroraToast } from './aurora-toast';

export function BillingNotifications() {
  return (
    <AuroraToast
      duration={6000}
      onToast={(notice) => console.info(notice.title)}
      autoplay={false}
    />
  );
}
```

## States

- **Empty**: The page at rest: no toast, no halo. Nothing renders until an event arrives.
- **Invoice paid**: The settled toast with its blue halo, after the wash; the invoice in the list now says Paid.
- **Payout sent**: The same toast with a card glyph; its wash stays cool, cyan to indigo.
- **Payment failed**: A warmer slate and an amber halo; the wash falls through amber, orange and rose.
- **Stacked**: Newest on top, 8 px apart; the halo takes the newest one’s tint.
- **Dark**: With `colorScheme="dark"`: a near-black page, a slightly lighter toast, and the wash added as light.

## How it works

- The wash is a crescent painted on a canvas a third of the stage’s size: a soft ellipse, its top cut away by a second one, with a fainter ellipse of the colour it just left trailing above. Stretched to the stage, the small canvas comes out soft without a blur filter on something that changes every frame.
- Its fall was measured frame by frame from 60 fps footage: from above the top edge, slow over the first 0.3 s, then about two stage heights a second, gone by 1.2 s; the strength rises over 0.32 s and fades from 0.92 s.
- Its colour comes from where it is: each kind has a ramp from the top of the stage to the bottom. Invoice paid runs green #8ef5bf, cyan, blue #7698fe, violet, magenta #e467d8, pink and peach; payout stays cyan to indigo; a failed payment runs amber to rose.
- Under it the page goes soft with backdrop-filter: a 3 px veil over all of it for the length of the wash, and a 12 px blur masked to an ellipse that follows the crescent through a --wash-y custom property the script writes each frame.
- The toast arrives 420 ms after the event, sliding down from above the top edge in 460 ms on cubic-bezier(0.22, 1.12, 0.36, 1); its row folds open with a grid-template-rows animation, so earlier toasts slide down 8 px under it, and folds shut as it leaves in 260 ms.
- The halo is a radial gradient of the kind’s tint with an 8 px dot screen and a 1 px backdrop blur, masked to an ellipse about twice the toast’s width; it fades in over 0.8 s and stays while any toast does.
- Sizes come from the reference at 1530 px, scaled to a 420 px toast: 72 px tall, a 17 px radius, a 40 px glyph, 15/20 and 14/19 type, a 24 px close button, 30 px from the top.
- Each toast has a 5 s timer that pauses while the pointer or the focus is on the toasts and keeps what it had left. The canvas only renders during a wash, and a wash is skipped while the stage is off screen.
- At night the canvas is added as light (mix-blend-mode: screen) at 78%; which scheme is in use is read back from a light-dark() colour on the canvas, so the prop and the page both work.

## API reference

- **duration** (`number`, default `5000`): How long each toast stays, in ms; 0 keeps it until it is closed.
- **mode** (`'stack' | 'replace'`, default `'stack'`): Stack keeps earlier toasts below the new one; replace sends the last one away.
- **max** (`number`, default `3`): The most toasts shown at once in stack mode; the oldest leaves to make room.
- **wash** (`boolean`, default `true`): The wash of colour before each toast. Off, or with reduced motion, the toast just fades in.
- **defaultToasts** (`('paid' | 'payout' | 'failed')[]`): Toasts already in place when it mounts, settled and without a wash, the first on top: a still for docs and screenshots. It turns the autoplay demo off.
- **onToast** (`(notice: Notice) => void`): Called with each toast as it arrives: its kind, title and detail.
- **onDismiss** (`(notice: Notice, reason: 'timeout' | 'close' | 'escape' | 'replaced') => void`): Called with each toast as it leaves, and why.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, a demo pointer raises a paid invoice and closes it, lets a payout leave on its own, then raises a failed payment; any input stops it.
- **colorScheme** (`'light' | 'dark' | 'system'`): Light or dark colours, or the reader’s; without it, the page’s color-scheme.
- **className** (`string`): A class for the stage.

## Accessibility

### Screen readers

- Each toast is said once, in a polite live region, as a sentence: “Your invoice has been paid. Invoice #0042, $3,240.00.”
- The toasts are an ordered list named Notifications, after the page in reading order; the close button is named after its toast.
- The glyphs, the halo, the wash and the demo pointer are hidden from screen readers.

### Keyboard

- Tab reaches the event buttons, then each toast’s close button. Enter or Space closes it.
- Escape anywhere on the stage closes the newest toast. When a toast with the focus leaves, the focus moves to the next toast’s ×, or back to the button that raised it.
- The focus inside the toasts pauses their timers, so a keyboard reader has all the time they need.

### Timing and motion

The timers pause on hover and focus (WCAG 2.2.1), and `duration={0}` keeps toasts until closed. With reduced motion there is no wash and no slide: the toast and its halo fade in over 240 ms. The wash is skipped while the stage is off screen.

### Colour and contrast

The title is white and the detail #b4babe on the #444a4f slate, about 9 : 1 and 4.6 : 1 (WCAG 1.4.3). The kind is said in the title, never by the tint alone (1.4.1).

### In this build

- Each toast is announced once in a polite live region, as a sentence (“Your invoice has been paid. Invoice #0042, $3,240.00.”); the toasts are an ordered list named Notifications.
- Each close button is named after its toast (“Dismiss: Your invoice has been paid”); Escape anywhere on the stage closes the newest toast.
- When a toast with the focus leaves, the focus moves to the next toast’s close button, or back to the button that raised it; a leaving toast is inert.
- The timers pause while the pointer or the focus is on the toasts (WCAG 2.2.1), and duration={0} keeps toasts until they are closed.
- Every button shows a focus ring on keyboard focus. The glyphs, the halo, the wash and the demo pointer are hidden from screen readers.
- With reduced motion there is no wash and no slide: the toast and its halo fade in, and the demo does not play.

## Source

### aurora-toast/aurora-toast.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { Dashboard } from './dashboard';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { EVENTS, RAMPS, type InvoiceStatus, type Kind, type Notice } from './events';
import { Cross, Glyph } from './glyphs';
import { useAutoplay } from './use-autoplay';
import { WASH_MS, paintWash, washAt, type Ramp } from './wash';
import styles from './aurora-toast.module.css';

/*
 * Aurora toast: a dark toast that arrives at the top of a quiet billing page, heralded by a wash
 * of colour that falls through the whole page and leaves a soft glow behind the toast.
 *
 * - The wash (wash.ts) is a crescent of colour painted on a small canvas that falls from above the
 *   stage to below it in about 1.2 s, its hue changing as it goes. Under it, two layers blur the
 *   page with backdrop-filter: a light veil over all of it for the length of the wash, and a
 *   stronger blur masked to the crescent, moving with it. They follow the custom properties the
 *   script writes each frame (--veil, --wash-y, --wash-glow).
 * - The toast slides in from above the stage's top edge 420 ms after the event, while the wash is
 *   still high, and a halo of the kind's tint (blue, or amber for a failed payment) with a fine
 *   dot screen fades in behind it and stays while any toast does.
 * - Toasts stack, newest on top, up to `max`; or each replaces the last. Each leaves on its own
 *   after `duration`, a timer that pauses while the pointer or the focus is on the toasts. The ×
 *   closes one; Escape anywhere on the stage closes the newest. A polite live region says each
 *   toast once, in words.
 * - Nothing renders frame by frame outside a wash, and a wash is skipped while the stage is off
 *   screen. With reduced motion there is no wash: the toast and its halo just fade in.
 * - While on screen and untouched, a demo pointer raises a paid invoice and closes it, lets a
 *   payout leave on its own, then raises a failed payment, in a loop.
 */

type Toast = { id: number; notice: Notice; leaving: boolean; still?: boolean };

export type DismissReason = 'timeout' | 'close' | 'escape' | 'replaced';

/** The toast arrives this long after its event, while the wash is still near the top. */
const ARRIVE = 420;
/** How long a toast takes to leave before it is removed. */
const LEAVE = 260;
const KINDS: Kind[] = ['paid', 'payout', 'failed'];

export function AuroraToast({
  duration = 5000,
  mode = 'stack',
  max = 3,
  wash = true,
  defaultToasts,
  onToast,
  onDismiss,
  autoplay = true,
  colorScheme,
  className = '',
}: {
  /** How long each toast stays, in ms; 0 keeps it until it is closed. */
  duration?: number;
  /** 'stack' keeps earlier toasts below the new one; 'replace' sends the last one away. */
  mode?: 'stack' | 'replace';
  /** The most toasts shown at once, in stack mode; the oldest leaves to make room. */
  max?: number;
  /** The wash of colour before each toast. Off, or with reduced motion, the toast just fades in. */
  wash?: boolean;
  /**
   * Toasts already in place when it mounts, settled and without a wash, as a still for docs and
   * screenshots; it also turns the autoplay demo off.
   */
  defaultToasts?: Kind[];
  /** Called with each toast as it arrives. */
  onToast?: (notice: Notice) => void;
  /** Called with each toast as it leaves, and why. */
  onDismiss?: (notice: Notice, reason: DismissReason) => void;
  /** While on screen and untouched, a demo pointer raises and closes toasts. */
  autoplay?: boolean;
  /** Light or dark colours, or the reader's ('system'); without it, the page's color-scheme. */
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>();
  /** Ids for new toasts, after the ones it starts with. */
  const nextId = useRef(defaultToasts?.length ?? 0);
  /** The toasts it starts with, each kind taking its events in turn, and the invoices they mark. */
  const [start] = useState(() => {
    const seen: Partial<Record<Kind, number>> = {};
    const notices = (defaultToasts ?? []).map((kind) => {
      const list = EVENTS[kind];
      const index = seen[kind] ?? 0;
      seen[kind] = index + 1;
      return list[index % list.length];
    });
    const marked: Record<string, InvoiceStatus> = {};
    for (const { invoice, mark } of notices) if (invoice && mark) marked[invoice] = mark;
    return { notices, marked };
  });
  const [toasts, setToasts] = useState<Toast[]>(() =>
    start.notices.map((notice, index) => ({ id: index, notice, leaving: false, still: true })),
  );
  const [statuses, setStatuses] = useState(start.marked);
  const [message, setMessage] = useState('');
  const [hovered, setHovered] = useState(false);
  const [focused, setFocused] = useState(false);
  const paused = hovered || focused;

  const canvas = useRef<HTMLCanvasElement>(null);
  const region = useRef<HTMLDivElement>(null);
  const pointer = useRef<HTMLSpanElement>(null);
  const triggers = useRef<Partial<Record<Kind, HTMLButtonElement | null>>>({});
  const lastTrigger = useRef<HTMLButtonElement | null>(null);
  const turn = useRef<Record<Kind, number>>({ paid: 0, payout: 0, failed: 0 });
  const toastsRef = useRef(toasts);
  toastsRef.current = toasts;
  const onScreen = useRef(false);
  const pending = useRef(new Set<number>());
  /** Each toast's timer: when it fires, or how long it had left when it was paused. */
  const clocks = useRef(new Map<number, { timer: number; due: number } | { left: number }>());
  const washState = useRef<{ start: number; ramp: Ramp; frame: number } | null>(null);
  const callbacks = useRef({ onToast, onDismiss });
  callbacks.current = { onToast, onDismiss };

  /** Repeats are made to differ, so screen readers announce them again. */
  const announce = (text: string) => setMessage((now) => (now === text ? `${text} ` : text));

  // Whether the stage is on screen, for the wash; and the canvas sized to a third of the stage.
  useEffect(() => {
    const stage = root.current;
    const paper = canvas.current;
    if (!stage || !paper) return;
    const observer = new IntersectionObserver(([entry]) => {
      onScreen.current = entry.isIntersecting;
      if (!entry.isIntersecting) stopWash();
    });
    observer.observe(stage);
    const resize = new ResizeObserver(() => {
      paper.width = Math.max(1, Math.round(stage.offsetWidth / 3));
      paper.height = Math.max(1, Math.round(stage.offsetHeight / 3));
    });
    resize.observe(stage);
    const timers = pending.current;
    const running = clocks.current;
    return () => {
      observer.disconnect();
      resize.disconnect();
      stopWash();
      timers.forEach((timer) => window.clearTimeout(timer));
      running.forEach((clock) => 'timer' in clock && window.clearTimeout(clock.timer));
    };
    // stopWash only touches refs.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [root]);

  /** A timeout that is cleared if the component goes away first. */
  const later = (fn: () => void, ms: number) => {
    const timer = window.setTimeout(() => {
      pending.current.delete(timer);
      fn();
    }, ms);
    pending.current.add(timer);
  };

  function stopWash() {
    const state = washState.current;
    if (state) cancelAnimationFrame(state.frame);
    washState.current = null;
    const stage = root.current;
    const paper = canvas.current;
    paper?.getContext('2d')?.clearRect(0, 0, paper.width, paper.height);
    if (stage) {
      stage.style.setProperty('--veil', '0');
      stage.style.setProperty('--wash-glow', '0');
    }
    if (stage) stage.dataset.washing = 'false';
  }

  const startWash = (kind: Kind) => {
    const stage = root.current;
    const paper = canvas.current;
    if (!stage || !paper) return;
    if (washState.current) cancelAnimationFrame(washState.current.frame);
    // The canvas's colour is light-dark(black, white): read back, it says which scheme is in use,
    // whatever set it (the page, or the colorScheme prop).
    paper.dataset.dark = String(getComputedStyle(paper).color === 'rgb(255, 255, 255)');
    const scratch = document.createElement('canvas');
    const state = { start: performance.now(), ramp: RAMPS[kind], frame: 0 };
    washState.current = state;
    stage.dataset.washing = 'true';
    const tick = (now: number) => {
      if (washState.current !== state) return;
      const elapsed = now - state.start;
      if (elapsed > WASH_MS || !onScreen.current) return stopWash();
      const frame = washAt(elapsed);
      stage.style.setProperty('--veil', frame.veil.toFixed(3));
      stage.style.setProperty('--wash-glow', frame.glow.toFixed(3));
      stage.style.setProperty('--wash-y', `${(frame.y * 100).toFixed(2)}%`);
      paintWash(paper, scratch, state.ramp, frame);
      state.frame = requestAnimationFrame(tick);
    };
    state.frame = requestAnimationFrame(tick);
  };

  /** Moves the focus off a toast that is leaving: to the next one's ×, or back to its trigger. */
  const rescueFocus = (id: number) => {
    const item = region.current?.querySelector(`[data-toast="${id}"]`);
    if (!item?.contains(document.activeElement)) return;
    const next = toastsRef.current.find((toast) => toast.id !== id && !toast.leaving);
    const close = next
      ? region.current?.querySelector<HTMLButtonElement>(`[data-toast="${next.id}"] button`)
      : null;
    (close ?? lastTrigger.current ?? triggers.current.paid)?.focus();
  };

  const dismiss = useCallback((id: number, reason: DismissReason) => {
    const toast = toastsRef.current.find((item) => item.id === id);
    if (!toast || toast.leaving) return;
    rescueFocus(id);
    const clock = clocks.current.get(id);
    if (clock && 'timer' in clock) window.clearTimeout(clock.timer);
    clocks.current.delete(id);
    setToasts((list) => list.map((item) => (item.id === id ? { ...item, leaving: true } : item)));
    later(() => setToasts((list) => list.filter((item) => item.id !== id)), LEAVE);
    callbacks.current.onDismiss?.(toast.notice, reason);
    // rescueFocus and later only touch refs.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fire = (kind: Kind, from?: HTMLButtonElement) => {
    if (from) lastTrigger.current = from;
    const list = EVENTS[kind];
    const notice = list[turn.current[kind] % list.length];
    turn.current[kind] += 1;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const washing = wash && !reduced && onScreen.current;
    if (washing) startWash(kind);
    const arrive = () => {
      const id = nextId.current++;
      const live = toastsRef.current.filter((toast) => !toast.leaving);
      // Replaced or pushed out: the oldest go, so at most `max` stay with the new one.
      const keep = mode === 'replace' ? 0 : Math.max(0, max - 1);
      live.slice(keep).forEach((toast) => dismiss(toast.id, 'replaced'));
      setToasts((now) => [{ id, notice, leaving: false }, ...now]);
      if (notice.invoice && notice.mark) {
        const { invoice, mark } = notice;
        setStatuses((now) => ({ ...now, [invoice]: mark }));
      }
      announce(`${notice.title}. ${notice.detail.replace(' · ', ', ')}.`);
      callbacks.current.onToast?.(notice);
    };
    if (washing) later(arrive, ARRIVE);
    else arrive();
  };

  // The timers: each toast's runs while nothing holds the toasts, and keeps what it had left.
  useEffect(() => {
    if (duration <= 0) return;
    const now = performance.now();
    for (const toast of toasts) {
      if (toast.leaving || toast.still) continue;
      const clock = clocks.current.get(toast.id);
      if (paused) {
        if (clock && 'timer' in clock) {
          window.clearTimeout(clock.timer);
          clocks.current.set(toast.id, { left: Math.max(600, clock.due - now) });
        }
      } else if (!clock || 'left' in clock) {
        const left = clock ? clock.left : duration;
        const timer = window.setTimeout(() => dismiss(toast.id, 'timeout'), left);
        clocks.current.set(toast.id, { timer, due: now + left });
      }
    }
  }, [toasts, paused, duration, dismiss]);

  // The demo: raise a paid invoice and close it, let a payout leave on its own, raise a failed
  // payment and close it; again.
  const demo = autoplay && !defaultToasts && playing;
  const fireRef = useRef(fire);
  fireRef.current = fire;
  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    if (!demo || !stage || !arrow) return;
    /** The middle of `element`, in the stage's own px. */
    const middle = (element: Element | null | undefined, dx = 0, dy = 0): Point => {
      const frame = stage.getBoundingClientRect();
      const scale = frame.width / stage.offsetWidth || 1;
      if (!element) return { x: stage.offsetWidth * 0.7, y: stage.offsetHeight * 0.6 };
      const rect = element.getBoundingClientRect();
      return {
        x: (rect.left + rect.width / 2 - frame.left) / scale + dx,
        y: (rect.top + rect.height / 2 - frame.top) / scale + dy,
      };
    };
    const press = (element: HTMLElement | null | undefined) => {
      if (!element) return;
      element.dataset.pressed = 'true';
      window.setTimeout(() => delete element.dataset.pressed, 160);
    };
    const newest = () => {
      const id = toastsRef.current.find((toast) => !toast.leaving)?.id;
      return id === undefined
        ? null
        : region.current?.querySelector<HTMLButtonElement>(`[data-toast="${id}"] button`);
    };
    const rest = () => middle(null);
    const stop = runDemo(stage, arrow, async ({ wait, glide, glyph }) => {
      const raise = async (kind: Kind) => {
        const button = triggers.current[kind];
        await glide(middle(button, 4, 3), 720);
        glyph('hand');
        await wait(220);
        press(button);
        fireRef.current(kind);
        await wait(260);
        glyph('arrow');
        await glide(rest(), 700);
      };
      const close = async () => {
        await glide(middle(newest(), 2, 2), 760);
        glyph('hand');
        await wait(260);
        const button = newest();
        press(button);
        const id = toastsRef.current.find((toast) => !toast.leaving)?.id;
        if (id !== undefined) dismiss(id, 'close');
        await wait(240);
        glyph('arrow');
        await glide(rest(), 700);
      };
      await glide(rest(), 600);
      for (;;) {
        await wait(700);
        await raise('paid');
        await wait(2200);
        await close();
        await wait(900);
        await raise('payout');
        await wait(duration > 0 ? duration + 900 : 2600);
        if (duration <= 0) await close();
        await raise('failed');
        await wait(2400);
        await close();
        await wait(1200);
      }
    });
    // The toasts it raised stay when the reader takes over; their timers still send them away.
    return stop;
  }, [demo, root, dismiss, duration]);

  // The pointer or the focus on the toasts holds their timers. Listened to natively: the region
  // is not a control, it only notices what happens inside it.
  useEffect(() => {
    const element = region.current;
    if (!element) return;
    const enter = () => setHovered(true);
    const leave = () => setHovered(false);
    const focusIn = () => setFocused(true);
    const focusOut = (event: FocusEvent) => {
      if (!element.contains(event.relatedTarget as Node | null)) setFocused(false);
    };
    element.addEventListener('pointerenter', enter);
    element.addEventListener('pointerleave', leave);
    element.addEventListener('focusin', focusIn);
    element.addEventListener('focusout', focusOut);
    return () => {
      element.removeEventListener('pointerenter', enter);
      element.removeEventListener('pointerleave', leave);
      element.removeEventListener('focusin', focusIn);
      element.removeEventListener('focusout', focusOut);
    };
  }, []);

  const shown = toasts.filter((toast) => !toast.leaving);
  const front = shown[0];

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="stage"
      data-color-scheme={colorScheme}
      onPointerDownCapture={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') take();
      }}
      // Any key hands the demo to the reader; Escape, anywhere on the stage, closes the newest.
      onKeyDownCapture={(event) => {
        take();
        if (event.key !== 'Escape' || !front) return;
        event.preventDefault();
        dismiss(front.id, 'escape');
      }}
    >
      <Dashboard
        statuses={statuses}
        onFire={fire}
        buttonRef={(kind) => (element) => {
          triggers.current[kind] = element;
        }}
      />

      {/* The wash: the veil over the whole page, the blur under the crescent, the crescent. */}
      <div className={styles.veil} aria-hidden="true" />
      <div className={styles.smear} aria-hidden="true" />
      <canvas ref={canvas} className={styles.wash} aria-hidden="true" data-part="wash" />

      {/* The glow behind the newest toast, as wide as the stage so nothing overflows it. */}
      <div
        className={styles.halo}
        aria-hidden="true"
        data-part="halo"
        data-shown={Boolean(front)}
        data-kind={front?.notice.kind}
        data-still={front?.still ? 'true' : undefined}
      />
      <div ref={region} className={styles.region} data-part="region">
        <ol className={styles.list} aria-label="Notifications">
          {toasts.map((toast) => (
            <li
              key={toast.id}
              className={styles.item}
              data-toast={toast.id}
              data-leaving={toast.leaving}
              data-still={toast.still ? 'true' : undefined}
              inert={toast.leaving}
            >
              <div className={styles.fold}>
                <div className={styles.toast} data-part="toast" data-kind={toast.notice.kind}>
                  <span className={styles.glyph} data-part="glyph">
                    <Glyph kind={toast.notice.kind} className={styles.glyphArt} />
                  </span>
                  <span className={styles.words}>
                    <span className={styles.title} data-part="title">
                      {toast.notice.title}
                    </span>
                    <span className={styles.detail} data-part="detail">
                      {toast.notice.detail}
                    </span>
                  </span>
                  <button
                    type="button"
                    className={styles.close}
                    data-part="close"
                    aria-label={`Dismiss: ${toast.notice.title}`}
                    onClick={() => dismiss(toast.id, 'close')}
                  >
                    <Cross className={styles.cross} />
                  </button>
                </div>
              </div>
            </li>
          ))}
        </ol>
      </div>

      <p className={styles.hidden} role="status" aria-live="polite">
        {message}
      </p>
      <div className={styles.pointerLayer} aria-hidden="true">
        <DemoPointer
          ref={pointer}
          className={styles.pointer}
          arrowClass={styles.arrow}
          handClass={styles.hand}
        />
      </div>
    </div>
  );
}

export { KINDS };
export type { Kind, Notice };
```

### aurora-toast/aurora-toast.module.css

```css
/* Copyright (c) 2026 Bruno Delorence. MIT License. */

/* Aurora toast (aurora-toast.tsx): a pale billing page, the wash that falls through it when an
   event arrives, and the dark toast at the top centre with its halo.

   Layers, bottom to top: the page; the veil (a light blur over all of it while a wash runs); the
   smear (a stronger blur masked to the crescent, following --wash-y); the canvas the crescent is
   painted on; the toasts and their halo; the demo pointer.

   Sizes were measured from the reference at 1530 px wide and scaled to a 420 px toast: 72 px tall,
   a 17 px radius, a 40 px glyph, 15/20 and 14/19 type, a 24 px close button, 30 px from the top.

   Colours are the tokens below, light-dark(light, dark) where the two differ: the component takes
   the color-scheme it inherits from the page, or the one its colorScheme prop sets. */

.root {
  --stage: #f5f5f5;
  --card: #fdfdfd;
  --line: #ececec;
  --ink: #3d4145;
  --muted: #6e7378;
  --strong: #26292c;
  --chip: #fff;
  --chip-edge: #e2e3e5;
  --chip-ink: #3d4145;
  --paid: #24733f;
  --paid-bg: #e6f4ea;
  --open: #5f6469;
  --open-bg: #f0f0f1;
  --failed: #b1452c;
  --failed-bg: #fbebe6;
  /* The toast: the same dark slate on both schemes, a shade lighter at night so it lifts. */
  --toast: #444a4f;
  --toast-warm: #4d4542;
  --toast-edge: rgb(255 255 255 / 0.06);
  --toast-shadow: rgb(20 30 40 / 0.22);
  --toast-title: #fff;
  --toast-detail: #b4babe;
  --close: #545e61;
  --close-hover: #626d71;
  --close-ink: #d3d8db;
  /* The halo: its core and its dot screen, cool for good news and warm for a failure. */
  --halo-core: rgb(150 205 245 / 0.62);
  --halo-dot: rgb(98 156 214 / 0.3);
  --halo-warm-core: rgb(250 196 150 / 0.6);
  --halo-warm-dot: rgb(214 132 80 / 0.3);
  --veil-tint: rgb(232 233 235 / 0.25);
  --focus: #387bff;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.25);
  --sans-stack: var(
    --sans,
    -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    Inter,
    Roboto,
    'Helvetica Neue',
    Arial,
    sans-serif
  );
  position: relative;
  container-type: inline-size;
  width: 100%;
  aspect-ratio: 16 / 10;
  min-height: 560px;
  max-height: 780px;
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background: var(--stage);
  box-shadow: inset 0 0 0 1px var(--line);
  color: var(--ink);
  font-family: var(--sans-stack);
  -webkit-tap-highlight-color: transparent;
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --stage: light-dark(#f5f5f5, #131416);
    --card: light-dark(#fdfdfd, #1b1c1f);
    --line: light-dark(#ececec, #26272b);
    --ink: light-dark(#3d4145, #c9ccd0);
    --muted: light-dark(#6e7378, #8d9196);
    --strong: light-dark(#26292c, #eceef0);
    --chip: light-dark(#fff, #1f2023);
    --chip-edge: light-dark(#e2e3e5, #303135);
    --chip-ink: light-dark(#3d4145, #d5d8db);
    --paid: light-dark(#24733f, #6fd093);
    --paid-bg: light-dark(#e6f4ea, rgb(80 190 120 / 0.14));
    --open: light-dark(#5f6469, #a2a6ab);
    --open-bg: light-dark(#f0f0f1, #26272b);
    --failed: light-dark(#b1452c, #f39a82);
    --failed-bg: light-dark(#fbebe6, rgb(240 120 90 / 0.15));
    --toast: light-dark(#444a4f, #3a4045);
    --toast-warm: light-dark(#4d4542, #463d3a);
    --toast-edge: light-dark(rgb(255 255 255 / 0.06), rgb(255 255 255 / 0.1));
    --toast-shadow: light-dark(rgb(20 30 40 / 0.22), rgb(0 0 0 / 0.55));
    --halo-core: light-dark(rgb(150 205 245 / 0.62), rgb(70 140 220 / 0.5));
    --halo-dot: light-dark(rgb(98 156 214 / 0.3), rgb(120 180 240 / 0.24));
    --halo-warm-core: light-dark(rgb(250 196 150 / 0.6), rgb(220 120 70 / 0.42));
    --halo-warm-dot: light-dark(rgb(214 132 80 / 0.3), rgb(240 160 110 / 0.22));
    --veil-tint: light-dark(rgb(232 233 235 / 0.25), rgb(10 10 12 / 0.3));
  }
}
.root[data-color-scheme='light'] {
  color-scheme: light;
}
.root[data-color-scheme='dark'] {
  color-scheme: dark;
}
.root[data-color-scheme='system'] {
  color-scheme: light dark;
}

/* ---- The page ---- */

.page {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  gap: 18px;
  padding: 0 clamp(16px, 3.4cqi, 40px) 24px;
  font-size: 13px;
  line-height: 1.4;
}
.page p {
  margin: 0;
}

.bar {
  display: flex;
  align-items: center;
  gap: 28px;
  height: 56px;
  margin: 0 calc(-1 * clamp(16px, 3.4cqi, 40px));
  padding: 0 clamp(16px, 3.4cqi, 40px);
  border-bottom: 1px solid var(--line);
  background: var(--card);
}
.brand {
  display: flex;
  align-items: center;
  gap: 9px;
  color: var(--strong);
  font-weight: 600;
  white-space: nowrap;
}
.mark {
  width: 22px;
  height: 22px;
  color: #6f8f7a;
}
.nav {
  display: flex;
  gap: 20px;
  color: var(--muted);
}
.nav [data-current='true'] {
  color: var(--strong);
  font-weight: 500;
}
.me {
  display: grid;
  place-items: center;
  width: 28px;
  height: 28px;
  margin-left: auto;
  border-radius: 50%;
  background: var(--open-bg);
  color: var(--muted);
  font-size: 11px;
  font-weight: 600;
}

.head {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  justify-content: space-between;
  gap: 12px 20px;
  margin-top: 10px;
}
.heading {
  color: var(--strong);
  font-size: 22px;
  font-weight: 600;
  letter-spacing: -0.01em;
  line-height: 1.2;
}
.sub {
  color: var(--muted);
}
.triggers {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.trigger {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  min-height: 34px;
  padding: 0 13px;
  border: 1px solid var(--chip-edge);
  border-radius: 999px;
  background: var(--chip);
  color: var(--chip-ink);
  font: inherit;
  font-weight: 500;
  cursor: pointer;
  transition:
    background-color 0.15s ease,
    transform 0.15s ease;
}
.trigger:hover {
  background: var(--open-bg);
}
.trigger:active,
.trigger[data-pressed='true'] {
  transform: scale(0.96);
}
.trigger:focus-visible,
.close:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}
.dot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: #7fb8e6;
}
.trigger[data-kind='paid'] .dot {
  background: #4fc08a;
}
.trigger[data-kind='failed'] .dot {
  background: #ec8a4f;
}

.figures {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 12px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.figure {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 0;
  padding: 16px 18px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--card);
}
.figureLabel,
.figureNote {
  overflow: hidden;
  color: var(--muted);
  text-overflow: ellipsis;
  white-space: nowrap;
}
.figureValue {
  color: var(--strong);
  font-size: 20px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
  letter-spacing: -0.01em;
}

.table {
  min-height: 0;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--card);
}
.tableTitle {
  padding: 14px 18px 10px;
  color: var(--strong);
  font-weight: 600;
}
.rows {
  margin: 0;
  padding: 0;
  list-style: none;
}
.row {
  display: grid;
  grid-template-columns: 64px minmax(0, 1.6fr) minmax(0, 1fr) minmax(0, 1fr) 70px;
  align-items: center;
  gap: 12px;
  min-height: 46px;
  padding: 0 18px;
  border-top: 1px solid var(--line);
}
.number,
.due {
  color: var(--muted);
  font-variant-numeric: tabular-nums;
}
.client {
  overflow: hidden;
  color: var(--strong);
  text-overflow: ellipsis;
  white-space: nowrap;
}
.amount {
  color: var(--strong);
  font-variant-numeric: tabular-nums;
  text-align: right;
}
.status {
  justify-self: end;
  padding: 2px 9px;
  border-radius: 999px;
  background: var(--open-bg);
  color: var(--open);
  font-size: 12px;
  font-weight: 500;
  transition:
    background-color 0.4s ease,
    color 0.4s ease;
}
.status[data-status='paid'] {
  background: var(--paid-bg);
  color: var(--paid);
}
.status[data-status='failed'] {
  background: var(--failed-bg);
  color: var(--failed);
}

@container (max-width: 760px) {
  .nav {
    display: none;
  }
  .figures {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
  .row {
    grid-template-columns: 52px minmax(0, 1fr) auto 62px;
  }
  .due {
    display: none;
  }
}
@container (max-width: 460px) {
  .figure {
    padding: 12px 14px;
  }
  .figureValue {
    font-size: 17px;
  }
  .row {
    grid-template-columns: minmax(0, 1fr) auto 58px;
    padding: 0 14px;
  }
  .number {
    display: none;
  }
}

/* ---- The wash ---- */

/* While a wash runs, the whole page goes a little soft and grey at once, before the colour. */
.veil {
  position: absolute;
  inset: 0;
  z-index: 1;
  background: var(--veil-tint);
  opacity: var(--veil, 0);
  -webkit-backdrop-filter: blur(3px) saturate(0.6);
  backdrop-filter: blur(3px) saturate(0.6);
  pointer-events: none;
}
/* Under the crescent the page smears harder: a blur masked to an ellipse that moves with it. */
.smear {
  position: absolute;
  inset: 0;
  z-index: 1;
  opacity: var(--wash-glow, 0);
  -webkit-backdrop-filter: blur(12px);
  backdrop-filter: blur(12px);
  -webkit-mask-image: radial-gradient(
    ellipse max(40%, 190px) max(26%, 150px) at 50% var(--wash-y, -50%),
    #000 35%,
    transparent 100%
  );
  mask-image: radial-gradient(
    ellipse max(40%, 190px) max(26%, 150px) at 50% var(--wash-y, -50%),
    #000 35%,
    transparent 100%
  );
  pointer-events: none;
}
.root:not([data-washing='true']) .veil,
.root:not([data-washing='true']) .smear {
  visibility: hidden;
}
/* The canvas is a third of the stage's px; stretched, its edges come out soft. Its colour is
   only read back by the script, to tell which scheme is in use. */
.wash {
  position: absolute;
  inset: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  color: #000;
  pointer-events: none;
}
@supports (color: light-dark(#fff, #000)) {
  .wash {
    color: light-dark(#000, #fff);
  }
}
/* At night the pastel colours would glare: they add light to the dark page instead. */
.wash[data-dark='true'] {
  mix-blend-mode: screen;
  opacity: 0.78;
}

/* ---- The toasts ---- */

.region {
  position: absolute;
  top: clamp(14px, 2.2cqi, 30px);
  left: 50%;
  z-index: 2;
  width: min(420px, calc(100% - 32px));
  transform: translateX(-50%);
}

/* The glow left behind the toast: a soft ellipse of the kind's tint and a fine dot screen, over a
   light blur of the page; it stays while any toast does. */
.halo {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  width: 100%;
  height: 270px;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.5s ease;
  -webkit-backdrop-filter: blur(1px);
  backdrop-filter: blur(1px);
  /* About twice the toast's width, as measured; never narrower than the stage allows. */
  -webkit-mask-image: radial-gradient(
    ellipse max(420px, 44%) 62% at 50% 20%,
    #000 25%,
    transparent 100%
  );
  mask-image: radial-gradient(ellipse max(420px, 44%) 62% at 50% 20%, #000 25%, transparent 100%);
  --core: var(--halo-core);
  --dots: var(--halo-dot);
  background:
    radial-gradient(circle at center, var(--dots) 0.9px, transparent 1.5px) 0 0 / 8px 8px,
    radial-gradient(ellipse max(400px, 42%) 56% at 50% 16%, var(--core), transparent 100%);
}
.halo[data-kind='failed'] {
  --core: var(--halo-warm-core);
  --dots: var(--halo-warm-dot);
}
.halo[data-shown='true'] {
  opacity: 1;
  transition: opacity 0.8s ease 0.18s;
}
.halo[data-still='true'] {
  transition: none;
}

.list {
  position: relative;
  margin: 0;
  padding: 0;
  list-style: none;
}
/* Each row folds open as it arrives and shut as it leaves, so the others slide to make room. */
.item {
  display: grid;
  grid-template-rows: 1fr;
  margin-bottom: 8px;
  animation: open 0.42s cubic-bezier(0.2, 0.9, 0.25, 1) both;
  transition:
    grid-template-rows 0.26s ease,
    margin-bottom 0.26s ease,
    opacity 0.2s ease,
    transform 0.26s ease;
}
.item[data-leaving='true'] {
  grid-template-rows: 0fr;
  margin-bottom: 0;
  opacity: 0;
  transform: translateY(-6px) scale(0.97);
}
.item[data-still='true'] {
  animation: none;
}
.fold {
  min-height: 0;
}
@keyframes open {
  from {
    grid-template-rows: 0fr;
    margin-bottom: 0;
  }
}

.toast {
  display: grid;
  grid-template-columns: 40px minmax(0, 1fr) 24px;
  align-items: center;
  gap: 14px;
  min-height: 72px;
  min-width: 0;
  padding: 13px 14px 13px 15px;
  border-radius: 17px;
  background: var(--toast);
  box-shadow:
    inset 0 0 0 1px var(--toast-edge),
    0 10px 28px -8px var(--toast-shadow),
    0 2px 6px var(--toast-shadow);
  color: var(--toast-title);
  /* It comes down from above the stage's top edge, quick, with a hair of overshoot. */
  animation: arrive 0.46s cubic-bezier(0.22, 1.12, 0.36, 1) both;
}
.toast[data-kind='failed'] {
  background: var(--toast-warm);
}
.item[data-still='true'] .toast {
  animation: none;
}
@keyframes arrive {
  from {
    opacity: 0.4;
    transform: translateY(calc(-100% - 40px));
  }
}
.glyph {
  display: grid;
  place-items: center;
  width: 40px;
  height: 40px;
}
.glyphArt {
  display: block;
  width: 40px;
  height: 40px;
}
.words {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}
.title {
  font-size: 15px;
  font-weight: 500;
  line-height: 20px;
}
.detail {
  color: var(--toast-detail);
  font-size: 14px;
  line-height: 19px;
  font-variant-numeric: tabular-nums;
}
.close {
  display: grid;
  place-items: center;
  align-self: start;
  width: 24px;
  height: 24px;
  margin-top: 2px;
  padding: 0;
  border: 0;
  border-radius: 50%;
  background: var(--close);
  color: var(--close-ink);
  cursor: pointer;
  transition:
    background-color 0.15s ease,
    transform 0.15s ease;
}
.close:hover {
  background: var(--close-hover);
}
.close:active,
.close[data-pressed='true'] {
  transform: scale(0.9);
}
.cross {
  width: 14px;
  height: 14px;
}

/* On a phone the glyph and the gaps shrink so the words keep their room; a long line wraps. */
@container (max-width: 460px) {
  .region {
    width: calc(100% - 20px);
  }
  .toast {
    grid-template-columns: 32px minmax(0, 1fr) 24px;
    gap: 10px;
    padding: 11px 11px 11px 12px;
    border-radius: 15px;
  }
  .glyph,
  .glyphArt {
    width: 32px;
    height: 32px;
  }
  .title {
    font-size: 14px;
    line-height: 19px;
  }
  .detail {
    font-size: 13px;
    line-height: 18px;
  }
}

/* ---- The demo pointer and the rest ---- */

.pointerLayer {
  position: absolute;
  inset: 0;
  z-index: 3;
  pointer-events: none;
}
.pointer {
  width: 24px;
  height: 24px;
}
.hand {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .arrow {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .hand {
  visibility: visible;
}

.hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  padding: 0;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

/* No wash runs under reduced motion (the script skips it); the toast and its halo just fade. */
@media (prefers-reduced-motion: reduce) {
  .item {
    animation: none;
    transition: opacity 0.2s ease;
  }
  .item[data-leaving='true'] {
    transform: none;
  }
  .toast {
    animation-name: fade;
    animation-duration: 0.24s;
    animation-timing-function: ease;
  }
  .trigger,
  .close {
    transition: none;
  }
}
@keyframes fade {
  from {
    opacity: 0;
  }
}
```

### aurora-toast/wash.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The aurora wash: a wide, soft bowl of colour that falls through the stage when a toast arrives,
 * changing hue as it goes, and the timeline that drives it and the blur over the page beneath.
 *
 * - The bowl is painted on a small canvas, a third of the stage's px, and the browser scales it
 *   up: the upscale itself softens it, so no blur filter runs on a canvas that changes each frame.
 * - Its shape is an ellipse with a softer ellipse cut out of its top, so it reads as a crescent,
 *   brightest along the bottom; a fainter ellipse of the colour it just left trails above it.
 * - Its colour comes from where it is: each kind of toast has a ramp from the top of the stage to
 *   the bottom (the paid one green, cyan, blue, violet, magenta, pink, peach).
 * - Where it falls was measured frame by frame from 60 fps footage: slow over the first third of a
 *   second while it comes in at the top, then about two stage heights a second to the bottom.
 */

export type Ramp = [stop: number, rgb: [number, number, number]][];

/** How long a wash lasts, in ms, from the event to the last of the blur. */
export const WASH_MS = 1500;

/** The bowl's middle, in stage heights, at each moment (in seconds) of the measured fall. */
const FALL: [t: number, y: number][] = [
  [0, -0.38],
  [0.3, -0.06],
  [0.5, 0.13],
  [0.6, 0.33],
  [0.7, 0.52],
  [0.8, 0.72],
  [0.9, 0.9],
  [1.05, 1.16],
  [1.2, 1.4],
];

const smooth = (x: number) => x * x * (3 - 2 * x);
const clamp = (x: number, low = 0, high = 1) => Math.min(high, Math.max(low, x));

/** The bowl's middle at `t` seconds, in stage heights; eased between measured frames. */
function fall(t: number) {
  if (t <= FALL[0][0]) return FALL[0][1];
  for (let i = 1; i < FALL.length; i += 1) {
    const [t1, y1] = FALL[i];
    const [t0, y0] = FALL[i - 1];
    if (t <= t1) {
      // Linear between frames reads as jerky at the joints; a light smoothing keeps the speed.
      const u = (t - t0) / (t1 - t0);
      return y0 + (y1 - y0) * (u * 0.6 + smooth(u) * 0.4);
    }
  }
  return FALL[FALL.length - 1][1];
}

/** The ramp's colour at `y` (0 at the top of the stage, 1 at the bottom). */
function hue(ramp: Ramp, y: number): [number, number, number] {
  const at = clamp(y);
  for (let i = 1; i < ramp.length; i += 1) {
    const [s1, c1] = ramp[i];
    const [s0, c0] = ramp[i - 1];
    if (at <= s1) {
      const u = (at - s0) / (s1 - s0 || 1);
      return [0, 1, 2].map((k) => Math.round(c0[k] + (c1[k] - c0[k]) * u)) as [
        number,
        number,
        number,
      ];
    }
  }
  return ramp[ramp.length - 1][1];
}

const rgba = ([r, g, b]: [number, number, number], a: number) => `rgb(${r} ${g} ${b} / ${a})`;

/** What the stylesheet needs at a moment of the wash: the veil, and where the bowl is. */
export type WashFrame = {
  /** The light blur over the whole page, 0 to 1. */
  veil: number;
  /** The bowl's strength, 0 to 1. */
  glow: number;
  /** The bowl's middle, in stage heights. */
  y: number;
};

/** The wash at `ms` after the event. */
export function washAt(ms: number): WashFrame {
  const t = ms / 1000;
  return {
    // The page goes soft at once, before the colour shows, and clears as the bowl leaves.
    veil: clamp(t / 0.2) * (1 - clamp((t - 1.05) / 0.45)),
    glow: clamp(t / 0.32) * (1 - clamp((t - 0.92) / 0.24)),
    y: fall(t),
  };
}

/** Paints the bowl for `frame` on `canvas` (sized to the stage at `scale`), using `cut` as scratch. */
export function paintWash(
  canvas: HTMLCanvasElement,
  cut: HTMLCanvasElement,
  ramp: Ramp,
  frame: WashFrame,
) {
  const context = canvas.getContext('2d');
  const scratch = cut.getContext('2d');
  if (!context || !scratch) return;
  const { width: w, height: h } = canvas;
  context.clearRect(0, 0, w, h);
  if (frame.glow <= 0.001) return;

  if (cut.width !== w || cut.height !== h) {
    cut.width = w;
    cut.height = h;
  }
  // On a narrow stage the bowl keeps a wider share of it, so it still spans the toast.
  const rx = w * (w < 220 ? 0.56 : 0.44);
  const ry = Math.max(h * 0.24, rx * 0.4);
  const cx = w / 2;
  const cy = frame.y * h;

  /** A soft ellipse: full `colour` at its middle, nothing at its edge. */
  const blot = (
    target: CanvasRenderingContext2D,
    x: number,
    y: number,
    sx: number,
    sy: number,
    stops: [number, string][],
  ) => {
    target.save();
    target.translate(x, y);
    target.scale(sx / sy, 1);
    const gradient = target.createRadialGradient(0, 0, 0, 0, 0, sy);
    stops.forEach(([at, colour]) => gradient.addColorStop(at, colour));
    target.fillStyle = gradient;
    target.beginPath();
    target.arc(0, 0, sy, 0, Math.PI * 2);
    target.fill();
    target.restore();
  };

  const lead = hue(ramp, frame.y - 0.2);
  const top = hue(ramp, frame.y - 0.08);
  const bottom = hue(ramp, frame.y + 0.06);

  // The colour it just left, fainter, trailing above it.
  blot(context, cx, cy - ry * 0.95, rx * 1.08, ry * 0.9, [
    [0, rgba(lead, 0.5 * frame.glow)],
    [0.55, rgba(lead, 0.22 * frame.glow)],
    [1, rgba(lead, 0)],
  ]);

  // The crescent, on the scratch canvas: a full ellipse shaded top to bottom, its top cut away.
  scratch.clearRect(0, 0, w, h);
  scratch.globalCompositeOperation = 'source-over';
  blot(scratch, cx, cy, rx, ry, [
    [0, rgba(bottom, 1)],
    [0.62, rgba(bottom, 0.9)],
    [1, rgba(bottom, 0)],
  ]);
  scratch.globalCompositeOperation = 'source-atop';
  const shade = scratch.createLinearGradient(0, cy - ry, 0, cy + ry);
  shade.addColorStop(0, rgba(top, 1));
  shade.addColorStop(0.55, rgba(bottom, 0));
  scratch.fillStyle = shade;
  scratch.fillRect(0, cy - ry, w, ry * 2);
  scratch.globalCompositeOperation = 'destination-out';
  blot(scratch, cx, cy - ry * 0.5, rx * 0.84, ry * 0.8, [
    [0, 'rgb(0 0 0 / 0.92)'],
    [0.6, 'rgb(0 0 0 / 0.6)'],
    [1, 'rgb(0 0 0 / 0)'],
  ]);
  scratch.globalCompositeOperation = 'source-over';

  context.globalAlpha = frame.glow;
  context.drawImage(cut, 0, 0);
  context.globalAlpha = 1;
}
```

### aurora-toast/events.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

import type { Ramp } from './wash';

/*
 * The billing workspace behind the toasts, and what can happen in it: the invoices in its list,
 * and the three kinds of event that raise a toast. Each kind has its words, the colour ramp its
 * wash falls through, and the tint of the glow it leaves behind the toast.
 */

export type Kind = 'paid' | 'payout' | 'failed';

export type InvoiceStatus = 'open' | 'paid' | 'failed';

export type Invoice = {
  id: string;
  client: string;
  due: string;
  amount: string;
  status: InvoiceStatus;
};

export const INVOICES: Invoice[] = [
  { id: '0042', client: 'Harbor & Pine Co.', due: 'Nov 4', amount: '$3,240.00', status: 'open' },
  { id: '0041', client: 'Quill Atelier', due: 'Nov 2', amount: '$1,180.00', status: 'open' },
  { id: '0040', client: 'Marlow Ceramics', due: 'Oct 30', amount: '$860.00', status: 'open' },
  { id: '0039', client: 'Bright Lane Dental', due: 'Oct 28', amount: '$2,075.00', status: 'open' },
  { id: '0038', client: 'Oakridge Bikes', due: 'Oct 24', amount: '$4,310.00', status: 'paid' },
  { id: '0037', client: 'Tidewater Books', due: 'Oct 21', amount: '$590.00', status: 'paid' },
];

/** One event: the toast's two lines, and the invoice it changes in the list (if any). */
export type Notice = {
  kind: Kind;
  title: string;
  detail: string;
  invoice?: string;
  mark?: InvoiceStatus;
};

/** Each kind's events, played in turn: firing a kind again takes its next one. */
export const EVENTS: Record<Kind, Notice[]> = {
  paid: [
    {
      kind: 'paid',
      title: 'Your invoice has been paid',
      detail: 'Invoice #0042 · $3,240.00',
      invoice: '0042',
      mark: 'paid',
    },
    {
      kind: 'paid',
      title: 'Your invoice has been paid',
      detail: 'Invoice #0041 · $1,180.00',
      invoice: '0041',
      mark: 'paid',
    },
    {
      kind: 'paid',
      title: 'Your invoice has been paid',
      detail: 'Invoice #0040 · $860.00',
      invoice: '0040',
      mark: 'paid',
    },
  ],
  payout: [
    { kind: 'payout', title: 'Payout sent to your bank', detail: '$12,460.00 · arrives Thursday' },
    { kind: 'payout', title: 'Payout sent to your bank', detail: '$7,915.00 · arrives Monday' },
  ],
  failed: [
    {
      kind: 'failed',
      title: 'A payment failed',
      detail: 'Invoice #0039 · card declined',
      invoice: '0039',
      mark: 'failed',
    },
  ],
};

/** What the trigger buttons say. */
export const KIND_LABEL: Record<Kind, string> = {
  paid: 'Invoice paid',
  payout: 'Payout sent',
  failed: 'Payment failed',
};

/*
 * The ramps, top of the stage to the bottom. The paid one is sampled from the reference frames:
 * green at the top, cyan, blue, violet past the middle, magenta, pink and a peach at the bottom.
 * The payout one stays cool; the failed one is warm all the way down.
 */
export const RAMPS: Record<Kind, Ramp> = {
  paid: [
    [0, [142, 245, 191]],
    [0.14, [126, 228, 212]],
    [0.32, [118, 152, 254]],
    [0.48, [168, 104, 253]],
    [0.66, [228, 103, 216]],
    [0.84, [250, 134, 192]],
    [1, [251, 178, 152]],
  ],
  payout: [
    [0, [128, 236, 222]],
    [0.25, [113, 203, 228]],
    [0.5, [110, 160, 252]],
    [0.75, [126, 128, 250]],
    [1, [160, 150, 250]],
  ],
  failed: [
    [0, [255, 214, 120]],
    [0.25, [255, 176, 96]],
    [0.5, [250, 132, 92]],
    [0.75, [240, 104, 120]],
    [1, [236, 120, 160]],
  ],
};
```

### aurora-toast/dashboard.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import type { Ref } from 'react';
import { INVOICES, KIND_LABEL, type InvoiceStatus, type Kind } from './events';
import { Mark } from './glyphs';
import styles from './aurora-toast.module.css';

/*
 * The quiet billing page the toasts arrive over: a header, a title row with the buttons that
 * raise each kind of event, a row of four figures and the recent invoices. It is kept pale and
 * low in contrast on purpose, so the wash and the dark toast stand out from it; its text still
 * meets 4.5 : 1. An invoice's status changes when an event names it.
 */

const STATUS_LABEL: Record<InvoiceStatus, string> = {
  open: 'Open',
  paid: 'Paid',
  failed: 'Failed',
};

const FIGURES = [
  { label: 'Collected this month', value: '$48,920.00', note: '+12% on October' },
  { label: 'Outstanding', value: '$9,415.00', note: '7 invoices' },
  { label: 'Next payout', value: '$12,460.00', note: 'Thursday, Nov 6' },
  { label: 'Failed payments', value: '2', note: 'Last 30 days' },
];

export function Dashboard({
  statuses,
  onFire,
  buttonRef,
}: {
  statuses: Record<string, InvoiceStatus>;
  onFire: (kind: Kind, from: HTMLButtonElement) => void;
  /** Each trigger button, by kind, for the demo pointer and to return the focus to. */
  buttonRef: (kind: Kind) => Ref<HTMLButtonElement>;
}) {
  return (
    <div className={styles.page} data-part="page">
      <div className={styles.bar}>
        <span className={styles.brand}>
          <Mark className={styles.mark} />
          Fernhill Studio
        </span>
        <span className={styles.nav} aria-hidden="true">
          <span data-current="true">Billing</span>
          <span>Customers</span>
          <span>Reports</span>
        </span>
        <span className={styles.me} aria-hidden="true">
          FS
        </span>
      </div>

      <div className={styles.head}>
        <div>
          <p className={styles.heading}>Billing</p>
          <p className={styles.sub}>November 2026</p>
        </div>
        <div className={styles.triggers} role="group" aria-label="Raise an event">
          {(Object.keys(KIND_LABEL) as Kind[]).map((kind) => (
            <button
              key={kind}
              ref={buttonRef(kind)}
              type="button"
              className={styles.trigger}
              data-part="trigger"
              data-kind={kind}
              onClick={(event) => onFire(kind, event.currentTarget)}
            >
              <span className={styles.dot} aria-hidden="true" />
              {KIND_LABEL[kind]}
            </button>
          ))}
        </div>
      </div>

      <ul className={styles.figures} aria-label="This month">
        {FIGURES.map((figure) => (
          <li key={figure.label} className={styles.figure}>
            <span className={styles.figureLabel}>{figure.label}</span>
            <span className={styles.figureValue}>{figure.value}</span>
            <span className={styles.figureNote}>{figure.note}</span>
          </li>
        ))}
      </ul>

      <div className={styles.table}>
        <p className={styles.tableTitle}>Recent invoices</p>
        <ul className={styles.rows}>
          {INVOICES.map((invoice) => {
            const status = statuses[invoice.id] ?? invoice.status;
            return (
              <li key={invoice.id} className={styles.row}>
                <span className={styles.number}>#{invoice.id}</span>
                <span className={styles.client}>{invoice.client}</span>
                <span className={styles.due}>Due {invoice.due}</span>
                <span className={styles.amount}>{invoice.amount}</span>
                <span className={styles.status} data-status={status}>
                  {STATUS_LABEL[status]}
                </span>
              </li>
            );
          })}
        </ul>
      </div>
    </div>
  );
}
```

### aurora-toast/glyphs.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

import { useId, type ReactNode } from 'react';

/*
 * The drawings: the toast's three glyphs (a sheet of paper for an invoice, a card with an arrow for
 * a payout, a sheet with a warning for a failed payment), the close cross, and the workspace's
 * mark. The glyphs are pale on the dark toast, each fading out toward its bottom as if it were
 * sliding out of a slot; they are decorative, since the title says the same in words.
 */

export type GlyphKind = 'paid' | 'payout' | 'failed';

function Sheet({ fade, children }: { fade: string; children?: ReactNode }) {
  return (
    <>
      <path d="M4 4.5A2.5 2.5 0 0 1 6.5 2h22.6L36 8.9V38H4z" fill={`url(#${fade})`} />
      <path d="M29.1 2v4.4A2.5 2.5 0 0 0 31.6 8.9H36z" fill="#c9ced2" />
      <rect x="8.5" y="8" width="12" height="2.6" rx="1.3" fill="#9aa1a7" />
      <rect x="8.5" y="13.4" width="17" height="1.8" rx="0.9" fill="#b8bec3" />
      {children}
    </>
  );
}

export function Glyph({ kind, className }: { kind: GlyphKind; className?: string }) {
  const fade = `${useId()}-fade`;
  return (
    <svg className={className} viewBox="0 0 40 40" aria-hidden="true" focusable="false">
      <defs>
        <linearGradient id={fade} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0.3" stopColor="#f4f6f7" />
          <stop offset="1" stopColor="#f4f6f7" stopOpacity="0.08" />
        </linearGradient>
      </defs>
      {kind === 'paid' && <Sheet fade={fade} />}
      {kind === 'failed' && (
        <Sheet fade={fade}>
          <path
            d="M27 20.5l7.6 13.2a1.4 1.4 0 0 1-1.2 2.1H18.2a1.4 1.4 0 0 1-1.2-2.1l7.6-13.2a1.4 1.4 0 0 1 2.4 0z"
            fill="#f0a35a"
          />
          <rect x="24.9" y="25" width="1.9" height="5.4" rx="0.95" fill="#3b2d24" />
          <circle cx="25.85" cy="32.6" r="1.1" fill="#3b2d24" />
        </Sheet>
      )}
      {kind === 'payout' && (
        <>
          <rect x="3" y="7" width="34" height="24" rx="3.2" fill={`url(#${fade})`} />
          <rect x="3" y="11.5" width="34" height="4" fill="#aeb5ba" />
          <rect x="7.5" y="20" width="9" height="2.4" rx="1.2" fill="#b8bec3" />
          <path
            d="M24 24.5h8m-3-3.2 3.2 3.2-3.2 3.2"
            fill="none"
            stroke="#7fb8e6"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </>
      )}
    </svg>
  );
}

export function Cross({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 16 16" aria-hidden="true" focusable="false">
      <path
        d="M4.5 4.5l7 7m0-7-7 7"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
      />
    </svg>
  );
}

/** The workspace's mark: two leaves, one over the other. */
export function Mark({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
      <rect width="24" height="24" rx="7" fill="currentColor" />
      <path
        d="M7 15.5c0-4.4 3.3-7.7 10-8-.3 6.7-3.6 10-8 10-1.2 0-2-.8-2-2z"
        fill="#fff"
        opacity="0.92"
      />
      <path d="M9.4 14.6 14 10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
    </svg>
  );
}
```

### aurora-toast/demo-pointer.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import type { CSSProperties, Ref } from 'react';

/*
 * The demo's pointer, and the steps that move it. A demo is a script of awaited steps: wait, or
 * glide the pointer somewhere. Stopping the demo (the reader takes over, or it scrolls away) ends
 * the step in progress at once: its promise rejects, which ends the script right there, and the
 * pointer fades out.
 *
 * Each glide is a curved flight played by the Web Animations API, so nothing runs frame by frame.
 * The points of the flight are handed to whoever wants to move along with it (nothing here uses
 * them yet). The arrow and the hand are HTML boxes
 * that swap by their visibility: a change of style inside an SVG would lay the SVG out again.
 */

export type Point = { x: number; y: number };

/** A glide's path and timing, for an animation that plays along with it. */
export type Flight = { points: Point[]; timing: KeyframeAnimationOptions };

export type Demo = {
  /** Resolves after `ms`. */
  wait: (ms: number) => Promise<void>;
  /** Glides the pointer to `to`, in the stage's own px, in `ms`; `along` gets the flight. */
  glide: (to: Point, ms: number, along?: (flight: Flight) => void) => Promise<void>;
  /** Shows the arrow, or the hand a link shows. */
  glyph: (name: 'arrow' | 'hand') => void;
};

/** What a stopped demo's pending step rejects with. */
class Stopped extends Error {}

/** Where the arrow's tip is, as shares of its box: the point the pointer stands on. */
const TIP: Point = { x: 0.15, y: 0.1 };

/** How many points a flight is drawn through. */
const SAMPLES = 24;

/** Plays `script` with the pointer over `stage`; returns the function that stops it. */
export function runDemo(
  stage: HTMLElement,
  pointer: HTMLElement,
  script: (demo: Demo) => Promise<void>,
): () => void {
  let alive = true;
  let flight: Animation | null = null;
  // The stylesheet sizes the pointer from the stage's width; its tip is where it stands.
  const tip = { x: pointer.offsetWidth * TIP.x, y: pointer.offsetHeight * TIP.y };
  const place = ({ x, y }: Point) => `translate(${x - tip.x}px, ${y - tip.y}px)`;
  const timers = new Set<number>();
  const pending = new Set<() => void>();
  // The pointer comes in from the lower right.
  let at: Point = { x: stage.offsetWidth * 0.8, y: stage.offsetHeight * 0.9 };

  /** Settles like `promise`, or rejects as soon as the demo stops. */
  const step = (promise: Promise<unknown>) =>
    new Promise<void>((resolve, reject) => {
      if (!alive) return reject(new Stopped());
      const cancel = () => reject(new Stopped());
      pending.add(cancel);
      promise.then(
        () => {
          pending.delete(cancel);
          if (alive) resolve();
        },
        () => {
          pending.delete(cancel);
          reject(new Stopped());
        },
      );
    });

  const wait = (ms: number) =>
    step(
      new Promise<void>((resolve) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          resolve();
        }, ms);
        timers.add(timer);
      }),
    );

  const glide: Demo['glide'] = (to, ms, along) => {
    const from = at;
    at = to;
    const dx = to.x - from.x;
    const dy = to.y - from.y;
    // A gentle curve, as a hand moves: the control point sits off the straight line.
    const bend = { x: (from.x + to.x) / 2 - dy * 0.18, y: (from.y + to.y) / 2 + dx * 0.18 };
    const points: Point[] = [];
    for (let i = 0; i <= SAMPLES; i += 1) {
      const t = i / SAMPLES;
      const u = 1 - t;
      points.push({
        x: u * u * from.x + 2 * u * t * bend.x + t * t * to.x,
        y: u * u * from.y + 2 * u * t * bend.y + t * t * to.y,
      });
    }
    const timing: KeyframeAnimationOptions = {
      duration: ms,
      easing: 'cubic-bezier(0.45, 0, 0.25, 1)',
    };
    flight?.cancel();
    // Where it rests once the flight is over.
    pointer.style.transform = place(to);
    flight = pointer.animate(
      points.map((point) => ({ transform: place(point) })),
      timing,
    );
    along?.({ points, timing });
    return step(flight.finished);
  };

  const glyph: Demo['glyph'] = (name) => {
    pointer.dataset.glyph = name;
  };

  pointer.dataset.glyph = 'arrow';
  pointer.style.transform = place(at);
  pointer.style.opacity = '1';
  script({ wait, glide, glyph }).catch((error: unknown) => {
    if (!(error instanceof Stopped)) throw error;
  });

  return () => {
    if (!alive) return;
    alive = false;
    timers.forEach((timer) => window.clearTimeout(timer));
    flight?.cancel();
    pending.forEach((cancel) => cancel());
    pointer.style.opacity = '0';
  };
}

/**
 * The pointer's box: it moves, on a layer of its own. Its size comes from its class, its colours
 * from the stage's tokens (aurora-toast.module.css).
 */
const POINTER: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  zIndex: 2,
  display: 'block',
  pointerEvents: 'none',
  opacity: 0,
  transition: 'opacity 0.3s ease',
  filter: 'drop-shadow(0 1px 1.5px var(--pointer-shadow))',
  willChange: 'transform',
};

/** One glyph over the other, each filling the box. */
const GLYPH: CSSProperties = { position: 'absolute', inset: 0, display: 'block' };
const DRAWING: CSSProperties = {
  display: 'block',
  width: '100%',
  height: '100%',
  overflow: 'visible',
};
/** The arrow is dark on a white edge, the hand white on a dark one, as the system draws them. */
const ARROW: CSSProperties = { fill: 'var(--pointer)', stroke: 'var(--pointer-edge)' };
const HAND: CSSProperties = { fill: 'var(--pointer-edge)', stroke: 'var(--pointer)' };

/**
 * The pointer the demo moves around: an arrow, or a pointing hand over a control. It is
 * decorative: what it does shows on the control itself. The stylesheet shows one glyph at a time,
 * from the box's data-glyph.
 */
export function DemoPointer({
  ref,
  className,
  arrowClass,
  handClass,
}: {
  ref: Ref<HTMLSpanElement>;
  className?: string;
  arrowClass?: string;
  handClass?: string;
}) {
  return (
    <span ref={ref} className={className} style={POINTER} aria-hidden="true">
      <span className={arrowClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          <path
            d="M3 2v14.5l3.6-3.3 2.6 5.6 2.4-1.1-2.6-5.5h5.2z"
            style={ARROW}
            strokeWidth="1.3"
            strokeLinejoin="round"
          />
        </svg>
      </span>
      <span className={handClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          {/* The tip of the finger sits where the arrow's tip is. */}
          <path
            d="M6.4 3.3c0-.8.6-1.4 1.3-1.4S9 2.5 9 3.3v5.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.7c.2-.4.6-.7 1.1-.7.7 0 1.2.5 1.2 1.2v3.5c0 2.8-1.9 4.9-4.6 4.9h-1.2c-1.8 0-3.1-.8-4.1-2.3l-2.6-3.9c-.4-.6-.2-1.3.4-1.7.6-.3 1.3-.2 1.7.4l.6.9z"
            style={HAND}
            strokeWidth="1.1"
            strokeLinejoin="round"
            transform="translate(-4.7 0.1)"
          />
        </svg>
      </span>
    </span>
  );
}
```

### aurora-toast/use-autoplay.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';

/*
 * When a demo may play on its own: while part of it is on screen and the tab is visible, never
 * under reduced motion, and never again once the reader has used it: `take()` hands it to the
 * reader for good (until the component mounts again), so it can't come back on its own.
 */
export function useAutoplay<T extends HTMLElement>() {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    let onScreen = false;
    const update = () => setVisible(onScreen && !document.hidden);
    const observer = new IntersectionObserver(
      ([entry]) => {
        onScreen = entry.isIntersecting;
        update();
      },
      { threshold: 0.3 },
    );
    observer.observe(element);
    document.addEventListener('visibilitychange', update);
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const readMotion = () => setReduced(motion.matches);
    readMotion();
    motion.addEventListener('change', readMotion);
    return () => {
      observer.disconnect();
      document.removeEventListener('visibilitychange', update);
      motion.removeEventListener('change', readMotion);
    };
  }, []);

  const take = useCallback(() => setTaken(true), []);

  return { ref, take, playing: visible && !reduced && !taken };
}
```