# Request trace

> A platform hero you can use: press anything in a small store and its request replaces the log’s top row, while a comet of light runs the circuit between the windows.

Two overlapping windows on a faint grid: a hosting platform’s request log, and a store it serves. Every action in the store, by hand or by a named cursor, sends a request. The log’s top row is replaced by it, with its method, path, region, services and time, and a small comet travels a thin line from one window to the other through a node whose icon says what is being called. Open a product and a slower request turns it into a 3D object that rises out of the page and can be turned by hand, drawn by a tiny WebGL renderer in the folder, with no library and no model files.

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

Category: Motion.

## Anatomy

1. **Request log**: The window behind: a breadcrumb, a label and a real table with Request, Execution and Status.
2. **Top row**: The latest request. It is replaced, not stacked, 0.2 s after the action, with a skeleton in between.
3. **Method badge**: A pill in a monospaced face: green for GET, blue for POST.
4. **Service chip**: What the request touched, joined by a short line: Cache, Database, Email or AI.
5. **Node**: A faint ring on the circuit; its icon changes to a database, an envelope or a box as the comet passes.
6. **Store**: The window in front: a working shop with a nav, a catalog and a product page.
7. **Product**: Stands out of the page over the window’s left and bottom edges. A slider: drag it, or use the arrow keys.
8. **Heading**: Your `headline`, below the stage and outside its scaling, so it keeps its size on a phone.

## Properties

### Opening product (`defaultProduct`)

1. **Flask (default)**: Tall and narrow: the most room for the windows behind it.
2. **Mug**: Wide and low, in glossy enamel.
3. **Lantern**: The busiest model, with glass and a flame.

Each is drawn by the same renderer. The product you open on is treated as already turned into 3D, so the slow request runs for the others.

## When to use

- A product page for a platform or an API, where what you sell happens behind the screen and needs showing: one action in an app, one request in a log.
- A hero that people can use, not only watch: the store responds by hand, and each action sends its own row.
- Explaining a round trip and what it touches, with the services named on each row.

## When not to use

- A real log or monitoring screen. The rows are simulated, and the times come from the `requests` data. Don’t present them as measurements of your service.
- A page that must weigh almost nothing: it needs a WebGL context and its own small renderer.
- A place with no room for two windows side by side. Under 620 px the windows stack, and their small text gets small.

### One request

- **0 s**: the top row turns to skeleton and the comet leaves the store, heading for the node.
- **0.2 s**: the new row is in, with Running… and its chips.
- **0.17 s**: the node’s icon changes as the comet goes through it.
- **0.65 s**: the comet reaches the log, a ring of dots pops, and the status turns to 200 OK. A catalog’s cards start here, 130 ms apart.
- **1.1 s**: the comet is back at the store, and Notify me or the bag count changes. The 3D request makes this trip twice.

### What the rows should say

- Pass `requests` with your own paths, descriptions and services; the store’s actions stay the same.
- Keep `ms` plausible for what the row describes: tens of ms for a read, seconds for an AI call.

## Do’s and don’ts

- **Do**: Name the services a request really uses in your product, in your own words.
- **Don’t**: Don’t quote the simulated times as your platform’s performance, here or in the paragraph under it.

## Installation

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

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

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

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

## Usage

```tsx
import { RequestTrace, Term } from './request-trace';

export function PlatformHero() {
  return (
    <RequestTrace
      tag="Platform"
      headline="Press anything in the shop. Follow the request it sends."
      requests={{ notify: { path: '/v2/alerts', ms: 64 } }}
      onRequest={(request) => console.log(request.method, request.path, request.status)}
    >
      <Term>Functions</Term> answer from the region nearest the shopper.
    </RequestTrace>
  );
}
```

## States

- **Product page**: The store on a product, and the row that loaded it: 200 OK with its time.
- **Running**: The status shows a spinner and Running… until the comet reaches the log.
- **Catalog**: Shop all: three cards. Each photo is one render, made the first time it is needed.
- **On the list**: Notify me becomes You’re on the list with a tick, and stays that way for that product.
- **Another product**: The enamel mug, with the same layout and its own sizes.
- **Dark**: With `colorScheme="dark"`: the windows and the text change, the products keep their colours.

## How it works

- One clock per request, timed: the row blanks to a skeleton for 0.2 s, the comet goes out in 0.65 s, the status turns to 200 OK on arrival, and the comet comes back in 0.45 s. The 3D request makes the trip twice, 2.2 s, and reports 2.3 s. The times are simulated from each request’s `ms`, with a small spread; nothing goes to a network.
- The comet is four strokes of one path with a set length of 1000: dashes of 160, 100, 46 and 18, yellow to red and 1 to 2.4 px wide, moved together by their dash offset with the Web Animations API. It passes under both windows, and a small ring of dots pops at each end. The node’s icon crossfades 0.17 s after it leaves.
- The products are surfaces of revolution from a profile, with tubes swept along a path for handles and wires. Rounded corners come from the profile; anything sharper than 50 degrees keeps two normals, so a lid keeps its edge. Contact shade is stored per vertex, including the handle’s on the mug’s wall.
- The light is what the surfaces reflect: a function paints a cove, a large softbox, a strip and a dim floor in reflection directions, sharp or blurred by roughness. So enamel shows a clean window, powder coat a broad sheen and steel the whole room. Pebble, knurling and enamel flecks tilt the normal or tint the colour in the fragment shader; the printed mark is a small canvas texture. The shadow is two soft blobs on the floor.
- The page holds one WebGL context, on a canvas outside the document: each instance asks for a frame and copies it to its own 2D canvas. It draws only while something moves, caps the device pixel ratio at 2, frees its bitmap off screen, and gives the context back 0.5 s after no instance is on screen. Catalog photos are one render each, kept as data URLs, at the same scale as the flight into the card, so the swap doesn’t show.
- Opening a product flies it from its card to its place in 1.05 s while turning, ease-out; going back shrinks it to its card in 0.62 s as the catalog request runs, and the other cards fade in 130 ms apart. A drag turns it 0.012 radians per px and leaves inertia that dies at a rate of 3.2 per second.
- The stage is designed at 872 px, or 500 px with the windows stacked under a 620 px container, and scaled with `zoom`, so it is laid out and rasterised at the size it shows. The text below is outside the zoom and keeps its size.
- While on screen and untouched, the named cursor uses Notify me, Shop all, a product, the drag, a size and Add to bag, in a loop of about 18 s; any input from the reader stops it for good. Colours are tokens with `light-dark()` pairs on the root; the products keep theirs in both schemes.

## API reference

- **headline** (`ReactNode`, default `Press anything in the shop. Follow the request it sends.`): The heading under the windows.
- **children** (`ReactNode`): The paragraph under the heading. `Term`, also exported, underlines a word.
- **tag** (`string`, default `'Platform'`): The small tag above the heading.
- **onRequest** (`(request: TraceRequest & { status: 'running' | 'done' }) => void`): Called when a request starts and again when it finishes.
- **requests** (`Partial<Record<RequestKind, Partial<Omit<TraceRequest, 'kind'>>>>`): Overrides by kind (page, catalog, model, stock, bag, notify): method, path, note, services and ms.
- **cursor** (`string`, default `'Alex'`): The name on the demo’s cursor and in the store’s bar.
- **region** (`{ city: string; code: string }`, default `Frankfurt, 'FRA · 08'`): Where the requests run.
- **defaultView** (`'product' | 'catalog'`, default `'product'`): Which page the store opens on.
- **defaultProduct** (`'flask' | 'mug' | 'lantern'`, default `'flask'`): Which product it opens on.
- **defaultRunning** (`boolean`, default `false`): Holds the top row in Running, as a still; it also turns the demo off.
- **defaultNotified** (`boolean`, default `false`): Starts with Notify me taken, as a still.
- **defaultBag** (`number`, default `0`): How many are in the bag at the start.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, the named cursor uses the store by itself.
- **colorScheme** (`'light' | 'dark' | 'system'`): Sets the scheme; left out, it follows the page.
- **className** (`string`): Added to the root.

## Accessibility

### Keyboard and screen readers

- The store’s controls are real buttons, the sizes a radio group, the log a real table, and the product a slider: left and right turn it, up and down tilt it, Home resets it.
- A status region reads out each finished request, with its method, path, status and time.
- When a page replaces the one with the control in use, the focus moves to the new title, or to the first card.

### Motion

- With reduced motion there is no comet, flight or inertia and no demo: rows and pages simply change. Dragging still turns the product.

### In this build

- The store is real buttons, a radio group for sizes and a heading per page; the log is a real table. A status region reads each finished request.
- The product is a slider: drag it, or use left and right to turn, up and down to tilt, Home to reset.
- When a new page replaces the control in use, the focus moves to the product’s title or the first card.
- With reduced motion there is no comet, flight, inertia or demo: rows and pages simply change.
- Where WebGL is missing or its context is lost, the products are drawn in SVG, and the renders come back if the context does.

## Source

### request-trace/request-trace.tsx

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

'use client';

import {
  useEffect,
  useEffectEvent,
  useRef,
  useState,
  type CSSProperties,
  type ReactNode,
} from 'react';
import { NamedCursor, runDemo, type Point } from './demo-pointer';
import {
  BagGlyph,
  BellGlyph,
  CheckGlyph,
  ChevronGlyph,
  Glyph,
  HistoryGlyph,
  KIND_ICON,
  NODE_ICON,
  PlatformMark,
  SERVICE_ICON,
  StoreMark,
} from './glyphs';
import { ProductStill } from './product-still';
import { ProductView, type ProductViewHandle } from './product-view';
import {
  baseRequest,
  nodeIconFor,
  PRODUCTS,
  product as productOf,
  SERVICE_NAMES,
  type ProductId,
  type RequestKind,
  type TraceRequest,
} from './products';
import { studioBroken, thumbnail } from './studio';
import { useAutoplay } from './use-autoplay';
import styles from './request-trace.module.css';

/*
 * Request trace: a hero for a hosting platform. Two windows on a faint grid: the platform's request
 * log, and a small store it serves. Whatever happens in the store (by hand, or by the named cursor
 * of the demo) sends a request: the log's top row is replaced by it, a comet of light runs along a
 * thin circuit from the store, through a node whose icon says what it is calling, to the log and
 * back. Pick a product in the catalog and a slower request turns it into a 3D object that rises out
 * of the page and can be turned by hand.
 *
 * - One clock per request, timed: the row blanks to skeleton for 0.2 s, the comet goes out in
 *   0.65 s, the status turns on arrival, and the comet returns in 0.45 s. The 3D request makes the
 *   trip twice, about 2.2 s.
 * - The comet is three strokes of one path with dashes of different lengths, animated by their
 *   dash offset with the Web Animations API; nothing runs frame by frame.
 * - The products are drawn by a small renderer of their own (studio.ts, meshes.ts), on demand, and
 *   the page never holds more than one WebGL context. Catalog photos are one render each.
 * - Times are made up from each request's `ms`, with a small spread. Nothing goes to any network.
 */

export type { ProductId, RequestKind, ServiceId, TraceRequest } from './products';

export type RequestEvent = TraceRequest & { status: 'running' | 'done' };

export type RequestTraceProps = {
  /** The heading under the windows; a line break is yours to add. */
  headline?: ReactNode;
  /** The paragraph under the heading. `Term` underlines a word. */
  children?: ReactNode;
  /** The small tag above the heading. */
  tag?: string;
  /** Called when a request starts and again when it finishes. */
  onRequest?: (request: RequestEvent) => void;
  /** Overrides, by kind, for what the rows say. */
  requests?: Partial<Record<RequestKind, Partial<Omit<TraceRequest, 'kind'>>>>;
  /** The name on the demo's cursor and in the store's bar. */
  cursor?: string;
  /** Where the requests run. */
  region?: { city: string; code: string };
  /** Which page the store opens on. */
  defaultView?: 'product' | 'catalog';
  /** Which product it opens on. */
  defaultProduct?: ProductId;
  /** Holds the top row in Running, as a still for docs. */
  defaultRunning?: boolean;
  /** Starts with Notify me taken, as a still. */
  defaultNotified?: boolean;
  /** Starts with one in the bag, as a still. */
  defaultBag?: number;
  /** While on screen and untouched, the named cursor uses the store by itself. */
  autoplay?: boolean;
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
};

/** Underlines a word in the paragraph. */
export const Term = ({ children }: { children: ReactNode }) => (
  <span className={styles.term}>{children}</span>
);

const OUT_MS = 650;
const BACK_MS = 450;
const SWAP_MS = 200;
const RISE_MS = 1050;
const SHRINK_MS = 620;
const CARD_STAGGER = 130;

/** The circuit, in the stage's own px: from the store, around the node, to the log. */
const LAYOUTS = {
  wide: {
    path: 'M750 404H780A48 48 0 0 1 828 356V165Q828 139 802 139H590',
    log: { x: 607, y: 139 },
    store: { x: 767, y: 404 },
  },
  narrow: {
    path: 'M472 280V150A22 22 0 0 0 472 106V72Q472 56 456 56H430',
    log: { x: 444, y: 56 },
    store: { x: 472, y: 268 },
  },
};

/** The catalog's cards, from the store window's corner; the product layer shares that corner. */
const CARD_Y = 201;
const cardX = (index: number) => 98 + index * 144;
/** The canvas's centre, from the same corner, and its side. */
const VIEW_CENTRE = { x: 60, y: 250 };
const VIEW_SIDE = 420;
const CARD_FRAME = 150;
/** A product in its card, against its size at rest. */
const IN_CARD = 0.5;

const cardPose = (index: number) => ({
  scale: IN_CARD,
  x: (cardX(index) - VIEW_CENTRE.x) / VIEW_SIDE,
  y: (CARD_Y - VIEW_CENTRE.y) / VIEW_SIDE,
});

const reducedMotion = () =>
  typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

const formatTime = (ms: number) => (ms >= 1000 ? `${(ms / 1000).toFixed(1)}s` : `${ms}ms`);

/** A small, repeating spread, so two rows of the same kind don't read the same. */
const SPREAD = [0, 3, -2, 6, 1, -3, 4, 2];

type Row = { request: TraceRequest; status: 'running' | 'done'; key: number };

export function RequestTrace({
  headline = (
    <>
      Press anything in the shop.
      <br />
      Follow the request it sends.
    </>
  ),
  children = (
    <>
      <Term>Functions</Term> answer from the region nearest the shopper. <Term>Cache</Term>,{' '}
      <Term>Database</Term>, <Term>Email</Term> and <Term>AI</Term> are one hop away, on every row.
    </>
  ),
  tag = 'Platform',
  onRequest,
  requests,
  cursor = 'Alex',
  region = { city: 'Frankfurt', code: 'FRA · 08' },
  defaultView = 'product',
  defaultProduct = 'flask',
  defaultRunning = false,
  defaultNotified = false,
  defaultBag = 0,
  autoplay = true,
  colorScheme,
  className = '',
}: RequestTraceProps) {
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>();
  const [view, setView] = useState(defaultView);
  const [id, setId] = useState<ProductId>(defaultProduct);
  const [filter, setFilter] = useState<string | undefined>();
  const [revealed, setRevealed] = useState(true);
  const [flying, setFlying] = useState(false);
  const [leaving, setLeaving] = useState(false);
  const [sizes, setSizes] = useState<Record<string, number>>({});
  const [bag, setBag] = useState(defaultBag);
  const [justAdded, setJustAdded] = useState(false);
  const [notified, setNotified] = useState<Record<string, boolean>>(
    defaultNotified ? { [defaultProduct]: true } : {},
  );
  const [row, setRow] = useState<Row | null>(() => {
    const request = makeRequest(
      requests,
      defaultView === 'catalog' ? 'catalog' : 'page',
      defaultProduct,
    );
    return { request, status: defaultRunning ? 'running' : 'done', key: 0 };
  });
  const [node, setNode] = useState<keyof typeof NODE_ICON>('database');
  const [nodeBusy, setNodeBusy] = useState(false);
  const [message, setMessage] = useState('');
  const [thumbs, setThumbs] = useState<Partial<Record<ProductId, string>>>({});
  const [broken, setBroken] = useState(false);

  const stage = useRef<HTMLDivElement>(null);
  const viewer = useRef<ProductViewHandle>(null);
  const pointer = useRef<HTMLSpanElement>(null);
  const comet = useRef<(SVGPathElement | null)[]>([]);
  const sparkLog = useRef<SVGCircleElement>(null);
  const sparkStore = useRef<SVGCircleElement>(null);
  const timers = useRef(new Set<number>());
  const generated = useRef(new Set<ProductId>(defaultView === 'product' ? [defaultProduct] : []));
  const settle = useRef<(() => void) | null>(null);
  const counter = useRef(0);
  const flights = useRef<Animation[]>([]);
  const moveFocus = useRef(false);

  const later = (fn: () => void, ms: number) => {
    const timer = window.setTimeout(() => {
      timers.current.delete(timer);
      fn();
    }, ms);
    timers.current.add(timer);
  };
  useEffect(() => {
    const pending = timers.current;
    return () => pending.forEach((timer) => window.clearTimeout(timer));
  }, []);

  /** Which circuit the stage draws; the stylesheet decides the layout from the container. */
  const layout = () => {
    const design = stage.current
      ? getComputedStyle(stage.current).getPropertyValue('--design')
      : '';
    return design.trim() === '500' ? LAYOUTS.narrow : LAYOUTS.wide;
  };

  const flyComet = (reverse: boolean, ms: number) => {
    const { path } = layout();
    // Each stroke's head is the same point; only the tail length differs. The path has a set
    // length of 1000, so the numbers read as shares.
    comet.current.forEach((stroke, index) => {
      if (!stroke) return;
      const tail = [160, 100, 46, 18][index] ?? 40;
      stroke.setAttribute('d', path);
      stroke.style.strokeDasharray = `${tail} 3000`;
      const head = reverse
        ? [{ strokeDashoffset: -1000 }, { strokeDashoffset: 170 }]
        : [{ strokeDashoffset: tail }, { strokeDashoffset: tail - 1170 }];
      flights.current.push(
        stroke.animate(head, {
          duration: ms,
          easing: 'cubic-bezier(0.35, 0.1, 0.7, 0.95)',
          fill: 'both',
        }),
      );
    });
  };

  const spark = (circle: SVGCircleElement | null, at: Point) => {
    if (!circle) return;
    circle.setAttribute('cx', String(at.x));
    circle.setAttribute('cy', String(at.y));
    circle.style.transformOrigin = `${at.x}px ${at.y}px`;
    circle.animate(
      [
        { opacity: 0, transform: 'scale(0.3)' },
        { opacity: 1, offset: 0.25 },
        { opacity: 0, transform: 'scale(1.25)' },
      ],
      { duration: 420, easing: 'ease-out' },
    );
  };

  /** Sends a request: the row, the comet out and back, and what happens at each end. */
  const trace = (
    kind: RequestKind,
    item: ProductId,
    {
      trips = 1,
      filterName,
      onArrive,
      onReturn,
      settled,
    }: {
      trips?: number;
      filterName?: string;
      onArrive?: () => void;
      onReturn?: () => void;
      /** Runs when it's back, or at once if another request cuts in. */
      settled?: () => void;
    } = {},
  ) => {
    settle.current?.();
    settle.current = settled ?? null;
    timers.current.forEach((timer) => window.clearTimeout(timer));
    timers.current.clear();
    flights.current.forEach((flight) => flight.cancel());
    flights.current = [];

    const request = makeRequest(requests, kind, item, filterName, counter.current);
    counter.current += 1;
    const key = counter.current;
    onRequest?.({ ...request, status: 'running' });

    const finish = () => {
      setRow({ request, status: 'done', key });
      setMessage(`${request.method} ${request.path}: 200 OK, ${formatTime(request.ms)}`);
      onRequest?.({ ...request, status: 'done' });
    };

    if (reducedMotion()) {
      setNode(nodeIconFor(request));
      finish();
      onArrive?.();
      settle.current?.();
      settle.current = null;
      onReturn?.();
      return;
    }

    setRow(null);
    later(() => setRow({ request, status: 'running', key }), SWAP_MS);
    setNodeBusy(true);
    later(() => setNode(nodeIconFor(request)), 170);

    const where = layout();
    let trip = 0;
    const go = () => {
      trip += 1;
      flyComet(false, OUT_MS);
      later(() => {
        spark(sparkLog.current, where.log);
        if (trip === trips) {
          finish();
          onArrive?.();
        }
        flyComet(true, BACK_MS);
        later(() => {
          spark(sparkStore.current, where.store);
          if (trip < trips) {
            go();
            return;
          }
          setNodeBusy(false);
          settle.current?.();
          settle.current = null;
          onReturn?.();
        }, BACK_MS);
      }, OUT_MS);
    };
    go();
  };

  /** The control in use is about to go with its page: the new page takes the focus. */
  const keepFocus = () => {
    moveFocus.current = !!stage.current?.contains(document.activeElement);
  };

  /** The product's page: its request, while the product rises out of its place. */
  const loadProduct = (next: ProductId, fromIndex: number | null) => {
    setId(next);
    setView('product');
    setRevealed(false);
    setLeaving(false);
    setFlying(false);
    if (reducedMotion() || studioBroken()) {
      viewer.current?.set(next);
    } else {
      const rest = { x: 0, y: 0, scale: 1 };
      const start = fromIndex === null ? { scale: 0.7, x: 0.16, y: -0.09 } : cardPose(fromIndex);
      viewer.current?.set(next, start);
      viewer.current?.fly(rest, RISE_MS);
    }
    trace('page', next, { onArrive: () => setRevealed(true) });
  };

  /** The catalog: the request, while the product shrinks back into its card. */
  const openCatalog = (name?: string) => {
    const wasProduct = view === 'product';
    keepFocus();
    setFilter(name);
    setLeaving(false);
    const index = PRODUCTS.findIndex((item) => item.id === id);
    setRevealed(false);
    if (wasProduct && !name && !reducedMotion() && !studioBroken()) {
      setFlying(true);
      viewer.current?.fly({ ...cardPose(index) }, SHRINK_MS);
    }
    const show = () => {
      setView('catalog');
      setFlying(false);
      setRevealed(true);
    };
    trace('catalog', id, { filterName: name, onArrive: show });
  };

  const pickProduct = (next: ProductId) => {
    const index = PRODUCTS.findIndex((item) => item.id === next);
    const shownIndex = filter ? null : index;
    keepFocus();
    if (generated.current.has(next) || reducedMotion()) {
      setLeaving(true);
      loadProduct(next, shownIndex);
      return;
    }
    // A first look at it: the slow request, then the page.
    trace('model', next, {
      trips: 2,
      onReturn: () => {
        generated.current.add(next);
        setLeaving(true);
        later(() => loadProduct(next, shownIndex), 180);
      },
    });
  };

  const pickSize = (index: number) => {
    setSizes((current) => ({ ...current, [id]: index }));
    trace('stock', id);
  };

  const addToBag = () => {
    trace('bag', id, {
      settled: () => {
        setBag((count) => count + 1);
        setJustAdded(true);
        window.setTimeout(() => setJustAdded(false), 1400);
      },
    });
  };

  const notify = () => {
    if (notified[id]) return;
    const item = id;
    trace('notify', item, {
      settled: () => setNotified((current) => ({ ...current, [item]: true })),
    });
  };

  useEffect(() => {
    if (!moveFocus.current) return;
    moveFocus.current = false;
    stage.current
      ?.querySelector<HTMLElement>(
        view === 'product' ? '[data-part="title"]' : '[data-part="card"]',
      )
      ?.focus({ preventScroll: true });
  }, [view]);

  // Catalog photos: one render each, the first time the catalog is near.
  useEffect(() => {
    if (view !== 'catalog' && !flying) return;
    const made: Partial<Record<ProductId, string>> = {};
    PRODUCTS.forEach((item) => {
      const url = thumbnail(item.id, CARD_FRAME * 3, (IN_CARD * VIEW_SIDE) / CARD_FRAME);
      if (url) made[item.id] = url;
    });
    // The effect only reports what the renderer could do.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setThumbs((current) => ({ ...current, ...made }));
    setBroken(studioBroken());
  }, [view, flying]);

  // The demo: notify, back to the catalog, the next product, turn it, pick a size, add to bag.
  const demo = autoplay && playing && !defaultRunning;
  const demoReset = useEffectEvent(() => {
    generated.current = new Set([defaultProduct]);
    setNotified({});
    setView('product');
    setId(defaultProduct);
    setFilter(undefined);
    setRevealed(true);
    setFlying(false);
    setLeaving(false);
    viewer.current?.set(defaultProduct);
  });
  const demoAct = useEffectEvent(
    (action: 'notify' | 'all' | 'add' | { pick: ProductId } | { size: number }) => {
      if (action === 'notify') {
        setNotified((current) => ({ ...current, [id]: false }));
        const item = id;
        trace('notify', item, {
          settled: () => setNotified((current) => ({ ...current, [item]: true })),
        });
      } else if (action === 'all') openCatalog();
      else if (action === 'add') addToBag();
      else if ('pick' in action) {
        generated.current.delete(action.pick);
        pickProduct(action.pick);
      } else pickSize(action.size);
    },
  );
  useEffect(() => {
    const frame = stage.current;
    const arrow = pointer.current;
    if (!demo || !frame || !arrow) return;
    /** The middle of an element, in the stage's own px. */
    const at = (selector: string): Point => {
      const box = frame.getBoundingClientRect();
      const design = Number(getComputedStyle(frame).getPropertyValue('--design')) || 872;
      const scale = box.width / design;
      const rect = frame.querySelector(selector)?.getBoundingClientRect();
      if (!rect) return { x: design * 0.7, y: 400 };
      return {
        x: (rect.left - box.left + rect.width / 2) / scale,
        y: (rect.top - box.top + rect.height / 2) / scale,
      };
    };
    demoReset();
    const order = PRODUCTS.map((item) => item.id).sort((a, b) =>
      a === defaultProduct ? 1 : b === defaultProduct ? -1 : 0,
    );
    const design = Number(getComputedStyle(frame).getPropertyValue('--design')) || 872;
    const stop = runDemo(arrow, { x: design * 0.86, y: 640 }, async ({ wait, glide, press }) => {
      for (let round = 0; ; round += 1) {
        await wait(700);
        await glide(at('[data-part="notify"]'), 800);
        await wait(180);
        press();
        demoAct('notify');
        await wait(OUT_MS + BACK_MS + 500);
        await glide(at('[data-part="nav-all"]'), 700);
        await wait(120);
        press();
        demoAct('all');
        await wait(OUT_MS + BACK_MS + 900);
        const next = order[round % order.length] as ProductId;
        await glide(at(`[data-part="card"][data-id="${next}"]`), 750);
        await wait(200);
        press();
        demoAct({ pick: next });
        await wait(2 * (OUT_MS + BACK_MS) + 180 + RISE_MS + 500);
        const middle = at('[data-part="viewer"]');
        await glide(middle, 650);
        press();
        viewer.current?.spin(Math.PI * 1.2, 1300);
        await glide({ x: middle.x + 46, y: middle.y + 8 }, 1300);
        await wait(300);
        await glide(at('[data-part="size"]:nth-child(2)'), 650);
        await wait(120);
        press();
        demoAct({ size: 1 });
        await wait(OUT_MS + BACK_MS + 350);
        await glide(at('[data-part="add"]'), 420);
        await wait(120);
        press();
        demoAct('add');
        await wait(OUT_MS + BACK_MS + 700);
      }
    });
    return stop;
  }, [demo, defaultProduct, root]);

  const item = productOf(id);
  const size = sizes[id] ?? 1;
  const isNotified = !!notified[id];
  const url = view === 'product' ? `fjellsupply.example/products/${id}` : 'fjellsupply.example';
  const shownProducts = PRODUCTS.filter((entry) => !filter || entry.category === filter);
  const activeNav = view === 'catalog' ? (filter ?? 'all') : item.category;

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="root"
      data-color-scheme={colorScheme}
      onPointerDownCapture={take}
      onKeyDownCapture={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') take();
      }}
    >
      <div ref={stage} className={styles.stage} data-part="stage">
        <Backdrop />

        <svg className={styles.circuit} data-part="circuit" aria-hidden="true">
          <path className={`${styles.line} ${styles.forWide}`} d={LAYOUTS.wide.path} />
          <path className={`${styles.line} ${styles.forNarrow}`} d={LAYOUTS.narrow.path} />
          <g className={styles.comet}>
            {[0, 1, 2, 3].map((index) => (
              <path
                key={index}
                ref={(element) => {
                  comet.current[index] = element;
                }}
                pathLength={1000}
                data-stroke={index}
              />
            ))}
          </g>
          <circle ref={sparkLog} className={styles.spark} r="9" />
          <circle ref={sparkStore} className={styles.spark} r="9" />
        </svg>

        <div className={styles.node} data-part="node" data-busy={nodeBusy} aria-hidden="true">
          {(Object.keys(NODE_ICON) as (keyof typeof NODE_ICON)[]).map((name) => (
            <span key={name} data-on={node === name}>
              <Glyph d={NODE_ICON[name]} />
            </span>
          ))}
        </div>

        {/* The platform's log. */}
        <section className={styles.log} data-part="log" aria-label="Request activity">
          <WindowBar>
            <span className={styles.address}>
              <PlatformMark className={styles.addressMark} />
              console.relay.example
            </span>
          </WindowBar>
          <div className={styles.frame}>
            <div className={styles.crumbs}>
              <PlatformMark className={styles.crumbMark} />
              <span>Functions</span>
              <ChevronGlyph className={styles.crumbChevron} />
              <span className={styles.storeDot}>
                <StoreMark />
              </span>
              <span>FJELL SUPPLY</span>
              <span className={styles.activity}>
                <HistoryGlyph />
                Request activity
              </span>
            </div>
            <table className={styles.table}>
              <colgroup>
                <col />
                <col className={styles.colWhere} />
                <col className={styles.colStatus} />
              </colgroup>
              <thead>
                <tr>
                  <th scope="col">Request</th>
                  <th scope="col">Execution</th>
                  <th scope="col">Status</th>
                </tr>
              </thead>
              <tbody>
                <RowView row={row} region={region} />
                <SkeletonRow />
                <SkeletonRow />
              </tbody>
            </table>
          </div>
        </section>

        {/* The store. */}
        <section className={styles.store} data-part="store" aria-label="Fjell Supply, a store">
          <WindowBar>
            <span className={styles.address} data-part="url">
              <span className={styles.storeDot}>
                <StoreMark />
              </span>
              {url}
            </span>
            <span className={styles.presence}>
              <i />
              {cursor} · {region.city}
            </span>
          </WindowBar>
          <div className={styles.frame}>
            <nav className={styles.nav} data-part="nav" aria-label="Store">
              <button type="button" className={styles.brand} onClick={() => openCatalog()}>
                <StoreMark />
                FJELL
              </button>
              <div className={styles.links}>
                <button
                  type="button"
                  data-part="nav-all"
                  aria-current={activeNav === 'all' ? 'page' : undefined}
                  onClick={() => openCatalog()}
                >
                  Shop all
                </button>
                {(['Drinkware', 'Lighting'] as const).map((name) => (
                  <button
                    key={name}
                    type="button"
                    aria-current={activeNav === name ? 'page' : undefined}
                    onClick={() => openCatalog(name)}
                  >
                    {name}
                  </button>
                ))}
              </div>
              <span className={styles.bagCount} data-part="bag-count" data-bump={justAdded}>
                Bag ({bag})
              </span>
            </nav>

            {view === 'product' ? (
              <div className={styles.page} data-part="page" data-in={revealed}>
                <div className={styles.photo} data-part="photo" />
                <div className={styles.details}>
                  <p className={styles.crumb} style={delay(0)}>
                    {item.category} / the field edit
                  </p>
                  <h3 className={styles.title} style={delay(1)} data-part="title" tabIndex={-1}>
                    {item.name}
                  </h3>
                  <p className={styles.price} style={delay(2)}>
                    ${item.price} <span>USD</span>
                  </p>
                  <p className={styles.colour} style={delay(3)}>
                    <i style={{ background: item.swatch }} />
                    {item.colour}
                  </p>
                  <div
                    className={styles.sizes}
                    style={delay(4)}
                    role="radiogroup"
                    aria-label="Size"
                    data-count={item.sizes.length}
                  >
                    {item.sizes.map((label, index) => (
                      <button
                        key={label}
                        type="button"
                        role="radio"
                        className={styles.size}
                        data-part="size"
                        aria-checked={size === index}
                        onClick={() => pickSize(index)}
                      >
                        {label}
                      </button>
                    ))}
                  </div>
                  <button
                    type="button"
                    className={styles.add}
                    style={delay(5)}
                    data-part="add"
                    onClick={addToBag}
                  >
                    {justAdded ? 'Added' : 'Add to bag'}
                    {justAdded ? <CheckGlyph /> : <BagGlyph />}
                  </button>
                  <button
                    type="button"
                    className={styles.notify}
                    style={delay(6)}
                    data-part="notify"
                    data-on={isNotified}
                    aria-disabled={isNotified || undefined}
                    onClick={notify}
                  >
                    {isNotified ? 'You’re on the list' : 'Notify me'}
                    {isNotified ? <CheckGlyph /> : <BellGlyph />}
                  </button>
                </div>
              </div>
            ) : (
              <div className={styles.catalog} data-part="catalog" data-in={revealed}>
                <h3 className={styles.catalogTitle}>
                  {filter ?? 'Shop all'} <span>({shownProducts.length})</span>
                </h3>
                <ul className={styles.cards}>
                  {shownProducts.map((entry, index) => (
                    <li key={entry.id} style={{ '--i': index } as CSSProperties}>
                      <button
                        type="button"
                        className={styles.card}
                        data-part="card"
                        data-id={entry.id}
                        data-leaving={leaving && entry.id !== id}
                        onClick={() => pickProduct(entry.id)}
                      >
                        <span className={styles.cardPhoto} data-part="card-photo">
                          {thumbs[entry.id] ? (
                            // eslint-disable-next-line @next/next/no-img-element -- a data URL just rendered
                            <img src={thumbs[entry.id]} alt="" draggable={false} />
                          ) : broken ? (
                            <ProductStill id={entry.id} />
                          ) : null}
                        </span>
                        <span className={styles.cardName}>{entry.name}</span>
                        <span className={styles.cardPrice}>${entry.price}</span>
                      </button>
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        </section>

        <ProductView
          ref={viewer}
          defaultProduct={defaultProduct}
          hidden={view === 'catalog' && !flying}
          className={styles.product}
          canvasClass={styles.render}
          hitClass={styles.hit}
          stillClass={styles.still}
        />

        <NamedCursor
          ref={pointer}
          name={cursor}
          className={styles.cursor}
          arrowClass={styles.cursorArrow}
          labelClass={styles.cursorLabel}
        />
      </div>

      <div className={styles.hero} data-part="hero">
        <p className={styles.tag} data-part="tag">
          <span>{tag}</span>
          <i />
          <i />
        </p>
        <h2 className={styles.headline} data-part="headline">
          {headline}
        </h2>
        <div className={styles.lead} data-part="lead">
          {children}
        </div>
      </div>

      <p className={styles.hidden} role="status" aria-live="polite">
        {message}
      </p>
    </div>
  );
}

function makeRequest(
  overrides: RequestTraceProps['requests'],
  kind: RequestKind,
  id: ProductId,
  filter?: string,
  count = 0,
): TraceRequest {
  const base = { ...baseRequest(kind, productOf(id), filter), ...overrides?.[kind] };
  const spread = SPREAD[count % SPREAD.length] ?? 0;
  return { ...base, ms: base.ms >= 1000 ? base.ms : Math.max(1, base.ms + spread) };
}

const delay = (index: number) => ({ '--i': index }) as CSSProperties;

function WindowBar({ children }: { children: ReactNode }) {
  return (
    <div className={styles.bar}>
      <span className={styles.lights} aria-hidden="true">
        <i />
        <i />
        <i />
      </span>
      <div className={styles.barMiddle}>{children}</div>
    </div>
  );
}

function RowView({ row, region }: { row: Row | null; region: { city: string; code: string } }) {
  if (!row) return <SkeletonRow active />;
  const { request, status } = row;
  return (
    <tr className={styles.row} data-part="row" key={row.key}>
      <td>
        <div className={styles.request}>
          <Glyph d={KIND_ICON[request.kind]} className={styles.kind} />
          <span className={styles.tree} aria-hidden="true" />
          <div className={styles.requestText}>
            <p className={styles.path}>
              <span className={styles.method} data-part="method" data-method={request.method}>
                {request.method}
              </span>
              {request.path}
            </p>
            <p className={styles.note}>{request.note}</p>
            <ul className={styles.chips} data-part="chips">
              {request.services.map((service) => (
                <li key={service} className={styles.chip} data-part="chip" data-service={service}>
                  <Glyph d={SERVICE_ICON[service]} />
                  {SERVICE_NAMES[service]}
                </li>
              ))}
            </ul>
          </div>
        </div>
      </td>
      <td>
        <p>{region.city}</p>
        <p className={styles.note}>{region.code}</p>
      </td>
      <td>
        <div className={styles.status} data-part="status" data-status={status}>
          {status === 'running' ? (
            <p className={styles.running}>
              <span className={styles.spinner} aria-hidden="true" />
              Running…
            </p>
          ) : (
            <>
              <p className={styles.ok}>
                <CheckGlyph />
                200 OK
              </p>
              <p className={`${styles.note} ${styles.time}`}>{formatTime(request.ms)}</p>
            </>
          )}
        </div>
      </td>
    </tr>
  );
}

function SkeletonRow({ active = false }: { active?: boolean }) {
  return (
    <tr className={styles.skeleton} data-active={active} aria-hidden="true">
      <td colSpan={3}>
        <i />
        <i />
        <i />
        <i />
      </td>
    </tr>
  );
}

/** The faint grid the two windows sit on. */
function Backdrop() {
  return (
    <svg className={styles.backdrop} aria-hidden="true">
      <g className={styles.forWide}>
        <path d="M84 -200V1500M161 -200V60M548 40V120M780 -200V1500M0 -22H1000M0 680H120M161 662V1500M548 662V720M702 662V770M84 618H240M84 700H120M625 139H702M702 139V300M625 215H702M625 292H740M664 190V300M625 165Q664 165 664 190" />
        <circle cx="828" cy="404" r="48" />
        <path d="M806 590A62 62 0 1 1 806 700M830 110C850 180 860 230 872 260" />
        <text x="738" y="10">
          01
        </text>
        <text x="806" y="10">
          02
        </text>
      </g>
      <g className={styles.forNarrow}>
        <path d="M18 -100V1500M484 -100V1500M0 8H500" />
        <circle cx="472" cy="128" r="22" />
      </g>
    </svg>
  );
}
```

### request-trace/request-trace.module.css

```css
/* Request trace (request-trace.tsx): a hero with two overlapping windows on a faint grid, and a
   tag, a heading and a paragraph under them.

   The stage is drawn on a fixed design width, 872 px, or 500 px where the container is under 620 px,
   and scaled with `zoom` so everything is laid out and rasterised at the size it shows. The text
   under it is outside the zoom and keeps its own size. Inside the stage, hairlines are inset
   box-shadows, because zoom snaps borders.

   Sizes at design width: the log 560 × 481, the store 480 × 361, overlapping by 320 × 181; each has
   a 38 px bar and an 8 px inset frame. The product canvas is 420 px square, centred 60 px right of
   the store's left edge, so the product hangs out over the edge and the bottom.

   Layers: grid and circuit (0), the log (1), the store (2), the product (3), the cursor (4).

   Colours are the tokens below, light-dark(light, dark) where the two differ. The products keep
   their colours in both. */

.root {
  --page: #fbfbfb;
  --grid: #ececed;
  --grid-text: #dcdcde;
  --window: #fff;
  --window-edge: rgb(0 0 0 / 0.07);
  --window-shadow: rgb(20 20 30 / 0.1);
  --frame-edge: #efeff0;
  --ink: #1d1d1f;
  --muted: #6d6d73;
  --faint: #98989e;
  --skeleton: #f2f2f3;
  --photo: #f4f4f5;
  --solid: #1d1d1f;
  --solid-ink: #fff;
  --control-edge: #e6e6e8;
  --control-hover: #f4f4f5;
  --get: #1d7a2e;
  --get-fill: #d9f8cf;
  --post: #0f6ea8;
  --post-fill: #d3effb;
  --ok: #128a3e;
  --running: #2a6df0;
  --cache: #1f9a44;
  --database: #1f9a44;
  --email: #f0620e;
  --ai: #a23cf0;
  --accent: #f4400f;
  --accent-ink: #fff;
  --presence: #c92a06;
  --comet-head: #f4310c;
  --comet-mid: #ff7a18;
  --comet-tail: #ffc531;
  --focus: #387bff;

  position: relative;
  isolation: isolate;
  width: 100%;
  overflow: clip;
  background: var(--page);
  color: var(--ink);
  font:
    400 14px / 1.4 -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    Inter,
    Roboto,
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -webkit-tap-highlight-color: transparent;
  container-type: inline-size;
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --page: light-dark(#fbfbfb, #0c0c0e);
    --grid: light-dark(#ececed, #1d1d20);
    --grid-text: light-dark(#dcdcde, #333338);
    --window: light-dark(#fff, #151517);
    --window-edge: light-dark(rgb(0 0 0 / 0.07), rgb(255 255 255 / 0.09));
    --window-shadow: light-dark(rgb(20 20 30 / 0.1), rgb(0 0 0 / 0.5));
    --frame-edge: light-dark(#efeff0, #242427);
    --ink: light-dark(#1d1d1f, #ededf0);
    --muted: light-dark(#6d6d73, #a2a2a9);
    --faint: light-dark(#98989e, #76767d);
    --skeleton: light-dark(#f2f2f3, #212124);
    --photo: light-dark(#f4f4f5, #1e1e21);
    --solid: light-dark(#1d1d1f, #ededf0);
    --solid-ink: light-dark(#fff, #151517);
    --control-edge: light-dark(#e6e6e8, #2c2c30);
    --control-hover: light-dark(#f4f4f5, #232326);
    --get: light-dark(#1d7a2e, #84e48f);
    --get-fill: light-dark(#d9f8cf, #16361c);
    --post: light-dark(#0f6ea8, #86d3f7);
    --post-fill: light-dark(#d3effb, #123246);
    --ok: light-dark(#128a3e, #4fd47e);
    --running: light-dark(#2a6df0, #7ba7ff);
    --cache: light-dark(#1f9a44, #4fd47e);
    --database: light-dark(#1f9a44, #4fd47e);
    --email: light-dark(#f0620e, #ff9150);
    --ai: light-dark(#a23cf0, #c78bff);
    --presence: light-dark(#c92a06, #ff7a55);
  }
}
.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;
}

:where(.root) :where(p, h2, h3, ul) {
  margin: 0;
  padding: 0;
}
:where(.root) :where(ul) {
  list-style: none;
}
:where(.root) :where(button) {
  border: 0;
  background: none;
  color: inherit;
  font: inherit;
  cursor: pointer;
}
.root button:focus-visible,
.hit:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}
.root svg {
  display: block;
}

/* The stage: its layout is fixed, the zoom fits it to the container. */
.stage {
  --design: 872;
  --store-left: 287px;
  --store-top: 300px;
  position: relative;
  width: 872px;
  height: 694px;
  zoom: tan(atan2(100cqw, 872px));
}

.backdrop,
.circuit {
  position: absolute;
  inset: 0;
  z-index: 0;
  width: 100%;
  height: 100%;
  overflow: visible;
  pointer-events: none;
}
.backdrop {
  fill: none;
  stroke: var(--grid);
  stroke-width: 1;
}
.backdrop text {
  fill: var(--grid-text);
  stroke: none;
  font-size: 11px;
}
.forNarrow {
  display: none;
}
.line {
  fill: none;
  stroke: var(--grid);
  stroke-width: 1;
}

/* The comet: long pale tail, short hot head. */
.comet path {
  fill: none;
  stroke-linecap: butt;
  stroke-dashoffset: 2000;
}
.comet [data-stroke='0'] {
  stroke: var(--comet-tail);
  stroke-width: 1;
  opacity: 0.8;
}
.comet [data-stroke='1'] {
  stroke: var(--comet-mid);
  stroke-width: 1.4;
}
.comet [data-stroke='2'] {
  stroke: var(--comet-head);
  stroke-width: 1.8;
}
.comet [data-stroke='3'] {
  stroke: var(--comet-head);
  stroke-width: 2.4;
}
.spark {
  fill: none;
  stroke: var(--comet-mid);
  stroke-width: 1.4;
  stroke-dasharray: 1 5;
  stroke-linecap: round;
  opacity: 0;
}

.node {
  position: absolute;
  top: 392px;
  left: 816px;
  z-index: 0;
  width: 24px;
  height: 24px;
  color: var(--faint);
  transition: color 0.2s ease;
}
.node[data-busy='true'] {
  color: var(--muted);
}
.node span {
  position: absolute;
  inset: 0;
  opacity: 0;
  scale: 0.7;
  transition:
    opacity 0.24s ease,
    scale 0.3s cubic-bezier(0.3, 1.4, 0.6, 1);
}
.node span[data-on='true'] {
  opacity: 1;
  scale: 1;
}
.node svg {
  width: 100%;
  height: 100%;
}

/* Windows. */
.log,
.store {
  position: absolute;
  display: flex;
  flex-direction: column;
  overflow: clip;
  background: var(--window);
  box-shadow:
    inset 0 0 0 1px var(--window-edge),
    0 18px 44px -8px var(--window-shadow);
}
.log {
  top: 60px;
  left: 47px;
  z-index: 1;
  width: 560px;
  height: 481px;
}
.store {
  top: var(--store-top);
  left: var(--store-left);
  z-index: 2;
  width: 480px;
  height: 361px;
}
.bar {
  position: relative;
  display: flex;
  flex: none;
  align-items: center;
  height: 38px;
  padding-inline: 16px;
}
.lights {
  display: flex;
  gap: 5px;
}
.lights i {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #ee4614;
}
.lights i:nth-child(2) {
  background: #f09a1a;
}
.lights i:nth-child(3) {
  background: #1fa64a;
}
.barMiddle {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-width: 0;
  padding-left: 20px;
}
.address {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 22px;
  padding-inline: 10px;
  border-radius: 11px;
  box-shadow: inset 0 0 0 1px var(--frame-edge);
  font-size: 11.5px;
  white-space: nowrap;
}
.addressMark {
  width: 14px;
  height: 14px;
}
.presence {
  display: inline-flex;
  flex: none;
  align-items: center;
  gap: 7px;
  height: 22px;
  margin-left: auto;
  padding-inline: 8px;
  border-radius: 11px;
  box-shadow: inset 0 0 0 1px var(--frame-edge);
  color: var(--presence);
  font-size: 11.5px;
  white-space: nowrap;
}
.presence i {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background: currentcolor;
}
.store .barMiddle .address {
  margin-left: auto;
}
.frame {
  flex: 1;
  min-height: 0;
  margin: 0 8px 8px;
  overflow: clip;
  box-shadow: inset 0 0 0 1px var(--frame-edge);
}
.storeDot {
  display: inline-grid;
  flex: none;
  place-items: center;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: var(--solid);
  color: var(--solid-ink);
}
.storeDot svg {
  width: 9px;
  height: 9px;
}

/* The log. */
.crumbs {
  display: flex;
  align-items: center;
  gap: 8px;
  height: 56px;
  padding-inline: 20px 16px;
  box-shadow: inset 0 -1px 0 var(--frame-edge);
  font-size: 14px;
}
.crumbs .storeDot {
  width: 20px;
  height: 20px;
  margin-left: 2px;
}
.crumbs .storeDot svg {
  width: 12px;
  height: 12px;
}
.crumbMark {
  width: 16px;
  height: 16px;
}
.crumbChevron {
  width: 11px;
  height: 11px;
  margin-inline: 4px;
  color: var(--faint);
}
.activity {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  height: 24px;
  margin-left: auto;
  padding-inline: 8px 10px;
  border-radius: 12px;
  box-shadow: inset 0 0 0 1px var(--frame-edge);
  color: var(--muted);
  font-size: 12.5px;
}
.activity svg {
  width: 13px;
  height: 13px;
}
.table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}
.colWhere {
  width: 122px;
}
.colStatus {
  width: 118px;
}
.table th {
  height: 42px;
  padding: 0 0 0 20px;
  box-shadow: inset 0 -1px 0 var(--frame-edge);
  color: var(--muted);
  font-size: 13.5px;
  font-weight: 400;
  text-align: left;
}
.table th + th,
.table td + td {
  padding-left: 0;
}
.table td {
  padding: 0;
  vertical-align: top;
}
.row {
  height: 118px;
  box-shadow: inset 0 -1px 0 var(--frame-edge);
  animation: rise 0.28s ease both;
}
.row td {
  padding: 20px 0 0;
  font-size: 13.5px;
  line-height: 20px;
}
.row td:first-child {
  padding-left: 20px;
}
.request {
  position: relative;
  display: flex;
  gap: 15px;
}
.kind {
  flex: none;
  width: 15px;
  height: 15px;
  margin-top: 3px;
  color: var(--muted);
}
.tree {
  position: absolute;
  top: 25px;
  left: 7px;
  width: 12px;
  height: 36px;
  border-bottom-left-radius: 6px;
  box-shadow:
    inset 1px 0 0 var(--control-edge),
    inset 0 -1px 0 var(--control-edge);
}
.requestText {
  min-width: 0;
  padding-right: 10px;
}
.path {
  display: flex;
  align-items: center;
  gap: 5px;
  white-space: nowrap;
}
.method {
  padding: 0 8px;
  border-radius: 9px;
  background: var(--get-fill);
  color: var(--get);
  font:
    500 11px / 18px ui-monospace,
    SFMono-Regular,
    Menlo,
    monospace;
}
.method[data-method='POST'] {
  background: var(--post-fill);
  color: var(--post);
}
.note {
  overflow: hidden;
  color: var(--muted);
  text-overflow: ellipsis;
  white-space: nowrap;
}
.chips {
  display: flex;
  gap: 18px;
  margin-top: 16px;
  animation: rise 0.3s 0.08s ease both;
}
.chip {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  height: 22px;
  padding-inline: 10px 12px;
  border-radius: 11px;
  box-shadow: inset 0 0 0 1px var(--frame-edge);
  font-size: 11.5px;
}
.chip svg {
  width: 13px;
  height: 13px;
}
.chip[data-service='cache'] svg {
  color: var(--cache);
}
.chip[data-service='database'] svg {
  color: var(--database);
}
.chip[data-service='email'] svg {
  color: var(--email);
}
.chip[data-service='ai'] svg {
  color: var(--ai);
}
.chip + .chip::before {
  content: '';
  position: absolute;
  top: 50%;
  left: -14px;
  width: 10px;
  height: 1px;
  background: var(--control-edge);
}
.status p {
  display: flex;
  align-items: center;
  gap: 12px;
}
.ok {
  color: var(--ok);
  animation: fade 0.24s ease both;
}
.ok svg {
  flex: none;
  width: 13px;
  height: 13px;
}
.time {
  padding-left: 25px;
  animation: fade 0.3s 0.1s ease both;
}
.running {
  color: var(--running);
  animation: fade 0.2s ease both;
}
.spinner {
  flex: none;
  width: 12px;
  height: 12px;
  border: 1.4px solid transparent;
  border-top-color: currentcolor;
  border-right-color: currentcolor;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}
.skeleton td {
  position: relative;
  height: 118px;
  box-shadow: inset 0 -1px 0 var(--frame-edge);
}
.skeleton i {
  position: absolute;
  border-radius: 7px;
  background: var(--skeleton);
}
.skeleton i:nth-child(1) {
  top: 22px;
  left: 20px;
  width: 15px;
  height: 15px;
  border-radius: 50%;
}
.skeleton i:nth-child(2) {
  top: 22px;
  left: 50px;
  width: 92px;
  height: 14px;
}
.skeleton i:nth-child(3) {
  top: 44px;
  left: 50px;
  width: 200px;
  height: 10px;
}
.skeleton i:nth-child(4) {
  top: 72px;
  left: 50px;
  width: 104px;
  height: 22px;
}
.skeleton[data-active='true'] td {
  animation: fade 0.1s ease both;
}

/* The store. */
.nav {
  display: flex;
  align-items: center;
  height: 46px;
  padding-inline: 20px 18px;
  box-shadow: inset 0 -1px 0 var(--frame-edge);
  font-size: 10.5px;
}
.root .brand {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  letter-spacing: 0.04em;
}
.brand svg {
  width: 13px;
  height: 13px;
}
.links {
  display: flex;
  gap: 12px;
  margin-left: 40px;
}
.root .links button {
  padding: 4px 0;
  color: var(--faint);
  transition: color 0.2s ease;
}
.root .links button:hover,
.root .links button[aria-current] {
  color: var(--ink);
}
.bagCount {
  margin-left: auto;
  color: var(--muted);
  font-variant-numeric: tabular-nums;
}
.bagCount[data-bump='true'] {
  color: var(--ink);
}

/* The product page: the text comes in line by line while the product rises. */
.page {
  position: relative;
  height: 269px;
}
.photo {
  position: absolute;
  top: 16px;
  left: 24px;
  width: 192px;
  height: 223px;
  background: var(--photo);
}
.details {
  position: absolute;
  top: 18px;
  left: 240px;
  width: 200px;
}
.details > * {
  transition:
    opacity 0.32s ease calc(var(--i) * 32ms),
    translate 0.32s ease calc(var(--i) * 32ms);
}
.page[data-in='false'] .details > * {
  opacity: 0;
  translate: 0 4px;
  transition-duration: 0.14s;
  transition-delay: 0s;
}
.crumb {
  color: var(--muted);
  font-size: 10px;
}
.title {
  margin-top: 5px;
  outline: none;
  font-size: 19.5px;
  font-weight: 500;
  letter-spacing: -0.012em;
  line-height: 1.2;
}
.price {
  margin-top: 7px;
  font-size: 12.5px;
}
.price span {
  color: var(--muted);
  font-size: 10px;
}
.colour {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 14px;
  font-size: 10.5px;
}
.colour i {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
.sizes {
  display: flex;
  gap: 6px;
  margin-top: 11px;
}
.root .size {
  flex: 1 1 0;
  height: 25px;
  padding: 0;
  box-shadow: inset 0 0 0 1px var(--control-edge);
  font-size: 10px;
  transition:
    background 0.15s ease,
    color 0.15s ease;
}
.root .size:hover {
  background: var(--control-hover);
}
.root .size[aria-checked='true'] {
  box-shadow: inset 0 0 0 1px var(--ink);
}
.root .add,
.root .notify {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 32px;
  padding-inline: 12px 13px;
  font-size: 12px;
}
.add svg,
.notify svg {
  width: 14px;
  height: 14px;
}
.root .add {
  margin-top: 8px;
  background: var(--solid);
  color: var(--solid-ink);
}
.root .add:hover {
  opacity: 0.88;
}
.root .notify {
  margin-top: 8px;
  box-shadow: inset 0 0 0 1px var(--control-edge);
}
.root .notify:hover {
  background: var(--control-hover);
}
.root .notify[data-on='true'] {
  cursor: default;
  background: none;
}
.notify[data-on='true'] svg {
  color: var(--ok);
}

/* The catalog. */
.catalog {
  padding: 24px 24px 0;
}
.catalogTitle {
  font-size: 12.5px;
  font-weight: 500;
}
.catalogTitle span {
  color: var(--faint);
  font-weight: 400;
}
.cards {
  display: grid;
  grid-template-columns: repeat(3, 132px);
  gap: 12px;
  margin-top: 12px;
}
.cards li {
  transition: opacity 0.38s ease calc(var(--i) * 130ms);
}
.catalog[data-in='false'] .cards li {
  opacity: 0;
  transition: none;
}
.root .card {
  display: block;
  width: 100%;
  padding: 0;
  text-align: left;
  transition: opacity 0.18s ease;
}
.root .card[data-leaving='true'] {
  opacity: 0.25;
}
.cardPhoto {
  position: relative;
  display: block;
  height: 150px;
  overflow: hidden;
  background: var(--photo);
}
.cardPhoto img,
.cardPhoto svg {
  position: absolute;
  top: 0;
  left: 50%;
  width: 150px;
  height: 150px;
  max-width: none;
  translate: -50% 0;
  transition: scale 0.24s cubic-bezier(0.2, 0.8, 0.2, 1);
  user-select: none;
}
.root .card:hover img {
  scale: 1.04;
}
.cardName {
  display: block;
  margin-top: 8px;
  font-size: 10.5px;
  font-weight: 500;
}
.cardPrice {
  display: block;
  color: var(--muted);
  font-size: 10px;
}

/* The product: its canvas hangs over the store's edge, and only the middle takes the pointer. */
.product {
  position: absolute;
  top: calc(var(--store-top) + 40px);
  left: calc(var(--store-left) - 150px);
  z-index: 3;
  width: 420px;
  height: 420px;
  pointer-events: none;
}
.product[data-hidden] {
  visibility: hidden;
}
.render,
.still {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
}
.still {
  scale: 0.74;
}
.hit {
  position: absolute;
  top: 80px;
  left: 90px;
  width: 240px;
  height: 260px;
  cursor: grab;
  pointer-events: auto;
  touch-action: pan-y;
}
.hit:active {
  cursor: grabbing;
}

/* The named cursor. */
.cursor {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 4;
  display: block;
  width: 16px;
  height: 16px;
  color: var(--accent);
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.3s ease;
  will-change: transform;
}
.cursorArrow {
  width: 16px;
  height: 16px;
}
.cursorLabel {
  position: absolute;
  top: 11px;
  left: 10px;
  padding: 3px 11px 4px;
  border-radius: 13px;
  background: var(--accent);
  color: var(--accent-ink);
  font-size: 12.5px;
  font-weight: 500;
  white-space: nowrap;
  box-shadow: 0 3px 8px rgb(220 50 0 / 0.3);
}

/* Under the stage: outside the zoom, in its own size. */
.hero {
  position: relative;
  z-index: 2;
  padding: 2.4cqw 6cqw 8cqw 19.2cqw;
  pointer-events: none;
}
.tag {
  display: flex;
  gap: 4px;
  align-items: stretch;
  height: 16px;
}
.tag span {
  padding-inline: 6px;
  background: var(--accent);
  color: var(--accent-ink);
  font:
    500 11px / 16px ui-monospace,
    SFMono-Regular,
    Menlo,
    monospace;
  letter-spacing: 0.08em;
  text-transform: uppercase;
}
.tag i {
  width: 2px;
  background: var(--comet-mid);
}
.tag i + i {
  align-self: center;
  height: 8px;
  margin-left: 2px;
  background: var(--comet-tail);
}
.headline {
  margin-top: 26px;
  font-size: clamp(25px, 3.7cqw, 33px);
  font-weight: 500;
  letter-spacing: -0.022em;
  line-height: 1.1;
  text-wrap: balance;
}
.lead {
  max-width: 33em;
  margin-top: 16px;
  color: var(--muted);
  font-size: clamp(15px, 1.85cqw, 16px);
  line-height: 1.5;
  pointer-events: auto;
}
.term {
  color: var(--ink);
  text-decoration: underline dotted 1.5px;
  text-decoration-color: var(--faint);
  text-underline-offset: 4px;
}

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

@keyframes rise {
  from {
    opacity: 0;
    translate: 0 2px;
  }
}
@keyframes fade {
  from {
    opacity: 0;
  }
}
@keyframes spin {
  to {
    rotate: 360deg;
  }
}

/* A narrow container: the windows stack with a smaller overlap, on a 500 px design width. */
@container (max-width: 620px) {
  .stage {
    --design: 500;
    --store-left: 28px;
    --store-top: 268px;
    width: 500px;
    height: 636px;
    zoom: tan(atan2(100cqw, 500px));
  }
  .forWide {
    display: none;
  }
  .forNarrow {
    display: revert;
  }
  .log {
    top: 16px;
    left: 4px;
    width: 440px;
    height: 280px;
  }
  .store {
    width: 472px;
  }
  .node {
    top: 118px;
    left: 462px;
    width: 20px;
    height: 20px;
  }
  .colWhere {
    width: 92px;
  }
  .colStatus {
    width: 96px;
  }
  .activity {
    display: none;
  }
  .nav,
  .links,
  .crumb,
  .colour,
  .root .size,
  .cardName,
  .cardPrice {
    font-size: 12px;
  }
  .address,
  .presence {
    font-size: 11px;
  }
  .hero {
    padding: 22px 16px 32px;
  }
}

@media (prefers-reduced-motion: reduce) {
  .row,
  .chips,
  .ok,
  .time,
  .running,
  .skeleton[data-active='true'] td {
    animation: none;
  }
  .spinner {
    animation-duration: 2s;
  }
  .details > *,
  .cards li,
  .node span,
  .root .card,
  .cardPhoto img {
    transition: none;
  }
}
```

### request-trace/products.ts

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

/*
 * The store's catalog and the requests each action sends. Plain data: the store, the dashboard and
 * the renderer all read from here, so a product's name, its colour and its model stay together.
 */

export type ProductId = 'flask' | 'mug' | 'lantern';

export type Product = {
  id: ProductId;
  name: string;
  /** The word used in a request's description: “Turn the flask into 3D”. */
  noun: string;
  category: 'Drinkware' | 'Lighting';
  price: number;
  colour: string;
  /** The colour's swatch, in the store's product section. */
  swatch: string;
  sizes: string[];
};

export const PRODUCTS: Product[] = [
  {
    id: 'mug',
    name: 'The Camp Mug',
    noun: 'mug',
    category: 'Drinkware',
    price: 28,
    colour: 'Saffron Enamel',
    swatch: '#f7ae00',
    sizes: ['250 ml', '350 ml', '500 ml'],
  },
  {
    id: 'flask',
    name: 'The Ridge Flask',
    noun: 'flask',
    category: 'Drinkware',
    price: 54,
    colour: 'Flare Orange',
    swatch: '#f4500f',
    sizes: ['0.35 L', '0.5 L', '0.75 L', '1 L'],
  },
  {
    id: 'lantern',
    name: 'The Hut Lantern',
    noun: 'lantern',
    category: 'Lighting',
    price: 86,
    colour: 'Spruce Green',
    swatch: '#12634a',
    sizes: ['Small', 'Medium', 'Large'],
  },
];

export const product = (id: ProductId) =>
  PRODUCTS.find((item) => item.id === id) ?? (PRODUCTS[0] as Product);

export type ServiceId = 'cache' | 'database' | 'email' | 'ai';

export const SERVICE_NAMES: Record<ServiceId, string> = {
  cache: 'Cache',
  database: 'Database',
  email: 'Email',
  ai: 'AI',
};

export type RequestKind = 'page' | 'catalog' | 'model' | 'stock' | 'bag' | 'notify';

export type TraceRequest = {
  kind: RequestKind;
  method: 'GET' | 'POST';
  path: string;
  /** The line under the path. */
  note: string;
  /** The chips under the row. */
  services: ServiceId[];
  /** The time the row reports, in ms. */
  ms: number;
};

/** What a request's own place on the circuit shows: the node's icon while it travels. */
export const nodeIconFor = (request: TraceRequest): 'database' | 'envelope' | 'box' =>
  request.kind === 'notify' ? 'envelope' : request.kind === 'model' ? 'box' : 'database';

/** The rows the store sends, before any `requests` overrides and the small spread in `ms`. */
export function baseRequest(kind: RequestKind, item: Product, filter?: string): TraceRequest {
  switch (kind) {
    case 'page':
      return {
        kind,
        method: 'GET',
        path: `/products/${item.id}`,
        note: 'Load the product · via Functions',
        services: ['cache', 'database'],
        ms: 38,
      };
    case 'catalog':
      return {
        kind,
        method: 'GET',
        path: filter ? `/api/catalog?c=${filter.toLowerCase()}` : '/api/catalog',
        note: 'Load the catalog · via Functions',
        services: ['cache', 'database'],
        ms: 41,
      };
    case 'model':
      return {
        kind,
        method: 'POST',
        path: '/api/3d',
        note: `Turn the ${item.noun} into 3D · via Functions`,
        services: ['ai'],
        ms: 2300,
      };
    case 'stock':
      return {
        kind,
        method: 'GET',
        path: `/api/stock/${item.id}`,
        note: 'Check this size · via Functions',
        services: ['cache'],
        ms: 12,
      };
    case 'bag':
      return {
        kind,
        method: 'POST',
        path: '/api/bag',
        note: 'Save the bag · via Functions',
        services: ['cache', 'database'],
        ms: 46,
      };
    case 'notify':
      return {
        kind,
        method: 'POST',
        path: '/api/notify',
        note: 'Send the restock alert · via Functions',
        services: ['database', 'email'],
        ms: 52,
      };
  }
}
```

### request-trace/product-view.tsx

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

'use client';

import {
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
  type KeyboardEvent,
  type PointerEvent,
  type Ref,
} from 'react';
import { modelOf } from './meshes';
import { ProductStill } from './product-still';
import { product as productOf, type ProductId } from './products';
import { onStudioChange, release, renderTo, retain, studioBroken, type Pose } from './studio';

/*
 * The product standing out of the page: a 2D canvas the shared studio paints into, only when
 * something has changed. It moves by flights (rising out of the page, shrinking back into a
 * catalog card), by dragging, and by the inertia a drag leaves. Off screen it draws nothing and
 * gives its bitmap back; where WebGL can't be had it shows the drawn still instead.
 */

export type ProductViewHandle = {
  /** Shows a product at once at `from`, or at rest. */
  set: (id: ProductId, from?: Partial<Pose>) => void;
  /** Flies from the current pose to `to`, over `ms`; `to` left out means the rest pose. */
  fly: (to: Partial<Pose>, ms: number, done?: () => void) => void;
  /** Turns by `angle` over `ms`, for the demo. */
  spin: (angle: number, ms: number) => void;
  rest: () => Pose;
};

/** Device pixels per CSS pixel, at most. */
const MAX_DPR = 2;
/** Inertia dies away by this much per second. */
const FRICTION = 3.2;
const TURN_PER_PX = 0.012;

const restPose = (id: ProductId): Pose => {
  const model = modelOf(id);
  return { yaw: model.yaw, pitch: model.pitch, scale: 1, x: 0, y: 0 };
};

const easeOut = (t: number) => 1 - (1 - t) ** 3.2;

export function ProductView({
  ref,
  defaultProduct,
  className,
  canvasClass,
  hitClass,
  stillClass,
  hidden,
}: {
  ref?: Ref<ProductViewHandle>;
  defaultProduct: ProductId;
  className?: string;
  canvasClass?: string;
  hitClass?: string;
  stillClass?: string;
  hidden?: boolean;
}) {
  const canvas = useRef<HTMLCanvasElement>(null);
  const state = useRef({
    id: defaultProduct,
    pose: restPose(defaultProduct),
    flight: null as null | {
      from: Pose;
      to: Pose;
      start: number;
      ms: number;
      done?: () => void;
    },
    velocity: 0,
    frame: 0,
    last: 0,
    onScreen: false,
    drag: null as null | { x: number; y: number; time: number },
    spin: null as null | { from: number; by: number; start: number; ms: number },
  });
  const [still, setStill] = useState(false);
  const [shown, setShown] = useState(defaultProduct);
  const [angle, setAngle] = useState(0);

  const paint = useRef(() => {});
  const schedule = useRef(() => {});

  useEffect(() => {
    const element = canvas.current;
    if (!element) return;
    const context = element.getContext('2d');
    const s = state.current;
    const fit = () => {
      const box = element.getBoundingClientRect();
      const dpr = Math.min(window.devicePixelRatio || 1, MAX_DPR);
      const width = Math.min(Math.round(box.width * dpr), 1200);
      const height = Math.min(Math.round(box.height * dpr), 1200);
      if (width > 0 && height > 0 && (element.width !== width || element.height !== height)) {
        element.width = width;
        element.height = height;
      }
    };

    paint.current = () => {
      if (!s.onScreen || !context) return;
      fit();
      if (!element.width || studioBroken()) return;
      const ok = renderTo(context, s.id, s.pose);
      setStill(!ok);
    };

    const tick = (now: number) => {
      s.frame = 0;
      const dt = Math.min((now - (s.last || now)) / 1000, 0.05);
      s.last = now;
      let moving = false;
      if (s.flight) {
        const { from, to, start, ms, done } = s.flight;
        const t = Math.min((now - start) / ms, 1);
        const k = easeOut(t);
        s.pose = {
          yaw: from.yaw + (to.yaw - from.yaw) * k,
          pitch: from.pitch + (to.pitch - from.pitch) * k,
          scale: from.scale + (to.scale - from.scale) * k,
          x: from.x + (to.x - from.x) * k,
          y: from.y + (to.y - from.y) * k,
        };
        if (t < 1) moving = true;
        else {
          s.flight = null;
          done?.();
        }
      }
      if (s.spin) {
        const t = Math.min((now - s.spin.start) / s.spin.ms, 1);
        const k = t * t * (3 - 2 * t);
        s.pose.yaw = s.spin.from + s.spin.by * k;
        if (t < 1) moving = true;
        else s.spin = null;
      }
      if (!s.drag && Math.abs(s.velocity) > 0.02) {
        s.pose.yaw += s.velocity * dt;
        s.velocity *= Math.exp(-FRICTION * dt);
        moving = true;
      } else if (!s.drag) s.velocity = 0;
      paint.current();
      if (moving && s.onScreen) schedule.current();
      else {
        s.last = 0;
        setAngle(Math.round(((((s.pose.yaw * 180) / Math.PI) % 360) + 360) % 360));
      }
    };
    schedule.current = () => {
      if (!s.frame) s.frame = requestAnimationFrame(tick);
    };

    let holding = false;
    const observer = new IntersectionObserver(
      ([entry]) => {
        s.onScreen = entry?.isIntersecting ?? false;
        if (s.onScreen) {
          if (!holding) {
            holding = true;
            setStill(!retain());
          }
          schedule.current();
        } else {
          if (holding) {
            holding = false;
            release();
          }
          // Off screen: no flight is worth finishing, and the bitmap goes back.
          if (s.flight) {
            s.pose = { ...s.flight.to };
            const done = s.flight.done;
            s.flight = null;
            done?.();
          }
          s.spin = null;
          s.velocity = 0;
          element.width = 0;
          element.height = 0;
        }
      },
      { rootMargin: '120px' },
    );
    observer.observe(element);

    const resize = new ResizeObserver(() => schedule.current());
    resize.observe(element);

    const stopListening = onStudioChange(() => {
      setStill(studioBroken());
      if (!studioBroken()) schedule.current();
    });

    return () => {
      observer.disconnect();
      resize.disconnect();
      stopListening();
      cancelAnimationFrame(s.frame);
      s.frame = 0;
      if (holding) release();
    };
  }, []);

  useImperativeHandle(
    ref,
    () => ({
      set: (id, from) => {
        const s = state.current;
        s.id = id;
        s.flight = null;
        s.spin = null;
        s.velocity = 0;
        s.pose = { ...restPose(id), ...from };
        setShown(id);
        schedule.current();
      },
      fly: (to, ms, done) => {
        const s = state.current;
        s.velocity = 0;
        s.spin = null;
        s.flight = {
          from: { ...s.pose },
          to: { ...restPose(s.id), ...to },
          start: performance.now(),
          ms,
          done,
        };
        schedule.current();
      },
      spin: (by, ms) => {
        const s = state.current;
        s.flight = null;
        s.spin = { from: s.pose.yaw, by, start: performance.now(), ms };
        schedule.current();
      },
      rest: () => restPose(state.current.id),
    }),
    [],
  );

  const reduced = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
    const s = state.current;
    event.currentTarget.setPointerCapture(event.pointerId);
    s.flight = null;
    s.spin = null;
    s.velocity = 0;
    s.drag = { x: event.clientX, y: event.clientY, time: event.timeStamp };
  };
  const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
    const s = state.current;
    if (!s.drag) return;
    const dx = event.clientX - s.drag.x;
    const dy = event.clientY - s.drag.y;
    const dt = Math.max((event.timeStamp - s.drag.time) / 1000, 0.001);
    s.pose.yaw += dx * TURN_PER_PX;
    s.pose.pitch = Math.max(-0.5, Math.min(0.8, s.pose.pitch + dy * TURN_PER_PX * 0.6));
    s.velocity = s.velocity * 0.5 + ((dx * TURN_PER_PX) / dt) * 0.5;
    s.drag = { x: event.clientX, y: event.clientY, time: event.timeStamp };
    schedule.current();
  };
  const onPointerEnd = (event: PointerEvent<HTMLDivElement>) => {
    const s = state.current;
    if (!s.drag) return;
    // A pause before letting go leaves nothing to carry on.
    if (event.timeStamp - s.drag.time > 80 || reduced()) s.velocity = 0;
    s.velocity = Math.max(-9, Math.min(9, s.velocity));
    s.drag = null;
    s.last = 0;
    schedule.current();
  };
  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    const s = state.current;
    const step = event.shiftKey ? Math.PI / 4 : Math.PI / 12;
    if (event.key === 'ArrowLeft') s.pose.yaw -= step;
    else if (event.key === 'ArrowRight') s.pose.yaw += step;
    else if (event.key === 'ArrowUp') s.pose.pitch = Math.max(-0.5, s.pose.pitch - 0.1);
    else if (event.key === 'ArrowDown') s.pose.pitch = Math.min(0.8, s.pose.pitch + 0.1);
    else if (event.key === 'Home') s.pose = restPose(s.id);
    else return;
    event.preventDefault();
    s.flight = null;
    s.velocity = 0;
    schedule.current();
  };

  return (
    <div className={className} data-hidden={hidden || undefined} aria-hidden={hidden || undefined}>
      <canvas ref={canvas} className={canvasClass} data-part="render" aria-hidden="true" />
      {still && <ProductStill id={shown} className={stillClass} />}
      {!hidden && (
        <div
          className={hitClass}
          data-part="viewer"
          role="slider"
          tabIndex={0}
          aria-label={`Turn ${productOf(shown).name}`}
          aria-valuemin={0}
          aria-valuemax={359}
          aria-valuenow={angle}
          aria-valuetext={`${angle} degrees`}
          onPointerDown={still ? undefined : onPointerDown}
          onPointerMove={still ? undefined : onPointerMove}
          onPointerUp={onPointerEnd}
          onPointerCancel={onPointerEnd}
          onKeyDown={still ? undefined : onKeyDown}
        />
      )}
    </div>
  );
}
```

### request-trace/studio.ts

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

import { modelOf, type Material, type Part } from './meshes';
import type { ProductId } from './products';

/*
 * The photo studio: one WebGL context for the whole page, however many of these components are
 * mounted. It lives on a canvas that is never in the document; each view asks for a frame and
 * copies it to its own 2D canvas, so a still costs one 2D bitmap and nothing while it rests.
 * When no view is on screen the context is given back to the browser.
 *
 * There are no lights to speak of: a product is lit by what it reflects. `studio()` paints a room
 * in reflection directions, a pale cove, a big softbox up on the left, a strip on the right and a
 * dim floor, and the surfaces read it sharp or blurred by their roughness. So enamel shows a clean
 * window, powder coat a broad sheen, and steel the whole room. The shadow is two soft blobs on the
 * floor; contact shade is stored per vertex by the meshes.
 */

export type Pose = {
  yaw: number;
  pitch: number;
  /** Relative to the product's size at rest. */
  scale: number;
  /** Offset from the canvas's centre, in shares of its size. */
  x: number;
  y: number;
};

const VERTEX = `
attribute vec3 aPos;
attribute vec3 aNor;
attribute float aAo;
uniform mat4 uProj;
uniform mat4 uModel;
varying vec3 vWorld;
varying vec3 vNor;
varying vec3 vLocal;
varying float vAo;
void main() {
  vec4 world = uModel * vec4(aPos, 1.0);
  vWorld = world.xyz;
  vNor = mat3(uModel) * aNor;
  vLocal = aPos;
  vAo = aAo;
  gl_Position = uProj * world;
}`;

const FRAGMENT = `
precision highp float;
varying vec3 vWorld;
varying vec3 vNor;
varying vec3 vLocal;
varying float vAo;
uniform mat4 uModel;
uniform vec3 uEye;
uniform vec3 uColour;
uniform float uMetal;
uniform float uRough;
uniform float uPeel;
uniform float uFleck;
uniform float uRibs;
uniform float uGlow;
uniform float uGlass;
uniform vec4 uLabel;
uniform vec3 uInk;
uniform sampler2D uMark;

float hash(vec3 p) {
  p = fract(p * 0.3183099 + 0.1);
  p *= 17.0;
  return fract(p.x * p.y * p.z * (p.x + p.y + p.z));
}
float noise(vec3 p) {
  vec3 i = floor(p);
  vec3 f = fract(p);
  f = f * f * (3.0 - 2.0 * f);
  return mix(
    mix(mix(hash(i), hash(i + vec3(1, 0, 0)), f.x), mix(hash(i + vec3(0, 1, 0)), hash(i + vec3(1, 1, 0)), f.x), f.y),
    mix(mix(hash(i + vec3(0, 0, 1)), hash(i + vec3(1, 0, 1)), f.x), mix(hash(i + vec3(0, 1, 1)), hash(i + vec3(1, 1, 1)), f.x), f.y),
    f.z);
}
float softbox(vec3 r, vec3 d, vec2 size, float soft) {
  float k = dot(r, d);
  if (k <= 0.0) return 0.0;
  vec3 t = normalize(cross(vec3(0.0, 1.0, 0.0), d));
  vec3 b = cross(d, t);
  vec2 p = vec2(dot(r, t), dot(r, b)) / k;
  return smoothstep(size.x + soft, size.x - soft, abs(p.x)) * smoothstep(size.y + soft, size.y - soft, abs(p.y));
}
vec3 studio(vec3 r, float rough) {
  float soft = 0.03 + rough * 1.1;
  float up = r.y * 0.5 + 0.5;
  vec3 room = mix(vec3(0.16, 0.155, 0.15), vec3(0.62, 0.63, 0.65), smoothstep(0.26, 0.8, up));
  room += vec3(0.25) * smoothstep(0.75, 1.0, up);
  room += vec3(3.4, 3.3, 3.15) * softbox(r, normalize(vec3(-0.62, 0.48, 0.62)), vec2(0.34, 0.62), soft);
  room += vec3(1.5, 1.55, 1.7) * softbox(r, normalize(vec3(0.96, 0.08, 0.2)), vec2(0.12, 0.95), soft);
  room += vec3(0.9) * softbox(r, normalize(vec3(-0.15, 0.2, -0.97)), vec2(1.0, 0.7), soft);
  return room;
}
vec3 linear(vec3 c) { return pow(c, vec3(2.2)); }

void main() {
  vec3 N = normalize(vNor);
  vec3 V = normalize(uEye - vWorld);
  if (dot(N, V) < 0.0 && uGlass > 0.5) N = -N;
  mat3 turn = mat3(uModel);
  float angle = atan(vLocal.x, vLocal.z);
  float scaleBack = 1.0 / length(turn[0]);

  // Knurling, and the coat's fine pebble: they only tilt the normal.
  if (uRibs > 0.0) {
    vec3 around = turn * vec3(cos(angle), 0.0, -sin(angle)) * scaleBack;
    N = normalize(N + around * sin(angle * uRibs) * 0.3);
  }
  if (uPeel > 0.0) {
    vec3 p = vLocal * 340.0;
    float e = 0.7;
    float n0 = noise(p);
    vec3 g = vec3(noise(p + vec3(e, 0, 0)) - n0, noise(p + vec3(0, e, 0)) - n0, noise(p + vec3(0, 0, e)) - n0);
    N = normalize(N + turn * g * scaleBack * 0.13 * uPeel);
  }

  vec3 base = linear(uColour);
  float rough = uRough;
  float metal = uMetal;

  if (uFleck > 0.0) {
    vec3 q = mat3(0.8, 0.36, -0.48, -0.6, 0.48, -0.64, 0.0, 0.8, 0.6) * vLocal;
    float spots = smoothstep(0.74, 0.8, noise(q * 310.0)) * smoothstep(0.34, 0.62, noise(q * 21.0 + 3.0));
    base = mix(base, base * vec3(0.22, 0.18, 0.16), spots * uFleck);
  }
  if (uLabel.x > 0.0) {
    vec2 uv = vec2(angle / uLabel.x + 0.5, (vLocal.y - uLabel.y) / (uLabel.z - uLabel.y));
    if (uv.x > 0.0 && uv.x < 1.0 && uv.y > 0.0 && uv.y < 1.0) {
      float ink = texture2D(uMark, vec2(uv.x, 1.0 - uv.y)).a;
      base = mix(base, linear(uInk), ink);
      rough = mix(rough, 0.32, ink);
    }
  }

  float nv = max(dot(N, V), 0.001);
  vec3 R = reflect(-V, N);
  vec3 f0 = mix(vec3(0.045), base, metal);
  float fres = pow(1.0 - nv, 5.0);
  vec3 F = f0 + (max(vec3(1.0 - rough), f0) - f0) * fres;
  float occlusion = vAo;

  if (uGlow > 0.5) {
    float core = pow(nv, 1.4);
    float height = clamp((vLocal.y - 0.345) / 0.17, 0.0, 1.0);
    vec3 hot = mix(vec3(1.0, 0.97, 0.78), vec3(1.0, 0.5, 0.07), height * 0.9 + (1.0 - core) * 0.5);
    gl_FragColor = vec4(hot * (0.7 + core * 0.45), 1.0);
    return;
  }
  if (uGlass > 0.5) {
    vec3 spec = studio(R, 0.03) * (0.05 + 0.95 * fres);
    float a = clamp(0.035 + 0.6 * fres + dot(spec, vec3(0.33)), 0.0, 0.95);
    vec3 c = spec + vec3(0.92, 0.96, 0.95) * (0.035 + 0.3 * fres);
    c = c / (1.0 + c * 0.35);
    gl_FragColor = vec4(pow(c, vec3(1.0 / 2.2)), a);
    gl_FragColor.rgb *= a;
    return;
  }

  // The light on the matte part of the surface: a sky, the key's wrap, a warm bounce from the floor.
  vec3 keyDir = normalize(vec3(-0.6, 0.62, 0.62));
  float key = clamp(dot(N, keyDir) * 0.66 + 0.34, 0.0, 1.0);
  float fill = clamp(dot(N, vec3(0.8, 0.05, 0.45)) * 0.5 + 0.5, 0.0, 1.0);
  float sky = N.y * 0.5 + 0.5;
  vec3 light = vec3(1.0, 0.985, 0.96) * key * key * 1.36
    + vec3(0.92, 0.95, 1.0) * fill * 0.1
    + mix(vec3(0.15), vec3(0.34), sky);
  // Shade deepens the colour instead of greying it, as a saturated paint does.
  vec3 deep = pow(base, vec3(1.0 + (1.0 - clamp(length(light), 0.0, 1.0)) * 0.3));
  vec3 diffuse = deep * light * (1.0 - metal) * mix(0.55, 1.0, occlusion);
  vec3 spec = studio(R, rough) * F * occlusion * occlusion;

  vec3 c = diffuse * occlusion + spec;
  // A soft shoulder that keeps saturated colours saturated.
  float peak = max(c.r, max(c.g, c.b));
  if (peak > 0.82) c *= (0.82 + (1.0 - exp(-(peak - 0.82) * 2.6)) * 0.18) / peak;
  gl_FragColor = vec4(pow(c, vec3(1.0 / 2.2)), 1.0);
}`;

const SHADOW_VERTEX = `
attribute vec3 aPos;
uniform mat4 uProj;
uniform mat4 uModel;
varying vec2 vP;
void main() {
  vP = aPos.xz;
  gl_Position = uProj * uModel * vec4(aPos, 1.0);
}`;

const SHADOW_FRAGMENT = `
precision mediump float;
varying vec2 vP;
uniform vec2 uRadii;
uniform vec2 uSize;
void main() {
  // Never reaches the canvas's edge: it would show as a straight line.
  float edge = smoothstep(1.0, 0.72, length(gl_FragCoord.xy / uSize * 2.0 - 1.0));
  vec2 q = vP / uRadii;
  float d = dot(q, q);
  float contact = exp(-d * 1.7) * 0.6;
  float wide = exp(-d * 0.62) * 0.2;
  float a = 1.0 - (1.0 - contact) * (1.0 - wide);
  gl_FragColor = vec4(0.09, 0.07, 0.06, 1.0) * a * edge;
}`;

type Program = {
  program: WebGLProgram;
  attrs: Record<string, number>;
  unis: Record<string, WebGLUniformLocation | null>;
};
type Uploaded = { part: Part; vertices: WebGLBuffer; indices: WebGLBuffer };

type Context = {
  canvas: HTMLCanvasElement;
  gl: WebGLRenderingContext;
  lit: Program;
  floor: Program;
  floorBuffer: WebGLBuffer;
  mark: WebGLTexture | null;
  meshes: Map<ProductId, Uploaded[]>;
};

let context: Context | null = null;
let users = 0;
let releaseTimer = 0;
/** Set once the browser has refused a context, or lost one: the views fall back to drawn stills. */
let broken = false;
const listeners = new Set<() => void>();

function compile(
  gl: WebGLRenderingContext,
  vs: string,
  fs: string,
  names: string[],
  attrs: string[],
): Program {
  const program = gl.createProgram() as WebGLProgram;
  for (const [kind, source] of [
    [gl.VERTEX_SHADER, vs],
    [gl.FRAGMENT_SHADER, fs],
  ] as const) {
    const shader = gl.createShader(kind) as WebGLShader;
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    gl.attachShader(program, shader);
  }
  attrs.forEach((name, index) => gl.bindAttribLocation(program, index, name));
  gl.linkProgram(program);
  const unis: Program['unis'] = {};
  names.forEach((name) => (unis[name] = gl.getUniformLocation(program, name)));
  return {
    program,
    unis,
    attrs: Object.fromEntries(attrs.map((name, index) => [name, index])),
  };
}

/** The mark printed on the products: a peak and the store's name, as alpha on a small texture. */
function markTexture(gl: WebGLRenderingContext) {
  const paint = document.createElement('canvas');
  paint.width = 512;
  paint.height = 256;
  const c = paint.getContext('2d');
  if (!c) return null;
  c.fillStyle = '#fff';
  c.beginPath();
  c.moveTo(256, 18);
  c.lineTo(316, 124);
  c.lineTo(282, 124);
  c.lineTo(256, 76);
  c.lineTo(226, 124);
  c.lineTo(196, 124);
  c.closePath();
  c.fill();
  c.font = '700 74px -apple-system, "Segoe UI", Inter, Roboto, sans-serif';
  c.textAlign = 'center';
  c.textBaseline = 'alphabetic';
  if ('letterSpacing' in c) (c as unknown as { letterSpacing: string }).letterSpacing = '14px';
  c.fillText('FJELL', 256, 216);
  const texture = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, paint);
  gl.generateMipmap(gl.TEXTURE_2D);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  return texture;
}

function open(): Context | null {
  if (context) return context;
  if (broken || typeof document === 'undefined') return null;
  const canvas = document.createElement('canvas');
  canvas.width = canvas.height = 16;
  const gl = canvas.getContext('webgl', {
    alpha: true,
    antialias: true,
    premultipliedAlpha: true,
    preserveDrawingBuffer: false,
    powerPreference: 'low-power',
  });
  if (!gl) {
    broken = true;
    return null;
  }
  canvas.addEventListener('webglcontextlost', (event) => {
    event.preventDefault();
    if (context?.canvas !== canvas) return;
    // Only a loss we didn't ask for: the views show their drawn stills until it comes back.
    context = null;
    broken = true;
    listeners.forEach((listener) => listener());
  });
  canvas.addEventListener('webglcontextrestored', () => {
    broken = false;
    listeners.forEach((listener) => listener());
  });
  const lit = compile(
    gl,
    VERTEX,
    FRAGMENT,
    [
      'uProj',
      'uModel',
      'uEye',
      'uColour',
      'uMetal',
      'uRough',
      'uPeel',
      'uFleck',
      'uRibs',
      'uGlow',
      'uGlass',
      'uLabel',
      'uInk',
      'uMark',
    ],
    ['aPos', 'aNor', 'aAo'],
  );
  const floor = compile(
    gl,
    SHADOW_VERTEX,
    SHADOW_FRAGMENT,
    ['uProj', 'uModel', 'uRadii', 'uSize'],
    ['aPos'],
  );
  if (!gl.getProgramParameter(lit.program, gl.LINK_STATUS)) {
    broken = true;
    return null;
  }
  const floorBuffer = gl.createBuffer() as WebGLBuffer;
  gl.bindBuffer(gl.ARRAY_BUFFER, floorBuffer);
  gl.bufferData(
    gl.ARRAY_BUFFER,
    new Float32Array([-1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, 1]),
    gl.STATIC_DRAW,
  );
  context = { canvas, gl, lit, floor, floorBuffer, mark: markTexture(gl), meshes: new Map() };
  return context;
}

/** A view wants the studio; returns whether WebGL can be had at all. */
export function retain(): boolean {
  window.clearTimeout(releaseTimer);
  users += 1;
  return open() !== null;
}

/** A view leaves; with nobody left, the context goes back to the browser a moment later. */
export function release() {
  users = Math.max(0, users - 1);
  if (users > 0) return;
  window.clearTimeout(releaseTimer);
  releaseTimer = window.setTimeout(() => {
    if (users > 0 || !context) return;
    const { gl } = context;
    context = null;
    gl.getExtension('WEBGL_lose_context')?.loseContext();
  }, 500);
}

/** Tells `listener` when WebGL goes away or comes back. Returns the unsubscribe. */
export function onStudioChange(listener: () => void) {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
}

export const studioBroken = () => broken;

function meshes(ctx: Context, id: ProductId): Uploaded[] {
  let list = ctx.meshes.get(id);
  if (list) return list;
  const { gl } = ctx;
  list = modelOf(id).parts.map((part) => {
    const vertices = gl.createBuffer() as WebGLBuffer;
    gl.bindBuffer(gl.ARRAY_BUFFER, vertices);
    gl.bufferData(gl.ARRAY_BUFFER, part.vertices, gl.STATIC_DRAW);
    const indices = gl.createBuffer() as WebGLBuffer;
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indices);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, part.indices, gl.STATIC_DRAW);
    return { part, vertices, indices };
  });
  ctx.meshes.set(id, list);
  return list;
}

type M4 = Float32Array;
const multiply = (a: M4, b: M4): M4 => {
  const out = new Float32Array(16);
  for (let c = 0; c < 4; c += 1)
    for (let r = 0; r < 4; r += 1) {
      let sum = 0;
      for (let k = 0; k < 4; k += 1) sum += (a[k * 4 + r] ?? 0) * (b[c * 4 + k] ?? 0);
      out[c * 4 + r] = sum;
    }
  return out;
};
const translate = (x: number, y: number, z: number): M4 =>
  new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]);
const scale = (s: number): M4 => new Float32Array([s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, 0, 0, 0, 1]);
const rotateX = (a: number): M4 => {
  const c = Math.cos(a);
  const s = Math.sin(a);
  return new Float32Array([1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1]);
};
const rotateY = (a: number): M4 => {
  const c = Math.cos(a);
  const s = Math.sin(a);
  return new Float32Array([c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1]);
};

/** The canvas shows 1.6 units from top to bottom, at the origin's depth. */
const VIEW_HEIGHT = 1.6;
const FOV = (20 * Math.PI) / 180;

function bindMaterial(gl: WebGLRenderingContext, program: Program, m: Material) {
  const u = program.unis;
  gl.uniform3fv(u.uColour as WebGLUniformLocation, m.colour);
  gl.uniform1f(u.uMetal as WebGLUniformLocation, m.metal ?? 0);
  gl.uniform1f(u.uRough as WebGLUniformLocation, m.rough);
  gl.uniform1f(u.uPeel as WebGLUniformLocation, m.peel ?? 0);
  gl.uniform1f(u.uFleck as WebGLUniformLocation, m.fleck ?? 0);
  gl.uniform1f(u.uRibs as WebGLUniformLocation, m.ribs ?? 0);
  gl.uniform1f(u.uGlow as WebGLUniformLocation, m.glow ?? 0);
  gl.uniform1f(u.uGlass as WebGLUniformLocation, m.glass ? 1 : 0);
  if (m.label) {
    gl.uniform4f(u.uLabel as WebGLUniformLocation, m.label.width, m.label.bottom, m.label.top, 0);
    gl.uniform3fv(u.uInk as WebGLUniformLocation, m.label.ink);
  } else gl.uniform4f(u.uLabel as WebGLUniformLocation, 0, 0, 0, 0);
}

/** Draws a product on the shared canvas, the size asked for; it has to be copied right away. */
function draw(ctx: Context, id: ProductId, pose: Pose, width: number, height: number) {
  const { gl, canvas, lit, floor } = ctx;
  if (canvas.width !== width || canvas.height !== height) {
    canvas.width = width;
    canvas.height = height;
  }
  gl.viewport(0, 0, width, height);
  gl.clearColor(0, 0, 0, 0);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  const model = modelOf(id);
  const distance = VIEW_HEIGHT / 2 / Math.tan(FOV / 2);
  const f = 1 / Math.tan(FOV / 2);
  const aspect = width / height;
  const near = distance - 2;
  const far = distance + 2;
  const perspective = new Float32Array([
    f / aspect,
    0,
    0,
    0,
    0,
    f,
    0,
    0,
    0,
    0,
    (far + near) / (near - far),
    -1,
    0,
    0,
    (2 * far * near) / (near - far),
    0,
  ]);
  const proj = multiply(perspective, translate(0, 0, -distance));
  const size = model.fit * pose.scale;
  const place = multiply(
    translate(pose.x * VIEW_HEIGHT * aspect, -pose.y * VIEW_HEIGHT, 0),
    multiply(scale(size), rotateX(pose.pitch)),
  );

  // The shadow lies on the floor, tilted with the view but not turning with the product.
  gl.disable(gl.DEPTH_TEST);
  gl.disable(gl.CULL_FACE);
  gl.enable(gl.BLEND);
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  gl.useProgram(floor.program);
  const reach = 4.4;
  const floorMatrix = multiply(
    place,
    multiply(
      translate(0, -model.pivot, 0),
      new Float32Array([
        model.shadow[0] * reach,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        model.shadow[1] * reach,
        0,
        0,
        0,
        0,
        1,
      ]),
    ),
  );
  gl.uniformMatrix4fv(floor.unis.uProj as WebGLUniformLocation, false, proj);
  gl.uniformMatrix4fv(floor.unis.uModel as WebGLUniformLocation, false, floorMatrix);
  gl.uniform2f(floor.unis.uRadii as WebGLUniformLocation, 1 / reach, 1 / reach);
  gl.uniform2f(floor.unis.uSize as WebGLUniformLocation, width, height);
  gl.bindBuffer(gl.ARRAY_BUFFER, ctx.floorBuffer);
  gl.enableVertexAttribArray(0);
  gl.disableVertexAttribArray(1);
  gl.disableVertexAttribArray(2);
  gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 12, 0);
  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

  // The product.
  gl.enable(gl.DEPTH_TEST);
  gl.depthFunc(gl.LEQUAL);
  gl.useProgram(lit.program);
  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, ctx.mark);
  gl.uniform1i(lit.unis.uMark as WebGLUniformLocation, 0);
  const matrix = multiply(place, multiply(rotateY(pose.yaw), translate(0, -model.pivot, 0)));
  gl.uniformMatrix4fv(lit.unis.uProj as WebGLUniformLocation, false, proj);
  gl.uniformMatrix4fv(lit.unis.uModel as WebGLUniformLocation, false, matrix);
  gl.uniform3f(lit.unis.uEye as WebGLUniformLocation, 0, 0, distance);
  gl.enableVertexAttribArray(1);
  gl.enableVertexAttribArray(2);
  const list = meshes(ctx, id);
  const drawPart = ({ part, vertices, indices }: Uploaded) => {
    bindMaterial(gl, lit, part.material);
    gl.bindBuffer(gl.ARRAY_BUFFER, vertices);
    gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 28, 0);
    gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 28, 12);
    gl.vertexAttribPointer(2, 1, gl.FLOAT, false, 28, 24);
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indices);
    gl.drawElements(gl.TRIANGLES, part.indices.length, gl.UNSIGNED_SHORT, 0);
  };
  gl.disable(gl.BLEND);
  list.filter((item) => !item.part.material.glass).forEach(drawPart);
  // Glass last: the far side, then the near side, over everything.
  gl.enable(gl.BLEND);
  gl.depthMask(false);
  gl.enable(gl.CULL_FACE);
  const glass = list.filter((item) => item.part.material.glass);
  gl.cullFace(gl.FRONT);
  glass.forEach(drawPart);
  gl.cullFace(gl.BACK);
  glass.forEach(drawPart);
  gl.depthMask(true);
  gl.disable(gl.CULL_FACE);
}

/** Paints a product onto a view's 2D canvas. False when WebGL can't do it. */
export function renderTo(target: CanvasRenderingContext2D, id: ProductId, pose: Pose): boolean {
  const ctx = open();
  if (!ctx) return false;
  const { width, height } = target.canvas;
  draw(ctx, id, pose, width, height);
  target.clearRect(0, 0, width, height);
  target.drawImage(ctx.canvas, 0, 0);
  return true;
}

const thumbs = new Map<ProductId, string>();

/** A product as a catalog photo, drawn once; `shrink` is its size in the frame against the rest pose. */
export function thumbnail(id: ProductId, frame: number, shrink: number): string | null {
  const cached = thumbs.get(id);
  if (cached) return cached;
  const ok = retain();
  const ctx = ok ? open() : null;
  let url: string | null = null;
  if (ctx) {
    const model = modelOf(id);
    draw(ctx, id, { yaw: model.yaw, pitch: model.pitch, scale: shrink, x: 0, y: 0 }, frame, frame);
    url = ctx.canvas.toDataURL('image/webp', 0.92);
    thumbs.set(id, url);
  }
  release();
  return url;
}
```

### request-trace/meshes.ts

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

import type { ProductId } from './products';

/*
 * The products' geometry: surfaces of revolution from a profile, and tubes swept along a path for
 * handles and wires. No model files: everything is built here once, as plain arrays, and the
 * renderer uploads it. Units: the floor is y = 0 and a product stands about 1 tall.
 *
 * A profile is walked from the axis at the bottom, up the outside, and back down the inside, so a
 * segment's outward normal is always (dy, -dr). Corners are rounded by `round`; what remains
 * sharper than 50 degrees keeps two normals, so a lid's edge stays an edge.
 */

export type Material = {
  /** sRGB, 0 to 1. */
  colour: [number, number, number];
  metal?: number;
  rough: number;
  /** How strong the powder coat's fine pebble is. */
  peel?: number;
  /** Fine dark flecks, as fired enamel has. */
  fleck?: number;
  /** Vertical knurling, as a count of ribs around. */
  ribs?: number;
  /** Lights itself: the flame. */
  glow?: number;
  /** See-through: drawn last, both sides. */
  glass?: boolean;
  /** The printed mark: angle range around the axis, then the height range. */
  label?: { width: number; bottom: number; top: number; ink: [number, number, number] };
};

export type Part = {
  material: Material;
  /** x, y, z, nx, ny, nz, ao per vertex. */
  vertices: Float32Array;
  indices: Uint16Array;
};

export type Model = {
  parts: Part[];
  /** The height the view turns around. */
  pivot: number;
  /** How large it stands at rest, against a canvas 1.6 units tall. */
  fit: number;
  yaw: number;
  pitch: number;
  /** The contact shadow's radii. */
  shadow: [number, number];
};

type P2 = [number, number];
type P3 = [number, number, number];

const rgb = (hex: string): [number, number, number] => [
  parseInt(hex.slice(1, 3), 16) / 255,
  parseInt(hex.slice(3, 5), 16) / 255,
  parseInt(hex.slice(5, 7), 16) / 255,
];

/** Rounds a polyline's corners; `radii` per point, or one radius for all. */
function round(points: P2[], radii: number | number[], steps = 6): P2[] {
  const out: P2[] = [];
  points.forEach((point, index) => {
    const radius = typeof radii === 'number' ? radii : (radii[index] ?? 0);
    const before = points[index - 1];
    const after = points[index + 1];
    if (!before || !after || radius <= 0) {
      out.push(point);
      return;
    }
    const toA: P2 = [before[0] - point[0], before[1] - point[1]];
    const toB: P2 = [after[0] - point[0], after[1] - point[1]];
    const lengthA = Math.hypot(toA[0], toA[1]);
    const lengthB = Math.hypot(toB[0], toB[1]);
    const reach = Math.min(radius, lengthA * 0.48, lengthB * 0.48);
    const start: P2 = [
      point[0] + (toA[0] / lengthA) * reach,
      point[1] + (toA[1] / lengthA) * reach,
    ];
    const end: P2 = [point[0] + (toB[0] / lengthB) * reach, point[1] + (toB[1] / lengthB) * reach];
    for (let step = 0; step <= steps; step += 1) {
      const t = step / steps;
      const u = 1 - t;
      out.push([
        u * u * start[0] + 2 * u * t * point[0] + t * t * end[0],
        u * u * start[1] + 2 * u * t * point[1] + t * t * end[1],
      ]);
    }
  });
  return out;
}

/** A smooth curve through points, for shoulders and globes. */
function curve(points: P2[], samples = 10): P2[] {
  const out: P2[] = [];
  for (let index = 0; index < points.length - 1; index += 1) {
    const p0 = points[index - 1] ?? (points[index] as P2);
    const p1 = points[index] as P2;
    const p2 = points[index + 1] as P2;
    const p3 = points[index + 2] ?? p2;
    for (let step = 0; step < samples; step += 1) {
      const t = step / samples;
      const at = (a: number, b: number, c: number, d: number) =>
        0.5 *
        (2 * b +
          (c - a) * t +
          (2 * a - 5 * b + 4 * c - d) * t * t +
          (3 * b - a - 3 * c + d) * t ** 3);
      out.push([at(p0[0], p1[0], p2[0], p3[0]), at(p0[1], p1[1], p2[1], p3[1])]);
    }
  }
  out.push(points[points.length - 1] as P2);
  return out;
}

type AoAt = (r: number, y: number, angle: number) => number;

function lathe(profile: P2[], material: Material, aoAt: AoAt = () => 1, around = 112): Part {
  // Each point gets the normals of its two segments, or their average when the turn is gentle.
  type Ring = { r: number; y: number; nr: number; ny: number };
  const rings: Ring[] = [];
  const normal = (a: P2, b: P2): P2 => {
    const dr = b[0] - a[0];
    const dy = b[1] - a[1];
    const length = Math.hypot(dr, dy) || 1;
    return [dy / length, -dr / length];
  };
  profile.forEach((point, index) => {
    const before = profile[index - 1];
    const after = profile[index + 1];
    const n0 = before ? normal(before, point) : null;
    const n1 = after ? normal(point, after) : null;
    const push = (n: P2) => rings.push({ r: point[0], y: point[1], nr: n[0], ny: n[1] });
    if (n0 && n1) {
      if (n0[0] * n1[0] + n0[1] * n1[1] < Math.cos((50 * Math.PI) / 180)) {
        push(n0);
        push(n1);
      } else {
        const sum: P2 = [n0[0] + n1[0], n0[1] + n1[1]];
        const length = Math.hypot(sum[0], sum[1]) || 1;
        push([sum[0] / length, sum[1] / length]);
      }
    } else push((n0 ?? n1) as P2);
  });
  const columns = around + 1;
  const vertices = new Float32Array(rings.length * columns * 7);
  let v = 0;
  for (const ring of rings) {
    for (let column = 0; column < columns; column += 1) {
      const angle = (column / around) * Math.PI * 2;
      const sin = Math.sin(angle);
      const cos = Math.cos(angle);
      vertices[v++] = ring.r * sin;
      vertices[v++] = ring.y;
      vertices[v++] = ring.r * cos;
      vertices[v++] = ring.nr * sin;
      vertices[v++] = ring.ny;
      vertices[v++] = ring.nr * cos;
      vertices[v++] = aoAt(ring.r, ring.y, angle);
    }
  }
  const indices: number[] = [];
  for (let row = 0; row < rings.length - 1; row += 1) {
    const a = rings[row] as Ring;
    const b = rings[row + 1] as Ring;
    // Two normals at one point: no quad between them.
    if (a.r === b.r && a.y === b.y) continue;
    for (let column = 0; column < around; column += 1) {
      const p = row * columns + column;
      const q = p + columns;
      indices.push(p, p + 1, q, q, p + 1, q + 1);
    }
  }
  return { material, vertices, indices: new Uint16Array(indices) };
}

const sub = (a: P3, b: P3): P3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const cross = (a: P3, b: P3): P3 => [
  a[1] * b[2] - a[2] * b[1],
  a[2] * b[0] - a[0] * b[2],
  a[0] * b[1] - a[1] * b[0],
];
const unit = (a: P3): P3 => {
  const length = Math.hypot(a[0], a[1], a[2]) || 1;
  return [a[0] / length, a[1] / length, a[2] / length];
};

/** A smooth 3D path through points. */
function path3(points: P3[], samples = 12): P3[] {
  const out: P3[] = [];
  for (let index = 0; index < points.length - 1; index += 1) {
    const p0 = points[index - 1] ?? (points[index] as P3);
    const p1 = points[index] as P3;
    const p2 = points[index + 1] as P3;
    const p3 = points[index + 2] ?? p2;
    for (let step = 0; step < samples; step += 1) {
      const t = step / samples;
      const point = [0, 1, 2].map((axis) => {
        const [a, b, c, d] = [p0[axis] ?? 0, p1[axis] ?? 0, p2[axis] ?? 0, p3[axis] ?? 0];
        return (
          0.5 *
          (2 * b +
            (c - a) * t +
            (2 * a - 5 * b + 4 * c - d) * t * t +
            (3 * b - a - 3 * c + d) * t ** 3)
        );
      }) as P3;
      out.push(point);
    }
  }
  out.push(points[points.length - 1] as P3);
  return out;
}

/** A tube along `path`, with an elliptical section; `flat` thins it across its plane. */
function tube(path: P3[], radius: number, material: Material, flat = 1, ao = 1): Part {
  const around = 18;
  // The ends close in a small dome.
  const caps = 3;
  const stations: { point: P3; tangent: P3; size: number }[] = [];
  path.forEach((point, index) => {
    const tangent = unit(
      sub(path[Math.min(index + 1, path.length - 1)] as P3, path[Math.max(index - 1, 0)] as P3),
    );
    stations.push({ point, tangent, size: 1 });
  });
  const first = stations[0];
  const last = stations[stations.length - 1];
  if (first && last) {
    for (let cap = 1; cap <= caps; cap += 1) {
      const angle = (cap / caps) * (Math.PI / 2);
      const back = Math.sin(angle) * radius;
      stations.unshift({
        point: [
          first.point[0] - first.tangent[0] * back,
          first.point[1] - first.tangent[1] * back,
          first.point[2] - first.tangent[2] * back,
        ],
        tangent: first.tangent,
        size: Math.max(Math.cos(angle), 0.001),
      });
      stations.push({
        point: [
          last.point[0] + last.tangent[0] * back,
          last.point[1] + last.tangent[1] * back,
          last.point[2] + last.tangent[2] * back,
        ],
        tangent: last.tangent,
        size: Math.max(Math.cos(angle), 0.001),
      });
    }
  }
  // A frame carried along the path, so the section doesn't twist.
  let side = unit(cross(stations[0]?.tangent ?? [0, 1, 0], [0.31, 0.17, 0.93]));
  const columns = around + 1;
  const vertices = new Float32Array(stations.length * columns * 7);
  let v = 0;
  for (const station of stations) {
    const up = unit(cross(station.tangent, side));
    side = unit(cross(up, station.tangent));
    for (let column = 0; column < columns; column += 1) {
      const angle = (column / around) * Math.PI * 2;
      const c = Math.cos(angle);
      const s = Math.sin(angle);
      const w = radius * station.size;
      const across = flat;
      for (let axis = 0; axis < 3; axis += 1)
        vertices[v++] =
          (station.point[axis] ?? 0) + (side[axis] ?? 0) * c * w * across + (up[axis] ?? 0) * s * w;
      const n = unit([
        side[0] * c * (1 / across) + up[0] * s,
        side[1] * c * (1 / across) + up[1] * s,
        side[2] * c * (1 / across) + up[2] * s,
      ]);
      vertices[v++] = n[0];
      vertices[v++] = n[1];
      vertices[v++] = n[2];
      vertices[v++] = ao;
    }
  }
  const indices: number[] = [];
  for (let row = 0; row < stations.length - 1; row += 1) {
    for (let column = 0; column < around; column += 1) {
      const p = row * columns + column;
      const q = p + columns;
      indices.push(p, q, p + 1, q, q + 1, p + 1);
    }
  }
  return { material, vertices, indices: new Uint16Array(indices) };
}

const smooth = (a: number, b: number, x: number) => {
  const t = Math.min(Math.max((x - a) / (b - a), 0), 1);
  return t * t * (3 - 2 * t);
};

const STEEL: Material = { colour: rgb('#c9ccd0'), metal: 1, rough: 0.26 };
const CHARCOAL: Material = { colour: rgb('#1d1e20'), rough: 0.52, peel: 0.3 };

function flask(): Model {
  const coat: Material = {
    colour: rgb('#ff5606'),
    rough: 0.34,
    peel: 1,
    label: { width: 1.06, bottom: 0.335, top: 0.415, ink: [0.98, 0.96, 0.92] },
  };
  const boot = lathe(
    round(
      [
        [0, 0.012],
        [0.09, 0.012],
        [0.13, 0],
        [0.153, 0],
        [0.157, 0.078],
        [0.147, 0.084],
      ],
      [0, 0.01, 0.01, 0.02, 0.007, 0],
    ),
    { colour: rgb('#222326'), rough: 0.62, peel: 0.15 },
    (_r, y) => 0.55 + 0.45 * smooth(0, 0.05, y),
  );
  const body = lathe(
    [
      [0.1485, 0.08] as P2,
      ...curve(
        [
          [0.15, 0.1],
          [0.15, 0.4],
          [0.15, 0.6],
          [0.14, 0.66],
          [0.11, 0.705],
          [0.094, 0.724],
          [0.092, 0.736],
        ],
        8,
      ),
    ],
    coat,
    (_r, y) => (0.72 + 0.28 * smooth(0.08, 0.14, y)) * (0.7 + 0.3 * smooth(0.738, 0.7, y)),
  );
  const collar = lathe(
    round(
      [
        [0.092, 0.734],
        [0.096, 0.738],
        [0.096, 0.752],
        [0.086, 0.756],
      ],
      0.003,
    ),
    STEEL,
    () => 0.75,
  );
  const lid = lathe(
    round(
      [
        [0.09, 0.756],
        [0.105, 0.758],
        [0.109, 0.766],
        [0.109, 0.858],
        [0.1, 0.872],
        [0.04, 0.88],
        [0, 0.88],
      ],
      [0, 0.004, 0.003, 0.004, 0.012, 0.03, 0],
    ),
    { ...CHARCOAL, ribs: 48 },
    (_r, y) => 0.65 + 0.35 * smooth(0.756, 0.78, y),
  );
  const pivots: Part[] = [-1, 1].map((side) =>
    tube(
      [
        [side * 0.107, 0.82, 0],
        [side * 0.124, 0.82, 0],
      ],
      0.015,
      STEEL,
    ),
  );
  const loop = tube(
    path3(
      [
        [-0.121, 0.82, 0],
        [-0.126, 0.875, 0],
        [-0.098, 0.94, 0],
        [-0.04, 0.968, 0],
        [0.04, 0.968, 0],
        [0.098, 0.94, 0],
        [0.126, 0.875, 0],
        [0.121, 0.82, 0],
      ],
      8,
    ),
    0.0105,
    CHARCOAL,
    1.8,
  );
  return {
    parts: [boot, body, collar, lid, ...pivots, loop],
    pivot: 0.49,
    fit: 1.03,
    yaw: -0.14,
    pitch: 0.12,
    shadow: [0.2, 0.15],
  };
}

function mug(): Model {
  const HANDLE = Math.PI / 2 - 0.0;
  const enamel: Material = {
    colour: rgb('#ffb800'),
    rough: 0.15,
    fleck: 0.85,
    label: { width: 0.86, bottom: 0.19, top: 0.325, ink: [0.1, 0.13, 0.18] },
  };
  const body = lathe(
    [
      ...round(
        [
          [0, 0.004],
          [0.235, 0.004],
          [0.25, 0],
          [0.285, 0],
          [0.3, 0.03],
          [0.315, 0.5],
        ],
        [0, 0.01, 0.008, 0.012, 0.02, 0],
      ),
    ],
    enamel,
    (_r, y, angle) => {
      // The handle's own shade on the wall it meets.
      const off = Math.atan2(Math.sin(angle - HANDLE), Math.cos(angle - HANDLE));
      const near = Math.exp(-off * off * 16) * (0.25 + 0.75 * Math.exp(-((y - 0.27) ** 2) * 12));
      return (0.7 + 0.3 * smooth(0, 0.06, y)) * (1 - 0.3 * near);
    },
  );
  const rim = lathe(
    round(
      [
        [0.3145, 0.492],
        [0.327, 0.5],
        [0.331, 0.512],
        [0.323, 0.524],
        [0.309, 0.522],
        [0.302, 0.49],
      ],
      0.006,
      5,
    ),
    { colour: rgb('#17202b'), rough: 0.14, fleck: 0.1 },
    () => 0.92,
  );
  const inside = lathe(
    round(
      [
        [0.302, 0.49],
        [0.282, 0.058],
        [0.255, 0.034],
        [0, 0.03],
      ],
      [0, 0.03, 0.03, 0],
    ),
    { colour: rgb('#f3eee0'), rough: 0.17, fleck: 0.5 },
    (_r, y) => 0.26 + 0.74 * smooth(0.04, 0.5, y) ** 1.4,
  );
  const handlePath = path3(
    [
      [0.312, 0.435, 0],
      [0.395, 0.44, 0],
      [0.468, 0.395, 0],
      [0.49, 0.29, 0],
      [0.455, 0.18, 0],
      [0.385, 0.125, 0],
      [0.305, 0.115, 0],
    ],
    10,
  );
  const handle = tube(handlePath, 0.034, { ...enamel, label: undefined }, 0.62, 0.96);
  return {
    parts: [body, rim, inside, handle],
    pivot: 0.27,
    fit: 1.12,
    yaw: -0.5,
    pitch: 0.3,
    shadow: [0.46, 0.36],
  };
}

function lantern(): Model {
  const enamel: Material = {
    colour: rgb('#0f6a4d'),
    rough: 0.2,
    peel: 0.25,
    label: { width: 0.9, bottom: 0.03, top: 0.118, ink: [0.95, 0.91, 0.78] },
  };
  const tank = lathe(
    [
      ...round(
        [
          [0, 0.006],
          [0.215, 0.006],
          [0.235, 0],
          [0.262, 0],
          [0.27, 0.02],
          [0.27, 0.128],
          [0.24, 0.185],
          [0.15, 0.226],
          [0.132, 0.232],
          [0.132, 0.25],
        ],
        [0, 0.01, 0.008, 0.012, 0.012, 0.04, 0.05, 0.02, 0.006, 0],
      ),
    ],
    enamel,
    (_r, y) => (0.68 + 0.32 * smooth(0, 0.05, y)) * (0.7 + 0.3 * smooth(0.25, 0.2, y)),
  );
  const seat = lathe(
    round(
      [
        [0.13, 0.226],
        [0.146, 0.232],
        [0.148, 0.262],
        [0.126, 0.266],
      ],
      0.004,
    ),
    STEEL,
    () => 0.85,
  );
  const burner = lathe(
    round(
      [
        [0, 0.25],
        [0.05, 0.25],
        [0.05, 0.3],
        [0.028, 0.33],
        [0.022, 0.355],
        [0, 0.355],
      ],
      0.006,
    ),
    { ...STEEL, rough: 0.34 },
    () => 0.92,
  );
  const flame = lathe(
    curve(
      [
        [0.0001, 0.345],
        [0.02, 0.365],
        [0.03, 0.4],
        [0.022, 0.445],
        [0.008, 0.485],
        [0.0001, 0.515],
      ],
      6,
    ),
    { colour: rgb('#ffb347'), rough: 1, glow: 1 },
    () => 1,
    28,
  );
  const globe = lathe(
    curve(
      [
        [0.128, 0.262],
        [0.172, 0.32],
        [0.206, 0.405],
        [0.206, 0.495],
        [0.17, 0.585],
        [0.126, 0.645],
        [0.115, 0.676],
      ],
      9,
    ),
    { colour: [0.9, 0.95, 0.94], rough: 0.05, glass: true },
    () => 1,
  );
  const hood = lathe(
    [
      ...round(
        [
          [0.11, 0.64],
          [0.14, 0.645],
          [0.232, 0.676],
          [0.236, 0.692],
          [0.18, 0.74],
          [0.11, 0.774],
          [0.085, 0.84],
          [0.03, 0.852],
          [0, 0.852],
        ],
        [0, 0.008, 0.012, 0.008, 0.04, 0.03, 0.016, 0.02, 0],
      ),
    ],
    enamel,
    (_r, y) => 0.72 + 0.28 * smooth(0.65, 0.72, y),
  );
  const wires: Part[] = [0.6, 2.17, 3.74, 5.31].map((angle) => {
    const at = (r: number, y: number): P3 => [r * Math.sin(angle), y, r * Math.cos(angle)];
    return tube(
      path3(
        [
          at(0.178, 0.228),
          at(0.214, 0.31),
          at(0.238, 0.405),
          at(0.238, 0.5),
          at(0.222, 0.59),
          at(0.202, 0.672),
        ],
        9,
      ),
      0.0062,
      STEEL,
    );
  });
  const hoop = tube(
    Array.from({ length: 65 }, (_, index) => {
      const angle = (index / 64) * Math.PI * 2;
      return [0.24 * Math.sin(angle), 0.452, 0.24 * Math.cos(angle)] as P3;
    }),
    0.0066,
    STEEL,
  );
  const bail = tube(
    path3(
      [
        [-0.277, 0.13, 0],
        [-0.32, 0.3, 0],
        [-0.325, 0.56, 0],
        [-0.275, 0.82, 0],
        [-0.155, 1.0, 0],
        [0, 1.055, 0],
        [0.155, 1.0, 0],
        [0.275, 0.82, 0],
        [0.325, 0.56, 0],
        [0.32, 0.3, 0],
        [0.277, 0.13, 0],
      ],
      8,
    ),
    0.0085,
    STEEL,
  );
  const lugs: Part[] = [-1, 1].map((side) =>
    tube(
      [
        [side * 0.264, 0.13, 0],
        [side * 0.292, 0.13, 0],
      ],
      0.018,
      STEEL,
    ),
  );
  return {
    parts: [tank, seat, burner, flame, hood, ...wires, hoop, bail, ...lugs, globe],
    pivot: 0.5,
    fit: 0.9,
    yaw: 0.0,
    pitch: 0.14,
    shadow: [0.38, 0.3],
  };
}

const built = new Map<ProductId, Model>();

/** A product's model; the arrays are built once, the first time it's asked for. */
export function modelOf(id: ProductId): Model {
  let model = built.get(id);
  if (!model) {
    model = id === 'flask' ? flask() : id === 'mug' ? mug() : lantern();
    built.set(id, model);
  }
  return model;
}
```

### request-trace/product-still.tsx

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

import type { ProductId } from './products';

/*
 * The products drawn in SVG: what shows where WebGL can't be had, or while a lost context is away.
 * The same products, the same colours, flat-lit: two gradients and a highlight per body.
 */

const Shadow = ({ cx, rx }: { cx: number; rx: number }) => (
  <ellipse cx={cx} cy="372" rx={rx} ry="12" fill="#000" opacity="0.16" />
);

export function ProductStill({ id, className }: { id: ProductId; className?: string }) {
  return (
    <svg className={className} viewBox="0 0 420 420" role="img" aria-hidden="true">
      <defs>
        <linearGradient id="rt-flask" x1="0" x2="1">
          <stop offset="0" stopColor="#ff7a2e" />
          <stop offset="0.35" stopColor="#f24a0c" />
          <stop offset="1" stopColor="#b02f04" />
        </linearGradient>
        <linearGradient id="rt-mug" x1="0" x2="1">
          <stop offset="0" stopColor="#ffd042" />
          <stop offset="0.4" stopColor="#f7ae00" />
          <stop offset="1" stopColor="#c07f00" />
        </linearGradient>
        <linearGradient id="rt-lantern" x1="0" x2="1">
          <stop offset="0" stopColor="#2a9472" />
          <stop offset="0.4" stopColor="#0f6a4d" />
          <stop offset="1" stopColor="#073a2a" />
        </linearGradient>
      </defs>
      {id === 'flask' && (
        <g>
          <Shadow cx={210} rx={72} />
          <rect x="150" y="320" width="120" height="50" rx="10" fill="#222326" />
          <path d="M152 324V145c0-22 24-32 28-56h60c4 24 28 34 28 56v179z" fill="url(#rt-flask)" />
          <rect x="176" y="50" width="68" height="40" rx="6" fill="#1d1e20" />
          <path
            d="M172 62c0-44 76-44 76 0"
            fill="none"
            stroke="#1d1e20"
            strokeWidth="7"
            strokeLinecap="round"
          />
          <path d="M210 200l22 38h-12l-10-17-10 17h-12z" fill="#fff8ee" />
        </g>
      )}
      {id === 'mug' && (
        <g>
          <Shadow cx={205} rx={110} />
          <path
            d="M266 180c74-14 74 110 0 110"
            fill="none"
            stroke="#e39b00"
            strokeWidth="20"
            strokeLinecap="round"
          />
          <path d="M112 150l10 202c1 14 20 20 83 20s82-6 83-20l10-202z" fill="url(#rt-mug)" />
          <ellipse cx="205" cy="150" rx="93" ry="24" fill="#17202b" />
          <ellipse cx="205" cy="150" rx="86" ry="19" fill="#cfc9ba" />
          <path d="M205 240l20 34h-11l-9-15-9 15h-11z" fill="#1a2230" />
        </g>
      )}
      {id === 'lantern' && (
        <g>
          <Shadow cx={210} rx={92} />
          <path
            d="M122 300C88 170 140 34 210 34s122 136 88 266"
            fill="none"
            stroke="#b9bdc2"
            strokeWidth="5"
          />
          <path d="M136 372v-66c0-16 40-34 74-34s74 18 74 34v66z" fill="url(#rt-lantern)" />
          <path d="M176 272c-32-40-32-80 0-112h68c32 32 32 72 0 112z" fill="#fff" opacity="0.45" />
          <path d="M210 196c14 18 14 36 0 48-14-12-14-30 0-48z" fill="#ffb347" />
          <path d="M140 160c8-22 40-44 70-50 30 6 62 28 70 50z" fill="url(#rt-lantern)" />
        </g>
      )}
    </svg>
  );
}
```

### request-trace/demo-pointer.tsx

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

'use client';

import type { Ref } from 'react';
import { CursorArrow } from './glyphs';

/*
 * The named cursor the demo moves around, and the steps that move it. A demo is a script of awaited
 * steps: wait, or glide 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 cursor fades out.
 *
 * Each glide is a curved flight played by the Web Animations API, so nothing runs frame by frame.
 */

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

export type Demo = {
  /** Resolves after `ms`. */
  wait: (ms: number) => Promise<void>;
  /** Glides the cursor to `to`, in the stage's own px, in `ms`. */
  glide: (to: Point, ms: number) => Promise<void>;
  /** Plays the small press on the cursor's label. */
  press: () => void;
};

class Stopped extends Error {}

const SAMPLES = 24;
/** Where the arrow's tip is in its box. */
const TIP = 2;

/** Plays `script` with the cursor over the stage; returns the function that stops it. */
export function runDemo(
  pointer: HTMLElement,
  start: Point,
  script: (demo: Demo) => Promise<void>,
): () => void {
  let alive = true;
  let flight: Animation | null = null;
  const place = ({ x, y }: Point) => `translate(${x - TIP}px, ${y - TIP}px)`;
  const timers = new Set<number>();
  const pending = new Set<() => void>();
  let at = start;

  const step = <T,>(promise: Promise<T>) =>
    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) => {
    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.14, y: (from.y + to.y) / 2 + dx * 0.14 };
    const frames: Keyframe[] = [];
    for (let i = 0; i <= SAMPLES; i += 1) {
      const t = i / SAMPLES;
      const u = 1 - t;
      frames.push({
        transform: place({
          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,
        }),
      });
    }
    flight?.cancel();
    pointer.style.transform = place(to);
    flight = pointer.animate(frames, { duration: ms, easing: 'cubic-bezier(0.45, 0, 0.25, 1)' });
    return step(flight.finished);
  };

  const press = () => {
    pointer.lastElementChild?.animate([{ scale: 1 }, { scale: 0.9, offset: 0.4 }, { scale: 1 }], {
      duration: 260,
      easing: 'ease-out',
    });
  };

  pointer.style.transform = place(at);
  pointer.style.opacity = '1';
  script({ wait, glide, press }).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 cursor: an arrow and a pill with a name. Decorative: what it does shows on the controls. */
export function NamedCursor({
  ref,
  name,
  className,
  arrowClass,
  labelClass,
}: {
  ref: Ref<HTMLSpanElement>;
  name: string;
  className?: string;
  arrowClass?: string;
  labelClass?: string;
}) {
  return (
    <span ref={ref} className={className} aria-hidden="true">
      <CursorArrow className={arrowClass} />
      <span className={labelClass}>{name}</span>
    </span>
  );
}
```

### request-trace/use-autoplay.ts

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

'use client';

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

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

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

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

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

### request-trace/glyphs.tsx

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

import type { RequestKind, ServiceId } from './products';

/* The small icons, stroked on a 16 px grid in the current colour. */

type Props = { className?: string };
const Icon = ({ className, d }: Props & { d: string }) => (
  <svg
    className={className}
    viewBox="0 0 16 16"
    fill="none"
    stroke="currentColor"
    strokeWidth="1.2"
    strokeLinecap="round"
    strokeLinejoin="round"
    aria-hidden="true"
  >
    <path d={d} />
  </svg>
);

const BAG = 'M3 3h10v10.5H3zM5.8 3v1.6a2.2 2.2 0 0 0 4.4 0V3';
const LIST = 'M2.5 4.5h1.2M6 4.5h7.5M2.5 8h1.2M6 8h7.5M2.5 11.5h1.2M6 11.5h7.5';
const ENVELOPE = 'M2.2 3.8h11.6v8.6H2.2zM2.4 4.2 8 8.8l5.6-4.6';
const CUBE = 'M8 1.8 13.6 5v6L8 14.2 2.4 11V5zM2.6 5.1 8 8.2l5.4-3.1M8 8.2v5.8';
const CACHE = 'M2.5 5.2h4l1.2 1.4h5.8v6.6H2.5zM2.5 5.2V3h4.4l1 1.3M6 9.6h4';
const DATABASE =
  'M3 4c0-1.2 2.2-2 5-2s5 .8 5 2-2.2 2-5 2-5-.8-5-2M3 4v8c0 1.2 2.2 2 5 2s5-.8 5-2V4M3 8c0 1.2 2.2 2 5 2s5-.8 5-2';
const SPARK =
  'M8 1.8 9.3 6l4.4 1.4-4.4 1.4L8 13l-1.3-4.2-4.4-1.4L6.7 6zM12.6 11.6l.5 1.5 1.4.5-1.4.5-.5 1.4-.5-1.4-1.4-.5 1.4-.5z';

export const KIND_ICON: Record<RequestKind, string> = {
  page: BAG,
  catalog: LIST,
  model: CUBE,
  stock: LIST,
  bag: BAG,
  notify: ENVELOPE,
};
export const SERVICE_ICON: Record<ServiceId, string> = {
  cache: CACHE,
  database: DATABASE,
  email: ENVELOPE,
  ai: SPARK,
};
export const NODE_ICON = { database: DATABASE, envelope: ENVELOPE, box: CUBE };

export const Glyph = ({ d, className }: Props & { d: string }) => (
  <Icon className={className} d={d} />
);
export const CheckGlyph = (props: Props) => <Icon {...props} d="M3 8.6 6.4 12 13 4.6" />;
export const ChevronGlyph = (props: Props) => <Icon {...props} d="M6 3.5 10.5 8 6 12.5" />;
export const BagGlyph = (props: Props) => <Icon {...props} d={BAG} />;
export const BellGlyph = (props: Props) => (
  <Icon
    {...props}
    d="M4.2 11.4V7.2a3.8 3.8 0 0 1 7.6 0v4.2l1 1.1H3.2zM6.8 14.2h2.4M2.6 4.2l1.2-1.5M13.4 4.2l-1.2-1.5"
  />
);
export const HistoryGlyph = (props: Props) => (
  <Icon {...props} d="M3 8a5.2 5.2 0 1 1 1.6 3.8M3 8 1.6 6.5M3 8l1.6-1.4M8 5.2V8l2 1.2" />
);

/** The hosting platform's mark: three chevrons. */
export const PlatformMark = ({ className }: Props) => (
  <svg className={className} viewBox="0 0 18 18" fill="none" aria-hidden="true">
    <path d="M6.2 3 2 9l4.2 6" stroke="#f0620e" strokeWidth="1.8" strokeLinejoin="round" />
    <path d="M9.4 3 13.6 9l-4.2 6" stroke="#f79a1c" strokeWidth="1.8" strokeLinejoin="round" />
    <path d="M12.6 3 16.8 9l-4.2 6" stroke="#f0620e" strokeWidth="1.8" strokeLinejoin="round" />
  </svg>
);

/** The store's mark: a peak, in the current colour. */
export const StoreMark = ({ className }: Props) => (
  <svg className={className} viewBox="0 0 18 18" fill="currentColor" aria-hidden="true">
    <path d="M9 2.5 16.8 15h-4L9 8.8 5.3 15H1.2z" />
  </svg>
);

/** The cursor's arrow: filled, tilted, its tip at the box's top left. */
export const CursorArrow = ({ className }: Props) => (
  <svg className={className} viewBox="0 0 18 18" aria-hidden="true">
    <path d="M1.5 1.5 16 6.6l-5.8 1.9L8 15z" fill="currentColor" />
  </svg>
);
```