# Budget pacing

> Each team’s budget paced to the end of the quarter, with the overrun hatched past the Budget line, and a card that moves money from a team with room to one that runs out.

Two stacked cards for a finance review. The first draws every team on one scale from nothing to 150% of its budget: what it has spent, where it lands at today’s pace, and the overrun hatched in red past the Budget line, with Today and Budget marked under the rows and a line on who runs out first. Month / Quarter recomputes it all. The second starts from the assistant’s suggestion (cover the team furthest over from the one with the most to spare): pick From and To, type the amount or take the chip that fills the gap, and see both teams move before and after. Over the approval limit, the footer names who signs off; Move applies it to the budgets above, with Undo. Light and dark.

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

Category: Dashboards.

## Anatomy

1. **Card header**: The icon tile, the title, the day of the period and the total spent, with Month / Quarter at the end.
2. **Period switch**: A radio group: Month paces each team’s share of the budget for this month, Quarter the whole quarter. Every bar, the axis and the insight follow.
3. **Legend**: Spent, Forecast to the period’s last day, and Over budget in the red hatch the rows use.
4. **Team row**: A letter, the name, the track and the share. The spent bar in the team’s colour, the forecast dimmer to its dot, the overrun hatched past the Budget line.
5. **Tooltip**: The row’s dollars: spent, forecast, budget, and how far over or under it lands. It follows the pointer along the row, or sits on the dot when the row has focus, and stays while the pointer is on it.
6. **Insight**: The team furthest over and the day it runs out at this pace, and the team that will leave the most unused.
7. **From and To**: Two menu buttons with each team’s colour and what it has left; the arrow between them swaps the two.
8. **Amount**: The figure is a field: type it, or step it with the arrow keys. The chips set it; the green one fills To’s gap.
9. **Before → after**: Both teams on the same 0–150% scale, a ring where they are and a dot where the move puts them, with the shares beside.
10. **Footer**: Who approves a move over the limit, Ask, and Move, which applies it to the budgets above with Undo in a toast.

## Properties

### Move card (`showMove`)

1. **Budgets and Move (default)**: The pacing card with the Move budget card under it; pressing a row picks it for a move.
2. **Budgets only**: The pacing card alone: the rows, their tooltips and the insight. Rows are no longer pressable.

Keep the Move card where the people reading can act on the budgets. For a report or a review that only informs, leave it out.

### Period at first (`defaultPeriod`)

1. **Quarter (default)**: Each team’s whole budget, paced by its forecast to the quarter’s last day.
2. **Month**: Each team’s planned share for this month, its month’s spend carried at its pace to the month’s last day.

Open on the period the review is about. Month / Quarter stays in the header either way, and every bar, the axis and the insight follow it.

### Approval limit (`approvalLimit`)

1. **$15k (default)**: The suggested $18k move is over it: the footer names the approver and Ask sits beside Move.
2. **$50k**: The same move is under it: no Ask, and the footer says no approval is needed.

Set it to the amount your policy says needs a sign-off. Over it, the footer names the approver and Ask sends the move to `onAskApproval`; Move stays available, so enforce the sign-off where moves are saved.

## When to use

- Budgets split across a handful of teams for a period, where the question is who will run over at the current pace, not only who has spent the most.
- A finance or ops review that needs the spend so far, the forecast to the period’s end and the overrun on one shared scale, so the rows compare at a glance.
- A suggestion to act on: moving money from a team with room to one that runs out, with the effect on both shown before anything changes.
- Moves that need a sign-off over a limit: the footer names who approves and asks them, under it the move goes through at once.

## When not to use

- Spend over time. A line or a burn-down chart shows the curve; the pacing rows only show where today’s pace lands.
- Dozens of cost centres. Past eight or ten rows, group them, or rank the furthest over and fold the rest.
- Line-item spending or invoices. Use a table with filters; a team’s row says nothing about what it bought.
- Budgets that are not meant to be spent evenly. The forecast is today’s pace carried to the end; for lumpy spend, forecast from the plan instead.
- Approvals with several steps. The card asks one person; a real workflow needs a request with its own status and history.

### Reading the rows

- **One scale per row**, from nothing to 150% of the team’s own budget, so the Budget line sits at two thirds for everyone and a small team compares with a large one by pace, not by size.
- **The spent bar** is in the team’s colour; the dimmer bar runs on to the forecast’s dot; past the Budget line the overrun is hatched in red.
- **The Today line** runs through every row: a spent bar well past it is spending ahead of the calendar.
- **The share** at the end of the row is the forecast over the budget, the same figure the label reads out.

### Moves and approval

- **The suggestion** covers the team furthest over from the one with the most to spare; after a move, the next one is picked from the budgets as they are now.
- **The gap chip** is To’s overrun to the $1k, never more than From can spare. It is only there when To is over.
- **An amount past what From has left** turns red, the footer says how much there is, and Move is off.
- **Move** applies at once and calls `onMove`; Undo in the toast puts both budgets and the picks back, and the toast stays until it is used or the next move replaces it. **Ask** calls `onAskApproval` and reads Asked until the move changes.

### Pacing rows vs. spend over time

**Pacing rows**
- Where each team lands at today’s pace, side by side.
- Who runs over first, and who has room to cover it.
- A review that ends in a decision: move budget, ask for more.

**Spend over time**
- How one budget got where it is, week by week.
- Spikes, slow months and when the pace changed.
- A line or a burn-down chart, one team or a total at a time.

## Do’s and don’ts

- **Do**: Give every team its own `tone`, so a row, its letter, its menu swatch and its before → after line read as one team.
- **Don’t**: Give teams the same tone. The rows still read, but the Move card’s From, To and before → after lines can no longer be told apart at a glance.
- **Do**: Keep it to the handful of teams that share a budget owner: four to eight rows compare at a glance.
- **Don’t**: Pour every cost centre in. Past eight or ten rows the chart is a list to scroll; group the teams, or show the furthest over and fold the rest.
- **Do**: Set `approvalLimit` to your sign-off policy, so a small fix like this $9k one goes through with Move alone.
- **Caution**: The month view carries this month’s spend at its pace to the month’s last day. Early in a month, or for spend that lands in lumps, read its overruns as a warning, not a figure.

## Content

The card is read in a review, often aloud: every word should match what the finance team calls things.

- **Team names of a word or two**, as people say them: `Engineering`, `G&A`. Long names are cut short with an ellipsis in the rows.
- **Budgets, spend and forecasts in whole dollars**; the card rounds them to `$43k` or `$1.2M` itself.
- **The assistant’s and the approver’s names** are a person’s or a tool’s name, nothing more: the subtitle and the footer build the sentence around them.
- **A forecast you can stand behind**: the quarter view draws the `forecast` you pass, so feed it from the plan or the run rate your team trusts.

## Installation

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

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

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

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

## Usage

```tsx
import { BudgetPacing, type Team } from './budget-pacing';

const teams: Team[] = [
  {
    id: 'growth',
    name: 'Growth',
    tone: 'pink',
    budget: 60_000,
    spent: 14_200,
    forecast: 76_800,
    phasing: [0.4, 0.3, 0.3],
  },
  {
    id: 'platform',
    name: 'Platform',
    tone: 'blue',
    budget: 210_000,
    spent: 31_500,
    forecast: 170_400,
    phasing: [0.33, 0.33, 0.34],
  },
];

export function BudgetReview() {
  return (
    <BudgetPacing
      teams={teams}
      day={17}
      approver="Mira Castell"
      approvalLimit={15_000}
      onMove={(move) => console.log('Move', move)}
      autoplay={false}
    />
  );
}
```

## States

- **Quarter**: The default: day 17 of 92, three teams over, and the assistant suggesting the gap from the team with the most to spare.
- **Row tooltip**: Marketing hovered: its spent, forecast and budget in dollars, and the overrun at this pace.
- **Month**: October on its own: each team’s share of the quarter planned for the month, paced to Oct 31. Sales leads the overrun here.
- **Under the limit**: A $10k move: no approval needed, so Ask leaves and the footer says so.
- **More than is left**: An amount past what From has left: the figure turns red, the footer says how much there is, and Move is off.
- **From menu**: Every team with what it has left; picking the one on the other side swaps them.
- **Approval asked**: After Ask: the button reads Asked and the footer waits on the approver until the move changes.
- **Moved**: The move applied: Marketing back at its budget, G&A lower, the next suggestion picked, and Undo in the toast.
- **Everyone on pace**: No team over: no red, no gap chip, and the subtitle says there is nothing to cover.
- **Budgets only**: With `showMove={false}` the Move card leaves and rows are no longer pressable.
- **Light**: With `colorScheme="light"`: white cards on a pale lavender wash, the team colours a step deeper.
- **Phone**: Under 560 px the switch goes under the title, From and To stack with the arrow turned down, and the footer’s buttons share the width.

## Examples

### Budgets only

The pacing card on its own, for a report or a review: the rows, the tooltip and the insight, with no Move card under them.

```tsx
import { BudgetPacing } from './budget-pacing';

/** The budgets on their own, for a report: no Move card under them. */
export function BudgetsOnly() {
  return <BudgetPacing showMove={false} autoplay={false} />;
}
```

### Everyone on pace

A calm quarter: every team lands inside its budget, nothing turns red, there is no gap to fill and the assistant has nothing to suggest.

```tsx
import { BudgetPacing } from './budget-pacing';
import { ON_PACE } from './data';

/** A calm quarter: nobody runs over, so nothing is suggested and no row turns red. */
export function EveryoneOnPace() {
  return <BudgetPacing teams={ON_PACE} autoplay={false} />;
}
```

### Small move, no approval

A four-team studio where Product runs a little over: the gap is under the $15k limit, so the footer needs no one and Move goes straight through.

```tsx
import { BudgetPacing } from './budget-pacing';
import { STUDIO } from './data';

/** A small studio: the gap is under the approval limit, so the move goes through on its own. */
export function SmallMove() {
  return (
    <BudgetPacing teams={STUDIO} assistant="Orrin" approver="Theo Lindqvist" autoplay={false} />
  );
}
```

### Monthly view

October on its own: each team’s planned share of the quarter for the month, paced to Oct 31, where Sales rather than Marketing runs furthest over.

```tsx
import { BudgetPacing } from './budget-pacing';

/** October on its own: the month's share of each budget, paced to Oct 31. */
export function MonthlyView() {
  return <BudgetPacing defaultPeriod="month" autoplay={false} />;
}
```

## How it works

- Every row shares one scale, from nothing to 150% of the team’s own budget, so the Budget line sits at two thirds for everyone and the rows compare by pace, not by size. The track takes the spent, forecast and in-budget positions as custom properties; the bars and the dot are absolutely placed from them and slide when they change.
- Under the bars, the zone past 100% is shaded and the Budget and Today lines run through every row: they sit over the track column alone, from the same column widths as the rows’ grid, so they line up without measuring anything.
- The quarter view uses each team’s forecast to Dec 31; the month view takes the team’s planned share of the quarter for this month and carries the month’s spend at its pace to the month’s last day. The insight finds the team furthest over and the day its budget runs out at the pace still to come, and the team that will leave the most unused.
- The suggestion is the team furthest over, covered from the one with the most to spare; the gap chip is To’s overrun to the $1k, never more than From can spare. After a move, the next suggestion is picked from the budgets as they are now.
- Hovering a row shows its dollars at the pointer’s x, clamped inside the chart; focusing it puts the tooltip on its forecast’s dot. Pressing a row picks it for a move: as To when it is over, as From when it is not.
- From and To are menu buttons placed on the stage in its own px, so a scaled gallery card keeps them under their trigger. Picking the team already on the other side swaps them, as the arrow does. The amount is a field: digits only, the arrow keys step it by $1k (Shift: $10k).
- Move adds to a list of moves the budgets are computed from, so Undo only puts the list back. Ask sends the move to `onAskApproval` and holds the button at Asked until the move changes.
- While on screen and untouched, a demo pointer hovers two rows, switches to the month and back, tries $10k and the gap, moves the budget and undoes it. Any real input hands it over; it comes back after 9 s of quiet.

## API reference

- **teams** (`Team[]`, default `six teams of a 120-person company`): The teams: id, name, a tone (blue, amber, pink, cyan, violet, grey, green, orange), the quarter’s budget, spent so far, the forecast to the quarter’s end, the budget’s split over its three months, and optionally the month’s spend so far.
- **day** (`number`, default `17`): Today, as the day of the quarter (1–92). It places the Today line and sets the month.
- **assistant** (`string`, default `'Orrin'`): Who suggests the move, in the Move card’s subtitle.
- **approver** (`string`, default `'Mira Castell'`): Who signs off on a move over the limit; their first name is on the Ask button.
- **approvalLimit** (`number`, default `15000`): Moves over this many dollars name the approver and show Ask.
- **defaultPeriod** (`'month' | 'quarter'`, default `'quarter'`): The period it opens on.
- **showMove** (`boolean`, default `true`): The Move budget card under the budgets. Without it, rows only show their tooltip.
- **onMove** (`(move: Move) => void`): Called with { from, to, amount } when Move is pressed.
- **onAskApproval** (`(move: Move) => void`): Called with the move when Ask is pressed.
- **defaultState** (`BudgetPacingState`): Opens locked in a moment (a period, a hovered row, From, To and the amount, a move made, the approver asked, a menu open) with the demo off.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, a demo pointer shows the main interactions. Any real input stops it.
- **colorScheme** (`'light' | 'dark' | 'system'`): Light or dark colours, or the reader’s; without it, the page’s color-scheme.
- **className** (`string`): Classes for the stage.

## Accessibility

### Rows in words

Each team row is a button whose label reads it in full: the share of budget, how far over or under, then spent, forecast and budget. The bars are hidden from assistive technology. Being over is never shown by colour alone: the overrun is hatched and the share reads over 100% (WCAG 1.4.1, Use of color).

### Keyboard

- Tab reaches each row; its tooltip shows on keyboard focus. Escape hides the tooltip wherever the focus is, and the pointer can move onto it without losing it (WCAG 1.4.13, Content on hover or focus). Enter or Space picks the row for a move when the Move card is there.
- Month / Quarter is a radio group with one tab stop; the arrow keys flip the period.
- From, To and More actions open menus that move with the arrow keys, Home and End, and close on Escape with the focus back on their button.
- In the amount field the up and down arrows step it by $1k, or $10k with Shift.

### Announcements and errors

- A change of period is read out in a polite live region; every move and request is reported in a `role="status"` toast (WCAG 4.1.3, Status messages).
- An amount past what From has left marks the field invalid, and the footer, which the field points to with `aria-describedby`, says how much is left (WCAG 3.3.1, Error identification).
- The toast with Undo stays until Undo is used or the next move or request replaces it; other toasts leave after about six seconds, never while the pointer or the focus is on them (WCAG 2.2.1, Timing adjustable).

### Targets, contrast and motion

- The smallest controls are the period segments (26 px tall), the amount chips (28 px) and the swap button (30 × 30 px), all above the 24 × 24 px minimum; Undo in the toast has its hit area grown to 24 px tall (WCAG 2.5.8, Target size).
- Text, the axis labels included, is at least 4.5:1 on its surface in both schemes, and the team colours, the Budget and Today lines and the edges of the chosen period and chip at least 3:1 on the panel (WCAG 1.4.3 and 1.4.11).
- The demo pointer stops for good at the reader’s first input (WCAG 2.2.2, Pause, stop, hide). Under reduced motion nothing slides or fades, and the demo never plays.

### In this build

- Each card is a section named by its title. Each team row is a button whose label reads it in words: “Marketing: forecast 142% of budget, $18.1k over. Spent $11.3k, forecast $61.1k, budget $43k.” The bars themselves are hidden from assistive technology.
- The row’s tooltip is a role="tooltip" the row points to with aria-describedby; it shows on hover and on keyboard focus, and Escape hides it.
- Month / Quarter is a radiogroup with one tab stop, moved with the arrow keys; the change is read out in a polite live region.
- From, To and ··· are menu buttons; their menus move with the arrows, Home and End and close on Escape with the focus back on their button. The swap button and the amount field are labelled; the field is marked invalid when the amount is more than From has left, and the footer says why.
- Every move and request is reported in a status toast; Undo is a real button in it. Under reduced motion nothing slides or fades and the demo never plays. The demo pointer is decorative.

## Source

### budget-pacing/budget-pacing.tsx

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

'use client';

import {
  useEffect,
  useEffectEvent,
  useId,
  useMemo,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
} from 'react';
import { MoveTrack, PacingChart, isOver, type Hover } from './chart';
import {
  QUARTER,
  TEAMS,
  dateOf,
  dollars,
  gapOf,
  money,
  paceOf,
  percent,
  periodLabels,
  suggest,
  type Move,
  type Pace,
  type Period,
  type Team,
} from './data';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { Icon } from './glyphs';
import { Menu, MenuItem } from './menu';
import { useAutoplay } from './use-autoplay';
import styles from './budget-pacing.module.css';

/*
 * Budget pacing: two cards over a dark stage. The first paces each team's budget for the quarter
 * (or the month): what it has spent, where it lands at this pace, and how far past its budget.
 * The second moves budget between two teams, starting from the assistant's suggestion: the team
 * furthest over, covered from the one with the most to spare.
 *
 * - Month / Quarter recomputes every bar, the axis, the subtitle and the insight.
 * - Hovering or focusing a row shows its dollars; pressing one picks it as To (over) or From.
 * - From and To are menus of teams with what each has left; the arrow swaps them. The amount is
 *   typed, stepped with the arrow keys or picked from the chips, one of which fills the gap.
 * - Before → after rows show both teams' shares moving on the same scale. Over the approval
 *   limit, the footer names who approves. Move applies it to the budgets above, with Undo in a
 *   toast that stays until it is used or replaced; other toasts leave after a few seconds, never
 *   while the pointer or the focus is on them.
 * - While on screen and untouched, a demo pointer hovers two rows, switches to the month and
 *   back, tries two amounts, moves the budget and undoes it, in a loop. The reader's first input
 *   stops it for good.
 */

export type { Move, Pace, Period, Team } from './data';

/** A moment to open in, locked: the docs draw each state from one. It turns the demo off. */
export type BudgetPacingState = {
  period?: Period;
  /** A row hovered, its tooltip shown on its forecast's dot. */
  hover?: string;
  from?: string;
  to?: string;
  amount?: number;
  /** The suggested move already made, with its Undo toast. */
  moved?: boolean;
  /** The approver already asked. */
  asked?: boolean;
  menu?: 'from' | 'to' | 'more';
};

type MenuState = { id: 'from' | 'to' | 'more'; anchor: HTMLElement; byReader: boolean };
type Snapshot = { moves: Move[]; from: string; to: string; amount: number };
type Toast = { n: number; text: string; undo?: Snapshot };

const PRESETS = [10_000, 25_000];

/** The pick when nothing needs covering: the most to spare, into the one closest to its budget. */
function fallback(paces: Pace[]) {
  const bySpare = [...paces].sort((a, b) => b.spare - a.spare);
  const byShare = [...paces].sort((a, b) => b.share - a.share);
  const from = bySpare[0]?.team.id ?? '';
  const to = byShare.find((p) => p.team.id !== from)?.team.id ?? '';
  return { from, to };
}

export function BudgetPacing({
  teams = TEAMS,
  day = 17,
  assistant = 'Orrin',
  approver = 'Mira Castell',
  approvalLimit = 15_000,
  defaultPeriod = 'quarter',
  showMove = true,
  onMove,
  onAskApproval,
  defaultState,
  autoplay = true,
  colorScheme,
  className = '',
}: {
  /** The teams, with the quarter's budget, spend so far and forecast. */
  teams?: Team[];
  /** Today, as the day of the quarter (1–92). */
  day?: number;
  /** Who suggests the move, in the Move card's subtitle. */
  assistant?: string;
  /** Who approves a move over the limit. */
  approver?: string;
  /** Moves over this many dollars need the approver. */
  approvalLimit?: number;
  defaultPeriod?: Period;
  /** The Move budget card under the budgets. */
  showMove?: boolean;
  /** Called when a move is applied. */
  onMove?: (move: Move) => void;
  /** Called when Ask is pressed. */
  onAskApproval?: (move: Move) => void;
  /** Opens locked in a moment, with the demo off. */
  defaultState?: BudgetPacingState;
  autoplay?: boolean;
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const uid = useId();
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>();
  const pointer = useRef<HTMLSpanElement>(null);
  const locked = defaultState !== undefined;

  // The suggestion on the budgets as they come, for the first From, To and amount.
  const start = useMemo(() => {
    const period = defaultState?.period ?? defaultPeriod;
    const paces = paceOf(teams, day, period, []);
    const pick = suggest(paces) ?? fallback(paces);
    const from = defaultState?.from ?? pick.from;
    const to = defaultState?.to ?? pick.to;
    const gap = gapOf(
      paces.find((p) => p.team.id === from),
      paces.find((p) => p.team.id === to),
    );
    const amount = defaultState?.amount ?? (gap || PRESETS[0]);
    // Opened after the move: the next suggestion, on the budgets as the move left them.
    let next = { from, to, amount };
    if (defaultState?.moved) {
      const paced = paceOf(teams, day, period, [{ from, to, amount }]);
      const again = suggest(paced);
      if (again)
        next = {
          ...again,
          amount:
            gapOf(
              paced.find((p) => p.team.id === again.from),
              paced.find((p) => p.team.id === again.to),
            ) || PRESETS[0],
        };
    }
    return { period, from, to, amount, next };
    // Only the first draw.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const [period, setPeriod] = useState<Period>(start.period);
  const [moves, setMoves] = useState<Move[]>(
    defaultState?.moved ? [{ from: start.from, to: start.to, amount: start.amount }] : [],
  );
  const [from, setFrom] = useState(start.next.from);
  const [to, setTo] = useState(start.next.to);
  const [amount, setAmount] = useState(start.next.amount);
  const [hover, setHover] = useState<Hover>(null);
  const [menu, setMenu] = useState<MenuState | null>(null);
  const [toast, setToast] = useState<Toast | null>(
    defaultState?.moved
      ? {
          n: 1,
          text: `Moved ${money(start.amount)} to ${teams.find((t) => t.id === start.to)?.name}`,
          undo: { moves: [], from: start.from, to: start.to, amount: start.amount },
        }
      : null,
  );
  const [asked, setAsked] = useState<string | null>(
    defaultState?.asked ? `${start.from}>${start.to}>${start.amount}` : null,
  );
  const [news, setNews] = useState('');
  /** The pointer or the focus is on the toast: it does not leave meanwhile. */
  const [held, setHeld] = useState({ pointer: false, focus: false });

  const paces = useMemo(() => paceOf(teams, day, period, moves), [teams, day, period, moves]);
  const paceById = (id: string) => paces.find((p) => p.team.id === id);
  const labels = periodLabels(day, period);
  const today = labels.day / labels.length;
  const totalBudget = paces.reduce((sum, p) => sum + p.budget, 0);
  const totalSpent = paces.reduce((sum, p) => sum + p.spent, 0);

  // ---- The insight -------------------------------------------------------------------------------

  const worst = [...paces].filter(isOver).sort((a, b) => b.share - a.share)[0];
  const roomiest = [...paces].filter((p) => p.spare > 0).sort((a, b) => b.spare - a.spare)[0];
  const suggestion = suggest(paces);

  // ---- The move ----------------------------------------------------------------------------------

  const source = paceById(from);
  const target = paceById(to);
  const gap = gapOf(source, target);
  const presets = [...new Set([...PRESETS, ...(gap ? [gap] : [])])].sort((a, b) => a - b);
  const left = source ? source.budget - source.spent : 0;
  const tooMuch = amount > left;
  const valid = amount > 0 && !tooMuch && from !== to && !!source && !!target;
  const needsApproval = amount > approvalLimit;
  const moveKey = `${from}>${to}>${amount}`;
  const after = (pace: Pace | undefined, delta: number) =>
    pace ? pace.forecast / Math.max(1, pace.budget + delta) : 0;
  const isSuggested = !!suggestion && suggestion.from === from && suggestion.to === to;

  // ---- Changes -----------------------------------------------------------------------------------

  const say = (text: string, undo?: Snapshot) =>
    setToast((now) => ({ n: (now?.n ?? 0) + 1, text, undo }));

  // A toast with Undo stays until it is used or replaced (WCAG 2.2.1); the others leave after
  // 5.6 s, counted afresh once the pointer and the focus are off them.
  const holding = held.pointer || held.focus;
  useEffect(() => {
    if (!toast || toast.undo || locked || holding) return;
    const timer = window.setTimeout(() => setToast(null), 5600);
    return () => window.clearTimeout(timer);
  }, [toast, locked, holding]);
  useEffect(() => {
    if (!toast) setHeld({ pointer: false, focus: false });
  }, [toast]);

  const openMenu = (id: MenuState['id'], anchor: HTMLElement, byReader = true) =>
    setMenu((now) => (now?.id === id ? null : { id, anchor, byReader }));
  const closeMenu = (back: boolean) => {
    if (back) menu?.anchor.focus();
    setMenu(null);
  };

  const choosePeriod = (next: Period) => {
    setPeriod(next);
    setHover(null);
    // A pair still on the suggestion follows it into the other period.
    if (isSuggested || !suggestion) {
      const paced = paceOf(teams, day, next, moves);
      const pick = suggest(paced);
      if (pick) {
        setFrom(pick.from);
        setTo(pick.to);
        setAmount(
          gapOf(
            paced.find((p) => p.team.id === pick.from),
            paced.find((p) => p.team.id === pick.to),
          ) || PRESETS[0],
        );
      }
    }
    const l = periodLabels(day, next);
    setNews(
      next === 'quarter'
        ? `Showing the quarter, day ${l.day} of ${l.length}`
        : `Showing ${dateOf(day).split(' ')[0]}, day ${l.day} of ${l.length}`,
    );
  };

  /** Picks a pair, and the amount that fills its gap when there is one. */
  const pair = (nextFrom: string, nextTo: string) => {
    setFrom(nextFrom);
    setTo(nextTo);
    const g = gapOf(paceById(nextFrom), paceById(nextTo));
    if (g) setAmount(g);
  };
  const pickFrom = (id: string) => (id === to ? pair(to, from) : pair(id, to));
  const pickTo = (id: string) => (id === from ? pair(to, from) : pair(from, id));

  const applyMove = () => {
    if (!valid || !source || !target) return;
    const move = { from, to, amount };
    const before: Snapshot = { moves, from, to, amount };
    const next = [...moves, move];
    setMoves(next);
    // The next suggestion, on the budgets as they are now.
    const paced = paceOf(teams, day, period, next);
    const pick = suggest(paced);
    if (pick) {
      setFrom(pick.from);
      setTo(pick.to);
      setAmount(
        gapOf(
          paced.find((p) => p.team.id === pick.from),
          paced.find((p) => p.team.id === pick.to),
        ) || PRESETS[0],
      );
    }
    setAsked(null);
    say(`Moved ${money(amount)} from ${source.team.name} to ${target.team.name}`, before);
    onMove?.(move);
  };

  const undo = (snapshot: Snapshot) => {
    setMoves(snapshot.moves);
    setFrom(snapshot.from);
    setTo(snapshot.to);
    setAmount(snapshot.amount);
    setToast(null);
    setNews('Move undone');
  };

  const ask = () => {
    if (!valid || !target) return;
    setAsked(moveKey);
    say(`Asked ${approver} to approve ${money(amount)} for ${target.team.name}`);
    onAskApproval?.({ from, to, amount });
  };

  const resetToSuggestion = () => {
    const pick = suggestion ?? fallback(paces);
    pair(pick.from, pick.to);
    if (!gapOf(paceById(pick.from), paceById(pick.to))) setAmount(PRESETS[0]);
  };

  const copySummary = () => {
    if (!source || !target) return;
    const text = `Move ${dollars(amount)} from ${source.team.name} to ${target.team.name}: ${
      target.team.name
    } ${percent(target.share)} → ${percent(after(target, amount))}, ${source.team.name} ${percent(
      source.share,
    )} → ${percent(after(source, -amount))}.`;
    navigator.clipboard?.writeText(text).catch(() => {});
    say('Copied the move as text');
  };

  // A locked menu opens on its trigger once it is drawn.
  useEffect(() => {
    const name = defaultState?.menu;
    if (!name) return;
    const anchor = root.current?.querySelector<HTMLElement>(`[data-demo="${name}"]`);
    if (anchor) setMenu({ id: name, anchor, byReader: false });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  // A locked tooltip sits on its row's forecast dot.
  useEffect(() => {
    const id = defaultState?.hover;
    if (!id) return;
    const frame = requestAnimationFrame(() => showOn(id));
    return () => cancelAnimationFrame(frame);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /** Shows a row's tooltip on its forecast's dot. */
  const showOn = (id: string) => {
    const plot = root.current?.querySelector<HTMLElement>('[data-part="chart"]');
    const dot = plot?.querySelector<HTMLElement>(`[data-dot="${id}"]`);
    if (!plot || !dot) return;
    const p = plot.getBoundingClientRect();
    const d = dot.getBoundingClientRect();
    const scale = p.width / plot.offsetWidth || 1;
    setHover({ id, x: (d.left + d.width / 2 - p.left) / scale });
  };

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

  const demo = autoplay && playing && !locked;
  const dirty = useEffectEvent(
    () => period !== start.period || moves.length > 0 || from !== start.from || to !== start.to,
  );
  const reset = useEffectEvent(() => {
    setPeriod(start.period);
    setMoves([]);
    setFrom(start.from);
    setTo(start.to);
    setAmount(start.amount);
    setAsked(null);
    setHover(null);
    setMenu(null);
  });
  const demoHover = useEffectEvent((id: string | null) => (id ? showOn(id) : setHover(null)));
  const demoClear = useEffectEvent(() => {
    setMenu(null);
    setHover(null);
  });

  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    if (!demo || !stage || !arrow) return;
    const find = (name: string) => stage.querySelector<HTMLElement>(`[data-demo="${name}"]`);
    const on = (element: Element | null, fx = 0.5, fy = 0.5): Point => {
      const frame = stage.getBoundingClientRect();
      const scale = frame.width / stage.offsetWidth || 1;
      const rect = element?.getBoundingClientRect() ?? frame;
      return {
        x: (rect.left + rect.width * fx - frame.left) / scale,
        y: (rect.top + rect.height * fy - frame.top) / scale,
      };
    };
    let over: HTMLElement | null = null;
    const stop = runDemo(stage, arrow, async ({ wait, glide, glyph }) => {
      const press = async (name: string, ms: number, after: number, fx = 0.5, fy = 0.5) => {
        const element = find(name);
        if (!element) return;
        glyph('arrow');
        await glide(on(element, fx, fy), ms);
        glyph('hand');
        over = element;
        element.dataset.over = '';
        await wait(240);
        const live = find(name) ?? element;
        delete element.dataset.over;
        over = null;
        live.click();
        await wait(after);
      };
      const point = async (id: string, ms: number, after: number) => {
        glyph('arrow');
        await glide(on(stage.querySelector(`[data-dot="${id}"]`)), ms);
        demoHover(id);
        await wait(after);
      };
      for (;;) {
        if (dirty()) {
          reset();
          await wait(400);
        }
        await wait(900);
        // Who runs over, and by how much.
        await point('marketing', 800, 1700);
        await point('sales', 560, 1500);
        demoHover(null);
        // The month, then back to the quarter.
        await press('period-month', 700, 1700);
        await press('period-quarter', 420, 1100);
        // A smaller move needs no approval; the gap does.
        await press('preset-10000', 900, 1500);
        await press('preset-gap', 520, 1100);
        // Move it: the budgets above take it at once.
        await press('move', 700, 2200);
        await press('undo', 800, 1300);
        glyph('arrow');
        await glide(on(stage, 0.84, 0.94), 800);
        await wait(1800);
      }
    });
    return () => {
      stop();
      if (over) delete over.dataset.over;
      demoClear();
    };
  }, [demo, root]);

  // ---- Drawing -----------------------------------------------------------------------------------

  const periodKeys = (event: ReactKeyboardEvent) => {
    if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) return;
    event.preventDefault();
    const next: Period = period === 'month' ? 'quarter' : 'month';
    choosePeriod(next);
    root.current?.querySelector<HTMLElement>(`[data-demo="period-${next}"]`)?.focus();
  };

  const select = (side: 'from' | 'to') => {
    const pace = side === 'from' ? source : target;
    return (
      <button
        type="button"
        className={styles.select}
        data-tone={pace?.team.tone}
        data-demo={side}
        data-part="select"
        aria-haspopup="menu"
        aria-expanded={menu?.id === side}
        aria-labelledby={`${uid}-${side} ${uid}-${side}-value`}
        onClick={(event) => openMenu(side, event.currentTarget)}
      >
        <span className={styles.swatch} aria-hidden="true" />
        <span className={styles.selectText} id={`${uid}-${side}-value`}>
          <span className={styles.selectName}>{pace?.team.name ?? 'Pick a team'}</span>
          {pace && (
            <span className={styles.selectLeft}>{money(pace.budget - pace.spent)} left</span>
          )}
        </span>
        <Icon name="chevronDown" className={styles.selectChevron} width={2} />
      </button>
    );
  };

  const subtitle = isSuggested
    ? `${assistant} suggests covering ${target?.team.name} from ${source?.team.name}`
    : suggestion
      ? `${assistant} suggests covering ${paceById(suggestion.to)?.team.name} from ${
          paceById(suggestion.from)?.team.name
        }`
      : `Every team is on pace: ${assistant} has nothing to cover`;

  const moveRow = (pace: Pace | undefined, delta: number) => {
    if (!pace) return null;
    const next = after(pace, delta);
    const beforeOver = isOver(pace);
    const afterOver = Math.round(next * 100) > 100;
    return (
      <li
        className={styles.moveRow}
        data-tone={pace.team.tone}
        data-part="before-after"
        aria-label={`${pace.team.name}: ${percent(pace.share)} of budget now, ${percent(next)} after the move`}
      >
        <span className={styles.swatch} aria-hidden="true" />
        <span className={styles.moveName}>{pace.team.name}</span>
        <MoveTrack before={pace.share} after={next} tone={pace.team.tone} over={afterOver} />
        <span className={styles.moveShares} aria-hidden="true">
          <span data-over={beforeOver || undefined}>{percent(pace.share)}</span>
          <Icon name="arrowRight" className={styles.moveArrow} />
          <b data-over={afterOver || undefined}>{percent(next)}</b>
        </span>
      </li>
    );
  };

  const approverFirst = approver.split(' ')[0];

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="stage"
      data-color-scheme={colorScheme}
      onPointerDownCapture={take}
      onKeyDownCapture={take}
      onWheel={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') take();
      }}
    >
      <div className={styles.cards}>
        <section className={styles.card} aria-labelledby={`${uid}-title`} data-part="budgets-card">
          <header className={styles.head} data-part="header">
            <span className={styles.tile} data-tone="green" aria-hidden="true">
              <Icon name="target" className={styles.tileIcon} width={2} />
            </span>
            <span className={styles.headText}>
              <h3 id={`${uid}-title`} className={styles.title}>
                {QUARTER.name} budgets by team
              </h3>
              <span className={styles.subtitle}>
                Day {labels.day} of {labels.length} · {money(totalSpent)} of {money(totalBudget)}{' '}
                spent
              </span>
            </span>
            <span
              role="radiogroup"
              aria-label="Period"
              className={styles.segmented}
              data-part="segmented"
            >
              {(['month', 'quarter'] as const).map((p) => (
                <button
                  key={p}
                  type="button"
                  role="radio"
                  aria-checked={period === p}
                  tabIndex={period === p ? 0 : -1}
                  className={styles.segment}
                  data-demo={`period-${p}`}
                  onKeyDown={periodKeys}
                  onClick={() => choosePeriod(p)}
                >
                  {p === 'month' ? 'Month' : 'Quarter'}
                </button>
              ))}
            </span>
          </header>

          <div className={styles.panel}>
            <ul className={styles.legend} aria-label="Legend" data-part="legend">
              <li>
                <span className={styles.keySpent} aria-hidden="true" />
                Spent
              </li>
              <li>
                <span className={styles.keyForecast} aria-hidden="true" />
                Forecast to {labels.end}
              </li>
              <li>
                <span className={styles.keyOver} aria-hidden="true" />
                Over budget
              </li>
            </ul>

            <PacingChart
              paces={paces}
              today={today}
              hover={hover}
              onHover={setHover}
              onPick={
                showMove
                  ? (pace) => {
                      if (isOver(pace)) pickTo(pace.team.id);
                      else pickFrom(pace.team.id);
                    }
                  : undefined
              }
            />

            <p className={styles.insight} data-part="insight">
              <Icon name="spark" className={styles.insightIcon} />
              <span>
                {worst ? (
                  <>
                    <span className={styles.insightTeam} data-tone={worst.team.tone}>
                      {worst.team.name}
                    </span>{' '}
                    {worst.runsOut ? (
                      <>
                        runs out on <b>{dateOf(worst.runsOut)}</b> at this pace.
                      </>
                    ) : (
                      <>
                        lands <b>{money(-worst.spare)}</b> over at this pace.
                      </>
                    )}
                  </>
                ) : (
                  <>Every team lands inside its budget at this pace.</>
                )}
                {roomiest && (
                  <>
                    {' '}
                    {roomiest.team.name} will leave {money(roomiest.spare)} unused.
                  </>
                )}
              </span>
            </p>
          </div>
        </section>

        {showMove && (
          <section
            className={styles.card}
            aria-labelledby={`${uid}-move-title`}
            data-part="move-card"
          >
            <header className={styles.head}>
              <span className={styles.tile} data-tone="violet" aria-hidden="true">
                <Icon name="swap" className={styles.tileIcon} width={2} />
              </span>
              <span className={styles.headText}>
                <h3 id={`${uid}-move-title`} className={styles.title}>
                  Move budget
                </h3>
                <span className={styles.subtitle}>{subtitle}</span>
              </span>
              <button
                type="button"
                className={styles.more}
                aria-label="More actions"
                aria-haspopup="menu"
                aria-expanded={menu?.id === 'more'}
                data-demo="more"
                onClick={(event) => openMenu('more', event.currentTarget)}
              >
                <Icon name="more" width={2.6} />
              </button>
            </header>

            <div className={styles.panel}>
              <div className={styles.pair} data-part="pair">
                <span className={styles.fieldLabel} id={`${uid}-from`}>
                  From
                </span>
                <span className={styles.fieldLabel} id={`${uid}-to`} data-side="to">
                  To
                </span>
                {select('from')}
                <button
                  type="button"
                  className={styles.swapButton}
                  aria-label="Swap From and To"
                  data-demo="swap"
                  data-part="swap"
                  onClick={() => pair(to, from)}
                >
                  <Icon name="chevronRight" width={2.2} />
                </button>
                {select('to')}
              </div>

              <div className={styles.amountRow} data-part="amount">
                <label className={styles.srOnly} htmlFor={`${uid}-amount`}>
                  Amount to move
                </label>
                <input
                  id={`${uid}-amount`}
                  className={styles.amount}
                  inputMode="numeric"
                  autoComplete="off"
                  value={dollars(amount)}
                  aria-invalid={tooMuch || amount === 0 || undefined}
                  aria-describedby={`${uid}-note`}
                  onChange={(event) => {
                    const digits = event.target.value.replace(/\D/g, '').slice(0, 8);
                    setAmount(Number(digits || 0));
                  }}
                  onKeyDown={(event) => {
                    if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
                      event.preventDefault();
                      const step = event.shiftKey ? 10_000 : 1000;
                      setAmount((now) =>
                        Math.max(0, now + (event.key === 'ArrowUp' ? step : -step)),
                      );
                    }
                  }}
                />
                <span className={styles.chips} role="group" aria-label="Preset amounts">
                  {presets.map((value) => (
                    <button
                      key={value}
                      type="button"
                      className={styles.chip}
                      data-gap={value === gap || undefined}
                      data-demo={value === gap ? 'preset-gap' : `preset-${value}`}
                      data-part={value === gap ? 'gap-chip' : 'chip'}
                      aria-pressed={amount === value}
                      onClick={() => setAmount(value)}
                    >
                      {money(value)}
                      {value === gap && ' · fills the gap'}
                    </button>
                  ))}
                </span>
              </div>

              <ul className={styles.moveRows} aria-label="Before and after the move">
                {moveRow(target, amount)}
                {moveRow(source, -amount)}
              </ul>
            </div>

            <footer className={styles.foot} data-part="footer">
              <span className={styles.approver} aria-hidden="true">
                {needsApproval ? approver[0] : <Icon name="check" width={2.4} />}
              </span>
              <span className={styles.note} id={`${uid}-note`} data-error={tooMuch || undefined}>
                {tooMuch && source ? (
                  <>
                    {source.team.name} has only <b>{money(left)}</b> left
                  </>
                ) : asked === moveKey ? (
                  <>
                    Waiting on <b>{approverFirst}</b> to approve
                  </>
                ) : needsApproval ? (
                  <>
                    Over {money(approvalLimit)} needs <b>{approverFirst}</b> to approve
                  </>
                ) : (
                  <>Under {money(approvalLimit)}, no approval needed</>
                )}
              </span>
              <span className={styles.actions}>
                {needsApproval && (
                  <button
                    type="button"
                    className={styles.secondary}
                    data-demo="ask"
                    aria-disabled={!valid || asked === moveKey || undefined}
                    onClick={() => {
                      if (asked !== moveKey) ask();
                    }}
                  >
                    {asked === moveKey ? (
                      <>
                        <Icon name="check" className={styles.buttonIcon} width={2.2} />
                        Asked
                      </>
                    ) : (
                      `Ask ${approverFirst}`
                    )}
                  </button>
                )}
                <button
                  type="button"
                  className={styles.primary}
                  data-demo="move"
                  data-part="move-button"
                  aria-disabled={!valid || undefined}
                  onClick={applyMove}
                >
                  Move {money(amount)}
                </button>
              </span>
            </footer>
          </section>
        )}
      </div>

      <p className={styles.srOnly} aria-live="polite">
        {news}
      </p>

      {menu && (
        <Menu
          anchor={menu.anchor}
          label={menu.id === 'from' ? 'Move from' : menu.id === 'to' ? 'Move to' : 'More actions'}
          align={menu.id === 'from' ? 'start' : 'end'}
          takeFocus={menu.byReader}
          onClose={closeMenu}
        >
          {menu.id === 'more' ? (
            <>
              <MenuItem
                lead={<Icon name="reset" className={styles.menuIcon} />}
                onSelect={() => {
                  resetToSuggestion();
                  closeMenu(true);
                }}
              >
                Back to the suggestion
              </MenuItem>
              <MenuItem
                lead={<Icon name="copy" className={styles.menuIcon} />}
                onSelect={() => {
                  copySummary();
                  closeMenu(true);
                }}
              >
                Copy the move as text
              </MenuItem>
            </>
          ) : (
            paces.map((pace) => (
              <MenuItem
                key={pace.team.id}
                radio
                checked={(menu.id === 'from' ? from : to) === pace.team.id}
                lead={
                  <span className={styles.swatch} data-tone={pace.team.tone} aria-hidden="true" />
                }
                trail={`${money(pace.budget - pace.spent)} left`}
                onSelect={() => {
                  if (menu.id === 'from') pickFrom(pace.team.id);
                  else pickTo(pace.team.id);
                  closeMenu(true);
                }}
              >
                {pace.team.name}
              </MenuItem>
            ))
          )}
        </Menu>
      )}

      {toast && (
        <div
          key={toast.n}
          className={styles.toast}
          role="status"
          data-part="toast"
          onPointerEnter={() => setHeld((now) => ({ ...now, pointer: true }))}
          onPointerLeave={() => setHeld((now) => ({ ...now, pointer: false }))}
          onFocus={() => setHeld((now) => ({ ...now, focus: true }))}
          onBlur={() => setHeld((now) => ({ ...now, focus: false }))}
        >
          <Icon name="check" className={styles.toastIcon} width={2.2} />
          <span>{toast.text}</span>
          {toast.undo && (
            <button
              type="button"
              className={styles.toastUndo}
              data-demo="undo"
              onClick={() => undo(toast.undo!)}
            >
              Undo
            </button>
          )}
        </div>
      )}

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

### budget-pacing/chart.tsx

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

'use client';

import { useEffect, useId, useRef, type CSSProperties } from 'react';
import { money, percent, type Pace } from './data';
import styles from './budget-pacing.module.css';

/*
 * The pacing chart: a row per team on one scale from nothing to 150% of its budget. The spent bar
 * in the team's colour, the forecast to the period's end dimmer and ending on a dot, and past the
 * Budget line the overrun hatched in red. Behind the rows: the shaded zone from 100% to 150%, the
 * Budget line and today's dotted line, labelled under the last row.
 *
 * Hovering a row (or focusing it) shows a tooltip with its dollars, at the pointer's x or on its
 * forecast's dot. The pointer can move onto the tooltip without losing it, and Escape hides it
 * wherever the focus is. Pressing a row picks it for a move: To when it is over, From when it is
 * not.
 */

/** The scale's end: 150% of a budget. */
export const MAX = 1.5;
/** A share as a position on the track, in %. */
export const x = (share: number) => (Math.min(Math.max(share, 0), MAX) / MAX) * 100;
/** Over budget, as the figure reads (100.4% reads 100% and is not). */
export const isOver = (pace: Pace) => Math.round(pace.share * 100) > 100;

export type Hover = { id: string; x: number } | null;

export function PacingChart({
  paces,
  today,
  hover,
  onHover,
  onPick,
}: {
  paces: Pace[];
  /** Today as a share of the period. */
  today: number;
  hover: Hover;
  onHover: (hover: Hover) => void;
  onPick?: (pace: Pace) => void;
}) {
  const plot = useRef<HTMLDivElement>(null);
  const tipId = useId();

  /** A client x as the plot's own px: a gallery card may scale the whole stage. */
  const local = (clientX: number) => {
    const box = plot.current;
    if (!box) return 0;
    const rect = box.getBoundingClientRect();
    return (clientX - rect.left) / (rect.width / box.offsetWidth || 1);
  };
  /** The x of a row's forecast dot, in the plot's px. */
  const dotX = (id: string) => {
    const dot = plot.current?.querySelector<HTMLElement>(`[data-dot="${id}"]`);
    if (!dot) return 0;
    const rect = dot.getBoundingClientRect();
    return local(rect.left + rect.width / 2);
  };

  const shown = hover ? paces.find((p) => p.team.id === hover.id) : undefined;

  // Escape hides a hovered tooltip even when the focus is somewhere else (WCAG 1.4.13).
  const open = !!hover;
  useEffect(() => {
    if (!open) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') onHover(null);
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onHover]);
  const shownIndex = shown ? paces.indexOf(shown) : -1;

  return (
    <div
      ref={plot}
      className={styles.plot}
      style={{ '--rows': paces.length } as CSSProperties}
      data-part="chart"
      onPointerLeave={(event) => {
        if (event.pointerType !== 'touch') onHover(null);
      }}
    >
      <div className={styles.guides} aria-hidden="true">
        <span className={styles.zone} data-part="zone" />
        <span className={styles.budgetLine} />
        <span className={styles.todayLine} style={{ left: `${x(today)}%` }} />
      </div>

      <ul className={styles.rows} aria-label="Teams by forecast against budget">
        {paces.map((pace) => {
          const over = isOver(pace);
          const { team } = pace;
          const label = `${team.name}: forecast ${percent(pace.share)} of budget${
            over ? `, ${money(-pace.spare, true)} over` : `, ${money(pace.spare, true)} to spare`
          }. Spent ${money(pace.spent, true)}, forecast ${money(pace.forecast, true)}, budget ${money(pace.budget, true)}.`;
          const track = {
            '--spent': `${x(pace.spent / pace.budget)}%`,
            '--forecast': `${x(pace.share)}%`,
            '--within': `${x(Math.min(pace.share, 1))}%`,
          } as CSSProperties;
          return (
            <li key={team.id}>
              <button
                type="button"
                className={styles.row}
                data-tone={team.tone}
                data-over={over || undefined}
                data-hover={hover?.id === team.id || undefined}
                data-part="team-row"
                data-demo={`row-${team.id}`}
                aria-label={label}
                aria-describedby={hover?.id === team.id ? tipId : undefined}
                onPointerMove={(event) => {
                  if (event.pointerType !== 'touch')
                    onHover({ id: team.id, x: local(event.clientX) });
                }}
                onFocus={(event) => {
                  if (event.currentTarget.matches(':focus-visible'))
                    onHover({ id: team.id, x: dotX(team.id) });
                }}
                onBlur={() => onHover(null)}
                onKeyDown={(event) => {
                  if (event.key === 'Escape') onHover(null);
                }}
                onClick={() => onPick?.(pace)}
              >
                <span className={styles.who}>
                  <span className={styles.avatar} aria-hidden="true">
                    {team.name[0]}
                  </span>
                  <span className={styles.teamName}>{team.name}</span>
                </span>
                <span className={styles.track} style={track} aria-hidden="true">
                  <span className={styles.forecastBar} />
                  {over && <span className={styles.overBar} />}
                  <span className={styles.spentBar} />
                  <span className={styles.dot} data-dot={team.id} />
                </span>
                <span className={styles.share}>{percent(pace.share)}</span>
              </button>
            </li>
          );
        })}
      </ul>

      <div className={styles.axis} aria-hidden="true">
        <span style={{ left: `${x(today)}%` }}>Today</span>
        <span style={{ left: `${x(1)}%` }}>Budget</span>
        <span style={{ left: '100%' }} data-end="">
          150%
        </span>
      </div>

      {shown && hover && (
        <div
          id={tipId}
          role="tooltip"
          className={styles.tip}
          data-part="tooltip"
          data-tone={shown.team.tone}
          style={
            {
              '--tip-x': `${hover.x}px`,
              '--tip-row': shownIndex,
            } as CSSProperties
          }
        >
          <span className={styles.tipHead}>
            <span className={styles.tipSwatch} aria-hidden="true" />
            {shown.team.name}
            <span className={styles.tipShare} data-over={isOver(shown) || undefined}>
              {percent(shown.share)}
            </span>
          </span>
          <span className={styles.tipGrid}>
            <span>Spent</span>
            <b>{money(shown.spent, true)}</b>
            <span>Forecast</span>
            <b>{money(shown.forecast, true)}</b>
            <span>Budget</span>
            <b>{money(shown.budget, true)}</b>
          </span>
          <span className={styles.tipFoot} data-over={isOver(shown) || undefined}>
            {isOver(shown)
              ? `${money(-shown.spare, true)} over at this pace`
              : `${money(shown.spare, true)} left at this pace`}
          </span>
        </div>
      )}
    </div>
  );
}

/** A team's share before and after a move, on the same scale: a ring, then a dot. */
export function MoveTrack({
  before,
  after,
  tone,
  over,
}: {
  before: number;
  after: number;
  tone: string;
  over: boolean;
}) {
  const a = x(before);
  const b = x(after);
  return (
    <span
      className={styles.moveTrack}
      data-tone={tone}
      data-over={over || undefined}
      aria-hidden="true"
      style={
        {
          '--from': `${Math.min(a, b)}%`,
          '--to': `${Math.max(a, b)}%`,
          '--before': `${a}%`,
          '--after': `${b}%`,
        } as CSSProperties
      }
    >
      <span className={styles.moveTick} />
      <span className={styles.moveSpan} />
      <span className={styles.moveRing} />
      <span className={styles.moveDot} />
    </span>
  );
}
```

### budget-pacing/budget-pacing.module.css

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

/* Budget pacing (budget-pacing.tsx): two cards stacked on a stage washed with soft gradients,
   near-black and indigo by night, pale lavender by day. Each card is a header (an icon tile, a
   title, a subtitle, a control at the end) over an inset panel; the Move card adds a footer.

   The pacing chart (chart.tsx) lays every row on one grid: the team, the track, the share. The
   guides (the zone past the budget, the Budget line, today's dotted line) and the axis sit over
   the track column only, from the same widths, so they line up with every bar.

   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
   (data-color-scheme). */

.root {
  --stage: #ebe9f5;
  --wash-1: rgb(150 140 245 / 0.42);
  --wash-2: rgb(196 180 252 / 0.5);
  --wash-3: rgb(120 150 240 / 0.3);
  --card: #ffffff;
  --card-edge: rgb(20 20 40 / 0.07);
  --panel: #f7f7f9;
  --panel-edge: #ececf1;
  --field: #ffffff;
  --field-edge: #e2e2e8;
  --ink: #17171c;
  --ink-2: #66666f;
  --ink-3: #717178;
  --track: #e8e8ee;
  --guide: #898990;
  --zone: rgb(226 84 62 / 0.06);
  --hover: rgb(20 20 40 / 0.035);
  --segment: #efeff3;
  --segment-on: #ffffff;
  --button: #efeff3;
  --button-hover: #e6e6ec;
  --primary: #17171c;
  --primary-ink: #ffffff;
  --red: #dd4b37;
  --red-ink: #c53a27;
  --gap-bg: #e6f7ef;
  --gap-edge: #8fd7b5;
  --gap-ink: #137f4e;
  --tip: #1b1b20;
  --tip-ink: #f2f2f4;
  --tip-ink-2: #a4a4ad;
  --menu: #ffffff;
  --shadow: rgb(30 30 60 / 0.1);
  --blue: #4568e6;
  --amber: #be840a;
  --pink: #d8468f;
  --cyan: #199cba;
  --violet: #7a62ef;
  --grey: #8a8a93;
  --green: #1f9e66;
  --orange: #db7328;
  --focus: #7786f5;
  /* The same on both schemes. */
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.3);
  --sans: var(--body, Inter, ui-sans-serif, system-ui, sans-serif);
  /* The chart's columns. */
  --name-w: 148px;
  --share-w: 58px;
  --col-gap: 14px;
  --pitch: 37px;
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --stage: light-dark(#ebe9f5, #0b0a12);
    --wash-1: light-dark(rgb(150 140 245 / 0.42), rgb(92 96 210 / 0.5));
    --wash-2: light-dark(rgb(196 180 252 / 0.5), rgb(70 64 170 / 0.45));
    --wash-3: light-dark(rgb(120 150 240 / 0.3), rgb(60 70 160 / 0.35));
    --card: light-dark(#ffffff, #111112);
    --card-edge: light-dark(rgb(20 20 40 / 0.07), rgb(255 255 255 / 0.07));
    --panel: light-dark(#f7f7f9, #161617);
    --panel-edge: light-dark(#ececf1, #222224);
    --field: light-dark(#ffffff, #101011);
    --field-edge: light-dark(#e2e2e8, #262628);
    --ink: light-dark(#17171c, #ededef);
    --ink-2: light-dark(#66666f, #9b9ba2);
    --ink-3: light-dark(#717178, #7f7f85);
    --track: light-dark(#e8e8ee, #252527);
    --guide: light-dark(#898990, #6c6c70);
    --zone: light-dark(rgb(226 84 62 / 0.06), rgb(240 110 80 / 0.07));
    --hover: light-dark(rgb(20 20 40 / 0.035), rgb(255 255 255 / 0.03));
    --segment: light-dark(#efeff3, #0d0d0e);
    --segment-on: light-dark(#ffffff, #2a2a2c);
    --button: light-dark(#efeff3, #232325);
    --button-hover: light-dark(#e6e6ec, #2c2c2f);
    --primary: light-dark(#17171c, #f4f4f5);
    --primary-ink: light-dark(#ffffff, #111112);
    --red: light-dark(#dd4b37, #f2725c);
    --red-ink: light-dark(#c53a27, #f47a63);
    --gap-bg: light-dark(#e6f7ef, #0f2a20);
    --gap-edge: light-dark(#8fd7b5, #2b9d6e);
    --gap-ink: light-dark(#137f4e, #4fe0a2);
    --tip: light-dark(#1b1b20, #232326);
    --tip-ink: light-dark(#f2f2f4, #f2f2f4);
    --tip-ink-2: light-dark(#a4a4ad, #9b9ba2);
    --menu: light-dark(#ffffff, #1b1b1d);
    --shadow: light-dark(rgb(30 30 60 / 0.1), rgb(0 0 0 / 0.55));
    --blue: light-dark(#4568e6, #6f8dff);
    --amber: light-dark(#be840a, #f6c04e);
    --pink: light-dark(#d8468f, #f27abb);
    --cyan: light-dark(#199cba, #3fcbe6);
    --violet: light-dark(#7a62ef, #9c8bff);
    --grey: light-dark(#8a8a93, #8b8b90);
    --green: light-dark(#1f9e66, #3fdc98);
    --orange: light-dark(#db7328, #f59a52);
    --focus: light-dark(#7786f5, #7c8cff);
  }
}
.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 {
  position: relative;
  container-type: inline-size;
  width: 100%;
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background:
    radial-gradient(42% 30% at 18% 6%, var(--wash-1), transparent 70%),
    radial-gradient(38% 34% at 92% 52%, var(--wash-2), transparent 70%),
    radial-gradient(46% 30% at 8% 96%, var(--wash-3), transparent 70%),
    radial-gradient(30% 22% at 70% 100%, var(--wash-1), transparent 70%), var(--stage);
  color: var(--ink);
  font-family: var(--sans);
  font-size: 13px;
  line-height: 1.35;
  -webkit-tap-highlight-color: transparent;
}
/* Low specificity, so every part's own colour wins. */
:where(.root) :where(button, input) {
  font: inherit;
  color: inherit;
}
:where(.root) button {
  cursor: pointer;
}
.root :focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}
.root svg {
  flex: none;
  display: block;
}
.srOnly {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

/* The tones: whatever carries one hands it to its parts as --tone. */
.root [data-tone='blue'] {
  --tone: var(--blue);
}
.root [data-tone='amber'] {
  --tone: var(--amber);
}
.root [data-tone='pink'] {
  --tone: var(--pink);
}
.root [data-tone='cyan'] {
  --tone: var(--cyan);
}
.root [data-tone='violet'] {
  --tone: var(--violet);
}
.root [data-tone='grey'] {
  --tone: var(--grey);
}
.root [data-tone='green'] {
  --tone: var(--green);
}
.root [data-tone='orange'] {
  --tone: var(--orange);
}

/* ---- Cards ------------------------------------------------------------------------------------ */

.cards {
  display: grid;
  gap: 14px;
  max-width: 656px;
  margin: 0 auto;
  padding: 56px 28px;
}
.card {
  display: grid;
  gap: 0;
  padding: 0 8px 8px;
  border: 1px solid var(--card-edge);
  border-radius: 22px;
  background: var(--card);
  box-shadow:
    0 1px 0 rgb(255 255 255 / 0.04) inset,
    0 24px 60px -24px var(--shadow);
}
.head {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 8px 14px;
}
.tile {
  display: grid;
  place-items: center;
  flex: none;
  width: 34px;
  height: 34px;
  border-radius: 10px;
  background: color-mix(in oklab, var(--tone) 16%, var(--card));
  color: var(--tone);
}
.tileIcon {
  width: 18px;
  height: 18px;
}
.headText {
  display: grid;
  flex: 1;
  min-width: 0;
  gap: 2px;
}
.title {
  margin: 0;
  font-size: 16.5px;
  font-weight: 600;
  letter-spacing: -0.01em;
  line-height: 1.2;
}
.subtitle {
  color: var(--ink-2);
  font-size: 12.5px;
  font-variant-numeric: tabular-nums;
}
.panel {
  position: relative;
  padding: 16px 16px 14px;
  border: 1px solid var(--panel-edge);
  border-radius: 16px;
  background: var(--panel);
}

/* Month / Quarter. */
.segmented {
  display: flex;
  flex: none;
  padding: 3px;
  border: 1px solid var(--panel-edge);
  border-radius: 11px;
  background: var(--segment);
}
.segment {
  height: 26px;
  padding: 0 12px;
  border: 0;
  border-radius: 8px;
  background: none;
  color: var(--ink-2);
  font-size: 13px;
  font-weight: 500;
  transition:
    background 0.2s ease,
    color 0.2s ease;
}
.segment:hover,
.segment[data-over] {
  color: var(--ink);
}
.segment[aria-checked='true'] {
  background: var(--segment-on);
  color: var(--ink);
  box-shadow:
    0 0 0 1px var(--guide),
    0 1px 2px rgb(0 0 0 / 0.12);
}

/* ---- The legend ------------------------------------------------------------------------------- */

.legend {
  display: flex;
  flex-wrap: wrap;
  gap: 6px 18px;
  margin: 0 0 14px;
  padding: 0;
  color: var(--ink-2);
  font-size: 12.5px;
  list-style: none;
}
.legend li {
  display: flex;
  align-items: center;
  gap: 7px;
}
.keySpent,
.keyForecast,
.keyOver {
  width: 14px;
  height: 7px;
  border-radius: 4px;
}
.keySpent {
  background: var(--ink);
}
.keyForecast {
  background: var(--ink-3);
}
.keyOver {
  background: repeating-linear-gradient(-60deg, var(--red) 0 1.6px, transparent 1.6px 3.6px);
  border-radius: 1px;
}

/* ---- The pacing chart ------------------------------------------------------------------------- */

.plot {
  position: relative;
}
.guides {
  position: absolute;
  left: calc(var(--name-w) + var(--col-gap));
  right: calc(var(--share-w) + var(--col-gap));
  top: -4px;
  height: calc(var(--rows) * var(--pitch) + 8px);
  pointer-events: none;
}
.zone {
  position: absolute;
  inset: 0 0 0 66.667%;
  background: var(--zone);
}
.budgetLine {
  position: absolute;
  top: 0;
  bottom: -4px;
  left: 66.667%;
  width: 1px;
  background: var(--guide);
}
.todayLine {
  position: absolute;
  top: 0;
  bottom: -4px;
  width: 0;
  border-left: 1px dotted var(--ink-3);
  transition: left 0.45s cubic-bezier(0.3, 0.7, 0.2, 1);
}
.rows {
  position: relative;
  display: grid;
  margin: 0;
  padding: 0;
  list-style: none;
}
.row {
  position: relative;
  display: grid;
  grid-template-columns: var(--name-w) minmax(0, 1fr) var(--share-w);
  align-items: center;
  column-gap: var(--col-gap);
  width: 100%;
  height: var(--pitch);
  padding: 0;
  border: 0;
  background: none;
  text-align: left;
}
.row::before {
  position: absolute;
  inset: 2px -8px;
  border-radius: 9px;
  background: var(--hover);
  opacity: 0;
  content: '';
  transition: opacity 0.15s ease;
}
.row[data-hover]::before {
  opacity: 1;
}
.row:focus-visible {
  outline-offset: 0;
  border-radius: 6px;
}
.who {
  position: relative;
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
}
.avatar {
  display: grid;
  flex: none;
  place-items: center;
  width: 21px;
  height: 21px;
  border-radius: 50%;
  background: color-mix(in oklab, var(--tone) 20%, var(--panel));
  color: var(--tone);
  font-size: 10.5px;
  font-weight: 600;
}
.teamName {
  overflow: hidden;
  font-size: 14.5px;
  font-weight: 500;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.track {
  position: relative;
  height: 5px;
  border-radius: 3px;
  background: var(--track);
}
.forecastBar,
.overBar,
.spentBar,
.dot {
  position: absolute;
  top: 50%;
  translate: 0 -50%;
}
.forecastBar,
.overBar,
.spentBar {
  left: 0;
  transition:
    width 0.5s cubic-bezier(0.3, 0.7, 0.2, 1),
    left 0.5s cubic-bezier(0.3, 0.7, 0.2, 1);
}
.forecastBar {
  width: var(--within);
  height: 5px;
  border-radius: 3px;
  background: color-mix(in oklab, var(--tone) 42%, var(--track));
}
.overBar {
  left: var(--within);
  width: calc(var(--forecast) - var(--within));
  height: 6px;
  background:
    repeating-linear-gradient(-60deg, var(--red) 0 1.6px, transparent 1.6px 4px),
    color-mix(in oklab, var(--red) 22%, var(--track));
}
.spentBar {
  width: max(8px, var(--spent));
  height: 8px;
  border-radius: 4px;
  background: var(--tone);
}
.dot {
  left: var(--forecast);
  width: 9px;
  height: 9px;
  margin-left: -4.5px;
  border-radius: 50%;
  background: var(--tone);
  transition: left 0.5s cubic-bezier(0.3, 0.7, 0.2, 1);
}
.row[data-over] .dot {
  background: var(--red);
}
.share {
  position: relative;
  font-size: 14.5px;
  font-weight: 500;
  font-variant-numeric: tabular-nums;
  text-align: right;
}
.row[data-over] .share {
  color: var(--red-ink);
}
.axis {
  position: relative;
  display: block;
  height: 26px;
  margin: 6px calc(var(--share-w) + var(--col-gap)) 0 calc(var(--name-w) + var(--col-gap));
  color: var(--ink-2);
  font-size: 12px;
}
.axis span {
  position: absolute;
  top: 4px;
  translate: -50% 0;
  white-space: nowrap;
  transition: left 0.45s cubic-bezier(0.3, 0.7, 0.2, 1);
}
.axis span[data-end] {
  translate: -100% 0;
  color: var(--ink-3);
}

/* The tooltip, above its row at the pointer's x. It takes the pointer, so it can be hovered
   (WCAG 1.4.13); a strip under it bridges the gap to its row. */
.tip {
  position: absolute;
  top: calc(var(--tip-row) * var(--pitch) - 2px);
  left: clamp(96px, var(--tip-x), calc(100% - 96px));
  z-index: 3;
  display: grid;
  gap: 7px;
  min-width: 176px;
  padding: 10px 12px;
  border-radius: 11px;
  background: var(--tip);
  color: var(--tip-ink);
  box-shadow: 0 14px 30px -10px rgb(0 0 0 / 0.45);
  font-size: 12px;
  translate: -50% -100%;
  animation: tip 0.14s ease;
}
.tip::after {
  position: absolute;
  top: 100%;
  right: 0;
  left: 0;
  height: 8px;
  content: '';
}
@keyframes tip {
  from {
    opacity: 0;
    transform: translateY(3px);
  }
}
.tipHead {
  display: flex;
  align-items: center;
  gap: 7px;
  font-size: 12.5px;
  font-weight: 600;
}
.tipSwatch {
  width: 8px;
  height: 8px;
  border-radius: 2px;
  background: var(--tone);
}
.tipShare {
  margin-left: auto;
  font-variant-numeric: tabular-nums;
}
.tipShare[data-over],
.tipFoot[data-over] {
  color: #f4826d;
}
.tipGrid {
  display: grid;
  grid-template-columns: auto auto;
  gap: 3px 16px;
  color: var(--tip-ink-2);
}
.tipGrid b {
  color: var(--tip-ink);
  font-weight: 500;
  font-variant-numeric: tabular-nums;
  text-align: right;
}
.tipFoot {
  padding-top: 7px;
  border-top: 1px solid rgb(255 255 255 / 0.1);
  color: var(--tip-ink-2);
}

/* The insight under the axis. */
.insight {
  display: flex;
  align-items: flex-start;
  gap: 9px;
  margin: 6px 0 0;
  color: var(--ink-2);
  font-size: 12.5px;
  line-height: 1.45;
}
.insightIcon {
  width: 12px;
  height: 12px;
  margin-top: 3px;
  color: var(--green);
}
.insight b {
  color: var(--ink);
  font-weight: 600;
}
.insightTeam {
  /* A step towards the ink, so every tone reads as text on the panel. */
  color: color-mix(in oklab, var(--tone) 65%, var(--ink));
  font-weight: 500;
}

/* ---- Move budget ------------------------------------------------------------------------------ */

.more {
  display: grid;
  flex: none;
  place-items: center;
  width: 32px;
  height: 32px;
  border: 0;
  border-radius: 9px;
  background: none;
  color: var(--ink-2);
}
.more svg {
  width: 20px;
  height: 20px;
}
.more:hover,
.more[aria-expanded='true'],
.more[data-over] {
  background: var(--button);
  color: var(--ink);
}

.pair {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 30px minmax(0, 1fr);
  grid-template-areas:
    'from-label . to-label'
    'from swap to';
  align-items: center;
  gap: 8px 10px;
}
.fieldLabel {
  grid-area: from-label;
  color: var(--ink-2);
  font-size: 12.5px;
}
.fieldLabel[data-side='to'] {
  grid-area: to-label;
}
.pair > .select:first-of-type {
  grid-area: from;
}
.pair > .select:last-of-type {
  grid-area: to;
}
.select {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
  height: 40px;
  padding: 0 12px;
  border: 1px solid var(--field-edge);
  border-radius: 11px;
  background: var(--field);
  text-align: left;
  transition: border-color 0.15s ease;
}
.select:hover,
.select[aria-expanded='true'],
.select[data-over] {
  border-color: var(--guide);
}
.swatch {
  flex: none;
  width: 9px;
  height: 9px;
  border-radius: 2.5px;
  background: var(--tone, var(--ink-3));
}
.selectText {
  display: flex;
  flex: 1;
  align-items: baseline;
  gap: 9px;
  min-width: 0;
  overflow: hidden;
  white-space: nowrap;
}
.selectName {
  font-size: 14.5px;
  font-weight: 500;
}
.selectLeft {
  overflow: hidden;
  color: var(--ink-2);
  font-size: 12.5px;
  text-overflow: ellipsis;
}
.selectChevron {
  width: 15px;
  height: 15px;
  color: var(--ink-2);
}
.swapButton {
  grid-area: swap;
  display: grid;
  place-items: center;
  width: 30px;
  height: 30px;
  border: 0;
  border-radius: 9px;
  background: var(--button);
  transition:
    background 0.15s ease,
    rotate 0.3s ease;
}
.swapButton svg {
  width: 15px;
  height: 15px;
}
.swapButton:hover,
.swapButton[data-over] {
  background: var(--button-hover);
}

.amountRow {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 10px 12px;
  padding: 16px 0 14px;
  border-bottom: 1px solid var(--panel-edge);
}
.amount {
  width: 9ch;
  min-width: 0;
  padding: 0;
  border: 0;
  border-radius: 6px;
  outline: none;
  background: none;
  font-size: 26px;
  font-weight: 650;
  letter-spacing: -0.02em;
  font-variant-numeric: tabular-nums;
}
.amount:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 3px;
}
.amount[aria-invalid] {
  color: var(--red-ink);
}
.chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.chip {
  height: 28px;
  padding: 0 10px;
  border: 1px solid transparent;
  border-radius: 9px;
  background: var(--button);
  color: var(--ink-2);
  font-size: 12.5px;
  font-weight: 500;
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
  transition:
    background 0.15s ease,
    border-color 0.15s ease;
}
.chip:hover,
.chip[data-over] {
  background: var(--button-hover);
  color: var(--ink);
}
.chip[aria-pressed='true'] {
  border-color: var(--guide);
  color: var(--ink);
}
.chip[data-gap] {
  border-color: color-mix(in oklab, var(--gap-edge) 60%, transparent);
  background: var(--gap-bg);
  color: var(--gap-ink);
}
.chip[data-gap][aria-pressed='true'] {
  border-color: var(--gap-edge);
}

.moveRows {
  display: grid;
  margin: 0;
  padding: 8px 0 0;
  list-style: none;
}
.moveRow {
  display: grid;
  grid-template-columns: 9px minmax(70px, 1fr) minmax(0, 1.25fr) auto;
  align-items: center;
  gap: 12px;
  height: 36px;
}
.moveName {
  overflow: hidden;
  font-size: 14.5px;
  font-weight: 500;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.moveTrack {
  position: relative;
  height: 14px;
}
.moveTrack::before {
  position: absolute;
  top: 50%;
  right: 0;
  left: 0;
  height: 2px;
  border-radius: 1px;
  background: var(--track);
  content: '';
  translate: 0 -50%;
}
.moveTick {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 66.667%;
  width: 1px;
  background: var(--guide);
}
.moveSpan,
.moveRing,
.moveDot {
  position: absolute;
  top: 50%;
  translate: 0 -50%;
  transition:
    left 0.4s cubic-bezier(0.3, 0.7, 0.2, 1),
    width 0.4s cubic-bezier(0.3, 0.7, 0.2, 1);
}
.moveSpan {
  left: var(--from);
  width: calc(var(--to) - var(--from));
  height: 2px;
  background: var(--tone);
}
.moveRing,
.moveDot {
  width: 10px;
  height: 10px;
  margin-left: -5px;
  border-radius: 50%;
}
.moveRing {
  left: var(--before);
  border: 1.6px solid var(--tone);
  background: var(--panel);
}
.moveDot {
  left: var(--after);
  background: var(--tone);
}
.moveShares {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 4px;
  min-width: 112px;
  color: var(--ink-2);
  font-size: 14.5px;
  font-variant-numeric: tabular-nums;
}
.moveShares b {
  color: var(--ink);
  font-weight: 500;
}
.moveShares [data-over] {
  color: var(--red-ink);
}
.moveArrow {
  width: 13px;
  height: 13px;
  color: var(--ink-3);
}

.foot {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px 12px;
  padding: 12px 8px 4px;
}
.approver {
  display: grid;
  flex: none;
  place-items: center;
  width: 24px;
  height: 24px;
  border: 1px solid var(--field-edge);
  border-radius: 50%;
  background: var(--button);
  font-size: 11.5px;
  font-weight: 600;
}
.approver svg {
  width: 12px;
  height: 12px;
  color: var(--green);
}
.note {
  flex: 1;
  min-width: 160px;
  color: var(--ink-2);
  font-size: 13px;
}
.note b {
  color: var(--ink);
  font-weight: 600;
}
.note[data-error] {
  color: var(--red-ink);
}
.actions {
  display: flex;
  gap: 8px;
}
.secondary,
.primary {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  height: 36px;
  padding: 0 15px;
  border: 0;
  border-radius: 11px;
  font-size: 14px;
  font-weight: 550;
  white-space: nowrap;
  transition:
    background 0.15s ease,
    opacity 0.15s ease;
}
.secondary {
  background: var(--button);
}
.secondary:hover,
.secondary[data-over] {
  background: var(--button-hover);
}
.primary {
  background: var(--primary);
  color: var(--primary-ink);
}
.primary:hover,
.primary[data-over] {
  opacity: 0.9;
}
.primary[aria-disabled='true'],
.secondary[aria-disabled='true'] {
  cursor: default;
  opacity: 0.45;
}
.buttonIcon {
  width: 14px;
  height: 14px;
  color: var(--green);
}

/* ---- Layers ----------------------------------------------------------------------------------- */

.menu {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 6;
  display: grid;
  min-width: 220px;
  max-height: 320px;
  padding: 5px;
  overflow-y: auto;
  border: 1px solid var(--field-edge);
  border-radius: 12px;
  outline: none;
  background: var(--menu);
  box-shadow: 0 18px 40px -12px var(--shadow);
  animation: pop 0.16s ease;
  scrollbar-width: thin;
}
@keyframes pop {
  from {
    opacity: 0;
    transform: translateY(-4px) scale(0.98);
  }
}
.menuItem {
  display: flex;
  align-items: center;
  gap: 10px;
  min-height: 34px;
  padding: 0 10px;
  border: 0;
  border-radius: 8px;
  outline: none;
  background: none;
  font-size: 13.5px;
  text-align: left;
}
.menuItem:hover,
.menuItem:focus-visible,
.menuItem[data-over] {
  background: var(--button);
}
.menuText {
  flex: 1;
  white-space: nowrap;
}
.menuTrail {
  color: var(--ink-2);
  font-size: 12px;
  font-variant-numeric: tabular-nums;
}
.menuCheck,
.menuIcon {
  width: 15px;
  height: 15px;
}
.menuIcon {
  color: var(--ink-2);
}

.toast {
  position: absolute;
  bottom: 18px;
  left: 50%;
  z-index: 7;
  display: flex;
  align-items: center;
  gap: 10px;
  max-width: calc(100% - 32px);
  padding: 10px 14px;
  border: 1px solid var(--field-edge);
  border-radius: 12px;
  background: var(--menu);
  box-shadow: 0 16px 36px -10px var(--shadow);
  white-space: nowrap;
  translate: -50% 0;
  animation: rise 0.22s ease;
}
.toast > span {
  overflow: hidden;
  text-overflow: ellipsis;
}
.toastIcon {
  width: 15px;
  height: 15px;
  color: var(--green);
}
.toastUndo {
  position: relative;
  margin-left: 4px;
  padding: 0;
  border: 0;
  background: none;
  color: var(--ink);
  font-weight: 600;
  text-decoration: underline;
  text-decoration-color: var(--guide);
  text-underline-offset: 3px;
}
/* A hit area 24 px tall around the word (WCAG 2.5.8). */
.toastUndo::after {
  position: absolute;
  inset: -4px -6px;
  content: '';
}
@keyframes rise {
  from {
    opacity: 0;
    transform: translateY(8px);
  }
}

/* ---- Narrow stages ---------------------------------------------------------------------------- */

@container (max-width: 560px) {
  .cards {
    --name-w: 88px;
    --share-w: 42px;
    --col-gap: 9px;
    gap: 10px;
    padding: 12px 8px 64px;
  }
  .card {
    padding: 0 6px 6px;
    border-radius: 18px;
  }
  .avatar {
    display: none;
  }
  .axis span {
    font-size: 11px;
  }
  .axis span:first-child {
    translate: calc(-100% + 2px) 0;
  }
  .axis span:nth-child(2) {
    translate: -2px 0;
  }
  .axis span[data-end] {
    display: none;
  }
  .head {
    flex-wrap: wrap;
  }
  .segmented {
    order: 3;
    width: 100%;
  }
  .segment {
    flex: 1;
  }
  .teamName,
  .share,
  .moveName,
  .moveShares {
    font-size: 13.5px;
  }
  .panel {
    padding: 14px 12px 12px;
  }
  .pair {
    grid-template-columns: minmax(0, 1fr) 30px;
    grid-template-areas:
      'from-label .'
      'from swap'
      'to-label to-label'
      'to to';
  }
  .swapButton {
    rotate: 90deg;
  }
  .amountRow {
    flex-direction: column;
    align-items: flex-start;
  }
  .moveRow {
    grid-template-columns: 9px minmax(0, 1fr) auto;
    grid-template-areas:
      'swatch name shares'
      '. track track';
    height: auto;
    gap: 2px 10px;
    padding: 6px 0;
  }
  .moveRow > .swatch {
    grid-area: swatch;
  }
  .moveName {
    grid-area: name;
  }
  .moveTrack {
    grid-area: track;
  }
  .moveShares {
    grid-area: shares;
    min-width: 0;
  }
  .actions {
    flex: 1 1 100%;
  }
  .actions > * {
    flex: 1;
  }
}

/* ---- The demo's pointer ----------------------------------------------------------------------- */

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

@media (prefers-reduced-motion: reduce) {
  .segment,
  .chip,
  .select,
  .swapButton,
  .forecastBar,
  .overBar,
  .spentBar,
  .dot,
  .todayLine,
  .axis span,
  .moveSpan,
  .moveRing,
  .moveDot,
  .row::before {
    transition: none;
  }
  .menu,
  .toast,
  .tip {
    animation: none;
  }
}
```

### budget-pacing/data.ts

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

/*
 * The budgets and the arithmetic of pacing: what each team has, has spent and will spend at its
 * current pace, by quarter or by month, and what a move between two teams does to both.
 */

export type Tone = 'blue' | 'amber' | 'pink' | 'cyan' | 'violet' | 'grey' | 'green' | 'orange';

export type Team = {
  id: string;
  name: string;
  /** The colour of its bars and its letter. */
  tone: Tone;
  /** The quarter's budget, in dollars. */
  budget: number;
  /** Spent so far this quarter. */
  spent: number;
  /** What the quarter will have cost by its last day at the current pace. */
  forecast: number;
  /** The quarter's budget split over its three months, as shares that add up to 1. */
  phasing: [number, number, number];
  /** Spent so far this month, when the quarter is past its first month. */
  monthSpent?: number;
};

export type Period = 'month' | 'quarter';

/** A move of budget from one team to another. */
export type Move = { from: string; to: string; amount: number };

/** The quarter: Q4 2026, from October 1 to December 31. */
export const QUARTER = { name: 'Q4', start: Date.UTC(2026, 9, 1), length: 92 };

const DAY_MS = 86_400_000;
const MONTHS = ['Oct', 'Nov', 'Dec'];

/** Day `day` of the quarter as “Nov 24”. */
export const dateOf = (day: number) => {
  const date = new Date(QUARTER.start + (Math.ceil(day) - 1) * DAY_MS);
  return `${MONTHS[date.getUTCMonth() - 9] ?? ''} ${date.getUTCDate()}`;
};

/** Where `day` of the quarter falls: its month (0–2), the day in it, the month's length. */
export function monthOf(day: number) {
  const date = new Date(QUARTER.start + (day - 1) * DAY_MS);
  const index = Math.min(2, Math.max(0, date.getUTCMonth() - 9));
  const length = new Date(Date.UTC(2026, 10 + index, 0)).getUTCDate();
  const first = Math.round((Date.UTC(2026, 9 + index, 1) - QUARTER.start) / DAY_MS) + 1;
  return { index, day: date.getUTCDate(), length, first };
}

/** A team in one period: the numbers the bars are drawn from. */
export type Pace = {
  team: Team;
  budget: number;
  spent: number;
  forecast: number;
  /** Forecast over budget, as a share (1.42 is 142%). */
  share: number;
  /** Budget left after the forecast: negative when over. */
  spare: number;
  /** The day of the quarter the budget runs out at this pace, when it does before the end. */
  runsOut: number | null;
};

/** Every team's pace in `period` on `day` of the quarter, after `moves`. */
export function paceOf(teams: Team[], day: number, period: Period, moves: Move[]): Pace[] {
  const month = monthOf(day);
  return teams.map((team) => {
    const moved = moves.reduce(
      (sum, move) =>
        sum + (move.to === team.id ? move.amount : 0) - (move.from === team.id ? move.amount : 0),
      0,
    );
    let budget: number;
    let spent: number;
    let forecast: number;
    let left: number;
    if (period === 'quarter') {
      budget = team.budget + moved;
      spent = team.spent;
      forecast = team.forecast;
      left = QUARTER.length - day;
    } else {
      budget = team.budget * team.phasing[month.index] + moved;
      spent = team.monthSpent ?? team.spent;
      forecast = (spent * month.length) / month.day;
      left = month.length - month.day;
    }
    // The pace from here on: what is still to spend, over the days still to go.
    const rate = left > 0 ? (forecast - spent) / left : 0;
    const out = rate > 0 ? (budget - spent) / rate : Infinity;
    const lastDay = period === 'quarter' ? QUARTER.length : month.first + month.length - 1;
    const runsOutOn = day + Math.max(0, out);
    return {
      team,
      budget,
      spent,
      forecast,
      share: budget > 0 ? forecast / budget : 0,
      spare: budget - forecast,
      runsOut: forecast > budget && runsOutOn <= lastDay ? runsOutOn : null,
    };
  });
}

/** What a period is called in the subtitle and the legend. */
export function periodLabels(day: number, period: Period) {
  const month = monthOf(day);
  return period === 'quarter'
    ? { day, length: QUARTER.length, end: dateOf(QUARTER.length) }
    : { day: month.day, length: month.length, end: dateOf(month.first + month.length - 1) };
}

/**
 * The move worth suggesting: to the team furthest over its budget, from the one with the most to
 * spare. Null when nobody is over, or nobody has room.
 */
export function suggest(paces: Pace[]) {
  const over = [...paces]
    .filter((p) => Math.round(p.share * 100) > 100)
    .sort((a, b) => b.share - a.share)[0];
  const room = [...paces].filter((p) => p.spare > 0).sort((a, b) => b.spare - a.spare)[0];
  if (!over || !room || over.team.id === room.team.id) return null;
  return { from: room.team.id, to: over.team.id };
}

/** What fills the gap: To's overrun, to the $1k, no more than From has to spare. */
export function gapOf(from: Pace | undefined, to: Pace | undefined) {
  if (!from || !to || to.spare >= 0) return 0;
  const gap = Math.round(-to.spare / 1000) * 1000;
  return Math.max(0, Math.min(gap, Math.floor(Math.max(0, from.spare) / 1000) * 1000));
}

/** $412k, $1.2M, $18k; `fine` keeps a decimal under $100k ($11.3k). */
export function money(value: number, fine = false) {
  const sign = value < 0 ? '−' : '';
  const v = Math.abs(value);
  if (v >= 1_000_000) return `${sign}$${trim(v / 1_000_000, v >= 10_000_000 ? 0 : 1)}M`;
  if (v >= 1000) return `${sign}$${trim(v / 1000, fine && v < 100_000 ? 1 : 0)}k`;
  return `${sign}$${Math.round(v)}`;
}
const trim = (value: number, digits: number) => String(Number(value.toFixed(digits)));

/** $18,000 */
export const dollars = (value: number) => `$${Math.round(value).toLocaleString('en-US')}`;

export const percent = (share: number) => `${Math.round(share * 100)}%`;

/** The six teams of a 120-person company, on day 17 of the quarter. */
export const TEAMS: Team[] = [
  {
    id: 'engineering',
    name: 'Engineering',
    tone: 'blue',
    budget: 490_000,
    spent: 86_920,
    forecast: 470_400,
    phasing: [0.33, 0.34, 0.33],
  },
  {
    id: 'sales',
    name: 'Sales',
    tone: 'amber',
    budget: 300_000,
    spent: 65_410,
    forecast: 354_000,
    phasing: [0.3, 0.32, 0.38],
  },
  {
    id: 'marketing',
    name: 'Marketing',
    tone: 'pink',
    budget: 43_000,
    spent: 11_280,
    forecast: 61_060,
    phasing: [0.45, 0.3, 0.25],
  },
  {
    id: 'operations',
    name: 'Operations',
    tone: 'cyan',
    budget: 160_000,
    spent: 24_830,
    forecast: 134_400,
    phasing: [0.34, 0.33, 0.33],
  },
  {
    id: 'design',
    name: 'Design',
    tone: 'violet',
    budget: 114_000,
    spent: 21_910,
    forecast: 118_560,
    phasing: [0.4, 0.32, 0.28],
  },
  {
    id: 'ga',
    name: 'G&A',
    tone: 'grey',
    budget: 93_000,
    spent: 12_200,
    forecast: 66_030,
    phasing: [0.3, 0.35, 0.35],
  },
];

/** The same company in a calm quarter: every team inside its budget. */
export const ON_PACE: Team[] = TEAMS.map((team) => {
  const share: Record<string, number> = {
    engineering: 0.93,
    sales: 0.97,
    marketing: 0.88,
    operations: 0.82,
    design: 0.95,
    ga: 0.74,
  };
  const forecast = Math.round(team.budget * share[team.id]);
  return {
    ...team,
    forecast,
    spent: Math.round((forecast * 17) / 92),
    phasing: [1 / 3, 1 / 3, 1 / 3],
  };
});

/** A small studio where one team runs a little over: a move under the approval limit fixes it. */
export const STUDIO: Team[] = [
  {
    id: 'product',
    name: 'Product',
    tone: 'blue',
    budget: 96_000,
    spent: 19_800,
    forecast: 104_700,
    phasing: [0.34, 0.33, 0.33],
  },
  {
    id: 'content',
    name: 'Content',
    tone: 'orange',
    budget: 38_000,
    spent: 5_340,
    forecast: 28_900,
    phasing: [0.33, 0.33, 0.34],
  },
  {
    id: 'research',
    name: 'Research',
    tone: 'green',
    budget: 52_000,
    spent: 9_400,
    forecast: 49_900,
    phasing: [0.3, 0.35, 0.35],
  },
  {
    id: 'brand',
    name: 'Brand',
    tone: 'violet',
    budget: 34_000,
    spent: 5_200,
    forecast: 27_800,
    phasing: [0.33, 0.33, 0.34],
  },
];
```

### budget-pacing/menu.tsx

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

'use client';

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type ReactNode,
} from 'react';
import { Icon } from './glyphs';
import styles from './budget-pacing.module.css';

/*
 * The menus: placed on the stage under their trigger (over it when there is no room below), in
 * the stage's own px, since a gallery card may scale the whole stage. The arrows, Home and End
 * move between items; Escape closes and gives the focus back; a press elsewhere closes.
 */

const ITEMS = '[role="menuitem"], [role="menuitemradio"]';

export function Menu({
  anchor,
  label,
  align = 'start',
  takeFocus,
  onClose,
  children,
}: {
  anchor: HTMLElement;
  label: string;
  align?: 'start' | 'end';
  /** Moves the focus to the checked or first item: when the reader opened it, not the demo. */
  takeFocus: boolean;
  /** `back`: give the focus back to the trigger. */
  onClose: (back: boolean) => void;
  children: ReactNode;
}) {
  const box = useRef<HTMLDivElement>(null);
  const [at, setAt] = useState<{ x: number; y: number } | null>(null);

  useLayoutEffect(() => {
    const menu = box.current;
    const frame = menu?.offsetParent as HTMLElement | null;
    if (!frame || !menu) return;
    const place = () => {
      const s = frame.getBoundingClientRect();
      const scale = s.width / frame.offsetWidth || 1;
      const a = anchor.getBoundingClientRect();
      const left = (a.left - s.left) / scale;
      const right = (a.right - s.left) / scale;
      const top = (a.top - s.top) / scale;
      const bottom = (a.bottom - s.top) / scale;
      const w = menu.offsetWidth;
      const h = menu.offsetHeight;
      let x = align === 'end' ? right - w : left;
      x = Math.max(8, Math.min(x, frame.clientWidth - w - 8));
      let y = bottom + 6;
      if (y + h > frame.clientHeight - 8 && top - h - 6 > 8) y = top - h - 6;
      setAt({ x, y });
    };
    place();
    const observer = new ResizeObserver(place);
    observer.observe(menu);
    return () => observer.disconnect();
  }, [anchor, align]);

  useEffect(() => {
    if (!takeFocus || !at) return;
    box.current
      ?.querySelector<HTMLElement>('[aria-checked="true"], [role^="menuitem"]')
      ?.focus({ preventScroll: true });
    // Only when it first shows.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [takeFocus, at === null]);

  useEffect(() => {
    const away = (event: PointerEvent) => {
      const target = event.target as Node;
      if (box.current?.contains(target) || anchor.contains(target)) return;
      onClose(false);
    };
    document.addEventListener('pointerdown', away);
    return () => document.removeEventListener('pointerdown', away);
  }, [anchor, onClose]);

  const onKeyDown = (event: ReactKeyboardEvent) => {
    const items = [...(box.current?.querySelectorAll<HTMLElement>(ITEMS) ?? [])];
    const index = items.indexOf(document.activeElement as HTMLElement);
    const move = (to: number) => {
      event.preventDefault();
      items[(to + items.length) % items.length]?.focus();
    };
    if (event.key === 'ArrowDown') move(index + 1);
    else if (event.key === 'ArrowUp') move(index - 1);
    else if (event.key === 'Home') move(0);
    else if (event.key === 'End') move(items.length - 1);
    else if (event.key === 'Escape') {
      event.preventDefault();
      event.stopPropagation();
      onClose(true);
    } else if (event.key === 'Tab') onClose(false);
  };

  return (
    <div
      ref={box}
      role="menu"
      tabIndex={-1}
      aria-label={label}
      className={styles.menu}
      data-part="menu"
      style={{
        transform: at ? `translate(${at.x}px, ${at.y}px)` : undefined,
        visibility: at ? undefined : 'hidden',
      }}
      onKeyDown={onKeyDown}
    >
      {children}
    </div>
  );
}

export function MenuItem({
  onSelect,
  checked,
  radio,
  tone,
  demo,
  lead,
  trail,
  children,
}: {
  onSelect: () => void;
  checked?: boolean;
  /** One of a set: it shows a check when chosen. */
  radio?: boolean;
  tone?: 'danger';
  demo?: string;
  /** Before the text: an icon, a team's swatch. */
  lead?: ReactNode;
  /** At the right end: what is left. */
  trail?: ReactNode;
  children: ReactNode;
}) {
  return (
    <button
      type="button"
      role={radio ? 'menuitemradio' : 'menuitem'}
      aria-checked={radio ? !!checked : undefined}
      tabIndex={-1}
      className={styles.menuItem}
      data-tone={tone}
      data-demo={demo}
      onClick={onSelect}
    >
      {lead}
      <span className={styles.menuText}>{children}</span>
      {trail !== undefined && <span className={styles.menuTrail}>{trail}</span>}
      {radio && checked && <Icon name="check" className={styles.menuCheck} width={2.2} />}
    </button>
  );
}
```

### budget-pacing/glyphs.tsx

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

/* The line icons: a 24-unit box, drawn with currentColor. */

const PATHS = {
  target:
    'M12 20.5a8.5 8.5 0 1 0 0-17 8.5 8.5 0 0 0 0 17zM12 16a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM12 12.6a.6.6 0 1 0 0-1.2.6.6 0 0 0 0 1.2z',
  swap: 'M5 8.5h13.5M15 5l3.5 3.5L15 12M19 15.5H5.5M9 12l-3.5 3.5L9 19',
  chevronDown: 'M7 10l5 5 5-5',
  chevronRight: 'M10 7l5 5-5 5',
  more: 'M6 12h.01M12 12h.01M18 12h.01',
  check: 'M5 12.5l4.5 4.5L19 7.5',
  spark: 'M12 4c.6 4.2 3.8 7.4 8 8-4.2.6-7.4 3.8-8 8-.6-4.2-3.8-7.4-8-8 4.2-.6 7.4-3.8 8-8z',
  arrowRight: 'M5 12h13M13 7l5 5-5 5',
  reset: 'M4.5 12a7.5 7.5 0 1 0 2.2-5.3M4.5 4.5v4h4',
  copy: 'M8.5 8.5h11v11h-11zM15.5 8.5v-4h-11v11h4',
  send: 'M20 4 9.5 14.5M20 4l-6.5 16-4-5.5L4 10.5z',
} as const;

export type IconName = keyof typeof PATHS;

export function Icon({
  name,
  className,
  width = 1.75,
}: {
  name: IconName;
  className?: string;
  width?: number;
}) {
  return (
    <svg
      viewBox="0 0 24 24"
      className={className}
      fill={name === 'spark' ? 'currentColor' : 'none'}
      stroke="currentColor"
      strokeWidth={name === 'spark' ? 0 : width}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d={PATHS[name]} />
    </svg>
  );
}
```

### budget-pacing/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. 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 (budget-pacing.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 what it can press. It is
 * decorative: what it does shows on the cards themselves. 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>
  );
}
```

### budget-pacing/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 (WCAG 2.2.2).
 */
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, visible, reduced, playing: visible && !reduced && !taken };
}
```