# Layout inspector

> An analytics page that turns into a wireframe and measures itself: grid, padding and alignment, live from the page, pink where it breaks.

A “Post performance” report for a small ceramics studio: a sidebar of reports, a top bar with search, a header with its tools and a table of twelve posts under a row of totals. Press Inspect and it strips down to a grey wireframe on a canvas with rulers, and layers of measurements draw over it, read from the live page: the regions, each row’s padding and its thumbnail’s alignment, the columns’ widths and edges, the header’s controls. Blue is on the 4-px grid or aligned; pink is off it, with the gap in px. Switch the draft to its revision and the marks follow the page as it moves, turning into check marks. Hover or focus anything to measure it, or let the tour walk the whole review.

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

Category: Dashboards.

## Anatomy

1. **Toolbar**: The inspector’s controls on one row: Inspect, the four layers, the page’s revision, and the tour.
2. **Inspect**: A toggle button (`aria-pressed`). On, the page turns into a grey wireframe and the marks can draw.
3. **Layer chip**: One per layer, with a count of the issues it finds: pink with a number, or blue with a check mark.
4. **Revision**: A radio group: the draft with its flaws, or the revision that fixes them.
5. **Canvas**: A grey canvas with rulers along the top and left, in the page’s own px; each guide shows as a tag on its ruler.
6. **Page**: The dashboard under inspection: a real responsive page, laid out at 1240 px or wider and scaled to fit.
7. **Report**: One line under the canvas that says, in words, what the layers drawn found.

## Properties

### Revision (`defaultRevision`)

1. **Draft (default)**: The page with a flaw in each layer, for showing what the review finds.
2. **Revised**: The page after the fixes, for showing the result: every mark blue.

Start on the draft when the point is the review; start on the revision when the point is the finished page and the inspector is there to prove it holds.

### Layers (`defaultLayers`)

1. **None (default)**: The page as it is; Inspect and the layers wait for the reader.
2. **One layer**: Opens on the wireframe with one layer drawn, for a still about that layer.
3. **All four**: Every measurement at once: dense, for a full audit at a large size.

One layer at a time reads best; giving any layer also starts in the wireframe and turns the demo off.

## When to use

- Reviewing a screen’s layout with a team: the wireframe takes colour and words out of the way, and the marks say where the spacing and the alignment break.
- A design review or a case study that shows an iteration: the draft’s flaws in pink, the revision’s fixes as check marks, measured on the same page.
- Teaching a spacing system: every padding, gap and size on the page is labelled, blue on the 4-px grid and pink off it.
- A dense data page, a table with a sidebar and a toolbar, where off-by-a-few-pixels problems are real and hard to see by eye.

## When not to use

- Inspecting your own app in development: the browser’s developer tools measure any page; this one inspects the page it ships with.
- A page people use to get work done. The inspector is a review surface; the finished dashboard works on its own without it.
- Pixel-perfect comparison with a design file. It checks the page against rules (the grid, alignment), not against a picture.
- Small screens as the main place it is read: on a phone the page lays out at phone width and the marks get dense; zoom in with the tour.

### Reading the marks

- **Blue** is a measurement on the 4-px grid, or two edges that meet: a check mark where they do.
- **Pink** is off the grid, or a gap between edges that should meet, with its width in px.
- **Green**, under the pointer or the focus, is an element’s padding; the blue box and its badge are its size.
- **Tags on the rulers** give each guide’s position in the page’s px, whatever the zoom.

### The four layers

- **Regions**: the sidebar’s width and padding, the top bar’s height, and the search box’s place in the bar, checked against its middle.
- **Rows**: each visible row’s padding, the thumbnail’s inset and gap, and whether the thumbnail ends where its text does.
- **Columns**: each column’s width, a guide on its header’s aligned edge, and the gap from that guide to every value in view.
- **Controls**: the header tools’ heights against the one most of them share, and the gaps between them.

## Do’s and don’ts

- **Do**: Draw one layer at a time and let the report say what it found.
- **Don’t**: Draw every layer at once at a small size: the badges cover the page they measure.
- **Do**: Show the revision with its layers on to prove a fix: the same marks, all blue.
- **Caution**: On a phone, the page is laid out at phone width; its numbers differ from the desktop page’s, as they should.

## Content

The words are the layer names, the step names of the tour, and the report’s issues.

- **Layer names are nouns**: `Regions`, `Rows`, `Columns`, `Controls`.
- **Issues say what and how much**, in px: “Row padding is 14 px, off the 4-px grid”, “Thumbnails end 16 px above their text”.
- **Numbers are measured**, rounded to one decimal; nothing on the marks is typed by hand.

## Installation

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

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

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 { LayoutInspector } from './layout-inspector';

export function LayoutReview() {
  return <LayoutInspector defaultLayers={['rows']} autoplay={false} />;
}
```

## States

- **Draft**: The finished page before review: grey thumbnails, a dark Compose, plain post types.
- **Wireframe**: Inspect on, no layer: text turns into bars, icons into squares, pictures into tiles.
- **Regions, draft**: The sidebar is 234 px with 14 px of padding, the top bar 50 px tall, the search off its middle.
- **Rows, draft**: Row padding 14 px, and the 40 px thumbnails end 16 px above their text.
- **Columns, draft**: Headers left, values right: every metric column shows its gap in pink.
- **Controls, draft**: The view toggle is 30 px among 28 px buttons, 6 px apart.
- **All layers, revised**: Every mark blue: on the grid, aligned, and the report says no issues.
- **Revised**: The finished page after review: colour thumbnails, post types as chips, a blue Compose.

## How it works

- Nothing on the marks is typed: each layer finds its pieces by data-m names and reads their client rects and computed padding, divided by the camera’s scale, so every value is in the page’s own CSS px at any zoom. Values print to one decimal.
- Two rules colour a mark. A size or a spacing is blue when it is a multiple of 4 px (within half a pixel) and pink when not; an alignment, a thumbnail’s foot against its text’s, a value’s edge against its header’s, a search box’s middle against the bar’s, is a check mark when the two meet and a pink gap with its width when they don’t.
- The draft and the revision are the same markup: custom properties on the page set the spacing (sidebar 234 → 240 px, row padding 14 → 16, thumbnails 40 → 56, tools 28 → 32 px tall and 6 → 8 apart) and move on 0.45 s ease transitions. For 700 ms after a change the marks are read again every frame, so they follow the page as it moves.
- The wireframe is a class on every piece of text: its background is a gradient bar of a registered colour (@property), 0.74 em tall, cloned on each line with box-decoration-break, that fades in over 0.4 s as the words turn transparent. Icons become squares and thumbnails grey tiles the same way.
- A desktop page is laid out at 1240 px or wider and scaled to the canvas; a phone-width canvas lays it out at its own width, where the sidebar and breadcrumbs go and the table scrolls in its own box. The table keeps its head sticky, and its marks are cut to the box’s visible part.
- A camera zooms on the part a layer is about, up to 3×, in one transform over page and marks, eased in log space over 1 s (cubic in-out). Lines and borders divide their width by the zoom and badges are scaled back by it, so they keep their screen size; the canvas rulers redraw each frame with ticks 56 px or more apart and a tag per guide.
- The tour is twelve steps: the draft, its wireframe, each layer’s flaws then its fix, the zoomed-out wireframe, and the rebuilt page with colour thumbnails and post types as chips. While on screen and untouched, a demo pointer plays it in about 27 s, with a hover over a thumbnail and a title; any input from the reader stops it.
- Every colour is a token on the root, light-dark() where the two schemes differ. The rulers read theirs from real properties of their canvases, and a 1 ms colour transition on them tells the script when the scheme changed, wherever the change came from.

## API reference

- **defaultRevision** (`'draft' | 'revised'`, default `'draft'`): The page it starts with: the draft, with a flaw in each layer, or the revision that fixes them.
- **defaultLayers** (`('regions' | 'rows' | 'columns' | 'controls')[]`, default `[]`): The layers drawn at the start; any layer also starts in the wireframe and turns the demo off.
- **defaultInspect** (`boolean`, default `false`): Starts in the wireframe; it turns the demo off.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, a demo pointer plays the tour; any input from the reader stops it.
- **colorScheme** (`'light' | 'dark' | 'system'`): Light or dark colours, or the reader’s; without it, the page’s color-scheme.
- **className** (`string`): A class for the root.

## Accessibility

### Keyboard

- Tab reaches Inspect, each layer, the revision and the tour. Enter or Space presses them; the arrows move the revision.
- With Inspect on, focusing anything in the page measures it, as a hover does; Escape turns Inspect off.
- The table’s scroll box is a focusable region, so the arrows scroll it.

### Screen readers

- Inspect and the layers are toggle buttons with `aria-pressed`; a layer’s name carries its count (“Rows, 2 issues”).
- The marks and the rulers are hidden from screen readers; the report under the canvas says the same in words, in a polite live region.
- The page under inspection is real markup: a banner, a navigation, a main region and a table with header cells.

### Colour and motion

Pink and blue are never the only cue: an issue has a number and a check mark has its glyph, and the report says each one in words. With reduced motion, the camera jumps, the wireframe and the fixes change at once, and the demo does not play.

### In this build

- The inspector’s controls are a toolbar: Inspect and the four layers are toggle buttons with aria-pressed, each layer named with its count (“Rows, 2 issues”); the revision is a radio group the arrows move; the tour is two buttons around the step’s name.
- With Inspect on, focusing an element of the page measures it as a hover does, and Escape turns Inspect off. The table’s scroll box is a focusable region the arrows scroll.
- The marks and the rulers are hidden from screen readers; the line under the canvas says what the drawn layers found, in words, in a polite live region (quiet while the demo plays).
- No mark relies on colour alone: an issue carries its number, an alignment its check glyph, and the report names each one.
- Every control shows a focus ring on keyboard focus. With reduced motion the camera jumps, the wireframe and the fixes change at once, and the demo does not play.

## Source

### layout-inspector/layout-inspector.tsx

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

'use client';

import {
  useCallback,
  useEffect,
  useEffectEvent,
  useLayoutEffect,
  useRef,
  useState,
  type CSSProperties,
  type FocusEvent as ReactFocusEvent,
  type PointerEvent as ReactPointerEvent,
} from 'react';
import { Dashboard } from './dashboard';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { Icon, type Glyph } from './glyphs';
import {
  LAYERS,
  measureElement,
  measureLayer,
  type Layer,
  type Mark,
  type Reading,
  type Rect,
} from './measure';
import { Overlay, drawRuler, rulerTags, type RulerColors } from './overlay';
import { useAutoplay } from './use-autoplay';
import styles from './layout-inspector.module.css';

/*
 * Layout inspector: an analytics page, "Post performance", that can be inspected in place.
 * Inspect turns the page into a grey wireframe (every piece of text a bar, every icon a square)
 * and draws measurements over it, read from the live page: the regions (sidebar, top bar, the
 * search's place in it), the rows' padding and their thumbnails' alignment, the columns' widths
 * and whether their values line up with their headers, and the header's controls' heights and
 * gaps. Blue is on the 4-px grid or aligned; pink is off it, with the size of the gap.
 *
 * - The page is a draft with flaws in each of those four places, and a revision that fixes
 *   them. The fixes are real changes of layout (custom properties the stylesheet sets), so the
 *   marks are measured again and turn from pink to blue check marks as the page moves.
 * - It sits on a grey canvas with rulers, like a design tool's. A camera zooms to the part a
 *   layer is about: page, overlay and all in one transformed layer, while lines and badges keep
 *   their screen size. The rulers follow it, with a tag for every guide.
 * - Hovering an element, or focusing one with the keyboard, measures it: its box, its padding
 *   and its size.
 * - The tour walks the sequence a designer would: the draft, its wireframe, each layer's flaws
 *   and their fix, then the finished page. While on screen and untouched, a demo pointer plays
 *   it; any input from the reader stops it for good.
 */

type Step = {
  label: string;
  inspect: boolean;
  layers: Layer[];
  fixed: Layer[];
  focus: Layer | null;
};

const ALL: Layer[] = ['regions', 'rows', 'columns', 'controls'];

export const STEPS: Step[] = [
  { label: 'The draft', inspect: false, layers: [], fixed: [], focus: null },
  { label: 'Wireframe', inspect: true, layers: [], fixed: [], focus: null },
  { label: 'Regions', inspect: true, layers: ['regions'], fixed: [], focus: null },
  { label: 'Regions, fixed', inspect: true, layers: ['regions'], fixed: ['regions'], focus: null },
  { label: 'Row spacing', inspect: true, layers: ['rows'], fixed: ['regions'], focus: 'rows' },
  {
    label: 'Row spacing, fixed',
    inspect: true,
    layers: ['rows'],
    fixed: ['regions', 'rows'],
    focus: 'rows',
  },
  {
    label: 'Column alignment',
    inspect: true,
    layers: ['columns'],
    fixed: ['regions', 'rows'],
    focus: 'columns',
  },
  {
    label: 'Column alignment, fixed',
    inspect: true,
    layers: ['columns'],
    fixed: ['regions', 'rows', 'columns'],
    focus: 'columns',
  },
  {
    label: 'Controls',
    inspect: true,
    layers: ['controls'],
    fixed: ['regions', 'rows', 'columns'],
    focus: 'controls',
  },
  { label: 'Controls, fixed', inspect: true, layers: ['controls'], fixed: ALL, focus: 'controls' },
  { label: 'Zoomed out', inspect: true, layers: [], fixed: ALL, focus: null },
  { label: 'Rebuilt', inspect: false, layers: [], fixed: ALL, focus: null },
];

const LAYER_ICON: Record<Layer, Glyph> = {
  regions: 'regions',
  rows: 'rows',
  columns: 'columns',
  controls: 'controls',
};

/** The camera: a zoom over the fitted page (1 = the whole page) and the page px at the middle. */
type Camera = { z: number; cx: number; cy: number };
/** The canvas's geometry: the viewport in screen px, the page's width and height in its own px. */
type Geometry = {
  vw: number;
  vh: number;
  ruler: number;
  margin: number;
  d: number;
  h: number;
  s0: number;
};

/** A desktop page narrower than this is laid out at this width and scaled down to fit. */
const DESIGN_WIDTH = 1240;
/** Under this many px of viewport the page is a phone page: laid out at its own width. */
const PHONE = 600;
const MAX_ZOOM = 3;
const CAMERA_MS = 1000;
/** After a change the marks are read again every frame for this long, as the page moves. */
const SETTLE_MS = 700;

const easeInOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);
const same = (a: Layer[], b: Layer[]) => a.length === b.length && a.every((x) => b.includes(x));

export function LayoutInspector({
  defaultInspect = false,
  defaultLayers = [],
  defaultRevision = 'draft',
  autoplay = true,
  colorScheme,
  className = '',
}: {
  /** Starts in the wireframe, with its measurements; it also turns the demo off. */
  defaultInspect?: boolean;
  /** The layers drawn at the start. */
  defaultLayers?: Layer[];
  /** The page it starts with: the draft, with its flaws, or the revision that fixes them. */
  defaultRevision?: 'draft' | 'revised';
  /** While on screen and untouched, a demo pointer plays the tour. */
  autoplay?: boolean;
  /** Light or dark colours, or the reader's ('system'); without it, the page's color-scheme. */
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>();
  const [inspect, setInspect] = useState(defaultInspect || defaultLayers.length > 0);
  const [layers, setLayers] = useState<Layer[]>(defaultLayers);
  const [fixed, setFixed] = useState<Layer[]>(defaultRevision === 'revised' ? ALL : []);
  const [focus, setFocus] = useState<Layer | null>(null);
  const [step, setStep] = useState<number | null>(null);
  const [readings, setReadings] = useState<Partial<Record<Layer, Reading>>>({});
  const [hoverMarks, setHoverMarks] = useState<Mark[]>([]);
  const [geometry, setGeometry] = useState<Geometry | null>(null);

  const viewport = useRef<HTMLDivElement>(null);
  const world = useRef<HTMLDivElement>(null);
  const page = useRef<HTMLDivElement>(null);
  const top = useRef<HTMLCanvasElement>(null);
  const left = useRef<HTMLCanvasElement>(null);
  const pointer = useRef<HTMLSpanElement>(null);
  const inspectButton = useRef<HTMLButtonElement>(null);
  const chips = useRef<Partial<Record<Layer, HTMLButtonElement | null>>>({});
  const camera = useRef<Camera>({ z: 1, cx: 0, cy: 0 });
  const geo = useRef<Geometry | null>(null);
  const tween = useRef(0);
  const settle = useRef(0);
  const hovered = useRef<HTMLElement | null>(null);
  const tags = useRef<ReturnType<typeof rulerTags>>({ x: [], y: [] });
  const colors = useRef<RulerColors | null>(null);

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

  // --- Camera and rulers ---------------------------------------------------------------------

  /** The rulers' colours, from tokens set on real properties (a custom property's own value is not resolved by light-dark()). */
  const readColors = () => {
    const canvas = top.current;
    if (!canvas) return;
    const style = getComputedStyle(canvas);
    colors.current = {
      ink: style.color,
      fill: style.backgroundColor,
      tick: style.borderTopColor,
      blue: style.outlineColor,
      pink: style.textDecorationColor,
      tagInk: style.caretColor,
    };
  };

  const drawRulers = () => {
    const g = geo.current;
    if (!g || !top.current || !left.current) return;
    if (!colors.current) readColors();
    const palette = colors.current;
    if (!palette) return;
    const { z, cx, cy } = camera.current;
    const s = g.s0 * z;
    const tx = g.vw / 2 - cx * s;
    const ty = g.vh / 2 - cy * s;
    drawRuler(top.current, 'x', -tx / s, s, tags.current.x, palette);
    drawRuler(left.current, 'y', -ty / s, s, tags.current.y, palette);
  };

  const applyCamera = () => {
    const g = geo.current;
    const layer = world.current;
    if (!g || !layer) return;
    const { z, cx, cy } = camera.current;
    const s = g.s0 * z;
    const tx = g.vw / 2 - cx * s;
    const ty = g.vh / 2 - cy * s;
    layer.style.transform = `translate(${tx.toFixed(2)}px, ${ty.toFixed(2)}px) scale(${s.toFixed(4)})`;
    layer.style.setProperty('--inv', (1 / s).toFixed(4));
    drawRulers();
  };

  /** Where the camera stands to frame `rect` (page px), or the whole page for null. */
  const frame = (rect: Rect | null): Camera => {
    const g = geo.current;
    if (!g) return camera.current;
    if (!rect) return { z: 1, cx: g.d / 2, cy: g.h / 2 };
    const room = { w: g.vw - g.margin * 2, h: g.vh - g.margin * 2 };
    const z = Math.min(
      Math.max(Math.min(room.w / (rect.w * g.s0), room.h / (rect.h * g.s0)), 1),
      MAX_ZOOM,
    );
    const s = g.s0 * z;
    const clamp = (centre: number, half: number, size: number) => {
      const low = half - g.margin / s;
      const high = size - half + g.margin / s;
      return low > high ? size / 2 : Math.min(Math.max(centre, low), high);
    };
    return {
      z,
      cx: clamp(rect.x + rect.w / 2, g.vw / 2 / s, g.d),
      cy: clamp(rect.y + rect.h / 2, g.vh / 2 / s, g.h),
    };
  };

  const moveCamera = (to: Camera, instant = false) => {
    cancelAnimationFrame(tween.current);
    if (instant || reduced()) {
      camera.current = to;
      applyCamera();
      return;
    }
    const from = { ...camera.current };
    const start = performance.now();
    const tick = (now: number) => {
      const t = Math.min((now - start) / CAMERA_MS, 1);
      const k = easeInOut(t);
      // The zoom is eased in log space, so zooming in and out feel alike.
      const z = Math.exp(Math.log(from.z) + (Math.log(to.z) - Math.log(from.z)) * k);
      camera.current = {
        z,
        cx: from.cx + (to.cx - from.cx) * k,
        cy: from.cy + (to.cy - from.cy) * k,
      };
      applyCamera();
      if (t < 1) tween.current = requestAnimationFrame(tick);
    };
    tween.current = requestAnimationFrame(tick);
  };

  // The canvas's size decides the page's: a desktop page at 1240 px or wider, scaled to fit, or
  // a phone page at the viewport's own width.
  useLayoutEffect(() => {
    const element = viewport.current;
    if (!element) return;
    const read = () => {
      const vw = element.clientWidth;
      const vh = element.clientHeight;
      if (!vw || !vh) return;
      const margin = vw < PHONE ? 12 : 24;
      const room = vw - margin * 2;
      const d = room < PHONE ? room : Math.max(room, DESIGN_WIDTH);
      const s0 = room / d;
      const next = { vw, vh, ruler: 0, margin, d, h: (vh - margin * 2) / s0, s0 };
      const before = geo.current;
      if (before && before.vw === vw && before.vh === vh) return;
      geo.current = next;
      setGeometry(next);
    };
    read();
    const observer = new ResizeObserver(read);
    observer.observe(element);
    return () => observer.disconnect();
  }, []);

  // --- Measurements --------------------------------------------------------------------------

  const state = useRef({ inspect, layers });
  state.current = { inspect, layers };

  const measure = useCallback(() => {
    const element = page.current;
    if (!element) return;
    const { inspect: on, layers: drawn } = state.current;
    if (!on) {
      setReadings((now) => (Object.keys(now).length ? {} : now));
      setHoverMarks((now) => (now.length ? [] : now));
      tags.current = { x: [], y: [] };
      drawRulers();
      return;
    }
    // Every layer is read, so each chip can count its issues; only the chosen ones are drawn.
    const next: Partial<Record<Layer, Reading>> = {};
    for (const layer of ALL) next[layer] = measureLayer(element, layer);
    setReadings(next);
    const target = hovered.current;
    setHoverMarks(target && element.contains(target) ? measureElement(element, target) : []);
    tags.current = rulerTags(drawn.map((layer) => next[layer]!).filter(Boolean));
    drawRulers();
    // drawRulers reads refs only.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /** Reads the marks now and on every frame for a while, so they follow the page as it moves. */
  const follow = useCallback(() => {
    cancelAnimationFrame(settle.current);
    const until = performance.now() + (reduced() ? 0 : SETTLE_MS);
    const tick = () => {
      measure();
      if (performance.now() < until) settle.current = requestAnimationFrame(tick);
    };
    tick();
  }, [measure]);

  useLayoutEffect(() => {
    if (!geometry) return;
    applyCamera();
    follow();
    // applyCamera reads refs only.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [geometry, inspect, layers, fixed, follow]);

  // The camera frames the focused layer's part of the page, read as it is now.
  useLayoutEffect(() => {
    if (!geometry) return;
    const element = page.current;
    // On a table too narrow for its columns, the box scrolls to the part the layer is about:
    // the values for the columns, the start for the other layers.
    const box = element?.querySelector<HTMLElement>('[data-m="tableBox"]');
    if (focus && box && box.scrollWidth > box.clientWidth + 1) {
      const first = box.querySelector<HTMLElement>('[data-m="colHead"]');
      const sticky = box.querySelector('thead th');
      const stuck = sticky && getComputedStyle(sticky).left !== 'auto';
      const to = focus === 'columns' && first && !stuck ? first.offsetLeft - 8 : 0;
      box.scrollTo({ left: to, behavior: reduced() ? 'instant' : 'smooth' });
    }
    const rect = focus && element ? measureLayer(element, focus).focus : null;
    moveCamera(frame(rect), !camera.current.cx);
    // moveCamera and frame read refs only; a new geometry re-frames at once.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [focus, geometry]);

  // Scrolling the table moves its marks. A change of scheme, from wherever it comes (the
  // prop, the reader's setting, a parent's color-scheme), runs the rulers' short colour
  // transition, and its end repaints them.
  useEffect(() => {
    const element = page.current;
    const ruler = top.current;
    if (!element || !ruler) return;
    let frameId = 0;
    const onScroll = () => {
      cancelAnimationFrame(frameId);
      frameId = requestAnimationFrame(measure);
    };
    const repaint = () => {
      colors.current = null;
      drawRulers();
    };
    element.addEventListener('scroll', onScroll, true);
    ruler.addEventListener('transitionend', repaint);
    return () => {
      element.removeEventListener('scroll', onScroll, true);
      ruler.removeEventListener('transitionend', repaint);
      cancelAnimationFrame(frameId);
    };
    // drawRulers reads refs only.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [measure]);

  useEffect(
    () => () => {
      cancelAnimationFrame(tween.current);
      cancelAnimationFrame(settle.current);
    },
    [],
  );

  // --- Hover and focus measure ---------------------------------------------------------------

  const hoverOn = (target: HTMLElement | null) => {
    const element = page.current;
    const next =
      target && element && element.contains(target) && target !== element ? target : null;
    if (hovered.current === next) return;
    hovered.current = next;
    setHoverMarks(next && inspect && element ? measureElement(element, next) : []);
  };
  const onPointerMove = (event: ReactPointerEvent) => {
    if (event.pointerType !== 'touch') take();
    if (!inspect) return;
    hoverOn(event.target as HTMLElement);
  };
  const onPointerDown = (event: ReactPointerEvent) => {
    if (inspect && event.pointerType === 'touch') hoverOn(event.target as HTMLElement);
  };
  const onFocusIn = (event: ReactFocusEvent) => {
    if (inspect) hoverOn(event.target as HTMLElement);
  };

  // --- Controls ------------------------------------------------------------------------------

  const applyStep = (index: number) => {
    const next = STEPS[index];
    setStep(index);
    setInspect(next.inspect);
    setLayers((now) => (same(now, next.layers) ? now : next.layers));
    setFixed((now) => (same(now, next.fixed) ? now : next.fixed));
    setFocus(next.focus);
    if (!next.inspect) hoverOn(null);
  };

  const toggleInspect = () => {
    setStep(null);
    setFocus(null);
    setInspect((on) => {
      if (on) hoverOn(null);
      return !on;
    });
  };

  const toggleLayer = (layer: Layer) => {
    setStep(null);
    setFocus(null);
    setInspect(true);
    setLayers((now) => (now.includes(layer) ? now.filter((x) => x !== layer) : [...now, layer]));
  };

  const setRevision = (revision: 'draft' | 'revised') => {
    setStep(null);
    setFixed(revision === 'revised' ? ALL : []);
  };

  const revision = fixed.length === ALL.length ? 'revised' : fixed.length === 0 ? 'draft' : null;

  // --- The demo ------------------------------------------------------------------------------

  const demoAct = useEffectEvent((act: { step: number } | { hover: HTMLElement | null }) => {
    if ('step' in act) applyStep(act.step);
    else hoverOn(act.hover);
  });
  const demo = autoplay && !defaultInspect && defaultLayers.length === 0 && playing;
  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    if (!demo || !stage || !arrow) return;
    const stop = runDemo(stage, arrow, async ({ wait, glide, glyph }) => {
      /** The middle of `element` (or a share across it), in the stage's px. */
      const at = (element: Element | null | undefined, fx = 0.5, fy = 0.55): Point => {
        const box = stage.getBoundingClientRect();
        const scale = box.width / stage.offsetWidth || 1;
        const r = element?.getBoundingClientRect() ?? box;
        return {
          x: (r.left + r.width * fx - box.left) / scale,
          y: (r.top + r.height * fy - box.top) / scale,
        };
      };
      const press = async (element: Element | null | undefined, then: () => void) => {
        await glide(at(element), 640);
        glyph('hand');
        await wait(140);
        then();
        await wait(220);
        glyph('arrow');
      };
      const chip = (layer: Layer) => chips.current[layer];
      for (;;) {
        demoAct({ step: 0 });
        await wait(1400);
        await press(inspectButton.current, () => demoAct({ step: 1 }));
        await wait(700);
        await press(chip('regions'), () => demoAct({ step: 2 }));
        await wait(2000);
        demoAct({ step: 3 });
        await wait(1500);
        await press(chip('rows'), () => demoAct({ step: 4 }));
        await wait(2000);
        demoAct({ step: 5 });
        await wait(1500);
        await press(chip('columns'), () => demoAct({ step: 6 }));
        await wait(2000);
        demoAct({ step: 7 });
        await wait(1500);
        await press(chip('controls'), () => demoAct({ step: 8 }));
        await wait(1800);
        demoAct({ step: 9 });
        await wait(1300);
        await press(chip('controls'), () => demoAct({ step: 10 }));
        await wait(900);
        // A hover over the finished wireframe: a thumbnail, then a value.
        const thumb = page.current?.querySelector('[data-m="thumb"]');
        await glide(at(thumb), 700);
        demoAct({ hover: thumb as HTMLElement });
        await wait(1100);
        const title = page.current?.querySelector('[data-m="row"] [data-m="postText"]');
        await glide(at(title, 0.4), 520);
        demoAct({ hover: title as HTMLElement });
        await wait(1100);
        demoAct({ hover: null });
        await press(inspectButton.current, () => demoAct({ step: 11 }));
        await glide(at(stage, 0.82, 0.9), 800);
        await wait(2600);
      }
    });
    return () => {
      stop();
      demoAct({ hover: null });
    };
  }, [demo, root]);

  // --- Render --------------------------------------------------------------------------------

  const drawn = inspect
    ? layers
        .filter((layer) => readings[layer])
        .map((layer) => ({ id: layer, groups: readings[layer]!.groups }))
    : [];
  const issues = inspect ? layers.flatMap((layer) => readings[layer]?.issues ?? []) : [];
  const report = !inspect
    ? 'Inspect to see the wireframe and its measurements.'
    : layers.length === 0
      ? 'Pick a layer to measure, or hover any element.'
      : issues.length === 0
        ? 'No issues: everything on these layers is on the grid and aligned.'
        : `${issues.length} issue${issues.length === 1 ? '' : 's'}: ${issues.join('. ')}.`;

  const g = geometry;
  const pageStyle = g ? ({ width: g.d, height: g.h } as CSSProperties) : undefined;

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="inspector"
      data-color-scheme={colorScheme}
      onPointerDownCapture={take}
      onKeyDownCapture={(event) => {
        take();
        if (event.key === 'Escape' && inspect) {
          event.preventDefault();
          toggleInspect();
        }
      }}
      onWheelCapture={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') take();
      }}
    >
      <div className={styles.bar} data-part="toolbar" role="toolbar" aria-label="Inspector">
        <button
          ref={inspectButton}
          type="button"
          className={styles.button}
          data-part="inspect"
          aria-pressed={inspect}
          aria-keyshortcuts="Escape"
          onClick={toggleInspect}
        >
          <Icon name="inspect" className={styles.barIcon} />
          Inspect
        </button>
        <div className={styles.chips} role="group" aria-label="Layers" data-part="layers">
          {LAYERS.map(({ id, label }) => {
            const count = readings[id]?.issues.length;
            const on = inspect && layers.includes(id);
            return (
              <button
                key={id}
                ref={(element) => {
                  chips.current[id] = element;
                }}
                type="button"
                className={styles.chip}
                data-part="layer"
                data-layer={id}
                aria-pressed={on}
                aria-label={
                  inspect && count !== undefined
                    ? `${label}, ${count === 0 ? 'no issues' : `${count} issue${count === 1 ? '' : 's'}`}`
                    : label
                }
                onClick={() => toggleLayer(id)}
              >
                <Icon name={LAYER_ICON[id]} className={styles.barIcon} />
                {label}
                {inspect && count !== undefined && (
                  <span className={styles.count} data-ok={count === 0} aria-hidden="true">
                    {count === 0 ? <Icon name="check" className={styles.countCheck} /> : count}
                  </span>
                )}
              </button>
            );
          })}
        </div>
        <div className={styles.segmented} role="radiogroup" aria-label="Page" data-part="revision">
          {(['draft', 'revised'] as const).map((value) => (
            <button
              key={value}
              type="button"
              role="radio"
              aria-checked={revision === value}
              tabIndex={revision === value || (revision === null && value === 'draft') ? 0 : -1}
              className={styles.segment}
              onClick={() => setRevision(value)}
              onKeyDown={(event) => {
                if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) {
                  event.preventDefault();
                  const other = value === 'draft' ? 'revised' : 'draft';
                  setRevision(other);
                  const sibling =
                    value === 'draft'
                      ? event.currentTarget.nextElementSibling
                      : event.currentTarget.previousElementSibling;
                  (sibling as HTMLElement | null)?.focus();
                }
              }}
            >
              {value === 'draft' ? 'Draft' : 'Revised'}
            </button>
          ))}
        </div>
        <div className={styles.tour} data-part="tour">
          <button
            type="button"
            className={styles.stepButton}
            aria-label="Previous step"
            onClick={() => applyStep(step === null || step === 0 ? STEPS.length - 1 : step - 1)}
          >
            <Icon name="prev" className={styles.barIcon} />
          </button>
          <span className={styles.stepLabel}>
            {step === null ? (
              'Tour'
            ) : (
              <>
                <span className={styles.stepCount}>
                  {step + 1}/{STEPS.length}
                </span>{' '}
                {STEPS[step].label}
              </>
            )}
          </span>
          <button
            type="button"
            className={styles.stepButton}
            aria-label="Next step"
            onClick={() => applyStep(step === null ? 0 : (step + 1) % STEPS.length)}
          >
            <Icon name="next" className={styles.barIcon} />
          </button>
        </div>
      </div>

      <div className={styles.canvas} data-part="canvas">
        <span className={styles.corner} aria-hidden="true" />
        <canvas ref={top} className={styles.rulerX} aria-hidden="true" />
        <canvas ref={left} className={styles.rulerY} aria-hidden="true" />
        {/* Hover only adds a measurement; the keyboard gets the same by focusing an element. */}
        {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
        <div
          ref={viewport}
          className={styles.viewport}
          data-inspect={inspect}
          onPointerMove={onPointerMove}
          onPointerLeave={() => hoverOn(null)}
          onPointerDown={onPointerDown}
          onFocus={onFocusIn}
          onBlur={() => hoverOn(null)}
        >
          <div ref={world} className={styles.world} style={pageStyle}>
            <div
              className={styles.frame}
              data-wire={inspect || undefined}
              data-fix-regions={fixed.includes('regions') || undefined}
              data-fix-rows={fixed.includes('rows') || undefined}
              data-fix-columns={fixed.includes('columns') || undefined}
              data-fix-controls={fixed.includes('controls') || undefined}
              data-polished={revision === 'revised' || undefined}
            >
              <Dashboard ref={page} />
            </div>
            {g && (
              <Overlay layers={drawn} hover={inspect ? hoverMarks : []} size={{ w: g.d, h: g.h }} />
            )}
          </div>
        </div>
      </div>

      <p className={styles.report} data-part="report" aria-live={demo ? 'off' : 'polite'}>
        {report}
      </p>

      <div className={styles.pointerLayer} aria-hidden="true">
        <DemoPointer
          ref={pointer}
          className={styles.pointer}
          arrowClass={styles.arrow}
          handClass={styles.hand}
        />
      </div>
    </div>
  );
}
```

### layout-inspector/layout-inspector.module.css

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

/* Layout inspector (layout-inspector.tsx): an inspector's toolbar over a grey canvas with
   rulers, the "Post performance" page on it, and a line under it that names what the
   measurements found.

   The page is drawn at 1240 px or wider and scaled to the canvas (a phone-width canvas lays it
   out at its own width instead); a camera zooms on it with a transform the script writes,
   along with --inv, one over the zoom, which the marks use to keep their lines one screen px
   thick and their badges one size.

   The draft and the revision differ by the custom properties set under .frame below: each
   data-fix-* attribute changes one area's spacing, and the measurements follow the layout as
   it moves (0.45 s, ease).

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

/* The wireframe's bars fade in and out: a registered colour can transition inside a gradient. */
@property --li-bar {
  syntax: '<color>';
  inherits: false;
  initial-value: transparent;
}

.root {
  --surface: #fff;
  --canvas: #efeff1;
  --edge: rgb(0 0 0 / 0.08);
  --bar-ink: #1d1d20;
  --bar-ink-2: #6e6e76;
  --bar-hover: #f2f2f4;
  --bar-pressed: #e8eefc;
  --bar-pressed-ink: #1d4fc4;
  --ruler-fill: #fbfbfc;
  --ruler-ink: #8e8e96;
  --ruler-tick: #c7c7cd;
  /* The page. */
  --page: #fff;
  --line: #ececef;
  --ink: #18181b;
  --ink-2: #686870;
  --ink-3: #96969e;
  --hover: #f4f4f5;
  --current: #f1f1f3;
  --sorted: #f7f7f8;
  --up: #15803d;
  --down: #c42b1c;
  --accent: #2563eb;
  --mark-ink: #fff;
  --shadow-near: rgb(0 0 0 / 0.06);
  --shadow-far: rgb(0 0 0 / 0.07);
  /* The wireframe: bars for text, a stronger one for bold text. */
  --bone: #e3e3e7;
  --bone-strong: #c9c9cf;
  /* The marks. */
  --blue: #2f74f0;
  --blue-line: #3b7ff2;
  --blue-fill: rgb(59 127 242 / 0.14);
  --blue-soft: rgb(59 127 242 / 0.07);
  --pink: #e0245e;
  --pink-line: #ec4d7c;
  --pink-fill: rgb(236 77 124 / 0.18);
  --pad-fill: rgb(46 164 104 / 0.2);
  --badge-ink: #fff;
  --badge-ring: #fff;
  --focus: #2f74f0;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.25);
  /* The kinds of post, as chips once the page is finished. */
  --reel: #fde4ee;
  --reel-ink: #a8124f;
  --article: #e2ecfd;
  --article-ink: #1d4fc4;
  --reply: #ddf4f7;
  --reply-ink: #0d6c7a;
  --carousel: #ede7fd;
  --carousel-ink: #5b2fc2;
  --video: #fde5e2;
  --video-ink: #b42318;
  --photo: #fdf3c8;
  --photo-ink: #7a5a00;
  --post: #f0f0f2;
  --post-ink: #4f4f57;
  /* The thumbnail of a post with no picture. */
  --tile: #f3f3f4;
  --tile-ink: #9a9aa1;

  position: relative;
  container-type: inline-size;
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 100%;
  color: var(--bar-ink);
  font:
    400 13px/1.4 ui-sans-serif,
    -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    Inter,
    Roboto,
    sans-serif;
  -webkit-font-smoothing: antialiased;
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --surface: light-dark(#fff, #1b1b1e);
    --canvas: light-dark(#efeff1, #0f0f11);
    --edge: light-dark(rgb(0 0 0 / 0.08), rgb(255 255 255 / 0.09));
    --bar-ink: light-dark(#1d1d20, #ececef);
    --bar-ink-2: light-dark(#6e6e76, #9d9da5);
    --bar-hover: light-dark(#f2f2f4, #26262a);
    --bar-pressed: light-dark(#e8eefc, #1c2a47);
    --bar-pressed-ink: light-dark(#1d4fc4, #9cbcff);
    --ruler-fill: light-dark(#fbfbfc, #161619);
    --ruler-ink: light-dark(#8e8e96, #6f6f78);
    --ruler-tick: light-dark(#c7c7cd, #393940);
    --page: light-dark(#fff, #18181b);
    --line: light-dark(#ececef, #2a2a2f);
    --ink: light-dark(#18181b, #ededf0);
    --ink-2: light-dark(#686870, #a0a0a8);
    --ink-3: light-dark(#96969e, #74747c);
    --hover: light-dark(#f4f4f5, #222226);
    --current: light-dark(#f1f1f3, #26262b);
    --sorted: light-dark(#f7f7f8, #1d1d21);
    --up: light-dark(#15803d, #4ade80);
    --down: light-dark(#c42b1c, #f87171);
    --accent: light-dark(#2563eb, #3b7ff2);
    --mark-ink: light-dark(#fff, #18181b);
    --shadow-near: light-dark(rgb(0 0 0 / 0.06), rgb(0 0 0 / 0.4));
    --shadow-far: light-dark(rgb(0 0 0 / 0.07), rgb(0 0 0 / 0.5));
    --bone: light-dark(#e3e3e7, #2c2c31);
    --bone-strong: light-dark(#c9c9cf, #45454c);
    --blue-line: light-dark(#3b7ff2, #5a95f5);
    --blue-fill: light-dark(rgb(59 127 242 / 0.14), rgb(90 149 245 / 0.2));
    --blue-soft: light-dark(rgb(59 127 242 / 0.07), rgb(90 149 245 / 0.1));
    --pink-line: light-dark(#ec4d7c, #f06b92);
    --pink-fill: light-dark(rgb(236 77 124 / 0.18), rgb(240 107 146 / 0.22));
    --pad-fill: light-dark(rgb(46 164 104 / 0.2), rgb(74 200 130 / 0.22));
    --badge-ring: light-dark(#fff, #18181b);
    --reel: light-dark(#fde4ee, #3d1526);
    --reel-ink: light-dark(#a8124f, #f7a1c2);
    --article: light-dark(#e2ecfd, #172641);
    --article-ink: light-dark(#1d4fc4, #9cbcff);
    --reply: light-dark(#ddf4f7, #0f3036);
    --reply-ink: light-dark(#0d6c7a, #8adbe6);
    --carousel: light-dark(#ede7fd, #26193f);
    --carousel-ink: light-dark(#5b2fc2, #c5b0fb);
    --video: light-dark(#fde5e2, #3b1714);
    --video-ink: light-dark(#b42318, #f8a59b);
    --photo: light-dark(#fdf3c8, #33290a);
    --photo-ink: light-dark(#7a5a00, #f1d36b);
    --post: light-dark(#f0f0f2, #26262b);
    --post-ink: light-dark(#4f4f57, #b3b3bb);
    --tile: light-dark(#f3f3f4, #25252a);
    --tile-ink: light-dark(#9a9aa1, #77777f);
  }
}
.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;
}

.root button {
  font: inherit;
  color: inherit;
}
.root :focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

/* --- The inspector's toolbar ------------------------------------------------------------- */

.bar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  font-size: 12.5px;
}
.button,
.chip,
.stepButton {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 32px;
  padding: 0 11px;
  border: 1px solid var(--edge);
  border-radius: 9px;
  background: var(--surface);
  cursor: pointer;
  white-space: nowrap;
  transition:
    background-color 0.15s ease,
    color 0.15s ease,
    border-color 0.15s ease;
}
.button:hover,
.chip:hover,
.stepButton:hover {
  background: var(--bar-hover);
}
.button[aria-pressed='true'],
.chip[aria-pressed='true'] {
  border-color: transparent;
  background: var(--bar-pressed);
  color: var(--bar-pressed-ink);
}
.button[aria-pressed='true'] {
  background: var(--blue);
  color: #fff;
}
.barIcon {
  flex: none;
  width: 15px;
  height: 15px;
}
.chips {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.chip {
  padding: 0 9px;
}
.count {
  display: inline-grid;
  place-items: center;
  min-width: 17px;
  height: 17px;
  padding: 0 5px;
  border-radius: 9px;
  background: var(--pink);
  color: #fff;
  font-size: 10.5px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}
.count[data-ok='true'] {
  padding: 0;
  background: var(--blue);
}
.countCheck {
  width: 12px;
  height: 12px;
  stroke-width: 2.2;
}
.segmented {
  display: inline-flex;
  padding: 2px;
  border: 1px solid var(--edge);
  border-radius: 9px;
  background: var(--surface);
}
.segment {
  height: 26px;
  padding: 0 10px;
  border: 0;
  border-radius: 7px;
  background: transparent;
  color: var(--bar-ink-2);
  cursor: pointer;
}
.segment[aria-checked='true'] {
  background: var(--bar-pressed);
  color: var(--bar-pressed-ink);
  font-weight: 600;
}
.tour {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  margin-left: auto;
}
.stepButton {
  width: 32px;
  padding: 0;
  justify-content: center;
}
.stepLabel {
  min-width: 13.5em;
  text-align: center;
  color: var(--bar-ink-2);
  white-space: nowrap;
}
.stepCount {
  color: var(--bar-ink);
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

/* --- The canvas, its rulers and the camera ----------------------------------------------- */

.canvas {
  --ruler: 20px;
  position: relative;
  height: clamp(440px, 62cqw, 680px);
  overflow: hidden;
  border: 1px solid var(--edge);
  border-radius: 16px;
  background: var(--canvas);
}
/* The rulers' colours are read by the script from real properties of the canvases. */
.rulerX,
.rulerY {
  position: absolute;
  z-index: 2;
  display: block;
  color: var(--ruler-ink);
  background-color: var(--ruler-fill);
  border: 0 solid var(--ruler-tick);
  outline: 0 solid var(--blue);
  text-decoration-color: var(--pink);
  caret-color: var(--badge-ink);
  /* Not for the eye: its end tells the script the scheme changed (it repaints the canvases). */
  transition: color 1ms;
}
.rulerX {
  top: 0;
  left: var(--ruler);
  width: calc(100% - var(--ruler));
  height: var(--ruler);
  box-shadow: 0 1px 0 var(--edge);
}
.rulerY {
  top: var(--ruler);
  left: 0;
  width: var(--ruler);
  height: calc(100% - var(--ruler));
  box-shadow: 1px 0 0 var(--edge);
}
.corner {
  position: absolute;
  z-index: 3;
  top: 0;
  left: 0;
  width: var(--ruler);
  height: var(--ruler);
  background: var(--ruler-fill);
  box-shadow: 1px 1px 0 var(--edge);
}
.viewport {
  position: absolute;
  inset: var(--ruler) 0 0 var(--ruler);
  overflow: hidden;
}
.viewport[data-inspect='true'] {
  cursor: crosshair;
}
.world {
  --inv: 1;
  position: absolute;
  top: 0;
  left: 0;
  transform-origin: 0 0;
  will-change: transform;
}
.frame {
  /* The draft's spacing; each data-fix-* below is one area's revision. */
  --side: 234px;
  --side-pad: 14px;
  --top-h: 50px;
  --row-pt: 14px;
  --row-px: 20px;
  --thumb-gap: 12px;
  --thumb: 40px;
  --tool-h: 28px;
  --toggle-h: 30px;
  --tool-gap: 6px;
  --move: 0.45s ease;
  position: absolute;
  inset: 0;
  /* Its sticky table head and column stack inside it, under the marks. */
  isolation: isolate;
  overflow: hidden;
  border-radius: 14px;
  background: var(--page);
  box-shadow:
    0 0 0 1px var(--edge),
    0 1px 2px var(--shadow-near),
    0 8px 28px var(--shadow-far);
}
.frame[data-fix-regions] {
  --side: 240px;
  --side-pad: 16px;
  --top-h: 48px;
}
.frame[data-fix-rows] {
  --row-pt: 16px;
  --row-px: 16px;
  --thumb: 56px;
}
.frame[data-fix-controls] {
  --tool-h: 32px;
  --toggle-h: 32px;
  --tool-gap: 8px;
}

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

.page {
  container: page / inline-size;
  display: flex;
  flex-direction: column;
  height: 100%;
  color: var(--ink);
  font-size: 13px;
  line-height: 1.4;
}
.page button {
  cursor: pointer;
}
.icon {
  flex: none;
  width: 15px;
  height: 15px;
}
.chev {
  flex: none;
  width: 13px;
  height: 13px;
  color: var(--ink-3);
}

/* Each piece of text; in the wireframe it turns into a bar of its own lines. */
.t {
  --li-bar: transparent;
  border-radius: 3px;
  background: linear-gradient(var(--li-bar), var(--li-bar)) 0 55% / 100% 0.74em no-repeat;
  -webkit-box-decoration-break: clone;
  box-decoration-break: clone;
  transition:
    color 0.4s ease,
    --li-bar 0.4s ease;
}
.frame[data-wire] .t {
  --li-bar: var(--bone);
  color: transparent !important;
}
.frame[data-wire] .t[data-strong] {
  --li-bar: var(--bone-strong);
}
.page svg {
  border-radius: 3px;
  transition:
    color 0.4s ease,
    background-color 0.4s ease,
    opacity 0.4s ease;
}
.frame[data-wire] .icon,
.frame[data-wire] .chev,
.frame[data-wire] .sort,
.frame[data-wire] .titleStar {
  color: transparent !important;
  background-color: var(--bone);
}

.topbar {
  display: grid;
  grid-template-columns: auto minmax(0, 280px) 1fr;
  align-items: center;
  gap: 16px;
  flex: none;
  height: var(--top-h);
  padding: 0 14px;
  border-bottom: 1px solid var(--line);
  transition: height var(--move);
}
.frame[data-fix-regions] .topbar {
  grid-template-columns: 1fr minmax(0, 280px) 1fr;
}
.topLeft {
  display: flex;
  align-items: center;
  min-width: 0;
}
.brand {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: none;
  width: calc(var(--side) - 14px);
  font-weight: 600;
  transition: width var(--move);
}
.mark {
  flex: none;
  width: 22px;
  height: 22px;
  color: var(--ink);
}
.frame[data-wire] .mark {
  color: var(--bone-strong);
  --mark-ink: transparent;
}
.crumbs {
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 0;
  overflow: hidden;
  color: var(--ink-2);
  font-size: 12px;
  white-space: nowrap;
  mask-image: linear-gradient(90deg, #000 calc(100% - 24px), transparent);
}
.crumbs [aria-current] {
  color: var(--ink);
}
.slash {
  color: var(--ink-3);
}
.search {
  display: flex;
  align-items: center;
  gap: 8px;
  height: 30px;
  min-width: 0;
  margin-left: 28px;
  padding: 0 8px 0 10px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--page);
  color: var(--ink-3);
  font-size: 12px;
  text-align: left;
}
.frame[data-fix-regions] .search {
  margin-left: 0;
}
.search > .t {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.kbd {
  display: inline-grid;
  place-items: center;
  min-width: 18px;
  height: 18px;
  border: 1px solid var(--line);
  border-radius: 5px;
  font: inherit;
  font-size: 10.5px;
}
.topActions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 6px;
}
.iconButton {
  display: grid;
  place-items: center;
  width: 30px;
  height: 30px;
  padding: 0;
  border: 0;
  border-radius: 8px;
  background: transparent;
  color: var(--ink-2);
}
.iconButton:hover,
.navItem:hover,
.filter:hover {
  background: var(--hover);
}
.compose {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 30px;
  padding: 0 11px;
  border: 0;
  border-radius: 8px;
  background: var(--ink);
  color: var(--page);
  font-size: 12px;
  font-weight: 600;
  transition: background-color 0.4s ease;
}
.frame[data-polished] .compose {
  background: var(--accent);
  color: #fff;
}
.frame[data-wire] .compose {
  background: var(--hover);
}

.body {
  display: grid;
  grid-template-columns: var(--side) minmax(0, 1fr);
  flex: 1;
  min-height: 0;
  transition: grid-template-columns var(--move);
}
.sidebar {
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  padding: 12px var(--side-pad);
  border-right: 1px solid var(--line);
  transition: padding var(--move);
}
.sideIcons {
  display: flex;
  gap: 4px;
  margin-bottom: 14px;
  color: var(--ink-2);
}
.sideIcon {
  display: grid;
  place-items: center;
  width: 24px;
  height: 24px;
  border-radius: 6px;
}
.sideIcon:nth-child(4) {
  background: var(--current);
  color: var(--ink);
}
.sideHeading {
  margin: 0 0 6px;
  padding: 0 8px;
  color: var(--ink-3);
  font-size: 11.5px;
}
.nav,
.subnav {
  margin: 0;
  padding: 0;
  list-style: none;
}
.subnav {
  margin: 2px 0 4px 14px;
}
.navItem {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 6px;
  width: 100%;
  height: 28px;
  padding: 0 8px;
  border: 0;
  border-radius: 7px;
  background: transparent;
  color: var(--ink-2);
  font-size: 12.5px;
  text-align: left;
  white-space: nowrap;
}
.navItem > .t {
  overflow: hidden;
  text-overflow: ellipsis;
}
.navItem[aria-current='page'] {
  background: var(--current);
  color: var(--ink);
  font-weight: 600;
}
.plan {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: auto;
  padding: 10px 8px 0;
}
.planLine {
  display: flex;
  justify-content: space-between;
  margin: 0;
  color: var(--ink-2);
  font-size: 11.5px;
}
.planBar {
  height: 3px;
  border-radius: 2px;
  background: linear-gradient(90deg, var(--ink) 25%, var(--line) 25%);
}
.frame[data-wire] .planBar {
  background: var(--bone);
}
.planButton {
  height: 28px;
  border: 1px solid var(--line);
  border-radius: 7px;
  background: var(--page);
  font-size: 12px;
}

.main {
  display: flex;
  flex-direction: column;
  min-width: 0;
  min-height: 0;
}
.head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  padding: 18px 24px 14px;
}
.titleBlock {
  min-width: 0;
}
.title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 20px;
  line-height: 26px;
  font-weight: 600;
  letter-spacing: -0.01em;
}
.titleStar {
  width: 15px;
  height: 15px;
  color: var(--ink-3);
}
.subtitle {
  margin: 4px 0 0;
  color: var(--ink-2);
  font-size: 12.5px;
}
.tools {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: flex-end;
  gap: var(--tool-gap);
  flex: none;
  transition: gap var(--move);
}
.toggle {
  display: inline-flex;
  align-items: stretch;
  height: var(--toggle-h);
  padding: 2px;
  border: 1px solid var(--line);
  border-radius: 8px;
  transition: height var(--move);
}
.toggle button {
  display: grid;
  place-items: center;
  width: 26px;
  padding: 0;
  border: 0;
  border-radius: 6px;
  background: transparent;
  color: var(--ink-2);
}
.toggle button[aria-pressed='true'] {
  background: var(--current);
  color: var(--ink);
}
.tool {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: var(--tool-h);
  padding: 0 10px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--page);
  font-size: 12px;
  white-space: nowrap;
  transition: height var(--move);
}
.vs {
  color: var(--ink-3);
}
.filters {
  display: flex;
  flex-wrap: wrap;
  gap: 4px 6px;
  padding: 0 18px 10px;
  border-bottom: 1px solid var(--line);
}
.filter {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  height: 26px;
  padding: 0 6px;
  border: 0;
  border-radius: 7px;
  background: transparent;
  color: var(--ink-2);
  font-size: 12px;
}
.filter > .t[data-strong] {
  color: var(--ink);
  font-weight: 600;
}

/* The table scrolls inside its own box, on both axes, under a sticky head and first column. */
.tableBox {
  flex: 1;
  min-height: 0;
  overflow: auto;
  overscroll-behavior: contain;
  scrollbar-width: thin;
}
.tableBox:focus-visible {
  outline-offset: -2px;
}
.table {
  width: 100%;
  min-width: 960px;
  border-collapse: separate;
  border-spacing: 0;
  font-variant-numeric: tabular-nums;
}
.table th,
.table td {
  padding: var(--row-pt) 12px 12px;
  border-bottom: 1px solid var(--line);
  vertical-align: top;
  font-weight: 400;
  transition: padding var(--move);
}
.table thead th {
  position: sticky;
  z-index: 1;
  top: 0;
  padding-top: 12px;
  background: var(--page);
  text-align: left;
}
.headLabel {
  display: block;
  color: var(--ink-2);
  font-size: 11.5px;
  white-space: nowrap;
}
.headLabel [data-m='headLabel'] {
  display: inline-flex;
  align-items: center;
  gap: 3px;
}
.sort {
  width: 12px;
  height: 12px;
  color: var(--ink);
}
.headTotal {
  display: block;
  margin-top: 2px;
  font-size: 17px;
  line-height: 22px;
  font-weight: 600;
}
.headNote,
.delta {
  display: block;
  color: var(--ink-3);
  font-size: 11px;
  white-space: nowrap;
}
.delta[data-up='true'] {
  color: var(--up);
}
.delta[data-up='false'] {
  color: var(--down);
}
.postHead,
.postCell {
  position: sticky;
  left: 0;
  z-index: 1;
  background: var(--page);
  text-align: left;
}
.table thead .postHead {
  z-index: 2;
  padding-left: var(--row-px);
}
.postCell {
  padding-left: var(--row-px) !important;
  border-right: 1px solid var(--line);
}
.pubHead,
.pubCell {
  width: 104px;
  background: var(--sorted) !important;
  white-space: nowrap;
}
.pubHead .headLabel {
  color: var(--ink);
  font-weight: 600;
}
.metricHead {
  width: 76px;
  white-space: nowrap;
}
.frame[data-fix-columns] .metricHead {
  text-align: right !important;
}
.metricCell {
  text-align: right;
  white-space: nowrap;
}
.value {
  font-size: 12.5px;
}
.time {
  display: block;
  color: var(--ink-3);
  font-size: 11px;
}
.row:hover > * {
  background: var(--hover);
}
.post {
  display: flex;
  align-items: flex-start;
  gap: var(--thumb-gap);
  width: 248px;
}
.thumb {
  position: relative;
  flex: none;
  width: var(--thumb);
  height: var(--thumb);
  overflow: hidden;
  border-radius: 7px;
  background: var(--bone);
  box-shadow: inset 0 0 0 1px var(--edge);
  transition:
    width var(--move),
    height var(--move);
}
.thumbArt {
  display: block;
  width: 100%;
  height: 100%;
  filter: grayscale(1) contrast(1.05);
  transition:
    filter 0.5s ease,
    opacity 0.4s ease !important;
}
.frame[data-polished] .thumbArt {
  filter: none;
}
.frame[data-wire] .thumbArt {
  opacity: 0;
}
.postText {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 0;
  min-height: 0;
  transition: min-height var(--move);
}
.frame[data-fix-rows] .postText {
  justify-content: space-between;
  min-height: var(--thumb);
}
.frame[data-wire] .postTitle {
  /* The clamp's ellipsis takes the block's colour, not its words'. */
  color: transparent;
}
.postTitle {
  display: -webkit-box;
  overflow: hidden;
  font-size: 12.5px;
  line-height: 17px;
  white-space: normal;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
}
.meta {
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--ink-2);
  font-size: 11px;
  line-height: 18px;
  white-space: nowrap;
}
.dot {
  width: 2px;
  height: 2px;
  border-radius: 50%;
  background: var(--ink-3);
}
.kind {
  border-radius: 4px;
  transition:
    background-color 0.4s ease,
    padding 0.4s ease;
}
.frame[data-polished]:not([data-wire]) .kind {
  padding: 0 5px;
  background: var(--post);
  color: var(--post-ink);
  line-height: 16px;
}
.frame[data-polished]:not([data-wire]) .kind[data-kind='Reel'] {
  background: var(--reel);
  color: var(--reel-ink);
}
.frame[data-polished]:not([data-wire]) .kind[data-kind='Article'] {
  background: var(--article);
  color: var(--article-ink);
}
.frame[data-polished]:not([data-wire]) .kind[data-kind='Reply'] {
  background: var(--reply);
  color: var(--reply-ink);
}
.frame[data-polished]:not([data-wire]) .kind[data-kind='Carousel'] {
  background: var(--carousel);
  color: var(--carousel-ink);
}
.frame[data-polished]:not([data-wire]) .kind[data-kind='Video'] {
  background: var(--video);
  color: var(--video-ink);
}
.frame[data-polished]:not([data-wire]) .kind[data-kind='Photo'] {
  background: var(--photo);
  color: var(--photo-ink);
}
.boosted {
  color: var(--ink);
  font-weight: 600;
}

/* A phone-width page: no sidebar or breadcrumbs, an icon-only search and compose, the tools
   under the title. */
@container page (width < 600px) {
  .topbar,
  .frame[data-fix-regions] .topbar {
    grid-template-columns: auto minmax(0, 1fr) auto;
    gap: 10px;
    padding: 0 10px;
  }
  .brand {
    width: auto;
  }
  .brand > .t,
  .crumbs,
  .compose > .t,
  .kbd {
    display: none;
  }
  .search {
    margin-left: 8px;
  }
  .frame[data-fix-regions] .search {
    margin-left: 0;
  }
  .compose {
    width: 30px;
    padding: 0;
    justify-content: center;
  }
  .iconButton:first-child {
    display: none;
  }
  .body {
    grid-template-columns: minmax(0, 1fr);
  }
  .sidebar {
    display: none;
  }
  .head {
    flex-direction: column;
    gap: 10px;
    padding: 14px 14px 10px;
  }
  .tools {
    justify-content: flex-start;
  }
  /* Only what fits one line each: the title, the tools, two filters. */
  .subtitle,
  .vs,
  .tool > .t:not([data-strong]),
  .filter:nth-child(n + 3) {
    display: none;
  }
  .tools {
    flex-wrap: nowrap;
  }
  .filters {
    padding: 0 8px 8px;
  }
  .table {
    min-width: 800px;
  }
  .post {
    width: 196px;
  }
  /* A sticky first column would take most of a phone's table: it scrolls with the rest. */
  .postCell {
    position: static;
  }
  .table thead .postHead {
    left: auto;
  }
}

/* --- The marks --------------------------------------------------------------------------- */

.overlay {
  position: absolute;
  z-index: 1;
  inset: 0;
  pointer-events: none;
}
.layer {
  position: absolute;
  inset: 0;
  animation: layer-in 0.3s ease both;
}
@keyframes layer-in {
  from {
    opacity: 0;
  }
}
.group {
  position: absolute;
}
.group[data-clipped] {
  overflow: hidden;
}
.mBox {
  position: absolute;
  box-sizing: border-box;
  border: calc(1px * var(--inv)) solid var(--blue-line);
  background: var(--blue-fill);
}
.mBox[data-soft] {
  border-color: color-mix(in srgb, var(--blue-line) 45%, transparent);
  background: var(--blue-soft);
}
.mBox[data-tone='pink'] {
  border-color: var(--pink-line);
  background: var(--pink-fill);
}
.mBox[data-tone='pad'] {
  border: 0;
  background: var(--pad-fill);
}
.mV,
.mH {
  position: absolute;
  border: 0 solid var(--blue-line);
}
.mV {
  top: 0;
  bottom: 0;
  border-left-width: calc(1px * var(--inv));
}
.mH {
  left: 0;
  right: 0;
  border-top-width: calc(1px * var(--inv));
}
.mV[data-tone='pink'],
.mH[data-tone='pink'] {
  border-color: var(--pink-line);
}
.mV[data-dashed],
.mH[data-dashed] {
  border-style: dashed;
}
.mBadge {
  position: absolute;
  display: grid;
  place-items: center;
  min-width: 22px;
  height: 19px;
  padding: 0 6px;
  border-radius: 10px;
  background: var(--blue);
  box-shadow: 0 0 0 1.5px var(--badge-ring);
  color: var(--badge-ink);
  font-size: 11px;
  font-weight: 600;
  line-height: 1;
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
  transform: translate(-50%, -50%) scale(var(--inv));
  transition: background-color 0.25s ease;
  animation: badge-in 0.35s cubic-bezier(0.3, 1.5, 0.5, 1) both;
}
.mBadge[data-tone='pink'] {
  background: var(--pink);
}
.mBadge[data-check] {
  width: 19px;
  min-width: 0;
  padding: 0;
}
.mCheck {
  width: 13px;
  height: 13px;
  stroke-width: 2.2;
}
@keyframes badge-in {
  from {
    opacity: 0;
    transform: translate(-50%, -50%) scale(calc(var(--inv) * 0.5));
  }
}

/* --- The report, the demo pointer -------------------------------------------------------- */

.report {
  min-height: 1.4em;
  margin: 0;
  padding: 0 4px;
  color: var(--bar-ink-2);
  font-size: 12.5px;
}
.pointerLayer {
  position: absolute;
  inset: 0;
  z-index: 5;
  pointer-events: none;
}
.pointer {
  width: 24px;
  height: 24px;
}
.hand {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .arrow {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .hand {
  visibility: visible;
}

@container (width < 600px) {
  .canvas {
    --ruler: 16px;
    height: 580px;
  }
  /* The tour on a line of its own, so a longer step name doesn't move the canvas. */
  .tour {
    flex-basis: 100%;
    margin-left: 0;
  }
  .stepLabel {
    min-width: 0;
    flex: 1;
  }
}

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

### layout-inspector/dashboard.tsx

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

'use client';

import { useState, type ReactNode, type Ref } from 'react';
import { Thumb } from './art';
import { BRAND, METRICS, NAV, POSTS, formatValue } from './data';
import { Icon, Mark, type Glyph } from './glyphs';
import styles from './layout-inspector.module.css';

/*
 * The page under inspection: a "Post performance" report with a sidebar of reports, a top bar
 * with a centred search, a header with its tools, filters, and a table of twelve posts under a
 * row of totals. It is an ordinary responsive page: the inspector only reads it. Every piece
 * of text sits in a span of class .t, which is what turns into a grey bar in the wireframe, and
 * the pieces the measurements look for carry a data-m name.
 *
 * Its spacing comes from custom properties that the draft and the revision set differently
 * (data-fix-* on the page, in the stylesheet), so a fix is a real change of layout that the
 * inspector measures again, not a different picture.
 */

const SIDE_ICONS: Glyph[] = ['home', 'star', 'network', 'people', 'coin', 'rocket', 'palette'];

function T({ children, strong }: { children: ReactNode; strong?: boolean }) {
  return (
    <span className={styles.t} data-strong={strong || undefined}>
      {children}
    </span>
  );
}

export function Dashboard({ ref }: { ref?: Ref<HTMLDivElement> }) {
  const [active, setActive] = useState('Post performance');

  return (
    <div ref={ref} className={styles.page} data-part="page">
      <header className={styles.topbar} data-m="topbar">
        <div className={styles.topLeft}>
          <div className={styles.brand} data-m="brand">
            <Mark className={styles.mark} />
            <T strong>{BRAND}</T>
          </div>
          <nav className={styles.crumbs} aria-label="Breadcrumb">
            <T>Reports</T>
            <span className={styles.slash} aria-hidden="true">
              /
            </span>
            <T>Cross-network</T>
            <span className={styles.slash} aria-hidden="true">
              /
            </span>
            <span aria-current="page">
              <T strong>Post performance</T>
            </span>
          </nav>
        </div>
        <button type="button" className={styles.search} data-m="search">
          <Icon name="search" className={styles.icon} />
          <T>Search posts</T>
          <kbd className={styles.kbd}>
            <T>/</T>
          </kbd>
        </button>
        <div className={styles.topActions}>
          <button type="button" className={styles.iconButton} aria-label="Notifications">
            <Icon name="bell" className={styles.icon} />
          </button>
          <button type="button" className={styles.iconButton} aria-label="Help">
            <Icon name="help" className={styles.icon} />
          </button>
          <button type="button" className={styles.compose}>
            <Icon name="pen" className={styles.icon} />
            <T>Compose</T>
          </button>
        </div>
      </header>

      <div className={styles.body}>
        <aside className={styles.sidebar} data-m="sidebar" aria-label="Reports">
          <div className={styles.sideIcons} aria-hidden="true">
            {SIDE_ICONS.map((name) => (
              <span key={name} className={styles.sideIcon}>
                <Icon name={name} className={styles.icon} />
              </span>
            ))}
          </div>
          <p className={styles.sideHeading}>
            <T strong>Reports</T>
          </p>
          <ul className={styles.nav}>
            {NAV.top.map((label) => (
              <li key={label}>
                <button type="button" className={styles.navItem} data-m="navItem">
                  <T>{label}</T>
                </button>
              </li>
            ))}
            <li>
              <button type="button" className={styles.navItem} aria-expanded="true">
                <T>{NAV.group}</T>
                <Icon name="chevronDown" className={styles.chev} />
              </button>
              <ul className={styles.subnav}>
                {NAV.children.map((label) => (
                  <li key={label}>
                    <button
                      type="button"
                      className={styles.navItem}
                      aria-current={label === active ? 'page' : undefined}
                      onClick={() => setActive(label)}
                    >
                      <T>{label}</T>
                    </button>
                  </li>
                ))}
              </ul>
            </li>
            {NAV.rest.map((label, index) => (
              <li key={label}>
                <button type="button" className={styles.navItem}>
                  <T>{label}</T>
                  {index < 3 && <Icon name="chevronRight" className={styles.chev} />}
                </button>
              </li>
            ))}
          </ul>
          <div className={styles.plan}>
            <p className={styles.planLine}>
              <T strong>Free trial</T>
              <T>23 days left</T>
            </p>
            <span className={styles.planBar} aria-hidden="true" />
            <button type="button" className={styles.planButton}>
              <T>Start subscription</T>
            </button>
          </div>
        </aside>

        <main className={styles.main} data-m="main">
          <div className={styles.head} data-m="head">
            <div className={styles.titleBlock}>
              <h3 className={styles.title}>
                <T strong>Post performance</T>
                <Icon name="star" className={styles.titleStar} />
              </h3>
              <p className={styles.subtitle}>
                <T>Lifetime activity on posts published in this period, in Lisbon time.</T>
              </p>
            </div>
            <div className={styles.tools} data-m="tools">
              <div className={styles.toggle} data-m="tool" role="group" aria-label="View">
                <button type="button" aria-label="List" aria-pressed="true">
                  <Icon name="list" className={styles.icon} />
                </button>
                <button type="button" aria-label="Grid" aria-pressed="false">
                  <Icon name="grid" className={styles.icon} />
                </button>
              </div>
              <button type="button" className={styles.tool} data-m="tool">
                <Icon name="calendar" className={styles.icon} />
                <T strong>1 – 31 Oct 2026</T>
                <span className={styles.vs}>
                  <T>vs 1 – 30 Sep</T>
                </span>
                <Icon name="chevronDown" className={styles.chev} />
              </button>
              <button type="button" className={styles.tool} data-m="tool">
                <Icon name="share" className={styles.icon} />
                <T>Share</T>
              </button>
              <button type="button" className={styles.tool} data-m="tool" aria-label="More">
                <Icon name="more" className={styles.icon} />
              </button>
            </div>
          </div>

          <div className={styles.filters}>
            {['Sources', 'Post types', 'Status', 'Authors'].map((label) => (
              <button key={label} type="button" className={styles.filter}>
                <T>{label}</T>
                <T strong>All</T>
                <Icon name="chevronDown" className={styles.chev} />
              </button>
            ))}
          </div>

          {/* A scroll box is focusable so the keyboard can scroll it (WCAG 2.1.1). */}
          <div
            className={styles.tableBox}
            data-m="tableBox"
            role="region"
            aria-label="Posts in the period"
            // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex
            tabIndex={0}
          >
            <table className={styles.table}>
              <thead>
                <tr>
                  <th className={styles.postHead} scope="col">
                    <span className={styles.headLabel}>
                      <T>Posts</T>
                    </span>
                    <span className={styles.headTotal}>
                      <T strong>12 posts</T>
                    </span>
                    <span className={styles.headNote}>
                      <T>1 – 31 Oct 2026</T>
                    </span>
                  </th>
                  <th className={styles.pubHead} scope="col" data-m="colHead" data-align="start">
                    <span className={styles.headLabel}>
                      <span data-m="headLabel">
                        <T strong>Published</T>
                        <Icon name="sort" className={styles.sort} />
                      </span>
                    </span>
                    <span className={styles.headTotal}>
                      <T strong>2.7</T>
                    </span>
                    <span className={styles.headNote}>
                      <T>posts a week</T>
                    </span>
                  </th>
                  {METRICS.map((metric) => (
                    <th key={metric.id} className={styles.metricHead} scope="col" data-m="colHead">
                      <span className={styles.headLabel}>
                        <span data-m="headLabel">
                          <T>{metric.label}</T>
                        </span>
                      </span>
                      <span className={styles.headTotal}>
                        <T strong>{metric.total}</T>
                      </span>
                      <span className={styles.delta} data-up={metric.up}>
                        <T>{metric.delta}</T>
                      </span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {POSTS.map((post) => (
                  <tr key={post.id} className={styles.row} data-m="row">
                    <th className={styles.postCell} scope="row" data-m="postCell">
                      <div className={styles.post}>
                        <span className={styles.thumb} data-m="thumb" data-art={post.art}>
                          <Thumb art={post.art} className={styles.thumbArt} />
                        </span>
                        <span className={styles.postText} data-m="postText">
                          <span className={styles.postTitle}>
                            <T>{post.title}</T>
                          </span>
                          <span className={styles.meta}>
                            <T>{post.author}</T>
                            <span className={styles.dot} aria-hidden="true" />
                            <span className={styles.kind} data-kind={post.kind}>
                              <T>{post.kind}</T>
                            </span>
                            {post.boosted && (
                              <span className={styles.boosted}>
                                <T strong>Boosted</T>
                              </span>
                            )}
                          </span>
                        </span>
                      </div>
                    </th>
                    <td className={styles.pubCell}>
                      <span className={styles.value} data-m="value">
                        <T>{post.date}</T>
                      </span>
                      <span className={styles.time}>
                        <T>{post.time}</T>
                      </span>
                    </td>
                    {METRICS.map((metric, index) => (
                      <td key={metric.id} className={styles.metricCell}>
                        <span className={styles.value} data-m="value">
                          <T>{formatValue(post.values[index], metric.format)}</T>
                        </span>
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </main>
      </div>
    </div>
  );
}
```

### layout-inspector/measure.ts

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

/*
 * The measurements, read from the live page every time they are drawn: nothing here is a typed
 * number. Each layer looks up its pieces by their data-m names, reads their boxes and computed
 * styles, and returns marks in page px (the page's own CSS px, whatever the camera's zoom), plus
 * the issues it found, in words.
 *
 * Two rules decide the colour of a mark. A spacing or a size is blue on the 4-px grid and pink
 * off it. An alignment (a thumbnail's foot and its text's, a value's edge and its header's, a
 * search box's middle and the bar's) is a check mark when the two meet and a pink gap, with its
 * width, when they don't.
 */

export type Layer = 'regions' | 'rows' | 'columns' | 'controls';
export const LAYERS: { id: Layer; label: string }[] = [
  { id: 'regions', label: 'Regions' },
  { id: 'rows', label: 'Rows' },
  { id: 'columns', label: 'Columns' },
  { id: 'controls', label: 'Controls' },
];

export type Rect = { x: number; y: number; w: number; h: number };
export type Tone = 'blue' | 'pink' | 'pad';

export type Mark =
  | ({ kind: 'box'; tone: Tone; soft?: boolean } & Rect)
  | { kind: 'badge'; x: number; y: number; tone: Tone; text?: string; check?: boolean }
  | { kind: 'vline'; x: number; tone: Tone; dashed?: boolean; tag?: boolean }
  | { kind: 'hline'; y: number; tone: Tone; dashed?: boolean; tag?: boolean };

/** Marks drawn inside a clip (a scroll box's visible part), or over the whole page (null). */
export type Group = { clip: Rect | null; marks: Mark[] };

export type Reading = {
  groups: Group[];
  issues: string[];
  /** What the camera frames for this layer, or null for the whole page. */
  focus: Rect | null;
};

/** How far off is still on the line: half a pixel, a rounding error. */
const TOLERANCE = 0.5;
const onGrid = (value: number) => Math.abs(value / 4 - Math.round(value / 4)) * 4 < TOLERANCE;
const tone = (value: number): Tone => (onGrid(value) ? 'blue' : 'pink');
/** Values print to one decimal at most, as an inspector shows them. */
export const print = (value: number) => String(Math.round(value * 10) / 10);

/** Reads boxes in page px: client rects relative to the page, undone from the camera's scale. */
export function reader(page: HTMLElement) {
  const frame = page.getBoundingClientRect();
  const scale = frame.width / page.offsetWidth || 1;
  const rect = (element: Element): Rect => {
    const r = element.getBoundingClientRect();
    return {
      x: (r.left - frame.left) / scale,
      y: (r.top - frame.top) / scale,
      w: r.width / scale,
      h: r.height / scale,
    };
  };
  const one = (name: string, within: ParentNode = page) =>
    within.querySelector<HTMLElement>(`[data-m="${name}"]`);
  const all = (name: string, within: ParentNode = page) => [
    ...within.querySelectorAll<HTMLElement>(`[data-m="${name}"]`),
  ];
  return { rect, one, all, size: { w: page.offsetWidth, h: page.offsetHeight } };
}

const px = (element: Element, property: string) =>
  parseFloat(getComputedStyle(element).getPropertyValue(property)) || 0;

const shown = (r: Rect) => r.w > 0.5 && r.h > 0.5;
const within = (r: Rect, clip: Rect) =>
  r.x >= clip.x - TOLERANCE &&
  r.x + r.w <= clip.x + clip.w + TOLERANCE &&
  r.y >= clip.y - TOLERANCE &&
  r.y + r.h <= clip.y + clip.h + TOLERANCE;
const union = (rects: Rect[], pad = 0): Rect => {
  const x = Math.min(...rects.map((r) => r.x)) - pad;
  const y = Math.min(...rects.map((r) => r.y)) - pad;
  const right = Math.max(...rects.map((r) => r.x + r.w)) + pad;
  const bottom = Math.max(...rects.map((r) => r.y + r.h)) + pad;
  return { x, y, w: right - x, h: bottom - y };
};

/** The table box's visible part under its sticky head, and right of its sticky first column. */
function tableClip(read: ReturnType<typeof reader>) {
  const box = read.one('tableBox');
  if (!box) return null;
  const outer = read.rect(box);
  const head = box.querySelector('thead');
  const first = box.querySelector('thead th');
  const headBottom = head ? read.rect(head).y + read.rect(head).h : outer.y;
  // Where the first column ends: sticky, it stays put; on a phone it scrolls away with the rest.
  const firstRight = Math.max(first ? read.rect(first).x + read.rect(first).w : outer.x, outer.x);
  // clientWidth/Height leave the scroll bars out.
  const inner = { w: box.clientWidth, h: box.clientHeight };
  return {
    box,
    outer: { ...outer, w: inner.w, h: inner.h },
    body: { x: outer.x, y: headBottom, w: inner.w, h: outer.y + inner.h - headBottom },
    columns: { x: firstRight, y: outer.y, w: outer.x + inner.w - firstRight, h: inner.h },
  };
}

function regions(read: ReturnType<typeof reader>): Reading {
  const marks: Mark[] = [];
  const issues: string[] = [];
  const side = read.one('sidebar');
  const sideRect = side ? read.rect(side) : null;
  if (side && sideRect && shown(sideRect)) {
    const pad = px(side, 'padding-left');
    marks.push({ kind: 'box', ...sideRect, tone: 'blue', soft: true });
    marks.push({ kind: 'box', x: sideRect.x, y: sideRect.y, w: pad, h: sideRect.h, tone: 'blue' });
    marks.push({ kind: 'vline', x: sideRect.x + sideRect.w, tone: 'blue', tag: true });
    marks.push({ kind: 'vline', x: sideRect.x + pad, tone: tone(pad), tag: true });
    const y = sideRect.y + sideRect.h * 0.56;
    marks.push({ kind: 'badge', x: sideRect.x + pad / 2, y, tone: tone(pad), text: print(pad) });
    marks.push({
      kind: 'badge',
      x: sideRect.x + sideRect.w * 0.55,
      y,
      tone: tone(sideRect.w),
      text: print(sideRect.w),
    });
    if (!onGrid(pad)) issues.push(`Sidebar padding is ${print(pad)} px, off the 4-px grid`);
    if (!onGrid(sideRect.w))
      issues.push(`Sidebar is ${print(sideRect.w)} px wide, off the 4-px grid`);
  }
  const bar = read.one('topbar');
  const search = read.one('search');
  if (bar) {
    const b = read.rect(bar);
    marks.push({ kind: 'box', ...b, tone: 'blue', soft: true });
    marks.push({ kind: 'hline', y: b.y + b.h, tone: tone(b.h), tag: true });
    if (!onGrid(b.h)) issues.push(`Top bar is ${print(b.h)} px tall, off the 4-px grid`);
    if (search) {
      const s = read.rect(search);
      const left = s.x - b.x;
      const right = b.x + b.w - (s.x + s.w);
      marks.push({ kind: 'box', x: b.x, y: s.y, w: left, h: s.h, tone: 'blue' });
      marks.push({ kind: 'box', x: s.x + s.w, y: s.y, w: right, h: s.h, tone: 'blue' });
      marks.push({
        kind: 'badge',
        x: b.x + left / 2,
        y: s.y + s.h / 2,
        tone: 'blue',
        text: print(left),
      });
      marks.push({
        kind: 'badge',
        x: s.x + s.w + right / 2,
        y: s.y + s.h / 2,
        tone: 'blue',
        text: print(right),
      });
      const middle = b.x + b.w / 2;
      const off = s.x + s.w / 2 - middle;
      marks.push({ kind: 'vline', x: middle, tone: 'blue', tag: true });
      const below = b.y + b.h + 14;
      if (Math.abs(off) < 1) {
        marks.push({ kind: 'badge', x: middle, y: below, tone: 'blue', check: true });
      } else {
        marks.push({ kind: 'vline', x: middle + off, tone: 'pink', dashed: true, tag: true });
        marks.push({
          kind: 'badge',
          x: middle + off,
          y: below,
          tone: 'pink',
          text: print(Math.abs(off)),
        });
        issues.push(`Search sits ${print(Math.abs(off))} px off the top bar’s middle`);
      }
      // The top bar's height, over its quieter left end.
      marks.push({
        kind: 'badge',
        x: b.x + Math.min(left / 2, 60),
        y: b.y + b.h / 2,
        tone: tone(b.h),
        text: print(b.h),
      });
    }
  }
  return { groups: [{ clip: null, marks }], issues, focus: null };
}

function rows(read: ReturnType<typeof reader>): Reading {
  const marks: Mark[] = [];
  const issues = new Set<string>();
  const clip = tableClip(read);
  if (!clip) return { groups: [], issues: [], focus: null };
  const seen: Rect[] = [];
  let firstBottom: number | null = null;
  for (const row of read.all('row', clip.box)) {
    const cell = read.one('postCell', row);
    const thumb = cell && read.one('thumb', cell);
    const text = cell && read.one('postText', cell);
    if (!cell || !thumb || !text) continue;
    const c = read.rect(cell);
    if (!within({ ...c, w: 1 }, clip.body)) continue;
    if (seen.length >= 5) break;
    seen.push(c);
    const t = read.rect(thumb);
    const s = read.rect(text);
    const top = px(cell, 'padding-top');
    const left = px(cell, 'padding-left');
    const gap = s.x - (t.x + t.w);
    const contentH = Math.max(t.h, s.h);
    marks.push({ kind: 'box', x: c.x, y: c.y, w: c.w, h: top, tone: 'blue', soft: true });
    marks.push({
      kind: 'box',
      x: c.x,
      y: c.y + top,
      w: left,
      h: contentH,
      tone: 'blue',
      soft: true,
    });
    marks.push({
      kind: 'box',
      x: t.x + t.w,
      y: c.y + top,
      w: gap,
      h: contentH,
      tone: 'blue',
      soft: true,
    });
    marks.push({
      kind: 'badge',
      x: c.x + c.w * 0.4,
      y: c.y + top / 2,
      tone: tone(top),
      text: print(top),
    });
    marks.push({
      kind: 'badge',
      x: c.x + left / 2,
      y: c.y + top + contentH / 2,
      tone: tone(left),
      text: print(left),
    });
    marks.push({
      kind: 'badge',
      x: t.x + t.w + gap / 2,
      y: c.y + top + contentH / 2,
      tone: tone(gap),
      text: print(gap),
    });
    const foot = s.y + s.h - (t.y + t.h);
    if (Math.abs(foot) <= TOLERANCE) {
      marks.push({ kind: 'badge', x: t.x + t.w / 2, y: t.y + t.h, tone: 'blue', check: true });
    } else {
      marks.push({ kind: 'box', x: t.x, y: t.y + t.h, w: t.w, h: foot, tone: 'pink' });
      marks.push({
        kind: 'badge',
        x: t.x + t.w / 2,
        y: t.y + t.h + foot / 2,
        tone: 'pink',
        text: print(Math.abs(foot)),
      });
      issues.add(`Thumbnails end ${print(Math.abs(foot))} px above their text`);
    }
    if (!onGrid(top)) issues.add(`Row padding is ${print(top)} px, off the 4-px grid`);
    if (!onGrid(left)) issues.add(`Cell inset is ${print(left)} px, off the 4-px grid`);
    if (!onGrid(gap)) issues.add(`Thumbnail gap is ${print(gap)} px, off the 4-px grid`);
    if (firstBottom === null) {
      firstBottom = c.y + c.h;
      marks.push({ kind: 'hline', y: firstBottom, tone: 'blue', tag: true });
      if (Math.abs(foot) > TOLERANCE) {
        marks.push({ kind: 'hline', y: t.y + t.h, tone: 'pink', dashed: true, tag: true });
      }
    }
  }
  const focus = seen.length
    ? union(
        seen.slice(0, 3).map((r) => ({ ...r, w: Math.min(r.w + 120, clip.outer.w) })),
        20,
      )
    : null;
  return { groups: [{ clip: clip.body, marks }], issues: [...issues], focus };
}

function columns(read: ReturnType<typeof reader>): Reading {
  const marks: Mark[] = [];
  let off = 0;
  const clip = tableClip(read);
  if (!clip) return { groups: [], issues: [], focus: null };
  const heads = read.all('colHead', clip.box);
  const rowsInView = read
    .all('row', clip.box)
    .filter((row) => within({ ...read.rect(row), w: 1, x: clip.body.x }, clip.body));
  const framed: Rect[] = [];
  heads.forEach((head, index) => {
    const h = read.rect(head);
    const label = read.one('headLabel', head);
    if (!label) return;
    const l = read.rect(label);
    const align = getComputedStyle(head).textAlign;
    const right = align === 'right' || align === 'end';
    const guide = right ? l.x + l.w : l.x;
    // A column counts while its guide is in view, even if part of it has scrolled away.
    if (guide < clip.columns.x || guide > clip.columns.x + clip.columns.w) return;
    marks.push({ kind: 'vline', x: guide, tone: 'blue', tag: true });
    marks.push({ kind: 'badge', x: h.x + h.w / 2, y: h.y + 7, tone: 'blue', text: print(h.w) });
    if (framed.length < 4) framed.push(h);
    let misses = 0;
    let firstValue: Rect | null = null;
    rowsInView.forEach((row, rowIndex) => {
      // The header's column index, past the post's own cell.
      const value = read.one('value', (row as HTMLTableRowElement).cells[index + 1] ?? row);
      if (!value) return;
      const v = read.rect(value);
      if (rowIndex === 0) firstValue = v;
      const edge = right ? v.x + v.w : v.x;
      const gap = right ? guide - edge : edge - guide;
      if (Math.abs(gap) <= TOLERANCE) return;
      misses += 1;
      const x = Math.min(edge, guide);
      marks.push({ kind: 'box', x, y: v.y, w: Math.abs(gap), h: v.h, tone: 'pink' });
      if (rowIndex === 0) {
        marks.push({
          kind: 'badge',
          x: x + Math.abs(gap) / 2,
          y: v.y + v.h + 12,
          tone: 'pink',
          text: print(Math.abs(gap)),
        });
      }
    });
    const first = firstValue as Rect | null;
    if (misses === 0 && first) {
      marks.push({ kind: 'badge', x: guide, y: first.y + first.h + 12, tone: 'blue', check: true });
    }
    if (misses) off += 1;
  });
  const issues = off
    ? [
        `${off} column${off === 1 ? '' : 's'} of values don’t line up with their header${off === 1 ? '' : 's'}`,
      ]
    : [];
  const lastRow = rowsInView[2] ?? rowsInView.at(-1);
  const focus = framed.length
    ? union([...framed, ...(lastRow ? [{ ...read.rect(lastRow), x: framed[0].x, w: 1 }] : [])], 16)
    : null;
  return { groups: [{ clip: clip.columns, marks }], issues, focus };
}

function controls(read: ReturnType<typeof reader>): Reading {
  const marks: Mark[] = [];
  const issues: string[] = [];
  const group = read.one('tools');
  if (!group) return { groups: [], issues, focus: null };
  const tools = read.all('tool', group).map(read.rect).filter(shown);
  if (!tools.length) return { groups: [], issues, focus: null };
  // The height most of them share is the one the others should have.
  const counts = new Map<string, number>();
  tools.forEach((t) => counts.set(print(t.h), (counts.get(print(t.h)) ?? 0) + 1));
  const usual = Number([...counts].sort((a, b) => b[1] - a[1])[0][0]);
  const top = Math.min(...tools.map((t) => t.y));
  const bottom = Math.max(...tools.map((t) => t.y + t.h));
  marks.push({ kind: 'hline', y: top, tone: 'blue', tag: true });
  marks.push({ kind: 'hline', y: bottom, tone: 'blue', tag: true });
  let odd = 0;
  const gaps = new Set<string>();
  tools.forEach((t, index) => {
    const fits = Math.abs(t.h - usual) <= TOLERANCE && onGrid(t.h);
    marks.push({ kind: 'box', ...t, tone: fits ? 'blue' : 'pink', soft: true });
    marks.push({
      kind: 'badge',
      x: t.x + t.w / 2,
      y: bottom + 14,
      tone: fits ? 'blue' : 'pink',
      text: print(t.h),
    });
    if (!fits) odd += 1;
    const next = tools[index + 1];
    if (next && next.y < t.y + t.h && next.x > t.x) {
      const gap = next.x - (t.x + t.w);
      marks.push({ kind: 'box', x: t.x + t.w, y: top, w: gap, h: bottom - top, tone: tone(gap) });
      marks.push({
        kind: 'badge',
        x: t.x + t.w + gap / 2,
        y: top - 14,
        tone: tone(gap),
        text: print(gap),
      });
      if (!onGrid(gap)) gaps.add(print(gap));
    }
  });
  if (odd)
    issues.push(
      `${odd} control${odd === 1 ? ' is' : 's are'} not ${print(usual)} px tall like the rest`,
    );
  gaps.forEach((gap) => issues.push(`Controls are ${gap} px apart, off the 4-px grid`));
  return { groups: [{ clip: null, marks }], issues, focus: union(tools, 44) };
}

export function measureLayer(page: HTMLElement, layer: Layer): Reading {
  const read = reader(page);
  if (layer === 'regions') return regions(read);
  if (layer === 'rows') return rows(read);
  if (layer === 'columns') return columns(read);
  return controls(read);
}

/** The element under the pointer or the focus: its box, its padding and its size. */
export function measureElement(page: HTMLElement, element: HTMLElement): Mark[] {
  const read = reader(page);
  const r = read.rect(element);
  if (!shown(r)) return [];
  const style = getComputedStyle(element);
  const [top, right, bottom, left] = ['top', 'right', 'bottom', 'left'].map(
    (side) => parseFloat(style.getPropertyValue(`padding-${side}`)) || 0,
  );
  const marks: Mark[] = [];
  if (top) marks.push({ kind: 'box', x: r.x, y: r.y, w: r.w, h: top, tone: 'pad', soft: true });
  if (bottom)
    marks.push({
      kind: 'box',
      x: r.x,
      y: r.y + r.h - bottom,
      w: r.w,
      h: bottom,
      tone: 'pad',
      soft: true,
    });
  if (left)
    marks.push({
      kind: 'box',
      x: r.x,
      y: r.y + top,
      w: left,
      h: r.h - top - bottom,
      tone: 'pad',
      soft: true,
    });
  if (right)
    marks.push({
      kind: 'box',
      x: r.x + r.w - right,
      y: r.y + top,
      w: right,
      h: r.h - top - bottom,
      tone: 'pad',
      soft: true,
    });
  marks.push({ kind: 'box', ...r, tone: 'blue' });
  marks.push({
    kind: 'badge',
    x: r.x + r.w / 2,
    y: r.y + r.h + 13,
    tone: 'blue',
    text: `${print(r.w)} × ${print(r.h)}`,
  });
  return marks;
}
```

### layout-inspector/overlay.tsx

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

'use client';

import type { CSSProperties } from 'react';
import { Icon } from './glyphs';
import { print, type Group, type Mark } from './measure';
import styles from './layout-inspector.module.css';

/*
 * The marks, drawn over the page in its own px: they sit in the same zoomed layer as the page,
 * so the camera moves them together. Lines and borders divide their width by the zoom (--inv)
 * and badges are scaled back by it, so at any zoom a line stays one screen pixel and a badge
 * stays the same size, as an inspector draws them. A group with a clip is cut to it: the marks
 * of the table stop at the edges of its scroll box, under its sticky head and first column.
 */

function MarkView({ mark, dx, dy }: { mark: Mark; dx: number; dy: number }) {
  if (mark.kind === 'box') {
    return (
      <span
        className={styles.mBox}
        data-tone={mark.tone}
        data-soft={mark.soft || undefined}
        style={{ left: mark.x - dx, top: mark.y - dy, width: mark.w, height: mark.h }}
      />
    );
  }
  if (mark.kind === 'vline' || mark.kind === 'hline') {
    const vertical = mark.kind === 'vline';
    return (
      <span
        className={vertical ? styles.mV : styles.mH}
        data-tone={mark.tone}
        data-dashed={mark.dashed || undefined}
        style={vertical ? { left: mark.x - dx } : { top: mark.y - dy }}
      />
    );
  }
  return (
    <span
      className={styles.mBadge}
      data-tone={mark.tone}
      data-check={mark.check || undefined}
      style={{ left: mark.x - dx, top: mark.y - dy } as CSSProperties}
    >
      {mark.check ? <Icon name="check" className={styles.mCheck} /> : mark.text}
    </span>
  );
}

export function Overlay({
  layers,
  hover,
  size,
}: {
  layers: { id: string; groups: Group[] }[];
  hover: Mark[];
  size: { w: number; h: number };
}) {
  const whole = { x: 0, y: 0, w: size.w, h: size.h };
  return (
    <div className={styles.overlay} aria-hidden="true">
      {layers.map((layer) => (
        <div key={layer.id} className={styles.layer} data-layer={layer.id}>
          {layer.groups.map((group, index) => {
            const clip = group.clip ?? whole;
            return (
              <div
                key={index}
                className={styles.group}
                data-clipped={group.clip ? true : undefined}
                style={{ left: clip.x, top: clip.y, width: clip.w, height: clip.h }}
              >
                {group.marks.map((mark, at) => (
                  <MarkView key={at} mark={mark} dx={clip.x} dy={clip.y} />
                ))}
              </div>
            );
          })}
        </div>
      ))}
      {hover.length > 0 && (
        <div className={styles.layer} data-layer="hover">
          <div className={styles.group} style={{ left: 0, top: 0, width: size.w, height: size.h }}>
            {hover.map((mark, at) => (
              <MarkView key={at} mark={mark} dx={0} dy={0} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

/** The guides that show on the rulers: a tag with the line's position, in page px. */
export function rulerTags(layers: { groups: Group[] }[]) {
  const x: { at: number; tone: string }[] = [];
  const y: { at: number; tone: string }[] = [];
  for (const layer of layers) {
    for (const group of layer.groups) {
      for (const mark of group.marks) {
        if (mark.kind === 'vline' && mark.tag) {
          const clip = group.clip;
          if (!clip || (mark.x >= clip.x && mark.x <= clip.x + clip.w))
            x.push({ at: mark.x, tone: mark.tone });
        } else if (mark.kind === 'hline' && mark.tag) {
          const clip = group.clip;
          if (!clip || (mark.y >= clip.y && mark.y <= clip.y + clip.h))
            y.push({ at: mark.y, tone: mark.tone });
        }
      }
    }
  }
  return { x, y };
}

export type RulerColors = {
  ink: string;
  tick: string;
  fill: string;
  blue: string;
  pink: string;
  tagInk: string;
};

/**
 * One ruler, on a canvas: ticks every 1, 2, 5 or 10 × 10ⁿ page px (whichever puts labels at least
 * 56 screen px apart), five minor ticks between, and a tag for each guide, written over the
 * ticks. `start` is the page px at the canvas's leading edge and `scale` the screen px per page px.
 */
export function drawRuler(
  canvas: HTMLCanvasElement,
  axis: 'x' | 'y',
  start: number,
  scale: number,
  tags: { at: number; tone: string }[],
  colors: RulerColors,
) {
  const ratio = window.devicePixelRatio || 1;
  const cssW = canvas.clientWidth;
  const cssH = canvas.clientHeight;
  if (!cssW || !cssH) return;
  if (canvas.width !== Math.round(cssW * ratio) || canvas.height !== Math.round(cssH * ratio)) {
    canvas.width = Math.round(cssW * ratio);
    canvas.height = Math.round(cssH * ratio);
  }
  const g = canvas.getContext('2d');
  if (!g) return;
  g.setTransform(ratio, 0, 0, ratio, 0, 0);
  g.clearRect(0, 0, cssW, cssH);
  g.fillStyle = colors.fill;
  g.fillRect(0, 0, cssW, cssH);
  const length = axis === 'x' ? cssW : cssH;
  const depth = axis === 'x' ? cssH : cssW;
  const raw = 56 / scale;
  const power = 10 ** Math.floor(Math.log10(raw));
  const step = [1, 2, 5, 10].map((k) => k * power).find((value) => value >= raw) ?? power * 10;
  const minor = step / 5;
  const end = start + length / scale;
  g.font = '500 9px ui-sans-serif, system-ui, -apple-system, sans-serif';
  g.textBaseline = 'middle';
  g.lineWidth = 1;
  for (let value = Math.floor(start / minor) * minor; value <= end; value += minor) {
    const at = Math.round((value - start) * scale) + 0.5;
    const major = Math.abs(value / step - Math.round(value / step)) < 1e-6;
    const tick = major ? depth * 0.45 : depth * 0.2;
    g.strokeStyle = colors.tick;
    g.beginPath();
    if (axis === 'x') {
      g.moveTo(at, cssH - tick);
      g.lineTo(at, cssH);
    } else {
      g.moveTo(cssW - tick, at);
      g.lineTo(cssW, at);
    }
    g.stroke();
    if (major) {
      g.fillStyle = colors.ink;
      const label = String(Math.round(value));
      if (axis === 'x') {
        g.textAlign = 'left';
        g.fillText(label, at + 3, depth * 0.38);
      } else {
        g.save();
        g.translate(depth * 0.38, at - 3);
        g.rotate(-Math.PI / 2);
        g.textAlign = 'left';
        g.fillText(label, 0, 0);
        g.restore();
      }
    }
  }
  g.font = '600 9px ui-sans-serif, system-ui, -apple-system, sans-serif';
  g.textAlign = 'center';
  for (const tag of tags) {
    const at = (tag.at - start) * scale;
    if (at < -20 || at > length + 20) continue;
    const label = print(Math.round(tag.at));
    const w = g.measureText(label).width + 8;
    const h = Math.min(depth - 4, 13);
    g.fillStyle = tag.tone === 'pink' ? colors.pink : colors.blue;
    g.beginPath();
    if (axis === 'x') g.roundRect(at - w / 2, (depth - h) / 2, w, h, 3);
    else g.roundRect((depth - h) / 2, at - w / 2, h, w, 3);
    g.fill();
    g.fillStyle = colors.tagInk;
    if (axis === 'x') g.fillText(label, at, depth / 2 + 0.5);
    else {
      g.save();
      g.translate(depth / 2 + 0.5, at);
      g.rotate(-Math.PI / 2);
      g.fillText(label, 0, 0);
      g.restore();
    }
  }
}
```

### layout-inspector/data.ts

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

/*
 * What the dashboard shows: a month of posts from a small ceramics studio, with their reach and
 * engagement. Plain data, so the page and the docs read the same numbers.
 */

export type Art = 'glaze' | 'kiln' | 'bowls' | 'wheel' | 'shelf' | 'vase' | 'text' | 'link';

export type Post = {
  id: string;
  title: string;
  author: string;
  kind: 'Reel' | 'Article' | 'Post' | 'Reply' | 'Carousel' | 'Video' | 'Photo';
  boosted?: boolean;
  art: Art;
  date: string;
  time: string;
  /** In the order of METRICS; null when the network doesn't report it. */
  values: (number | null)[];
};

export type Metric = {
  id: string;
  label: string;
  total: string;
  /** The change from the period before, as printed. */
  delta: string;
  up: boolean;
  /** How a cell prints its value. */
  format: 'count' | 'rate';
};

export const BRAND = 'Tidewell Studio';

export const METRICS: Metric[] = [
  {
    id: 'impressions',
    label: 'Impressions',
    total: '241.6k',
    delta: '+64.2%',
    up: true,
    format: 'count',
  },
  { id: 'reach', label: 'Reach', total: '22.9k', delta: '+12.4%', up: true, format: 'count' },
  { id: 'rate', label: 'Eng. rate', total: '7.1%', delta: '+0.3 pt', up: true, format: 'rate' },
  {
    id: 'engagements',
    label: 'Engagements',
    total: '17.2k',
    delta: '+71.0%',
    up: true,
    format: 'count',
  },
  {
    id: 'reactions',
    label: 'Reactions',
    total: '11.4k',
    delta: '−4.8%',
    up: false,
    format: 'count',
  },
  { id: 'comments', label: 'Comments', total: '812', delta: '+52.6%', up: true, format: 'count' },
  { id: 'saves', label: 'Saves', total: '1,964', delta: '+18.9%', up: true, format: 'count' },
];

export const POSTS: Post[] = [
  {
    id: 'p1',
    title: 'Forty seconds of glazing the spring mugs, dip to kiln. Sound on for the door.',
    author: '@tidewell.studio',
    kind: 'Reel',
    art: 'glaze',
    date: '30 Oct 2026',
    time: '8:10 am',
    values: [46820, 37410, 8.4, 3932, 2870, 196, 412],
  },
  {
    id: 'p2',
    title: 'We switched every order to paper wrap this year. What it cost and what broke.',
    author: 'Tidewell Studio',
    kind: 'Article',
    art: 'shelf',
    date: '28 Oct 2026',
    time: '12:40 pm',
    values: [11930, 9120, 9.6, 1145, 388, 61, 240],
  },
  {
    id: 'p3',
    title: 'A cup should be heavier than it looks. We will not be taking questions.',
    author: '@tidewell',
    kind: 'Post',
    art: 'text',
    date: '27 Oct 2026',
    time: '5:05 pm',
    values: [8710, null, 4.9, 427, 301, 92, 34],
  },
  {
    id: 'p4',
    title:
      'Yes, the speckled bowls are back on Monday. A few are set aside for the people who asked.',
    author: '@tidewell',
    kind: 'Reply',
    art: 'text',
    date: '23 Oct 2026',
    time: '8:55 pm',
    values: [598, null, 6.2, 37, 22, 7, 8],
  },
  {
    id: 'p5',
    title: 'Five ways to keep a glaze from crawling, from the test tiles we threw away.',
    author: '@tidewell.studio',
    kind: 'Carousel',
    art: 'bowls',
    date: '22 Oct 2026',
    time: '9:30 am',
    values: [25410, 20660, 9.1, 2312, 1704, 83, 525],
  },
  {
    id: 'p6',
    title: 'Inside the kiln room: how one firing turns grey clay into the colours you see.',
    author: 'Tidewell Workshop',
    kind: 'Video',
    art: 'kiln',
    date: '20 Oct 2026',
    time: '11:15 am',
    values: [14870, 10540, 6.9, 1026, 655, 71, 300],
  },
  {
    id: 'p7',
    title: 'We are hiring a studio assistant in Porto. You would run the wheel room with us.',
    author: 'Tidewell Studio',
    kind: 'Post',
    art: 'link',
    date: '17 Oct 2026',
    time: '4:45 pm',
    values: [6940, 5310, 9.4, 652, 187, 24, 441],
  },
  {
    id: 'p8',
    title: 'The autumn vase is here. Ash glaze, a rough foot, and it ships Thursday.',
    author: '@tidewell.studio',
    kind: 'Photo',
    boosted: true,
    art: 'vase',
    date: '15 Oct 2026',
    time: '8:00 am',
    values: [61250, 49880, 7.3, 4471, 2296, 128, 1047],
  },
  {
    id: 'p9',
    title: 'A reminder that a recipe is a starting point. Test it, then trust your hands.',
    author: '@tidewell',
    kind: 'Post',
    art: 'text',
    date: '12 Oct 2026',
    time: '7:20 pm',
    values: [3990, null, 3.8, 152, 121, 17, 14],
  },
  {
    id: 'p10',
    title: 'Throwing a set of six, start to finish, at one third speed so you can follow along.',
    author: '@tidewell.studio',
    kind: 'Reel',
    art: 'wheel',
    date: '9 Oct 2026',
    time: '10:00 am',
    values: [38200, 30120, 8.0, 3056, 2214, 141, 701],
  },
  {
    id: 'p11',
    title: 'Seconds sale this weekend: small marks, same mugs. Doors open at nine.',
    author: 'Tidewell Studio',
    kind: 'Photo',
    art: 'shelf',
    date: '5 Oct 2026',
    time: '6:30 pm',
    values: [17630, 14020, 5.6, 987, 760, 54, 173],
  },
  {
    id: 'p12',
    title: 'Glaze notes from September, for anyone mixing their first celadon.',
    author: 'Tidewell Workshop',
    kind: 'Article',
    art: 'glaze',
    date: '2 Oct 2026',
    time: '9:05 am',
    values: [5280, 4170, 10.2, 538, 104, 9, 425],
  },
];

/** A cell's value as printed: thousands with commas, rates with one decimal, a dash for none. */
export function formatValue(value: number | null, format: Metric['format']) {
  if (value === null) return '—';
  if (format === 'rate') return `${value.toFixed(1)}%`;
  return value.toLocaleString('en-US');
}

export const NAV = {
  top: ['Reports home', 'Favorites'],
  group: 'Cross-network',
  children: [
    'Profile performance',
    'Post performance',
    'Tag performance',
    'Paid performance',
    'Competitor performance',
  ],
  rest: ['Profiles by network', 'Paid by network', 'Competitors by network', 'Customize branding'],
};
```

### layout-inspector/art.tsx

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

import type { ReactNode } from 'react';
import type { Art } from './data';

/*
 * The posts' thumbnails, drawn: a few flat studio scenes (a glazed mug, the kiln, a stack of
 * bowls, the wheel, a shelf, a vase) and two plain tiles for posts with no picture (a text post
 * and a link). Each is a 40-unit square that fills its box; the stylesheet greys them in the
 * draft and in the wireframe.
 */

const SCENES: Record<Art, ReactNode> = {
  glaze: (
    <>
      <rect width="40" height="40" fill="#2f4a5c" />
      <rect y="28" width="40" height="12" fill="#5c4434" />
      <path d="M12 13h14v13a5 5 0 0 1-5 5h-4a5 5 0 0 1-5-5z" fill="#7fc3c9" />
      <path d="M12 13h14v5c-2 2-4-1-7 1s-5 0-7-1z" fill="#d9efe9" />
      <path d="M26 16h2a3 3 0 0 1 0 6h-2" fill="none" stroke="#7fc3c9" strokeWidth="2" />
      <ellipse cx="19" cy="13" rx="7" ry="1.6" fill="#a6dbd9" />
    </>
  ),
  kiln: (
    <>
      <rect width="40" height="40" fill="#3b2a24" />
      <rect x="7" y="8" width="26" height="26" rx="2" fill="#6d5246" />
      <rect x="11" y="12" width="18" height="16" rx="1.5" fill="#f08a3c" />
      <rect x="13" y="14" width="14" height="12" rx="1" fill="#ffc46b" />
      <path d="M15 26v-5h3v5zM22 26v-7h3v7z" fill="#c4572a" />
      <rect x="9" y="31" width="22" height="2" fill="#4c3830" />
    </>
  ),
  bowls: (
    <>
      <rect width="40" height="40" fill="#d8cfc2" />
      <path d="M8 22h24a12 7 0 0 1-24 0z" fill="#b5654a" />
      <path d="M10 16h20a10 6 0 0 1-20 0z" fill="#e8b25d" />
      <path d="M12 10h16a8 5 0 0 1-16 0z" fill="#5f8f7e" />
      <rect x="15" y="31" width="10" height="2" rx="1" fill="#8b4c37" />
    </>
  ),
  wheel: (
    <>
      <rect width="40" height="40" fill="#495a4b" />
      <ellipse cx="20" cy="30" rx="15" ry="4" fill="#2d382e" />
      <path d="M14 29c0-6 2-9 2-13h8c0 4 2 7 2 13z" fill="#c9a17c" />
      <ellipse cx="20" cy="16" rx="4" ry="1.2" fill="#a77f5d" />
      <path
        d="M6 19c4-1 7 1 8 4M34 19c-4-1-7 1-8 4"
        stroke="#e3c3a4"
        strokeWidth="2.4"
        fill="none"
        strokeLinecap="round"
      />
    </>
  ),
  shelf: (
    <>
      <rect width="40" height="40" fill="#efe6d8" />
      <rect y="17" width="40" height="2" fill="#a88c6c" />
      <rect y="33" width="40" height="2" fill="#a88c6c" />
      <path d="M5 17v-7h6v7zM14 17v-5h5v5zM22 17v-9h5v9zM30 17v-6h6v6z" fill="#46707a" />
      <path d="M5 33v-6h7v6zM15 33v-8h5v8zM24 33v-5h6v5zM32 33v-7h4v7z" fill="#cf7d55" />
    </>
  ),
  vase: (
    <>
      <rect width="40" height="40" fill="#22262b" />
      <rect y="30" width="40" height="10" fill="#3a3f46" />
      <path d="M17 7h6v3c0 2 5 5 5 11s-3 10-8 10-8-4-8-10 5-9 5-11z" fill="#9aa69a" />
      <path d="M13 22c3 2 11 2 14 0v2c-3 2-11 2-14 0z" fill="#6f7d70" />
    </>
  ),
  text: (
    <>
      <rect width="40" height="40" fill="var(--tile)" />
      <path
        d="M13 17h14M13 21h14M13 25h9"
        stroke="var(--tile-ink)"
        strokeWidth="1.6"
        strokeLinecap="round"
      />
    </>
  ),
  link: (
    <>
      <rect width="40" height="40" fill="var(--tile)" />
      <path
        d="M18.5 22.5l3-3M17 19l-1.8 1.8a2.6 2.6 0 0 0 3.7 3.7L20.8 23M23 21l1.8-1.8a2.6 2.6 0 0 0-3.7-3.7L19.2 17"
        stroke="var(--tile-ink)"
        strokeWidth="1.6"
        fill="none"
        strokeLinecap="round"
      />
    </>
  ),
};

export function Thumb({ art, className }: { art: Art; className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 40 40"
      aria-hidden="true"
      focusable="false"
      preserveAspectRatio="xMidYMid slice"
    >
      {SCENES[art]}
    </svg>
  );
}
```

### layout-inspector/glyphs.tsx

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

/*
 * The dashboard's icons and the inspector's, drawn by hand on a 16-unit grid with a 1.4-unit
 * stroke in currentColor. Each is decorative: the control it sits in carries the name.
 */

const PATHS = {
  home: 'M2.8 7.2 8 3l5.2 4.2V13H9.6V9.8H6.4V13H2.8z',
  star: 'M8 2.6l1.7 3.5 3.8.5-2.8 2.6.7 3.8L8 11.2 4.6 13l.7-3.8-2.8-2.6 3.8-.5z',
  network:
    'M4.5 5.5a2 2 0 1 0 0-.01M11.5 5.5a2 2 0 1 0 0-.01M8 12.5a2 2 0 1 0 0-.01M5.6 7.2 7 10.6M10.4 7.2 9 10.6',
  people:
    'M6 7.4a2.2 2.2 0 1 0 0-4.4 2.2 2.2 0 0 0 0 4.4zM2.4 13c0-2.2 1.6-3.6 3.6-3.6s3.6 1.4 3.6 3.6M10.6 7a1.8 1.8 0 1 0 0-3.6M11.4 9.5c1.3.3 2.2 1.5 2.2 3.5',
  coin: 'M8 13.4A5.4 5.4 0 1 0 8 2.6a5.4 5.4 0 0 0 0 10.8zM9.8 6.2C9.4 5.6 8.8 5.4 8 5.4c-1 0-1.8.5-1.8 1.3 0 1.9 3.8.9 3.8 2.8 0 .8-.9 1.3-2 1.3-.8 0-1.5-.3-1.9-.9M8 4.4v7.2',
  rocket:
    'M9.6 3.2c2-.8 3.2-.6 3.2-.6s.2 1.2-.6 3.2L8.4 9.6 6.4 7.6zM6.4 7.6 4 7.4l1.6-1.8h2.2M8.4 9.6l.2 2.4 1.8-1.6V8.2M4.6 11.4 3 13',
  palette:
    'M8 2.6a5.4 5.4 0 0 0 0 10.8c.8 0 1.2-.5 1.2-1.1 0-.8-.6-1-.6-1.7 0-.6.5-1 1.1-1h1.5c1.5 0 2.4-1.2 2.4-2.6 0-2.4-2.5-4.4-5.6-4.4zM5.2 7.4h.01M7 5h.01M10 5.2h.01',
  chevronRight: 'M6.5 4.5 10 8l-3.5 3.5',
  chevronDown: 'M4.5 6.5 8 10l3.5-3.5',
  bell: 'M4.2 11V7.4a3.8 3.8 0 0 1 7.6 0V11l1 1.2H3.2zM6.6 13.6a1.5 1.5 0 0 0 2.8 0',
  help: 'M8 13.4A5.4 5.4 0 1 0 8 2.6a5.4 5.4 0 0 0 0 10.8zM6.4 6.6a1.7 1.7 0 0 1 3.3.4c0 1.2-1.7 1.4-1.7 2.6M8 11.3h.01',
  pen: 'M10.4 3.4l2.2 2.2-6.8 6.8-2.8.6.6-2.8zM9.2 4.6l2.2 2.2',
  list: 'M3 4.5h10M3 8h10M3 11.5h10',
  grid: 'M3 3h4v4H3zM9 3h4v4H9zM3 9h4v4H3zM9 9h4v4H9z',
  calendar: 'M3 4.4h10V13H3zM3 7.2h10M5.6 2.8v2.6M10.4 2.8v2.6',
  share: 'M8 2.8v7M5.2 5.4 8 2.6l2.8 2.8M4 8.6V13h8V8.6',
  more: 'M3.6 8h.01M8 8h.01M12.4 8h.01',
  search: 'M7.2 11.8a4.6 4.6 0 1 0 0-9.2 4.6 4.6 0 0 0 0 9.2zM10.6 10.6l2.8 2.8',
  sort: 'M8 3.4v9M4.8 9.4 8 12.6l3.2-3.2',
  inspect:
    'M2.8 2.8h4M2.8 2.8v4M13.2 2.8h-4M13.2 2.8v4M2.8 13.2h4M2.8 13.2v-4M8.6 8.6l4.6 1.8-2 .8-.8 2z',
  regions: 'M2.8 3h10.4v10H2.8zM6.4 3v10M6.4 6.2h6.8',
  rows: 'M2.8 3h10.4v2.6H2.8zM2.8 6.7h10.4v2.6H2.8zM2.8 10.4h10.4V13H2.8z',
  columns: 'M3 2.8v10.4M8 2.8v10.4M13 2.8v10.4M3 8h10',
  controls: 'M2.6 5.4h4.6v5.2H2.6zM8.8 5.4h4.6v5.2H8.8z',
  prev: 'M9.5 4.5 6 8l3.5 3.5',
  next: 'M6.5 4.5 10 8l-3.5 3.5',
  check: 'M4.2 8.3 6.8 10.8 11.8 5.4',
} as const;

export type Glyph = keyof typeof PATHS;

export function Icon({ name, className }: { name: Glyph; className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 16 16"
      width="16"
      height="16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d={PATHS[name]} />
    </svg>
  );
}

/** The studio's mark: a thrown cup in a rounded square. */
export function Mark({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 20 20" aria-hidden="true" focusable="false">
      <rect width="20" height="20" rx="5" fill="currentColor" />
      <path d="M6 7h8v4.5A3.5 3.5 0 0 1 10.5 15h-1A3.5 3.5 0 0 1 6 11.5z" fill="var(--mark-ink)" />
      <path d="M5 7h10" stroke="var(--mark-ink)" strokeWidth="1.4" strokeLinecap="round" />
    </svg>
  );
}
```

### layout-inspector/demo-pointer.tsx

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

'use client';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

### layout-inspector/use-autoplay.ts

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

'use client';

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

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

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

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

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