# Motion specimens

> A drifting wall of wireframe app windows, each looping one interaction you can also play yourself.

A light grid of small greyscale app windows, each named in a pill under it and each playing its own interaction with a pointer of its own: a command palette opens over a dimmed dashboard and a result is picked, toasts stack in and drain away, a heart bursts and its count rolls from 24 to 25, a stat card grows into a dialog with a bar chart, a drawer slides in, a page gives way to the next, a menu reorders a list, tabs morph a chart. The wall drifts slowly across the stage. Rest the pointer on a tile and its demo stops: every click in it works.

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

Category: Motion.

## Anatomy

1. **Stage**: The light panel with its hairline grid. With eight specimens it is 16 : 9 and the wall drifts across it; with four or fewer it is a still grid.
2. **Tile**: One cell of the grid: a window, and its name 14 px under it. On the wall a tile is 42% of the stage wide, 4 : 3.
3. **Window**: A wireframe app, drawn at 322 × 218 px and scaled to its tile, so every proportion stays the one measured.
4. **Title bar**: Three dots, the address bar and two buttons, 20 px tall: the window reads as an app at any size.
5. **Dim**: A veil over the page while something is open on it; a press on it closes what is open.
6. **Opened surface**: What the interaction brings in, here the command palette: white, 7 px corners, a soft shadow under it.
7. **Name**: The specimen’s name in a pill, 500 weight, about 13 px on a wall tile.

## Properties

### Specimens (`specimens`)

1. **All eight (default)**: A wall four by two, wider than the stage, that drifts.
2. **Four**: Two by two in a still grid: the palette, the toast, the like and the card.

Eight for a showcase the reader browses; four or fewer where the specimens sit among other content and should keep still.

### Pose (`pose`)

1. **Rest (default)**: Every tile starts at rest and its demo plays it.
2. **Open**: Every tile starts with its interaction at its end: a still for docs and screenshots.

Rest on a live page. Open for an image, a print or a page that must not move; the tiles still answer clicks.

## When to use

- Showing a set of interactions at a glance: a component library’s landing page, a motion guide, a design system’s overview.
- Comparing motion side by side: how a palette, a drawer and a dialog open in the same product, at the same speed.
- A hero or a section break where the product’s feel matters more than its words, each tile playable by the reader.
- Teaching what a pattern is called: the wireframe strips the page down to the motion, and the name sits under it.

## When not to use

- Demonstrating one interaction in depth. Show the real component, at full size, with its states.
- Documentation that must be read without motion, or printed: give a still per state with a caption.
- Inside an app’s working screens. Specimens are pictures of an interface, not the interface: they hold no data.
- A page already busy with animation. Eight loops at once compete with anything else that moves; show four, or turn the drift off.

### Playing a specimen

- **On its own**, each tile’s pointer plays its interaction in a loop of about six seconds, the tiles starting one after another so the wall doesn’t move in step.
- **The reader’s pointer or focus on a tile** rests its demo; it comes back 0.9 s after they leave. A click or a key in the tile hands it over for good.
- **Real clicks run the same code** the demo does: the palette, the toasts, the like, the dialog, the drawer, the links, the menu and the tabs all work.

### Staying light

- **Moves are CSS transitions and one-shot Web Animations**: nothing runs frame by frame in script.
- **A tile out of view stops**, by an IntersectionObserver that counts the stage’s clip, so tiles drifted off the stage rest too; the drift stops off screen and in a hidden tab.
- **Nothing loops forever in CSS**: a toast’s bar drains once, the caret doesn’t blink.

## Do’s and don’ts

- **Do**: Name each specimen by its pattern, in two words or fewer: Command palette, Toast, Card expand.
- **Don’t**: Put two walls on one page, or a wall beside other animation: sixteen loops are noise.
- **Do**: Use `pose="open"` where the page must keep still: each tile shows its interaction’s end.
- **Caution**: Below about 240 px a window’s controls get small to press; on a phone the wall becomes one column.

## Content

The only words on screen are the specimens’ names; everything in the windows is drawn.

- **A pattern’s common name**, in sentence case: `Command palette`, `Like burst`, `Page transition`.
- **No made-up words in the windows**: bars stand for text, so the motion is what reads.
- **Screen readers get real names**: each control in a window is named (“Search”, “Save changes”, “Like, 24”, “Sort by Newest”).

## Installation

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

```sh
npx shadcn@latest add https://brunodelorence.com/r/motion-specimens.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/motion-specimens
```

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
'use client';

import { MotionSpecimens } from './motion-specimens';

export function MotionSection() {
  return (
    <MotionSpecimens
      onInteract={(specimen, action) => console.log(specimen, action)}
    />
  );
}
```

## States

- **Four at rest**: The reference’s four, two by two, nothing open: what the wall shows between loops.
- **Command palette**: Open over the dimmed dashboard, the second result lit.
- **Toast**: Two toasts stacked at the page’s left, their bars draining.
- **Like burst**: Liked: the heart filled, the count at 25.
- **Card expand**: The third card grown into a dialog with its bar chart.
- **Drawer**: In from the right over the list, the row it belongs to marked.
- **Page transition**: On the second page, the underline under its link.
- **Sort menu**: The menu out of its button’s corner, the current order ticked.
- **Tabs**: The second tab chosen, the bars at its heights.
- **Dark**: With `colorScheme="dark"` the wireframes invert: light bars and ink on dark windows.

## How it works

- Every window is a wireframe drawn at 322 × 218 px (a 20 px title bar over the page), the size measured in the reference, and scaled as a whole to its tile with --s, read from one frame’s width by a ResizeObserver. The window takes 67% of its tile, its name pill 14 px under it.
- Eight specimens make a wall four by two, each tile 42% of a 16 : 9 stage wide. The drift is one Web Animation on the wall, corner to corner and back at 14 px a second; it stops while the mouse is over the wall, off screen and in a hidden tab, and keyboard focus in a tile out of view slides the wall 420 ms to show it.
- Each tile’s demo is a pointer that glides on curved paths and dips 220 ms on a press, calling the same functions as the reader’s clicks. It plays only while half the tile is in view (an IntersectionObserver, which counts the stage’s clip), starts 450 ms after its neighbour, rests while the pointer or focus is on the tile and comes back 0.9 s after; a click or a key there hands the tile over for good.
- Openings run 200–340 ms on cubic-bezier(0.2, 0.8, 0.2, 1) and closings faster on an ease-in: the palette drops 5 px from 97%, the drawer slides in 340 ms and out 220 ms, toasts enter from 14 px below at 94% (@starting-style) and leave 16 px to the left, draining their bar over 3.2 s.
- The card expands by a FLIP: the 218 × 154 dialog is laid out in place, then played from the card’s rect in 380 ms and back in 260 ms; its eight bars rise 35 ms apart. The like dips to 72%, pops to 128% and throws six dots 11 px out, one-shot Web Animations, while the count rolls.
- Slides that land use a spring written as linear() (a 7% overshoot, settled in 0.45 s): the sidebar’s current item, the page underline, the sorted rows, the tab pill and the chart’s twelve bars, 22 ms apart.
- Under 640 px of stage the wall becomes a grid of two columns, and one under 480, with no drift. Every colour is a light-dark() token: at night the wireframes invert. Reduced motion stops the drift and the demos, and every interaction lands on its end state at once.

## API reference

- **specimens** (`('palette' | 'toast' | 'like' | 'expand' | 'drawer' | 'pages' | 'sort' | 'tabs')[]`, default `all eight`): Which specimens, in order. More than four make a drifting wall four wide; four sit two by two, fewer in one row.
- **pose** (`'rest' | 'open'`, default `'rest'`): open starts every tile with its interaction at its end, as a still for docs and screenshots, and turns the demos off.
- **drift** (`boolean`, default `true`): Whether a wall wider than the stage drifts slowly across it.
- **autoplay** (`boolean`, default `true`): While a tile is on screen and untouched, its pointer plays its interaction in a loop; input in the tile stops it.
- **onInteract** (`(specimen: SpecimenId, action: string) => void`): Called when the reader (never the demo) does something in a tile: "open palette", "save", "like", "sort by Name"…
- **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

### Keyboard

- Tab reaches each window’s controls in turn. Focus in a tile out of view slides the wall to bring it in, and stops the drift.
- Opened surfaces take the focus (the palette’s first result, the dialog’s and the drawer’s close button, the menu’s current item) and give it back on Escape.
- The palette and the menu move with the arrows; the tabs move with Left and Right.

### Screen readers

- Each window is a group named after its specimen; the title bars, the bars and the demo pointer are hidden.
- The palette, the dialog and the drawer are dialogs with names; the sort menu is a menu of radio items; the tabs are a tablist.
- New toasts are read from a polite live region: “Changes saved”.

### Motion

With reduced motion there is no drift and no demo, and every interaction lands on its end state at once: no transitions, pops, bursts or FLIPs.

### In this build

- Each window is a group named after its specimen; its controls are real buttons with names (“Search”, “Save changes”, “Like, 24”, “Sort by Newest”). The title bars, the wireframe bars and the demo pointer are hidden from screen readers.
- The palette, the card’s dialog and the drawer take the focus when the reader opens them and give it back to their opener on Escape or close; closed, they are inert.
- The palette moves with Up and Down, the sort menu (a menu of radio items) with Up, Down, Home and End, the tabs (a tablist with one tab stop) with Left and Right.
- Focus in a tile out of view slides the wall to show it and stops the drift; every control shows a 2 px focus ring, thickened by the window’s scale.
- New toasts are read from a polite live region (“Changes saved”).
- With reduced motion there is no drift and no demo, and every interaction lands on its end state at once.

## Source

### motion-specimens/motion-specimens.tsx

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

'use client';

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type ComponentType,
  type CSSProperties,
} from 'react';
import { DemoPointer, runDemo } from './demo-pointer';
import { Like, Pages, Sort, Tabs } from './in-place';
import { WIN, makeKit, type BodyProps, type Pose, type SpecimenHandle } from './kit';
import { Drawer, Expand, Palette, Toasts } from './overlays';
import { useAutoplay } from './use-autoplay';
import styles from './motion-specimens.module.css';

/*
 * Motion specimens: a wall of small greyscale app windows, each with its name under it and one
 * interaction looping inside it (a command palette, toasts, a like that bursts, a card that
 * expands into a dialog, a drawer, a page transition, a sort menu, tabs), while the wall drifts
 * slowly across the stage.
 *
 * - Every window is a wireframe drawn at 322 × 218 px, the size measured in the reference, and
 *   scaled as a whole to its cell; the stage measures one window's frame and sets the scale, --s.
 * - Each tile's demo is a pointer that glides over the window and plays the same functions the
 *   reader's clicks do. It plays only while its tile is on screen (an IntersectionObserver, which
 *   counts the stage's clip, so tiles drifted out of view stop) and the tab is visible, and rests
 *   while the pointer or the focus is in the tile; a click or a key there hands the tile over.
 * - The drift is one Web Animation on the wall, corner to corner and back at 14 px a second,
 *   eased at the ends; it stops while the reader is over the wall, off screen, or the tab is
 *   hidden, and moves a tile into view when the keyboard focus lands in one out of view.
 * - Under 640 px of stage the wall is a plain grid of two columns (one under 480), with no drift.
 * - Reduced motion: no drift, no demos, and every interaction lands on its end state at once.
 */

export type SpecimenId =
  'palette' | 'toast' | 'like' | 'expand' | 'drawer' | 'pages' | 'sort' | 'tabs';

const SPECIMENS: Record<SpecimenId, { label: string; Body: ComponentType<BodyProps> }> = {
  palette: { label: 'Command palette', Body: Palette },
  toast: { label: 'Toast', Body: Toasts },
  like: { label: 'Like burst', Body: Like },
  expand: { label: 'Card expand', Body: Expand },
  drawer: { label: 'Drawer', Body: Drawer },
  pages: { label: 'Page transition', Body: Pages },
  sort: { label: 'Sort menu', Body: Sort },
  tabs: { label: 'Tabs', Body: Tabs },
};

/** The wall's order, row by row: the reference's four first, top left, then the others. */
export const ALL_SPECIMENS: SpecimenId[] = [
  'palette',
  'toast',
  'drawer',
  'pages',
  'like',
  'expand',
  'sort',
  'tabs',
];
/** The wall lays the default eight out four by two, wider than the stage, and drifts. */
const WALL_COLUMNS = 4;
/** Drift speed, in px a second, and how long the wall takes to bring a focused tile in. */
const DRIFT_SPEED = 14;
const REVEAL = 420;
/** How long a tile waits after the pointer or the focus leaves before its demo comes back. */
const RELEASE = 900;

type Point = { x: number; y: number };
const shift = ({ x, y }: Point) => `translate(${x}px, ${y}px)`;
/** Where the wall is now, animation included. */
const placeOf = (wall: HTMLElement): Point => {
  const matrix = new DOMMatrixReadOnly(getComputedStyle(wall).transform);
  return { x: matrix.m41, y: matrix.m42 };
};

export function MotionSpecimens({
  specimens = ALL_SPECIMENS,
  pose = 'rest',
  drift = true,
  autoplay = true,
  onInteract,
  colorScheme,
  className,
}: {
  /** Which specimens, in order. Eight drift as a wall; up to four sit in a still grid. */
  specimens?: SpecimenId[];
  /** 'open' starts every tile with its interaction played to the end, and turns the demos off. */
  pose?: Pose;
  /** Whether a wall wider than the stage drifts across it. */
  drift?: boolean;
  /** While on screen and untouched, each tile's pointer plays its interaction in a loop. */
  autoplay?: boolean;
  /** Called with the tile and what the reader did in it ('open palette', 'like', 'undo'…). */
  onInteract?: (specimen: SpecimenId, action: string) => void;
  /** Light or dark colours, or the reader's ('system'); without it, the page's color-scheme. */
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const {
    ref: stageRef,
    playing: stagePlaying,
    hold: holdStage,
    reduced,
  } = useAutoplay<HTMLDivElement>(0);
  const wallRef = useRef<HTMLDivElement>(null);
  const [scale, setScale] = useState<number | null>(null);
  const [roomy, setRoomy] = useState(false);
  const toward = useRef(true);
  const report = useRef(onInteract);
  useLayoutEffect(() => {
    report.current = onInteract;
  });
  const layout = specimens.length > 4 ? 'wall' : 'grid';

  // The scale of every window, from one frame's width; and whether the wall overflows the stage.
  useLayoutEffect(() => {
    // The window onto the wall: the wall's parent, which the stage sizes and clips.
    const root = wallRef.current?.parentElement;
    const wall = wallRef.current;
    const frame = wall?.querySelector<HTMLElement>(`.${styles.frame}`);
    if (!root || !wall || !frame) return;
    const measure = () => {
      setScale(frame.offsetWidth / WIN.width);
      setRoomy(
        wall.offsetWidth > root.clientWidth + 1 || wall.offsetHeight > root.clientHeight + 1,
      );
    };
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(root);
    observer.observe(frame);
    return () => observer.disconnect();
  }, [stageRef, specimens.length]);

  const moving = drift && layout === 'wall' && roomy && stagePlaying;

  // The drift: corner to corner and back, from wherever the wall is when it starts again.
  useEffect(() => {
    // The window onto the wall: the wall's parent, which the stage sizes and clips.
    const root = wallRef.current?.parentElement;
    const wall = wallRef.current;
    if (!moving || !root || !wall) return;
    let alive = true;
    let flight: Animation | null = null;
    const leg = (turns = 0) => {
      const far = {
        x: Math.min(0, root.clientWidth - wall.offsetWidth),
        y: Math.min(0, root.clientHeight - wall.offsetHeight),
      };
      const from = placeOf(wall);
      const to = toward.current ? far : { x: 0, y: 0 };
      const distance = Math.hypot(to.x - from.x, to.y - from.y);
      if (distance < 1) {
        toward.current = !toward.current;
        if (turns < 1) leg(turns + 1);
        return;
      }
      flight = wall.animate([{ transform: shift(from) }, { transform: shift(to) }], {
        duration: (distance / DRIFT_SPEED) * 1000,
        easing: 'cubic-bezier(0.45, 0, 0.55, 1)',
        fill: 'forwards',
      });
      flight.onfinish = () => {
        if (!alive) return;
        wall.style.transform = shift(to);
        flight?.cancel();
        toward.current = !toward.current;
        leg();
      };
    };
    leg();
    return () => {
      alive = false;
      const at = placeOf(wall);
      flight?.cancel();
      wall.style.transform = shift(at);
    };
  }, [moving, stageRef]);

  // A stage too narrow for the wall lays it out as a grid: the drift's offset goes.
  useLayoutEffect(() => {
    const wall = wallRef.current;
    if (wall && (!roomy || layout !== 'wall')) wall.style.transform = '';
  }, [roomy, layout]);

  const release = useRef(0);
  const holdWall = (on: boolean) => {
    window.clearTimeout(release.current);
    if (on) holdStage(true);
    else release.current = window.setTimeout(() => holdStage(false), RELEASE);
  };
  useEffect(() => () => window.clearTimeout(release.current), []);

  /** Brings the tile the focus went into fully into the stage, if the wall is a drifting one. */
  const reveal = (target: HTMLElement) => {
    holdWall(true);
    // The window onto the wall: the wall's parent, which the stage sizes and clips.
    const root = wallRef.current?.parentElement;
    const wall = wallRef.current;
    const cell = target.closest<HTMLElement>('[data-cell]');
    if (!root || !wall || !cell || layout !== 'wall' || !roomy) return;
    const from = placeOf(wall);
    wall.getAnimations().forEach((animation) => animation.cancel());
    const clamp = (value: number, low: number, high: number) =>
      Math.min(high, Math.max(low, value));
    const fit = (at: number, start: number, size: number, room: number, wallSize: number) =>
      clamp(clamp(at, room - (start + size), -start), Math.min(0, room - wallSize), 0);
    const to = {
      x: fit(from.x, cell.offsetLeft, cell.offsetWidth, root.clientWidth, wall.offsetWidth),
      y: fit(from.y, cell.offsetTop, cell.offsetHeight, root.clientHeight, wall.offsetHeight),
    };
    wall.style.transform = shift(to);
    if (reduced || (to.x === from.x && to.y === from.y)) return;
    wall.animate([{ transform: shift(from) }, { transform: shift(to) }], {
      duration: REVEAL,
      easing: 'cubic-bezier(0.2, 0.8, 0.2, 1)',
    });
  };

  // The reader over the wall (a mouse; a touch only taps) or the focus in it stops the drift.
  const listen = useRef({ holdWall, reveal });
  useLayoutEffect(() => {
    listen.current = { holdWall, reveal };
  });
  useEffect(() => {
    const wall = wallRef.current;
    if (!wall) return;
    const enter = (event: PointerEvent) => {
      if (event.pointerType === 'mouse') listen.current.holdWall(true);
    };
    const leave = () => listen.current.holdWall(false);
    const focusIn = (event: globalThis.FocusEvent) =>
      listen.current.reveal(event.target as HTMLElement);
    const focusOut = (event: globalThis.FocusEvent) => {
      if (!wall.contains(event.relatedTarget as Node | null)) listen.current.holdWall(false);
    };
    wall.addEventListener('pointerenter', enter);
    wall.addEventListener('pointerleave', leave);
    wall.addEventListener('focusin', focusIn);
    wall.addEventListener('focusout', focusOut);
    return () => {
      wall.removeEventListener('pointerenter', enter);
      wall.removeEventListener('pointerleave', leave);
      wall.removeEventListener('focusin', focusIn);
      wall.removeEventListener('focusout', focusOut);
    };
  }, []);

  return (
    <div
      ref={stageRef}
      className={className ? `${styles.root} ${className}` : styles.root}
      data-part="stage"
      data-layout={layout}
      data-color-scheme={colorScheme}
      style={
        {
          '--s': scale ?? undefined,
          // Four sit two by two; fewer sit in one row.
          '--columns':
            layout === 'wall' ? WALL_COLUMNS : specimens.length === 4 ? 2 : specimens.length,
        } as CSSProperties
      }
    >
      <div className={styles.viewport}>
        <div ref={wallRef} className={styles.wall} data-count={specimens.length}>
          {specimens.map((id, index) => (
            <Tile
              key={id}
              id={id}
              index={index}
              pose={pose}
              autoplay={autoplay && pose === 'rest'}
              report={(action) => report.current?.(id, action)}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

/** One specimen: its window (title bar, page, demo pointer) and its name under it. */
function Tile({
  id,
  index,
  pose,
  autoplay,
  report,
}: {
  id: SpecimenId;
  index: number;
  pose: Pose;
  autoplay: boolean;
  report: (action: string) => void;
}) {
  const { label, Body } = SPECIMENS[id];
  const { ref, playing, take, hold } = useAutoplay<HTMLElement>(0.5);
  const win = useRef<HTMLDivElement>(null);
  const pointer = useRef<HTMLSpanElement>(null);
  const handle = useRef<SpecimenHandle>(null);
  const demo = autoplay && playing;

  useEffect(() => {
    const frame = win.current;
    const arrow = pointer.current;
    if (!demo || !frame || !arrow) return;
    const stop = runDemo(frame, arrow, async (steps) => {
      const kit = makeKit(steps, frame, arrow);
      // The tiles start one after another, so the wall doesn't move in step.
      await steps.wait(350 + (index % 4) * 450);
      for (;;) {
        const body = handle.current;
        if (!body) return;
        await body.play(kit);
      }
    });
    const body = handle.current;
    return () => {
      stop();
      body?.reset();
    };
  }, [demo, index]);

  // The pointer or the focus in the tile rests its demo; a click or a key hands it over for good.
  useEffect(() => {
    const cell = ref.current;
    if (!cell) return;
    let timer = 0;
    const holdTile = (on: boolean) => {
      window.clearTimeout(timer);
      if (on) hold(true);
      else timer = window.setTimeout(() => hold(false), RELEASE);
    };
    const enter = () => holdTile(true);
    const leave = () => holdTile(false);
    const focusOut = (event: globalThis.FocusEvent) => {
      if (!cell.contains(event.relatedTarget as Node | null)) holdTile(false);
    };
    const key = (event: KeyboardEvent) => {
      if (event.key !== 'Tab' && event.key !== 'Shift') take();
    };
    const events: [string, EventListener][] = [
      ['pointerenter', enter],
      ['pointerleave', leave],
      ['focusin', enter],
      ['focusout', focusOut as EventListener],
      ['pointerdown', take],
      ['keydown', key as EventListener],
    ];
    events.forEach(([name, run]) => cell.addEventListener(name, run));
    return () => {
      window.clearTimeout(timer);
      events.forEach(([name, run]) => cell.removeEventListener(name, run));
    };
  }, [ref, hold, take]);

  return (
    <figure ref={ref} className={styles.cell} data-cell data-part="tile" data-specimen={id}>
      <div className={styles.frame}>
        <div ref={win} className={styles.win} role="group" aria-label={label} data-part="window">
          <div className={styles.chrome} aria-hidden="true" data-part="title-bar">
            <span className={styles.dots} />
            <span className={styles.url} />
            <span className={styles.tools} />
          </div>
          <div className={styles.body}>
            <Body ref={handle} pose={pose} report={report} />
          </div>
          <DemoPointer
            ref={pointer}
            className={styles.pointer}
            arrowClass={styles.arrow}
            handClass={styles.hand}
          />
        </div>
      </div>
      <figcaption className={styles.label} data-part="label">
        {label}
      </figcaption>
    </figure>
  );
}
```

### motion-specimens/motion-specimens.module.css

```css
/* Motion specimens (motion-specimens.tsx): a wall of greyscale wireframe windows on a light grid,
   each with its name in a pill under it and one interaction looping inside it.

   Sizes. Every window is drawn at 322 × 218 px (a 20 px title bar over the page) and scaled as a
   whole by --s, which the script reads from one frame's width: so the px below are the window's
   own, as measured in the reference. A cell is 480 × 360 window px in the reference: the window
   takes 67% of its width, its name 14 px under it. Cells are containers, so the frame and the
   name follow the cell (cqi).

   Layout. Eight specimens make a wall of four columns, each 42% of the stage wide, wider than the
   stage, which the script drifts. Up to four sit in a still grid. Under 640 px of stage both are a
   grid of two columns, and one under 480.

   Colours are the tokens below, light-dark(light, dark): at night the wireframes invert, light
   bars on dark windows, and the ink (dark buttons, the heart, the pointer) turns light.

   Motion. Openings are 200–340 ms on an ease-out (cubic-bezier(0.2, 0.8, 0.2, 1)), closings
   faster on an ease-in; slides that land (the sidebar's mark, the underline, the rows, the pill,
   the bars) use a spring written as linear(). Reduced motion drops every transition and
   animation, so each interaction lands on its end state at once. */

.root {
  --stage: #f7f7f9;
  --grid: #e9e9ec;
  --win: #fff;
  --chrome: #fafafb;
  --side: #f6f6f8;
  --line: rgb(0 0 0 / 0.05);
  --edge: rgb(0 0 0 / 0.12);
  --edge-soft: rgb(0 0 0 / 0.06);
  --card: #f2f3f5;
  --sk-soft: #eeeff1;
  --sk: #e2e3e6;
  --sk-strong: #cfd0d4;
  --ink: #18181a;
  --ink-mid: #6c6d72;
  --on-ink: #fff;
  --dim: rgb(24 24 30 / 0.26);
  --panel: #fff;
  --hover: #eff0f2;
  --toast: #e4e5e8;
  --shadow: rgb(0 0 0 / 0.16);
  --shadow-soft: rgb(0 0 0 / 0.1);
  --win-shadow: rgb(20 20 30 / 0.07);
  --area: #e6e7ea;
  --area-line: #bfc0c5;
  --label: #eceef1;
  --label-ink: #3b3c40;
  --focus: #387bff;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.25);
  /* A spring that lands with a small overshoot (damping about 0.7), settled in 0.45 s. */
  --spring: linear(
    0,
    0.08 4%,
    0.29 9%,
    0.55 15%,
    0.79 22%,
    0.96 30%,
    1.05 38%,
    1.07 45%,
    1.05 53%,
    1.02 62%,
    1 72%,
    0.995 84%,
    1
  );
  --ease-out: cubic-bezier(0.2, 0.8, 0.2, 1);
  --ease-in: cubic-bezier(0.5, 0, 0.75, 0.4);
  position: relative;
  container: stage / inline-size;
  width: 100%;
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background: var(--stage);
  box-shadow: inset 0 0 0 1px var(--line);
  -webkit-tap-highlight-color: transparent;
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --stage: light-dark(#f7f7f9, #111113);
    --grid: light-dark(#e9e9ec, #222226);
    --win: light-dark(#fff, #1b1b1e);
    --chrome: light-dark(#fafafb, #1f1f23);
    --side: light-dark(#f6f6f8, #1e1e21);
    --line: light-dark(rgb(0 0 0 / 0.05), rgb(255 255 255 / 0.06));
    --edge: light-dark(rgb(0 0 0 / 0.12), rgb(255 255 255 / 0.14));
    --edge-soft: light-dark(rgb(0 0 0 / 0.06), rgb(255 255 255 / 0.08));
    --card: light-dark(#f2f3f5, #242428);
    --sk-soft: light-dark(#eeeff1, #2a2a2e);
    --sk: light-dark(#e2e3e6, #333338);
    --sk-strong: light-dark(#cfd0d4, #4a4b51);
    --ink: light-dark(#18181a, #ececef);
    --ink-mid: light-dark(#6c6d72, #a3a4aa);
    --on-ink: light-dark(#fff, #18181a);
    --dim: light-dark(rgb(24 24 30 / 0.26), rgb(0 0 0 / 0.5));
    --panel: light-dark(#fff, #27272b);
    --hover: light-dark(#eff0f2, #323237);
    --toast: light-dark(#e4e5e8, #34343a);
    --shadow: light-dark(rgb(0 0 0 / 0.16), rgb(0 0 0 / 0.55));
    --shadow-soft: light-dark(rgb(0 0 0 / 0.1), rgb(0 0 0 / 0.4));
    --win-shadow: light-dark(rgb(20 20 30 / 0.07), rgb(0 0 0 / 0.45));
    --area: light-dark(#e6e7ea, #2c2c31);
    --area-line: light-dark(#bfc0c5, #5a5b61);
    --label: light-dark(#eceef1, #1f1f23);
    --label-ink: light-dark(#3b3c40, #c6c7cc);
    --pointer: light-dark(#1c1c1e, #f4f4f6);
    --pointer-edge: light-dark(#fff, #111113);
    --pointer-shadow: light-dark(rgb(0 0 0 / 0.25), rgb(0 0 0 / 0.6));
  }
}
.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 window onto the wall, sized here and not on the stage itself, so the stage's container
   queries below can reach it. The drifting wall: four columns of 42% of the stage, two rows, on a
   16 : 9 window. */
.viewport {
  position: relative;
  overflow: hidden;
  overflow: clip;
}
.root[data-layout='wall'] .viewport {
  aspect-ratio: 16 / 9;
  min-height: 420px;
  max-height: 760px;
}
.wall {
  display: grid;
  grid-template-columns: repeat(var(--columns), minmax(0, 1fr));
}
.root[data-layout='wall'] .wall {
  position: absolute;
  top: 0;
  left: 0;
  grid-template-columns: repeat(var(--columns), 42cqi);
  grid-auto-rows: 31.5cqi;
  will-change: transform;
}
.root[data-layout='grid'] .cell {
  aspect-ratio: 4 / 3;
}

/* A cell: the window, and its name under it, centred; hairlines between cells. */
.cell {
  container-type: inline-size;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0;
  min-width: 0;
  box-shadow:
    1px 0 0 var(--grid),
    0 1px 0 var(--grid);
}
.frame {
  position: relative;
  width: 67cqi;
  aspect-ratio: 322 / 218;
  flex: none;
  /* 14 px under a 322 px window, as measured; cqi here is the cell's. */
  margin-bottom: 2.9cqi;
}
.win {
  position: absolute;
  top: 0;
  left: 0;
  width: 322px;
  height: 218px;
  scale: var(--s, 1);
  transform-origin: 0 0;
  overflow: hidden;
  overflow: clip;
  border-radius: 7px;
  background: var(--win);
  box-shadow:
    0 0 0 1px var(--edge-soft),
    0 1px 2px var(--win-shadow),
    0 6px 18px var(--win-shadow);
}
.label {
  padding: 0.32em 0.95em 0.38em;
  border-radius: 999px;
  background: var(--label);
  color: var(--label-ink);
  font-family: inherit;
  font-size: clamp(11px, 2.75cqi, 15px);
  font-weight: 500;
  line-height: 1.3;
  white-space: nowrap;
}

/* The title bar: three dots, the address bar, two buttons at the right. */
.chrome {
  position: absolute;
  top: 0;
  left: 0;
  width: 322px;
  height: 20px;
  background: var(--chrome);
  box-shadow: inset 0 -1px 0 var(--line);
}
.dots,
.url,
.tools {
  position: absolute;
  display: block;
  background: var(--sk);
}
.dots {
  top: 7.8px;
  left: 8px;
  width: 4.4px;
  height: 4.4px;
  border-radius: 50%;
  box-shadow:
    7px 0 0 var(--sk),
    14px 0 0 var(--sk);
}
.url {
  top: 5.5px;
  left: 36px;
  width: 125px;
  height: 9px;
  border-radius: 4.5px;
  background: var(--sk-soft);
}
.tools {
  top: 6.5px;
  left: 307px;
  width: 7px;
  height: 7px;
  border-radius: 1.5px;
  background: var(--sk-soft);
  box-shadow: -11px 0 0 var(--sk-soft);
}
.body {
  position: absolute;
  top: 20px;
  left: 0;
  width: 322px;
  height: 198px;
  overflow: hidden;
  overflow: clip;
  isolation: isolate;
}
.scene {
  position: absolute;
  inset: 0;
}

/* The demo's pointer, in window px: one glyph at a time. */
.pointer {
  width: 15px;
  height: 15px;
}
.pointer[data-glyph='arrow'] .hand,
.pointer[data-glyph='hand'] .arrow {
  visibility: hidden;
}

/* The wireframe's pieces. */
.sk {
  position: absolute;
  display: block;
  border-radius: 99px;
  background: var(--sk);
}
.sk[data-tone='soft'] {
  background: var(--sk-soft);
}
.sk[data-tone='strong'] {
  background: var(--sk-strong);
}
.sk[data-tone='ink'] {
  background: var(--ink);
}
.sk[data-tone='card'] {
  background: var(--card);
  box-shadow: inset 0 0 0 1px var(--edge-soft);
}
.sk.onInk {
  background: var(--on-ink);
}
.sk.key {
  background: transparent;
  box-shadow: inset 0 0 0 1px var(--edge);
}
/* The controls the reader (and the demo) presses: buttons with no look of their own. */
.hot {
  position: absolute;
  display: block;
  margin: 0;
  padding: 0;
  border: 0;
  border-radius: 4px;
  background: transparent;
  color: inherit;
  font: inherit;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
}
.box {
  position: absolute;
  display: block;
}
.side {
  background: var(--side);
  box-shadow: inset -1px 0 0 var(--line);
}
.navHi {
  position: absolute;
  border-radius: 4px;
  background: var(--win);
  box-shadow:
    0 0 0 0.5px var(--edge-soft),
    0 1px 2px var(--shadow-soft);
  transition: translate 0.45s var(--spring);
}
.card {
  border-radius: 5px;
  background: var(--card);
}
.outline {
  border-radius: 4px;
  background: var(--win);
  box-shadow: inset 0 0 0 1px var(--edge);
}
.dark {
  border-radius: 4px;
  background: var(--ink);
}
.area {
  position: absolute;
  top: 30px;
  left: 9px;
  width: 200px;
  height: 58px;
  overflow: visible;
}
.glyph {
  display: block;
  width: 100%;
  height: 100%;
}

.hot.card,
.hot.outline,
.hot.dark {
  transition: filter 0.15s ease;
}
.hot.card:hover,
.hot.outline:hover {
  filter: brightness(0.97);
}
.hot.dark:hover {
  filter: brightness(1.25);
}
/* The ring is drawn in window px, so it is thickened by the window's scale to stay 2 px. */
.hot:focus-visible {
  z-index: 3;
  outline: calc(2px / var(--s, 1)) solid var(--focus);
  outline-offset: calc(1.5px / var(--s, 1));
}
.closeButton {
  display: grid;
  place-items: center;
  color: var(--ink-mid);
}
.closeButton .glyph {
  width: 9px;
  height: 9px;
}
.closeButton:hover {
  background: var(--hover);
}

/* The dim over the page, under whatever opened. */
.dim {
  position: absolute;
  inset: 0;
  z-index: 1;
  background: var(--dim);
  opacity: 0;
  border-radius: 0;
  pointer-events: none;
  cursor: default;
  transition: opacity 0.2s ease;
}
.scene[data-open] .dim {
  opacity: 1;
  pointer-events: auto;
}
.panel {
  z-index: 2;
  border-radius: 7px;
  background: var(--panel);
  box-shadow:
    0 0 0 1px var(--edge-soft),
    0 12px 30px -8px var(--shadow);
}

/* Command palette: drops in from 5 px above at 97%; the query types itself in four steps. */
.palette {
  opacity: 0;
  transform: translateY(-5px) scale(0.97);
  transition:
    opacity 0.14s ease,
    transform 0.16s var(--ease-in);
}
.scene[data-open] .palette {
  opacity: 1;
  transform: none;
  transition:
    opacity 0.16s ease,
    transform 0.24s var(--ease-out);
}
.query {
  position: absolute;
  width: 0;
  border-radius: 99px;
  background: var(--sk-strong);
}
.query::after {
  content: '';
  position: absolute;
  top: -1.5px;
  right: -3px;
  width: 1px;
  height: 10px;
  background: var(--ink);
}
.scene[data-open] .query {
  width: 17px;
  transition: width 0.32s steps(4, jump-start) 0.14s;
}
.item[data-hi] {
  background: var(--hover);
}
.menu .item:hover,
.menu .item:focus-visible {
  background: var(--hover);
}
.itemHint {
  opacity: 0;
}
.item[data-hi] .itemHint {
  opacity: 1;
}

/* Card expand: the dialog is played from the card's rect by the script (a FLIP); its contents
   fade in once it has mostly grown, and its bars rise one after another. */
.modal {
  overflow: hidden;
  overflow: clip;
  transform-origin: 0 0;
}
.scene:not([data-open]) .modal {
  pointer-events: none;
}
.modalInner {
  position: absolute;
  inset: 0;
  animation: fade-in 0.22s ease 0.12s both;
}
.scene:not([data-open]) .modalInner {
  opacity: 0;
  transition: opacity 0.12s ease;
}
.growBar {
  transform-origin: 50% 100%;
  animation: grow 0.46s var(--ease-out) both;
  animation-delay: calc(0.16s + var(--i) * 35ms);
}
@keyframes fade-in {
  from {
    opacity: 0;
  }
}
@keyframes grow {
  from {
    scale: 1 0;
  }
}

/* The settings page's switches. */
.switch {
  position: absolute;
  display: block;
  width: 20px;
  height: 10px;
  border-radius: 5px;
  background: var(--sk);
}
.switch::after {
  content: '';
  position: absolute;
  top: 1.5px;
  left: 1.5px;
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: var(--win);
}
.switch[data-on] {
  background: var(--ink);
}
.switch[data-on]::after {
  translate: 10px 0;
  background: var(--on-ink);
}

/* Toasts: each in its slot (--y), entering from 14 px below at 94%, leaving 16 px to the left;
   the bar under its words drains over its life. */
.toasts {
  position: absolute;
  z-index: 2;
  width: 183px;
  height: 112px;
  pointer-events: none;
}
.toast {
  position: absolute;
  top: 0;
  left: 0;
  width: 183px;
  height: 52px;
  border-radius: 7px;
  background: var(--toast);
  box-shadow:
    0 0 0 1px var(--edge-soft),
    0 10px 20px -8px var(--shadow);
  transform: translateY(var(--y));
  pointer-events: auto;
  transition:
    transform 0.32s var(--ease-out),
    opacity 0.2s ease;
}
@starting-style {
  .toast {
    opacity: 0;
    transform: translateY(calc(var(--y) + 14px)) scale(0.94);
  }
}
.toast[data-leaving] {
  opacity: 0;
  transform: translateY(var(--y)) translateX(-16px) scale(0.96);
  pointer-events: none;
  transition-duration: 0.22s;
  transition-timing-function: var(--ease-in);
}
.toastMark {
  position: absolute;
  inset: 2px;
  color: var(--on-ink);
}
.progress {
  position: absolute;
  top: 42px;
  left: 10px;
  width: 116px;
  height: 1.5px;
  border-radius: 1px;
  background: var(--ink);
  transform-origin: 0 50%;
  animation: drain var(--life) linear forwards;
}
@keyframes drain {
  to {
    scale: 0 1;
  }
}

/* Drawer: slides in from past the right edge, slower in than out. */
.tableRow:hover,
.tableRow[data-hi] {
  background: var(--hover);
}
.drawer {
  z-index: 2;
  background: var(--panel);
  box-shadow:
    -1px 0 0 var(--edge-soft),
    -12px 0 26px -10px var(--shadow);
  translate: calc(100% + 12px) 0;
  transition: translate 0.22s var(--ease-in);
}
.scene[data-open] .drawer {
  translate: 0 0;
  transition: translate 0.34s cubic-bezier(0.2, 0.85, 0.25, 1);
}

/* Like burst: the heart, its six dots (played by the script) and the count that rolls. */
.likeButton:hover {
  background: var(--hover);
}
.heart {
  position: absolute;
  top: 3px;
  left: 4px;
  display: block;
  width: 14px;
  height: 14px;
  color: var(--ink);
}
.burst {
  position: absolute;
  top: 10px;
  left: 11px;
  width: 0;
  height: 0;
}
.burst span {
  position: absolute;
  top: -1.5px;
  left: -1.5px;
  width: 3px;
  height: 3px;
  border-radius: 50%;
  background: var(--ink);
  opacity: 0;
}
.count {
  position: absolute;
  top: 2px;
  left: 25px;
  height: 16px;
  overflow: hidden;
  overflow: clip;
  color: var(--ink);
  font-family: inherit;
  font-size: 13px;
  font-weight: 600;
  line-height: 16px;
  font-variant-numeric: tabular-nums;
}
.count span {
  display: block;
}
.count [data-roll='up'] {
  animation: roll-up 0.3s var(--ease-out);
}
.count [data-roll='down'] {
  animation: roll-down 0.3s var(--ease-out);
}
@keyframes roll-up {
  from {
    opacity: 0;
    translate: 0 75%;
  }
}
@keyframes roll-down {
  from {
    opacity: 0;
    translate: 0 -75%;
  }
}

/* Page transition: the page going slides 18 px toward where it came from, the new one slides in
   from the other side 90 ms later; the underline glides on the spring. */
.link:hover .sk {
  background: var(--sk-strong);
}
.underline {
  position: absolute;
  left: 0;
  display: block;
  background: var(--ink);
  transform-origin: 0 0;
  transition:
    translate 0.45s var(--spring),
    scale 0.45s var(--spring);
}
.pages {
  position: absolute;
  left: 0;
  width: 322px;
  overflow: hidden;
  overflow: clip;
}
.page {
  position: absolute;
  inset: 0;
  transition:
    opacity 0.2s ease,
    translate 0.28s var(--ease-in),
    visibility 0s 0.28s;
}
.page[data-pos='before'],
.page[data-pos='after'] {
  opacity: 0;
  visibility: hidden;
}
.page[data-pos='before'] {
  translate: -18px 0;
}
.page[data-pos='after'] {
  translate: 18px 0;
}
.page[data-pos='here'] {
  transition:
    opacity 0.26s ease 0.09s,
    translate 0.36s var(--ease-out) 0.09s,
    visibility 0s;
}
.picture {
  overflow: hidden;
  overflow: clip;
}
.pictureArt {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 72%;
  color: var(--sk);
}
.caption {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  height: 11px;
  background: var(--win);
}

/* Sort menu: scales out of its top-right corner, its items arriving 35 ms apart; the rows slide
   to their new ranks on the spring. */
.chevron {
  position: absolute;
  top: 3px;
  left: 59px;
  width: 10px;
  height: 10px;
  color: var(--ink-mid);
}
.sortLabel {
  transition: width 0.26s var(--ease-out);
}
.sortRow {
  position: absolute;
  left: 16px;
  display: block;
  width: 290px;
  height: 28px;
  transition: translate 0.5s var(--spring);
}
.menu {
  transform-origin: 100% 0;
  opacity: 0;
  scale: 0.92;
  transition:
    opacity 0.12s ease,
    scale 0.14s var(--ease-in);
}
.menu:not([inert]) {
  opacity: 1;
  scale: 1;
  transition:
    opacity 0.14s ease,
    scale 0.22s var(--ease-out);
}
.menu .item {
  opacity: 0;
  translate: 0 -3px;
  transition:
    opacity 0.1s ease,
    translate 0.1s ease;
}
.menu:not([inert]) .item {
  opacity: 1;
  translate: 0 0;
  transition:
    opacity 0.16s ease,
    translate 0.22s var(--ease-out);
  transition-delay: calc(40ms + var(--i) * 35ms);
}
.check {
  position: absolute;
  top: 3px;
  left: 5px;
  width: 10px;
  height: 10px;
  color: var(--ink);
}

/* Tabs: the pill slides on the spring; the bars follow it, 22 ms apart, to their new heights. */
.track {
  border-radius: 6px;
  background: var(--card);
}
.pill {
  position: absolute;
  display: block;
  border-radius: 5px;
  background: var(--win);
  box-shadow:
    0 0 0 0.5px var(--edge-soft),
    0 1px 2px var(--shadow-soft);
  transition: translate 0.45s var(--spring);
}
.tab:hover .sk {
  background: var(--sk-strong);
}
.chartBar {
  position: absolute;
  display: block;
  border-radius: 2px 2px 0 0;
  background: var(--sk);
  transform-origin: 50% 100%;
  transition: scale 0.55s var(--spring);
  transition-delay: calc(var(--i) * 22ms);
}
.chartBar[data-tone='strong'] {
  background: var(--sk-strong);
}
.total {
  transition: width 0.3s var(--ease-out);
}

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

/* A still (pose 'open'): what opened is already there, with nothing played on the way in. */
.scene[data-still] .modalInner,
.scene[data-still] .growBar {
  animation: none;
}
.scene[data-still] .toast {
  transition: none;
}
.scene[data-still] .progress {
  animation-play-state: paused;
  animation-delay: calc(var(--life) * -0.4);
}

/* A narrow stage: a plain grid that scrolls with the page, two columns, then one. */
@container stage (max-width: 639px) {
  .root[data-layout] .viewport {
    aspect-ratio: auto;
    min-height: 0;
    max-height: none;
  }
  .root[data-layout] .wall {
    position: relative;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    grid-auto-rows: auto;
    transform: none !important;
  }
  .root[data-layout] .wall[data-count='1'] {
    grid-template-columns: minmax(0, 1fr);
  }
  .root[data-layout] .cell {
    aspect-ratio: auto;
    padding: 9cqi 0 8cqi;
  }
  .frame {
    width: 86cqi;
  }
  .label {
    font-size: clamp(11px, 4.4cqi, 14px);
  }
}
@container stage (max-width: 479px) {
  .root[data-layout] .wall {
    grid-template-columns: minmax(0, 1fr);
  }
  .root[data-layout] .cell {
    padding: 7cqi 0 6cqi;
  }
  .frame {
    width: 88cqi;
  }
  .label {
    font-size: clamp(11px, 3.6cqi, 14px);
  }
}

@media (prefers-reduced-motion: reduce) {
  .root *,
  .root *::before,
  .root *::after {
    transition-duration: 0s !important;
    transition-delay: 0s !important;
    animation: none !important;
  }
}
```

### motion-specimens/overlays.tsx

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

'use client';

import {
  useEffect,
  useImperativeHandle,
  useLayoutEffect,
  useRef,
  useState,
  type CSSProperties,
  type Ref,
} from 'react';
import { AreaChart, Close, Saved } from './glyphs';
import { WIN, Sk, focus, reducedMotion, useKeys, type BodyProps } from './kit';
import styles from './motion-specimens.module.css';

/*
 * The specimens that open something over the page: the command palette, the card that expands
 * into a dialog, the toasts and the drawer. Each draws its page as a wireframe (Sk bars in px of
 * the 322 × 198 body), keeps its own state, and hands its tile a demo that plays the same
 * functions the reader's clicks do.
 *
 * Opening and closing are CSS transitions on data attributes (the dim, the palette, the drawer,
 * the toasts' slots), except the card's dialog, which grows out of the card it was opened from
 * by a FLIP played with the Web Animations API. Under reduced motion the stylesheet drops the
 * transitions and the script skips the FLIP, so each one lands on its end state at once.
 */

/** The centre of each sidebar item, in body px (measured: 42.5 to 116.5, 18.5 apart). */
const NAV_TOP = 42.5;
const NAV_STEP = 18.5;
const NAV_WIDTHS = [31, 22, 31, 18, 24];

type Opener = {
  attach?: Ref<HTMLButtonElement>;
  label: string;
  expanded?: boolean;
  onClick: () => void;
};

/**
 * The dashboard behind the palette and the expanding card: a sidebar with five items (one of them
 * current), a header with a search field and a dark button, three stat cards and an area chart.
 */
function Dashboard({
  nav,
  search,
  searchRef,
  card,
}: {
  nav: number;
  searchRef?: Ref<HTMLButtonElement>;
  search?: Opener;
  card?: (index: number) => Opener;
}) {
  return (
    <>
      <div
        className={`${styles.box} ${styles.side}`}
        style={{ left: 0, top: 0, width: 73, height: 198 }}
      >
        <Sk x={11} y={11} w={12} h={12} tone="strong" />
        <Sk x={27} y={15} w={30} h={4} tone="strong" />
        <span
          className={styles.navHi}
          style={{
            left: 7,
            top: NAV_TOP - 8,
            width: 59,
            height: 16,
            translate: `0 ${nav * NAV_STEP}px`,
          }}
        />
        {NAV_WIDTHS.map((width, i) => (
          <span key={i}>
            <Sk
              x={16}
              y={NAV_TOP + i * NAV_STEP - 3}
              w={6}
              h={6}
              r={1.5}
              tone={i === nav ? 'strong' : 'mid'}
            />
            <Sk
              x={25}
              y={NAV_TOP + i * NAV_STEP - 2}
              w={width}
              h={4}
              tone={i === nav ? 'strong' : 'mid'}
            />
          </span>
        ))}
        <Sk x={11} y={174} w={12} h={12} tone="mid" />
        <Sk x={27} y={178} w={26} h={3} tone="soft" />
      </div>
      <Sk x={87} y={13} w={76} h={8} />
      <Sk x={87} y={25} w={50} h={4} tone="soft" />
      {search ? (
        <button
          ref={searchRef}
          type="button"
          className={`${styles.hot} ${styles.outline}`}
          style={{ left: 168, top: 10, width: 54, height: 15 }}
          aria-label={search.label}
          aria-haspopup="dialog"
          aria-expanded={search.expanded}
          data-hot="search"
          onClick={search.onClick}
        >
          <Sk x={5} y={5} w={4} h={4} tone="strong" />
          <Sk x={12} y={5.5} w={16} h={3} tone="soft" />
          <Sk x={32} y={3.5} w={7} h={7} r={1.5} tone="soft" className={styles.key} />
          <Sk x={41} y={3.5} w={7} h={7} r={1.5} tone="soft" className={styles.key} />
        </button>
      ) : (
        <Sk x={168} y={10} w={54} h={15} r={4} tone="soft" />
      )}
      <Sk x={228} y={10} w={16} h={16} r={4} tone="soft" />
      <span
        className={`${styles.box} ${styles.dark}`}
        style={{ left: 251, top: 10, width: 55, height: 16 }}
      >
        <Sk x={8} y={6} w={4} h={4} r={1} tone="ink" className={styles.onInk} />
        <Sk x={16} y={6.5} w={30} h={3} tone="ink" className={styles.onInk} />
      </span>
      {[87.5, 162.5, 237].map((left, i) => {
        const opener = card?.(i);
        const inner = (
          <>
            <Sk x={8} y={9} w={26} h={3} tone="mid" />
            <Sk x={57} y={7} w={6} h={6} tone="mid" />
            <Sk x={8} y={18} w={39} h={7} tone="mid" />
            <Sk x={8} y={29} w={20} h={3} tone="strong" />
          </>
        );
        const place = { left, top: 42, width: 68.5, height: 36 };
        return opener ? (
          <button
            key={i}
            ref={opener.attach}
            type="button"
            className={`${styles.hot} ${styles.card}`}
            style={place}
            aria-label={opener.label}
            aria-haspopup="dialog"
            aria-expanded={opener.expanded}
            data-hot={`card-${i}`}
            onClick={opener.onClick}
          >
            {inner}
          </button>
        ) : (
          <span key={i} className={`${styles.box} ${styles.card}`} style={place}>
            {inner}
          </span>
        );
      })}
      <div
        className={`${styles.box} ${styles.card}`}
        style={{ left: 87.5, top: 88, width: 218, height: 95.5 }}
      >
        <Sk x={9} y={10} w={50} h={4} tone="mid" />
        <Sk x={171} y={10} w={4} h={4} tone="strong" />
        <Sk x={178} y={11} w={11} h={2.5} tone="mid" />
        <Sk x={193} y={10} w={4} h={4} tone="mid" />
        <Sk x={200} y={11} w={8} h={2.5} tone="mid" />
        <AreaChart className={styles.area} />
      </div>
    </>
  );
}

/**
 * The dim over the page while something is open: a press on it closes that. It is a button out of
 * the tab order, since Escape and the close buttons are the keyboard's way out.
 */
function Dim({ onClose }: { onClose: () => void }) {
  return (
    <button
      type="button"
      className={`${styles.hot} ${styles.dim}`}
      data-part="dim"
      tabIndex={-1}
      aria-hidden="true"
      onClick={onClose}
    />
  );
}

/** Arrow keys move through a list of buttons, wrapping; returns the index the focus went to. */
function roam(event: globalThis.KeyboardEvent, buttons: (HTMLElement | null)[], at: number) {
  const step = event.key === 'ArrowDown' ? 1 : event.key === 'ArrowUp' ? -1 : 0;
  if (!step) return null;
  event.preventDefault();
  const next = (at + step + buttons.length) % buttons.length;
  focus(buttons[next]);
  return next;
}

/** Which sidebar item each of the palette's two results goes to. */
const PICKS = [1, 3];
const RESULTS = ['Go to Reports', 'Go to Settings'];

/**
 * Command palette: the search field opens a palette over the dimmed dashboard; the query types
 * itself in, a result lights under the pointer (or the arrows), and picking it closes the palette
 * and moves the sidebar's current item.
 */
export function Palette({ ref, pose, report }: BodyProps) {
  const still = pose === 'open';
  const [open, setOpen] = useState(still);
  const [hi, setHi] = useState(still ? 1 : 0);
  const [nav, setNav] = useState(0);
  const round = useRef(0);
  const searchRef = useRef<HTMLButtonElement>(null);
  const items = useRef<(HTMLButtonElement | null)[]>([]);
  // Set by the reader's own opening, so the focus follows them in.
  const enter = useRef(false);

  useEffect(() => {
    if (!open || !enter.current) return;
    enter.current = false;
    focus(items.current[0]);
  }, [open]);

  const close = (real: boolean) => {
    setOpen(false);
    if (real) focus(searchRef.current);
  };
  const pick = (index: number) => {
    setOpen(false);
    setNav(PICKS[index]);
  };

  const scene = useRef<HTMLDivElement>(null);
  useKeys(scene, (event) => {
    if (!open) return;
    if (event.key === 'Escape') {
      event.stopPropagation();
      close(true);
      return;
    }
    const next = roam(event, items.current, hi);
    if (next !== null) setHi(next);
  });

  useImperativeHandle(
    ref,
    () => ({
      reset: () => setOpen(false),
      play: async (kit) => {
        const target = round.current++ % 2 === 0 ? 1 : 0;
        await kit.to('search', 800);
        await kit.press();
        setHi(0);
        setOpen(true);
        await kit.wait(700);
        await kit.to('item-0', 420);
        if (target === 1) {
          await kit.wait(160);
          await kit.to('item-1', 320);
          setHi(1);
        }
        await kit.wait(360);
        await kit.press();
        pick(target);
        await kit.wait(700);
        await kit.glide({ x: 262, y: 196 }, 900);
        await kit.wait(800);
      },
    }),
    // The demo calls setters and refs only, which stay the same from render to render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  return (
    <div
      ref={scene}
      className={styles.scene}
      data-open={open || undefined}
      data-still={still || undefined}
    >
      <Dashboard
        nav={nav}
        searchRef={searchRef}
        search={{
          label: 'Search',
          expanded: open,
          onClick: () => {
            enter.current = true;
            setHi(0);
            setOpen(true);
            report('open palette');
          },
        }}
      />
      <Dim onClose={() => close(true)} />
      <div
        className={`${styles.box} ${styles.panel} ${styles.palette}`}
        data-part="palette"
        style={{ left: 99, top: 21, width: 195, height: 105 }}
        role="dialog"
        aria-label="Command palette"
        inert={!open}
      >
        <Sk x={11} y={10} w={6} h={6} tone="strong" />
        <span className={styles.query} style={{ left: 22, top: 9.5, height: 7 }} />
        <Sk x={0} y={25} w={195} h={1} r={0} tone="soft" />
        {RESULTS.map((label, i) => (
          <span key={label}>
            <Sk x={10} y={33 + i * 27} w={i ? 18 : 23} h={2.5} tone="mid" />
            <button
              ref={(button) => {
                items.current[i] = button;
              }}
              type="button"
              className={`${styles.hot} ${styles.item}`}
              style={{ left: 4, top: 40 + i * 27, width: 187, height: 16 }}
              data-hi={hi === i || undefined}
              data-hot={`item-${i}`}
              aria-label={label}
              onPointerEnter={() => setHi(i)}
              onFocus={() => setHi(i)}
              onClick={() => {
                pick(i);
                focus(searchRef.current);
                report(label);
              }}
            >
              <Sk x={9} y={4.5} w={7} h={7} r={1.5} tone="mid" />
              <Sk x={20} y={6.5} w={i ? 52 : 59} h={3} tone="mid" />
              <Sk x={160} y={6.5} w={18} h={3} tone="soft" className={styles.itemHint} />
            </button>
          </span>
        ))}
        <Sk x={0} y={88} w={195} h={1} r={0} tone="soft" />
        <Sk x={10} y={94} w={7} h={7} r={1.5} tone="soft" />
        <Sk x={20} y={96} w={18} h={3} tone="soft" />
        <Sk x={147} y={94} w={11} h={7} r={1.5} tone="soft" />
        <Sk x={161} y={96} w={24} h={3} tone="soft" />
      </div>
    </div>
  );
}

/** The three stat cards' names, and how tall each bar of the dialog's chart is (of 46 px). */
const CARDS = ['Revenue', 'Orders', 'Visitors'];
const BARS = [
  [17, 25, 22, 32, 29, 39, 35, 46],
  [30, 22, 34, 27, 38, 31, 42, 36],
  [12, 18, 26, 24, 33, 30, 40, 44],
];
/** The dialog's place in the body: measured, 218 × 154 over the cards and the chart. */
const MODAL = { left: 87, top: 34, width: 218, height: 154 };

/**
 * Card expand: a stat card grows into a dialog with a bar chart and a short list, over the dimmed
 * dashboard, and shrinks back into the same card when it closes.
 */
export function Expand({ ref, pose, report }: BodyProps) {
  const still = pose === 'open';
  const [open, setOpen] = useState<number | null>(still ? 2 : null);
  const [shown, setShown] = useState(still);
  const cards = useRef<(HTMLButtonElement | null)[]>([]);
  const modal = useRef<HTMLDivElement>(null);
  const closeRef = useRef<HTMLButtonElement>(null);
  const flight = useRef<Animation | null>(null);
  const enter = useRef(false);
  const round = useRef(0);

  /** The transform that lays the dialog over card `index`, in the body's own px. */
  const overCard = (index: number) => {
    const card = cards.current[index];
    const box = modal.current;
    if (!card || !box) return 'none';
    const from = card.getBoundingClientRect();
    const to = box.getBoundingClientRect();
    const s = to.width / MODAL.width || 1;
    return `translate(${(from.left - to.left) / s}px, ${(from.top - to.top) / s}px) scale(${from.width / to.width}, ${from.height / to.height})`;
  };

  // Grow out of the card: the dialog is laid out in its place, then played from the card's rect.
  useLayoutEffect(() => {
    if (open === null || !shown || still) return;
    const box = modal.current;
    if (!box) return;
    if (!reducedMotion()) {
      flight.current?.cancel();
      flight.current = box.animate(
        [{ transform: overCard(open), borderRadius: '12px' }, { transform: 'none' }],
        {
          duration: 380,
          easing: 'cubic-bezier(0.25, 0.9, 0.3, 1)',
        },
      );
    }
    if (enter.current) {
      enter.current = false;
      focus(closeRef.current);
    }
  }, [open, shown, still]);

  const expand = (index: number) => {
    setOpen(index);
    setShown(true);
  };
  /** Shrinks back into the card, then unmounts; `real` returns the focus to the card. */
  const close = (real: boolean) => {
    const index = open;
    setShown(false);
    const box = modal.current;
    const done = () => {
      setOpen((current) => (current === index ? null : current));
      if (real && index !== null) focus(cards.current[index]);
    };
    if (!box || index === null || reducedMotion()) return done();
    flight.current?.cancel();
    flight.current = box.animate(
      [{ transform: 'none' }, { transform: overCard(index), opacity: 0.4 }],
      {
        duration: 260,
        easing: 'cubic-bezier(0.5, 0, 0.75, 0.6)',
        fill: 'forwards',
      },
    );
    flight.current.onfinish = done;
  };
  const scene = useRef<HTMLDivElement>(null);
  useKeys(scene, (event) => {
    if (event.key !== 'Escape' || open === null) return;
    event.stopPropagation();
    close(true);
  });
  // The demo's close reads `open` from the render it was made in, so it goes through a ref.
  const closeLatest = useRef(close);
  useLayoutEffect(() => {
    closeLatest.current = close;
  });

  useImperativeHandle(
    ref,
    () => ({
      reset: () => closeLatest.current(false),
      play: async (kit) => {
        const index = round.current++ % 2 === 0 ? 2 : 0;
        await kit.to(`card-${index}`, 900);
        await kit.press();
        expand(index);
        await kit.wait(1700);
        await kit.to('close', 650);
        await kit.press();
        closeLatest.current(false);
        await kit.wait(800);
        await kit.glide({ x: 250 - index * 40, y: 190 }, 800);
        await kit.wait(600);
      },
    }),
    // The demo calls setters and refs only, which stay the same from render to render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  return (
    <div
      className={styles.scene}
      ref={scene}
      data-open={shown || undefined}
      data-still={still || undefined}
    >
      <Dashboard
        nav={0}
        card={(i) => ({
          attach: (button: HTMLButtonElement | null) => {
            cards.current[i] = button;
          },
          label: CARDS[i],
          expanded: open === i,
          onClick: () => {
            enter.current = true;
            expand(i);
            report(`expand ${CARDS[i]}`);
          },
        })}
      />
      <Dim onClose={() => open !== null && close(true)} />
      {open !== null && (
        <div
          ref={modal}
          className={`${styles.box} ${styles.panel} ${styles.modal}`}
          style={MODAL}
          role="dialog"
          aria-label={`${CARDS[open]} details`}
        >
          <div className={styles.modalInner}>
            <Sk x={16} y={15} w={24} h={3} tone="soft" />
            <Sk x={16} y={22} w={39} h={8} tone="mid" />
            <Sk x={16} y={34} w={20} h={3} tone="strong" />
            <button
              ref={closeRef}
              type="button"
              className={`${styles.hot} ${styles.closeButton}`}
              style={{ left: 194, top: 10, width: 16, height: 16 }}
              aria-label="Close"
              data-hot="close"
              onClick={() => {
                close(true);
                report('close');
              }}
            >
              <Close className={styles.glyph} />
            </button>
            <Sk x={10} y={50} w={68} h={3} tone="soft" />
            {BARS[open].map((height, i) => (
              <Sk
                key={i}
                x={10 + i * 15}
                y={112 - height}
                w={9}
                h={height}
                r={1.5}
                tone={i === 7 ? 'strong' : 'mid'}
                className={styles.growBar}
                style={{ '--i': i } as CSSProperties}
              />
            ))}
            {[50, 72, 94].map((top, i) => (
              <span
                key={top}
                className={`${styles.box} ${styles.card}`}
                style={{ left: 137, top, width: 72, height: 16 }}
              >
                <Sk x={6} y={4.5} w={7} h={7} tone="mid" />
                <Sk x={17} y={6.5} w={30 - i * 4} h={3} tone="mid" />
                <Sk x={54} y={6.5} w={12} h={3} tone="strong" />
              </span>
            ))}
            <Sk x={10} y={123} w={198} h={1} r={0} tone="soft" />
            <span
              className={`${styles.box} ${styles.dark}`}
              style={{ left: 10, top: 130, width: 63, height: 16 }}
            />
            <Sk x={81} y={136} w={37} h={3} tone="soft" />
          </div>
        </div>
      )}
    </div>
  );
}

/**
 * The settings page behind the toasts: a header with a dark Save button, four tabs and five rows,
 * each with a toggle, a select or a button at its right.
 */
function Settings({ onSave }: { onSave: () => void }) {
  return (
    <>
      <Sk x={16} y={13} w={64} h={8} />
      <Sk x={16} y={25} w={112} h={4} tone="soft" />
      <button
        type="button"
        className={`${styles.hot} ${styles.dark}`}
        style={{ left: 260, top: 11, width: 46, height: 17 }}
        aria-label="Save changes"
        data-hot="save"
        onClick={onSave}
      />
      {[
        [16, 23],
        [53, 27],
        [86, 25],
        [122, 30],
      ].map(([x, w], i) => (
        <Sk key={x} x={x} y={42} w={w} h={4} tone={i ? 'soft' : 'mid'} />
      ))}
      <Sk x={16} y={51} w={23} h={1.5} r={0} tone="ink" />
      <Sk x={16} y={53} w={290} h={1} r={0} tone="soft" />
      {[0, 1, 2, 3, 4].map((row) => {
        const top = 62 + row * 25;
        return (
          <span key={row}>
            <Sk x={16} y={top + 4} w={[52, 44, 34, 30, 32][row]} h={4} tone="mid" />
            <Sk x={16} y={top + 12} w={[52, 45, 43, 30, 42][row] * 2} h={3} tone="soft" />
            {row < 4 && <Sk x={16} y={top + 23} w={290} h={1} r={0} tone="soft" />}
            {row === 1 ? (
              <span
                className={`${styles.box} ${styles.outline}`}
                style={{ left: 241, top: top + 2, width: 64, height: 13 }}
              >
                <Sk x={6} y={4.5} w={30} h={3} tone="soft" />
                <Sk x={52} y={5} w={5} h={2} tone="mid" />
              </span>
            ) : row === 4 ? (
              <Sk x={260} y={top} w={46} h={16} r={4} tone="soft" />
            ) : (
              <span
                className={styles.switch}
                data-on={row === 2 || undefined}
                style={{ left: 286, top: top + 3 }}
              />
            )}
          </span>
        );
      })}
    </>
  );
}

type Toast = { id: number; slot: number; leaving: boolean };
/** How long a toast stays, the time its bar drains in. */
const TOAST_LIFE = 3200;
const TOAST_SLOT = 60;
const TOAST_LEAVE = 220;

/**
 * Toast: Save stacks a toast at the page's left, newest at the bottom, two at most; each drains
 * its bar and goes, or goes at once from its Undo button.
 */
export function Toasts({ ref, pose, report }: BodyProps) {
  const still = pose === 'open';
  const [toasts, setToasts] = useState<Toast[]>(
    still
      ? [
          { id: 1, slot: 0, leaving: false },
          { id: 2, slot: 1, leaving: false },
        ]
      : [],
  );
  const next = useRef(3);
  const timers = useRef(new Set<number>());

  useEffect(() => {
    const pending = timers.current;
    return () => pending.forEach((timer) => window.clearTimeout(timer));
  }, []);

  const later = (ms: number, run: () => void) => {
    const timer = window.setTimeout(() => {
      timers.current.delete(timer);
      run();
    }, ms);
    timers.current.add(timer);
  };

  /** Marks a toast as leaving (it keeps its slot while it fades), then drops it. */
  const dismiss = (id: number) => {
    setToasts((list) =>
      list.map((toast) =>
        toast.id === id && !toast.leaving ? { ...toast, leaving: true } : toast,
      ),
    );
    later(reducedMotion() ? 0 : TOAST_LEAVE, () =>
      setToasts((list) => list.filter((toast) => toast.id !== id)),
    );
  };

  const add = () => {
    const id = next.current++;
    setToasts((list) => {
      const live = list.filter((toast) => !toast.leaving);
      // A third pushes the oldest out.
      const oldest = live.length >= 2 ? live[0].id : null;
      if (oldest !== null) later(0, () => dismiss(oldest));
      return [...list, { id, slot: 0, leaving: false }];
    });
    later(TOAST_LIFE, () => dismiss(id));
  };

  useImperativeHandle(
    ref,
    () => ({
      reset: () => setToasts((list) => list.map((toast) => ({ ...toast, leaving: true }))),
      play: async (kit) => {
        await kit.to('save', 900);
        await kit.press();
        add();
        await kit.wait(900);
        await kit.press();
        add();
        await kit.wait(700);
        await kit.to('undo-first', 700);
        await kit.wait(200);
        await kit.press();
        // The oldest toast still up, read from state, since this closure's list is stale.
        setToasts((list) => {
          const oldest = list.find((toast) => !toast.leaving);
          if (oldest) later(0, () => dismiss(oldest.id));
          return list;
        });
        await kit.wait(600);
        await kit.glide({ x: 228, y: 120 }, 800);
        await kit.wait(1800);
      },
    }),
    // The demo calls setters and refs only, which stay the same from render to render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  // Live toasts fill the slots from the top; a leaving one keeps the slot it had.
  let slot = 0;
  const placed = toasts.map((toast) => (toast.leaving ? toast : { ...toast, slot: slot++ }));
  const firstLive = placed.find((toast) => !toast.leaving)?.id;

  return (
    <div className={styles.scene} data-still={still || undefined}>
      <Settings
        onSave={() => {
          add();
          report('save');
        }}
      />
      <div className={styles.toasts} style={{ left: 16, top: 60 }} role="status" aria-live="polite">
        {placed.map((toast) => (
          <div
            key={toast.id}
            className={styles.toast}
            data-leaving={toast.leaving || undefined}
            style={
              {
                '--y': `${toast.slot * TOAST_SLOT}px`,
                '--life': `${TOAST_LIFE}ms`,
              } as CSSProperties
            }
          >
            <span className={styles.srOnly}>Changes saved</span>
            <span
              className={`${styles.box} ${styles.dark}`}
              style={{ left: 10, top: 12, width: 16, height: 16 }}
            >
              <Saved className={styles.toastMark} />
            </span>
            <Sk x={34} y={13} w={toast.id % 2 ? 75 : 62} h={5} tone="ink" />
            <Sk x={34} y={22} w={90} h={3} tone="mid" />
            <button
              type="button"
              className={`${styles.hot} ${styles.dark}`}
              style={{ left: 139, top: 9, width: 34, height: 20 }}
              aria-label="Undo"
              data-hot={toast.id === firstLive ? 'undo-first' : undefined}
              tabIndex={toast.leaving ? -1 : undefined}
              onClick={() => {
                dismiss(toast.id);
                report('undo');
              }}
            >
              <Sk x={9} y={8.5} w={16} h={3} tone="ink" className={styles.onInk} />
            </button>
            <span className={styles.progress} />
          </div>
        ))}
      </div>
    </div>
  );
}

/** The drawer's list: each row's name and amount widths, so each opens a drawer of its own. */
const ORDERS = [
  { name: 46, amount: 22, label: 'Order 1042' },
  { name: 38, amount: 18, label: 'Order 1041' },
  { name: 52, amount: 24, label: 'Order 1040' },
  { name: 34, amount: 20, label: 'Order 1039' },
  { name: 44, amount: 16, label: 'Order 1038' },
];
const DRAWER_WIDTH = 134;

/**
 * Drawer: a row of the table opens a drawer that slides in from the right over the dimmed list,
 * with the row's details and two actions; X, Escape or the dim close it.
 */
export function Drawer({ ref, pose, report }: BodyProps) {
  const still = pose === 'open';
  const [open, setOpen] = useState(still);
  const [row, setRow] = useState(1);
  const rows = useRef<(HTMLButtonElement | null)[]>([]);
  const closeRef = useRef<HTMLButtonElement>(null);
  const enter = useRef(false);

  useEffect(() => {
    if (!open || !enter.current) return;
    enter.current = false;
    focus(closeRef.current);
  }, [open]);

  const show = (index: number) => {
    setRow(index);
    setOpen(true);
  };
  const close = (real: boolean) => {
    setOpen(false);
    if (real) focus(rows.current[row]);
  };

  useImperativeHandle(
    ref,
    () => ({
      reset: () => setOpen(false),
      play: async (kit) => {
        await kit.to('row-1', 900);
        await kit.press();
        show(1);
        await kit.wait(1500);
        await kit.to('drawer-close', 700);
        await kit.press();
        setOpen(false);
        await kit.wait(800);
        await kit.to('row-3', 700);
        await kit.press();
        show(3);
        await kit.wait(1400);
        await kit.glide({ x: 80, y: 150 }, 800);
        await kit.press();
        setOpen(false);
        await kit.wait(1200);
      },
    }),
    // The demo calls setters and refs only, which stay the same from render to render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  const scene = useRef<HTMLDivElement>(null);
  useKeys(scene, (event) => {
    if (event.key !== 'Escape' || !open) return;
    event.stopPropagation();
    close(true);
  });

  const order = ORDERS[row];
  return (
    <div
      className={styles.scene}
      ref={scene}
      data-open={open || undefined}
      data-still={still || undefined}
    >
      <Sk x={16} y={13} w={58} h={8} />
      <Sk x={16} y={25} w={88} h={4} tone="soft" />
      <span
        className={`${styles.box} ${styles.dark}`}
        style={{ left: 252, top: 11, width: 54, height: 17 }}
      />
      <span
        className={`${styles.box} ${styles.card}`}
        style={{ left: 16, top: 38, width: 290, height: 14 }}
      >
        {[8, 40, 160, 236].map((x, i) => (
          <Sk key={x} x={x} y={5.5} w={[20, 24, 18, 22][i]} h={3} tone="mid" />
        ))}
      </span>
      {ORDERS.map((item, i) => (
        <button
          key={item.label}
          ref={(button) => {
            rows.current[i] = button;
          }}
          type="button"
          className={`${styles.hot} ${styles.tableRow}`}
          style={{ left: 16, top: 55 + i * 27, width: 290, height: 26 }}
          data-hi={(open && row === i) || undefined}
          data-hot={`row-${i}`}
          aria-label={item.label}
          aria-haspopup="dialog"
          onClick={() => {
            enter.current = true;
            show(i);
            report(`open ${item.label}`);
          }}
        >
          <Sk x={8} y={9} w={8} h={8} r={2} tone="soft" />
          <Sk x={40} y={8} w={item.name} h={4} tone="mid" />
          <Sk x={40} y={15} w={item.name + 20} h={3} tone="soft" />
          <Sk x={160} y={9} w={32} h={8} r={4} tone={i % 2 ? 'soft' : 'strong'} />
          <Sk x={236} y={11} w={item.amount} h={4} tone="mid" />
          {i < 4 && <Sk x={0} y={26} w={290} h={1} r={0} tone="soft" />}
        </button>
      ))}
      <Dim onClose={() => open && close(true)} />
      <div
        className={`${styles.box} ${styles.drawer}`}
        style={{ left: WIN.width - DRAWER_WIDTH, top: 0, width: DRAWER_WIDTH, height: 198 }}
        role="dialog"
        aria-label={`${order.label} details`}
        inert={!open}
      >
        <Sk x={12} y={13} w={order.name + 10} h={7} tone="mid" />
        <Sk x={12} y={24} w={44} h={3} tone="soft" />
        <button
          ref={closeRef}
          type="button"
          className={`${styles.hot} ${styles.closeButton}`}
          style={{ left: 110, top: 9, width: 16, height: 16 }}
          aria-label="Close"
          data-hot="drawer-close"
          onClick={() => {
            close(true);
            report('close drawer');
          }}
        >
          <Close className={styles.glyph} />
        </button>
        <span
          className={`${styles.box} ${styles.card}`}
          style={{ left: 12, top: 38, width: 110, height: 40 }}
        >
          <Sk x={8} y={8} w={24} h={24} r={12} tone="mid" />
          <Sk x={38} y={12} w={42} h={4} tone="mid" />
          <Sk x={38} y={21} w={28} h={3} tone="soft" />
        </span>
        {[0, 1, 2, 3].map((i) => (
          <span key={i}>
            <Sk x={12} y={90 + i * 16} w={28} h={3} tone="soft" />
            <Sk
              x={122 - [36, order.amount + 10, 28, 40][i]}
              y={90 + i * 16}
              w={[36, order.amount + 10, 28, 40][i]}
              h={3}
              tone="mid"
            />
          </span>
        ))}
        <Sk x={0} y={160} w={DRAWER_WIDTH} h={1} r={0} tone="soft" />
        <Sk x={12} y={170} w={52} h={16} r={4} tone="soft" />
        <span
          className={`${styles.box} ${styles.dark}`}
          style={{ left: 70, top: 170, width: 52, height: 16 }}
        />
      </div>
    </div>
  );
}
```

### motion-specimens/in-place.tsx

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

'use client';

import {
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
  type CSSProperties,
  type KeyboardEvent,
} from 'react';
import { Check, Chevron, Heart, Picture } from './glyphs';
import { Sk, focus, reducedMotion, type BodyProps } from './kit';
import styles from './motion-specimens.module.css';

/*
 * The specimens that change the page in place: the like that bursts, the page transition, the
 * sort menu that reorders a list and the tabs that morph a chart. Moves are CSS transitions on
 * custom properties (a row's rank, the underline's link, a bar's height), so the browser runs them
 * off the main thread; the like's pop and its burst of six dots are one-shot Web Animations.
 */

/** Each list row's widths: its name, its line under it, and the meta at its right. */
const PEOPLE = [
  { name: 55, line: 142, meta: 23 },
  { name: 40, line: 122, meta: 20 },
  { name: 62, line: 150, meta: 0 },
  { name: 46, line: 112, meta: 22 },
  { name: 38, line: 134, meta: 24 },
];
/** The row with the heart (the third, as measured), and the six directions of its burst. */
const LIKED_ROW = 2;
const BURST = [0, 60, 120, 180, 240, 300];

/**
 * Like burst: the heart in a list row fills, pops and throws six dots out, and the count rolls up
 * from 24 to 25; a second press takes the like back.
 */
export function Like({ ref, pose, report }: BodyProps) {
  const still = pose === 'open';
  const [liked, setLiked] = useState(still);
  const [rolled, setRolled] = useState(false);
  const heart = useRef<HTMLSpanElement>(null);
  const burst = useRef<HTMLSpanElement>(null);

  // The like as of now, for the demo's closures, which were made in an older render.
  const current = useRef(still);
  const toggle = () => {
    const was = current.current;
    current.current = !was;
    setRolled(true);
    setLiked(!was);
    if (!was) pop();
  };

  /** The heart's pop and the dots' flight: played only on a like, never on an unlike. */
  const pop = () => {
    if (reducedMotion()) return;
    heart.current?.animate(
      [{ scale: 1 }, { scale: 0.72, offset: 0.25 }, { scale: 1.28, offset: 0.6 }, { scale: 1 }],
      {
        duration: 420,
        easing: 'ease-out',
      },
    );
    const dots = burst.current?.children ?? [];
    for (let i = 0; i < dots.length; i += 1) {
      const angle = (BURST[i] * Math.PI) / 180;
      const x = Math.cos(angle) * 11;
      const y = Math.sin(angle) * 11;
      dots[i].animate(
        [
          { transform: 'translate(0, 0) scale(0.4)', opacity: 0 },
          { transform: `translate(${x * 0.6}px, ${y * 0.6}px) scale(1)`, opacity: 1, offset: 0.35 },
          { transform: `translate(${x}px, ${y}px) scale(0.2)`, opacity: 0 },
        ],
        { duration: 520, delay: 90, easing: 'cubic-bezier(0.2, 0.7, 0.3, 1)', fill: 'backwards' },
      );
    }
  };

  useImperativeHandle(
    ref,
    () => ({
      reset: () => {
        current.current = false;
        setLiked(false);
      },
      play: async (kit) => {
        await kit.to('heart', 1000);
        await kit.wait(200);
        await kit.press();
        toggle();
        await kit.wait(1300);
        await kit.glide({ x: 130, y: 172 }, 900);
        await kit.wait(900);
        await kit.to('heart', 800);
        await kit.wait(200);
        await kit.press();
        toggle();
        await kit.wait(700);
        await kit.glide({ x: 124, y: 186 }, 900);
        await kit.wait(700);
      },
    }),
    // The demo calls setters and refs only, which stay the same from render to render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  const count = liked ? 25 : 24;
  return (
    <div className={styles.scene} data-still={still || undefined}>
      <Sk x={16} y={15} w={55} h={8} />
      <span
        className={`${styles.box} ${styles.outline}`}
        style={{ left: 172, top: 11, width: 101, height: 15 }}
      >
        <Sk x={6} y={5} w={4} h={4} tone="strong" />
        <Sk x={14} y={5.5} w={40} h={3} tone="soft" />
      </span>
      <Sk x={280} y={11} w={26} h={15} r={4} tone="soft" />
      {[
        [16, 32, 'strong'],
        [52, 37, 'soft'],
        [94, 27, 'soft'],
      ].map(([x, w, tone]) => (
        <Sk key={x} x={x as number} y={37} w={w as number} h={11} r={6} tone={tone as 'soft'} />
      ))}
      {PEOPLE.map((person, i) => {
        const middle = 70 + i * 26.3;
        return (
          <span key={i}>
            <Sk x={22.5} y={middle - 7.5} w={15} h={15} tone="soft" />
            <Sk x={45} y={middle - 6} w={person.name} h={4} tone="mid" />
            <Sk x={45} y={middle + 2} w={person.line} h={3} tone="soft" />
            {person.meta > 0 && (
              <>
                <Sk x={276} y={middle - 5} w={person.meta} h={3} tone="soft" />
                {i === 0 && <Sk x={294} y={middle + 1.5} w={4} h={4} tone="strong" />}
              </>
            )}
            {i < PEOPLE.length - 1 && <Sk x={45} y={middle + 13} w={261} h={1} r={0} tone="soft" />}
          </span>
        );
      })}
      <button
        type="button"
        className={`${styles.hot} ${styles.likeButton}`}
        style={{ left: 248, top: 70 + LIKED_ROW * 26.3 - 10, width: 52, height: 20 }}
        aria-pressed={liked}
        aria-label={`Like, ${count}`}
        data-hot="heart"
        onClick={() => {
          toggle();
          report(liked ? 'unlike' : 'like');
        }}
      >
        <span ref={heart} className={styles.heart}>
          <Heart filled={liked} className={styles.glyph} />
        </span>
        <span ref={burst} className={styles.burst} aria-hidden="true">
          {BURST.map((angle) => (
            <span key={angle} />
          ))}
        </span>
        <span className={styles.count} aria-hidden="true">
          <span key={count} data-roll={rolled ? (liked ? 'up' : 'down') : undefined}>
            {count}
          </span>
        </span>
      </button>
    </div>
  );
}

/** The site's three pages and where each nav link sits (x, in body px). */
const LINKS = [
  { label: 'Home', x: 152, w: 24 },
  { label: 'Work', x: 188, w: 26 },
  { label: 'About', x: 226, w: 28 },
];

/**
 * Page transition: three links over a small site; the page that goes slides out toward the way
 * it came and fades, the new one slides in from the other side, and the underline glides to the
 * link.
 */
export function Pages({ ref, pose, report }: BodyProps) {
  const still = pose === 'open';
  const [page, setPage] = useState(still ? 1 : 0);
  const links = useRef<(HTMLButtonElement | null)[]>([]);

  useImperativeHandle(
    ref,
    () => ({
      reset: () => setPage(0),
      play: async (kit) => {
        for (const next of [1, 2, 0]) {
          await kit.to(`link-${next}`, 850);
          await kit.wait(150);
          await kit.press();
          setPage(next);
          await kit.wait(1500);
        }
      },
    }),
    // The demo calls setters and refs only, which stay the same from render to render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  const link = LINKS[page];
  return (
    <div className={styles.scene} data-still={still || undefined}>
      <Sk x={16} y={10} w={11} h={11} tone="strong" />
      <Sk x={31} y={13.5} w={28} h={4} tone="mid" />
      <nav aria-label="Site">
        {LINKS.map((item, i) => (
          <button
            key={item.label}
            ref={(button) => {
              links.current[i] = button;
            }}
            type="button"
            className={`${styles.hot} ${styles.link}`}
            style={{ left: item.x - 4, top: 6, width: item.w + 8, height: 19 }}
            aria-current={page === i ? 'page' : undefined}
            aria-label={item.label}
            data-hot={`link-${i}`}
            onClick={() => {
              setPage(i);
              report(`go to ${item.label}`);
            }}
          >
            <Sk x={4} y={7.5} w={item.w} h={4} tone={page === i ? 'strong' : 'mid'} />
          </button>
        ))}
      </nav>
      <span
        className={styles.underline}
        style={{ top: 23, width: 1, height: 1.5, translate: `${link.x}px 0`, scale: `${link.w} 1` }}
      />
      <span
        className={`${styles.box} ${styles.dark}`}
        style={{ left: 264, top: 8, width: 42, height: 15 }}
      />
      <Sk x={0} y={30} w={322} h={1} r={0} tone="soft" />
      <div className={styles.pages} style={{ top: 31, height: 167 }}>
        {[0, 1, 2].map((i) => (
          <div
            key={i}
            className={styles.page}
            data-pos={i === page ? 'here' : i < page ? 'before' : 'after'}
            inert={i !== page}
          >
            {i === 0 && <Home />}
            {i === 1 && <Work />}
            {i === 2 && <About />}
          </div>
        ))}
      </div>
    </div>
  );
}

function Home() {
  return (
    <>
      <Sk x={16} y={22} w={120} h={10} tone="mid" />
      <Sk x={16} y={36} w={92} h={10} tone="mid" />
      <Sk x={16} y={54} w={118} h={4} tone="soft" />
      <Sk x={16} y={62} w={84} h={4} tone="soft" />
      <span
        className={`${styles.box} ${styles.dark}`}
        style={{ left: 16, top: 76, width: 46, height: 15 }}
      />
      <span
        className={`${styles.box} ${styles.outline}`}
        style={{ left: 68, top: 76, width: 40, height: 15 }}
      />
      <span
        className={`${styles.box} ${styles.card} ${styles.picture}`}
        style={{ left: 166, top: 16, width: 140, height: 84 }}
      >
        <Picture className={styles.pictureArt} />
      </span>
      {[16, 113, 210].map((x) => (
        <span
          key={x}
          className={`${styles.box} ${styles.card}`}
          style={{ left: x, top: 116, width: 96, height: 38 }}
        >
          <Sk x={8} y={8} w={9} h={9} r={2.5} tone="mid" />
          <Sk x={8} y={22} w={46} h={3} tone="mid" />
          <Sk x={8} y={29} w={62} h={3} tone="soft" />
        </span>
      ))}
    </>
  );
}

function Work() {
  return (
    <>
      <Sk x={16} y={14} w={60} h={8} tone="mid" />
      {[0, 1, 2, 3, 4, 5].map((i) => (
        <span
          key={i}
          className={`${styles.box} ${styles.card} ${styles.picture}`}
          style={{
            left: 16 + (i % 3) * 97,
            top: 32 + Math.floor(i / 3) * 66,
            width: 90,
            height: 58,
          }}
        >
          <Picture className={styles.pictureArt} />
          <span className={styles.caption}>
            <Sk x={6} y={4} w={[40, 32, 46, 36, 28, 42][i]} h={3} tone="mid" />
          </span>
        </span>
      ))}
    </>
  );
}

function About() {
  return (
    <>
      <Sk x={16} y={20} w={44} h={44} tone="mid" />
      <Sk x={74} y={22} w={96} h={9} tone="mid" />
      <Sk x={74} y={36} w={52} h={4} tone="strong" />
      {[220, 206, 214, 150, 0, 218, 196, 120].map((w, i) =>
        w ? <Sk key={i} x={74} y={54 + i * 9} w={w} h={3.5} tone="soft" /> : null,
      )}
      <span
        className={`${styles.box} ${styles.card}`}
        style={{ left: 74, top: 132, width: 232, height: 24 }}
      >
        <Sk x={0} y={0} w={2} h={24} r={0} tone="strong" />
        <Sk x={10} y={7} w={150} h={3.5} tone="mid" />
        <Sk x={10} y={14} w={90} h={3.5} tone="soft" />
      </span>
    </>
  );
}

/** The sort menu's orders: each lists the rows' ranks (row i goes to place ORDERS[mode][i]). */
const SORTS = [
  { label: 'Newest', w: 22, ranks: [0, 1, 2, 3, 4] },
  { label: 'Name', w: 16, ranks: [1, 3, 4, 0, 2] },
  { label: 'Most liked', w: 30, ranks: [2, 4, 0, 3, 1] },
];
/** Each row's look: the shade of its avatar, its name's width, its number's width. */
const SORT_ROWS = [
  { tone: 'strong', name: 58, sub: 92, num: 14 },
  { tone: 'soft', name: 40, sub: 120, num: 22 },
  { tone: 'mid', name: 70, sub: 80, num: 10 },
  { tone: 'ink', name: 34, sub: 104, num: 18 },
  { tone: 'card', name: 50, sub: 130, num: 26 },
] as const;
const SORT_ROW = 29;

/**
 * Sort menu: the Sort button drops a menu that scales out of its corner, items arriving one after
 * the other; picking an order closes it and the rows slide to their new places.
 */
export function Sort({ ref, pose, report }: BodyProps) {
  const still = pose === 'open';
  const [open, setOpen] = useState(still);
  const [mode, setMode] = useState(0);
  const button = useRef<HTMLButtonElement>(null);
  const items = useRef<(HTMLButtonElement | null)[]>([]);
  const enter = useRef(false);

  useEffect(() => {
    if (!open || !enter.current) return;
    enter.current = false;
    focus(items.current[mode]);
  }, [open, mode]);

  const close = (real: boolean) => {
    setOpen(false);
    if (real) focus(button.current);
  };

  useImperativeHandle(
    ref,
    () => ({
      reset: () => setOpen(false),
      play: async (kit) => {
        for (const next of [2, 1, 0]) {
          await kit.to('sort', 850);
          await kit.press();
          setOpen(true);
          await kit.wait(500);
          await kit.to(`sort-${next}`, 450);
          await kit.wait(250);
          await kit.press();
          setMode(next);
          setOpen(false);
          await kit.wait(1300);
        }
      },
    }),
    // The demo calls setters and refs only, which stay the same from render to render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  const onMenuKey = (event: KeyboardEvent) => {
    if (event.key === 'Escape' || event.key === 'Tab') {
      if (event.key === 'Escape') event.preventDefault();
      event.stopPropagation();
      close(event.key === 'Escape');
      return;
    }
    const at = items.current.findIndex((item) => item === document.activeElement);
    roamMenu(event, items.current, at);
  };

  return (
    <div className={styles.scene} data-still={still || undefined}>
      <Sk x={16} y={13} w={70} h={8} />
      <Sk x={16} y={25} w={50} h={4} tone="soft" />
      <button
        ref={button}
        type="button"
        className={`${styles.hot} ${styles.outline} ${styles.sortButton}`}
        style={{ left: 232, top: 11, width: 74, height: 16 }}
        aria-haspopup="menu"
        aria-expanded={open}
        aria-label={`Sort by ${SORTS[mode].label}`}
        data-hot="sort"
        onClick={() => {
          enter.current = !open;
          setOpen((was) => !was);
          report(open ? 'close sort' : 'open sort');
        }}
      >
        <Sk x={7} y={6.5} w={14} h={3} tone="soft" />
        <Sk x={24} y={6} w={SORTS[mode].w} h={4} tone="strong" className={styles.sortLabel} />
        <Chevron className={styles.chevron} />
      </button>
      <Sk x={16} y={38} w={290} h={1} r={0} tone="soft" />
      {SORT_ROWS.map((row, i) => (
        <span
          key={i}
          className={styles.sortRow}
          style={{ top: 42, translate: `0 ${SORTS[mode].ranks[i] * SORT_ROW}px` }}
        >
          <Sk x={4} y={6} w={16} h={16} tone={row.tone} />
          <Sk x={28} y={8} w={row.name} h={4} tone="mid" />
          <Sk x={28} y={16} w={row.sub} h={3} tone="soft" />
          <Sk x={282 - row.num} y={11} w={row.num} h={4} tone="mid" />
        </span>
      ))}
      <div
        className={`${styles.box} ${styles.panel} ${styles.menu}`}
        style={{ left: 206, top: 31, width: 100, height: 58 }}
        role="menu"
        aria-label="Sort by"
        tabIndex={-1}
        inert={!open}
        onKeyDown={onMenuKey}
      >
        {SORTS.map((sort, i) => (
          <button
            key={sort.label}
            ref={(item) => {
              items.current[i] = item;
            }}
            type="button"
            role="menuitemradio"
            aria-checked={mode === i}
            aria-label={sort.label}
            tabIndex={-1}
            className={`${styles.hot} ${styles.item}`}
            style={{ left: 4, top: 4 + i * 17, width: 92, height: 16, '--i': i } as CSSProperties}
            data-hot={`sort-${i}`}
            onClick={() => {
              setMode(i);
              close(true);
              report(`sort by ${sort.label}`);
            }}
          >
            {mode === i && <Check className={styles.check} />}
            <Sk x={18} y={6.5} w={sort.w + 12} h={3} tone="mid" />
          </button>
        ))}
      </div>
    </div>
  );
}

/** Up and Down move through a menu's items, wrapping; Home and End jump. */
function roamMenu(event: KeyboardEvent, items: (HTMLButtonElement | null)[], at: number) {
  const last = items.length - 1;
  const next =
    event.key === 'ArrowDown'
      ? at >= last
        ? 0
        : at + 1
      : event.key === 'ArrowUp'
        ? at <= 0
          ? last
          : at - 1
        : event.key === 'Home'
          ? 0
          : event.key === 'End'
            ? last
            : null;
  if (next === null) return;
  event.preventDefault();
  focus(items[next]);
}

/** The tabs' names, and each one's chart: twelve bars, as shares of the chart's height. */
const TABS = [
  {
    label: 'Week',
    total: 58,
    bars: [0.42, 0.55, 0.38, 0.62, 0.7, 0.51, 0.66, 0.58, 0.74, 0.69, 0.82, 0.77],
  },
  {
    label: 'Month',
    total: 44,
    bars: [0.3, 0.36, 0.45, 0.4, 0.52, 0.6, 0.56, 0.68, 0.64, 0.75, 0.86, 0.94],
  },
  {
    label: 'Year',
    total: 72,
    bars: [0.88, 0.72, 0.64, 0.7, 0.5, 0.58, 0.46, 0.52, 0.4, 0.44, 0.34, 0.3],
  },
];
const TAB_WIDTH = 50;
const CHART_HEIGHT = 72;

/**
 * Tabs: a segmented control whose pill slides on a spring to the chosen tab; the chart's bars grow
 * and shrink to the new period, one after the other, and the total under the tabs changes width.
 */
export function Tabs({ ref, pose, report }: BodyProps) {
  const still = pose === 'open';
  const [tab, setTab] = useState(still ? 1 : 0);
  const tabs = useRef<(HTMLButtonElement | null)[]>([]);

  useImperativeHandle(
    ref,
    () => ({
      reset: () => setTab(0),
      play: async (kit) => {
        for (const next of [1, 2, 0]) {
          await kit.to(`tab-${next}`, 850);
          await kit.wait(150);
          await kit.press();
          setTab(next);
          await kit.wait(1600);
        }
      },
    }),
    // The demo calls setters and refs only, which stay the same from render to render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  const choose = (index: number) => {
    setTab(index);
    report(`tab ${TABS[index].label}`);
  };

  const current = TABS[tab];
  return (
    <div className={styles.scene} data-still={still || undefined}>
      <Sk x={16} y={13} w={70} h={8} />
      <Sk x={16} y={25} w={100} h={4} tone="soft" />
      <div
        className={`${styles.box} ${styles.track}`}
        style={{ left: 16, top: 38, width: TAB_WIDTH * 3 + 4, height: 18 }}
        role="tablist"
        aria-label="Period"
        tabIndex={-1}
        onKeyDown={(event) => {
          const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0;
          if (!step) return;
          event.preventDefault();
          const next = (tab + step + TABS.length) % TABS.length;
          choose(next);
          focus(tabs.current[next]);
        }}
      >
        <span
          className={styles.pill}
          style={{
            left: 2,
            top: 2,
            width: TAB_WIDTH,
            height: 14,
            translate: `${tab * TAB_WIDTH}px 0`,
          }}
        />
        {TABS.map((item, i) => (
          <button
            key={item.label}
            ref={(button) => {
              tabs.current[i] = button;
            }}
            type="button"
            role="tab"
            aria-selected={tab === i}
            tabIndex={tab === i ? 0 : -1}
            className={`${styles.hot} ${styles.tab}`}
            style={{ left: 2 + i * TAB_WIDTH, top: 2, width: TAB_WIDTH, height: 14 }}
            data-hot={`tab-${i}`}
            onClick={() => choose(i)}
          >
            <span className={styles.srOnly}>{item.label}</span>
            <Sk x={TAB_WIDTH / 2 - 11} y={5.5} w={22} h={3} tone={tab === i ? 'strong' : 'mid'} />
          </button>
        ))}
      </div>
      <Sk x={246} y={43} w={4} h={4} tone="strong" />
      <Sk x={253} y={44} w={20} h={3} tone="mid" />
      <Sk x={280} y={43} w={4} h={4} tone="mid" />
      <Sk x={287} y={44} w={18} h={3} tone="mid" />
      <div
        className={styles.box}
        style={{ left: 0, top: 60, width: 322, height: 138 }}
        role="tabpanel"
        aria-label={`${current.label} totals`}
      >
        <Sk x={16} y={6} w={current.total} h={12} tone="mid" className={styles.total} />
        <Sk x={16} y={22} w={40} h={4} tone="soft" />
        {[0, 1, 2].map((line) => (
          <Sk key={line} x={16} y={40 + line * 24} w={290} h={1} r={0} tone="soft" />
        ))}
        {current.bars.map((share, i) => (
          <span
            key={i}
            className={styles.chartBar}
            style={
              {
                left: 22 + i * 24,
                top: 112 - CHART_HEIGHT,
                width: 14,
                height: CHART_HEIGHT,
                scale: `1 ${share}`,
                '--i': i,
              } as CSSProperties
            }
            data-tone={i === current.bars.length - 1 ? 'strong' : 'mid'}
          />
        ))}
        <Sk x={16} y={112} w={290} h={1} r={0} tone="mid" />
      </div>
    </div>
  );
}
```

### motion-specimens/kit.tsx

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

'use client';

import {
  useEffect,
  useLayoutEffect,
  useRef,
  type CSSProperties,
  type Ref,
  type RefObject,
} from 'react';
import type { Demo, Point } from './demo-pointer';
import styles from './motion-specimens.module.css';

/*
 * What the specimens share: the window's size, the pieces of wireframe they are drawn from, and
 * the kit a tile's demo plays with.
 *
 * Every window is drawn at 322 × 218 px (a 20 px title bar over a 322 × 198 body), the size
 * measured in the reference, and scaled as a whole to its cell: so every length below is a plain
 * px number, and the demo pointer, a child of the window, scales with it.
 */

export const WIN = { width: 322, height: 218 };

/** How a tile starts: at rest, or with its interaction played to the end (a still for docs). */
export type Pose = 'rest' | 'open';

/** A demo's steps, in the window's own px. */
export type Kit = {
  wait: (ms: number) => Promise<void>;
  glide: (to: Point, ms: number) => Promise<void>;
  /** Glides to the middle of the window's `[data-hot="…"]` element, nudged by `nudge`. */
  to: (hot: string, ms?: number, nudge?: Point) => Promise<void>;
  /** The pointer dips, as a click does, and waits a beat. */
  press: () => Promise<void>;
};

/** What a specimen hands its tile: one round of its demo, and a way back to rest. */
export type SpecimenHandle = { play: (kit: Kit) => Promise<void>; reset: () => void };

export type BodyProps = {
  ref: Ref<SpecimenHandle>;
  pose: Pose;
  /** Called by the reader's own clicks and keys (never the demo's), with what they did. */
  report: (action: string) => void;
};

export function makeKit(demo: Demo, win: HTMLElement, pointer: HTMLElement): Kit {
  const to: Kit['to'] = (hot, ms = 700, nudge = { x: 0, y: 0 }) => {
    const target = win.querySelector(`[data-hot="${hot}"]`);
    if (!target) return demo.wait(ms);
    const box = target.getBoundingClientRect();
    const frame = win.getBoundingClientRect();
    // The window is scaled: its rect is in screen px, the pointer moves in the window's.
    const s = frame.width / WIN.width || 1;
    return demo.glide(
      {
        x: (box.left + box.width / 2 - frame.left) / s + nudge.x,
        y: (box.top + box.height * 0.55 - frame.top) / s + nudge.y,
      },
      ms,
    );
  };
  const press = () => {
    for (const glyph of pointer.children) {
      glyph.animate([{ scale: 1 }, { scale: 0.8 }, { scale: 1 }], {
        duration: 220,
        easing: 'ease-out',
      });
    }
    return demo.wait(170);
  };
  return { wait: demo.wait, glide: demo.glide, to, press };
}

/** Whether the reader asked for less motion, read at the moment it matters. */
export const reducedMotion = () =>
  typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

type Tone = 'soft' | 'mid' | 'strong' | 'ink' | 'card';

/**
 * A skeleton piece: a rounded bar (or a block, or a dot) placed in px in its parent. The whole
 * wireframe is made of these, so the tones are the only colours it has.
 */
export function Sk({
  x,
  y,
  w,
  h = 4,
  tone = 'mid',
  r,
  className,
  style,
}: {
  x: number;
  y: number;
  w: number;
  h?: number;
  tone?: Tone;
  r?: number;
  className?: string;
  style?: CSSProperties;
}) {
  return (
    <span
      className={className ? `${styles.sk} ${className}` : styles.sk}
      data-tone={tone}
      style={{ left: x, top: y, width: w, height: h, borderRadius: r, ...style }}
    />
  );
}

/** Moves the focus without letting the browser scroll the wall (or the page) to it. */
export const focus = (element: HTMLElement | null | undefined) =>
  element?.focus({ preventScroll: true });

/**
 * Listens for keys on `target` with the latest `onKey`: the scenes take Escape (and the palette its
 * arrows) wherever the focus is inside them.
 */
export function useKeys(
  target: RefObject<HTMLElement | null>,
  onKey: (event: KeyboardEvent) => void,
) {
  const latest = useRef(onKey);
  useLayoutEffect(() => {
    latest.current = onKey;
  });
  useEffect(() => {
    const element = target.current;
    if (!element) return;
    const listen = (event: KeyboardEvent) => latest.current(event);
    element.addEventListener('keydown', listen);
    return () => element.removeEventListener('keydown', listen);
  }, [target]);
}
```

### motion-specimens/glyphs.tsx

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

/*
 * The few drawn glyphs of the wireframes, each on its own small viewBox and coloured by
 * currentColor, so a tone class (or the dark scheme) recolours them.
 */

type GlyphProps = { className?: string };

const svg = { 'aria-hidden': true, focusable: false } as const;

/** A heart: outlined, or filled once liked. */
export function Heart({ className, filled }: GlyphProps & { filled: boolean }) {
  return (
    <svg {...svg} className={className} viewBox="0 0 16 16">
      <path
        d="M8 13.6 2.7 8.5a3.2 3.2 0 0 1 4.5-4.6l.8.8.8-.8a3.2 3.2 0 0 1 4.5 4.6z"
        fill={filled ? 'currentColor' : 'none'}
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function Close({ className }: GlyphProps) {
  return (
    <svg {...svg} className={className} viewBox="0 0 10 10">
      <path
        d="M2 2l6 6M8 2 2 8"
        stroke="currentColor"
        strokeWidth="1.3"
        strokeLinecap="round"
        fill="none"
      />
    </svg>
  );
}

export function Chevron({ className }: GlyphProps) {
  return (
    <svg {...svg} className={className} viewBox="0 0 10 10">
      <path
        d="M2.5 4 5 6.5 7.5 4"
        stroke="currentColor"
        strokeWidth="1.3"
        strokeLinecap="round"
        strokeLinejoin="round"
        fill="none"
      />
    </svg>
  );
}

export function Check({ className }: GlyphProps) {
  return (
    <svg {...svg} className={className} viewBox="0 0 10 10">
      <path
        d="M2 5.2 4.2 7.3 8 2.8"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
        strokeLinejoin="round"
        fill="none"
      />
    </svg>
  );
}

/** The toast's mark: a tray with a tick, drawn light on its dark square. */
export function Saved({ className }: GlyphProps) {
  return (
    <svg {...svg} className={className} viewBox="0 0 12 12">
      <path
        d="M2.5 3.2h7v6.3h-7zM2.5 5h7M4.6 7.2l1 .9 1.8-1.9"
        stroke="currentColor"
        strokeWidth="1"
        strokeLinecap="round"
        strokeLinejoin="round"
        fill="none"
      />
    </svg>
  );
}

/** A picture placeholder: a hill and a sun, in the wireframe's tones. */
export function Picture({ className }: GlyphProps) {
  return (
    <svg {...svg} className={className} viewBox="0 0 120 80" preserveAspectRatio="xMidYMax slice">
      <circle cx="86" cy="26" r="9" fill="currentColor" opacity="0.5" />
      <path d="M0 80 34 42l22 22 16-14 48 30z" fill="currentColor" />
    </svg>
  );
}

/** The dashboard's area chart: a rising, zigzag line over its fill, 200 × 48. */
const AREA = [38, 34, 36, 27, 29, 21, 24, 15, 17, 9, 11, 5];
const LINE = AREA.map(
  (y, i) => `${i ? 'L' : 'M'}${((i * 200) / (AREA.length - 1)).toFixed(1)} ${y}`,
).join('');

export function AreaChart({ className }: GlyphProps) {
  return (
    <svg {...svg} className={className} viewBox="0 0 200 48" preserveAspectRatio="none">
      <path d={`${LINE}L200 48L0 48z`} fill="var(--area)" />
      <path
        d={LINE}
        fill="none"
        stroke="var(--area-line)"
        strokeWidth="1"
        strokeLinejoin="round"
        vectorEffect="non-scaling-stroke"
      />
    </svg>
  );
}
```

### motion-specimens/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 (motion-specimens.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>
  );
}
```

### motion-specimens/use-autoplay.ts

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

'use client';

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

/*
 * When something may move on its own: while part of it is on screen and the tab is visible, never
 * under reduced motion, not while the reader holds it (the pointer rests on it, or the focus is in
 * it), and never again once the reader has used it: `take()` hands it to the reader for good
 * (until the component mounts again). Each tile of the wall has one, and so has the wall's drift,
 * so a tile scrolled or drifted out of view stops its demo.
 */
export function useAutoplay<T extends HTMLElement>(threshold = 0.3) {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);
  const [held, setHeld] = 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 },
    );
    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);
    };
  }, [threshold]);

  const take = useCallback(() => setTaken(true), []);
  const hold = useCallback((on: boolean) => setHeld(on), []);

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