# Chart studio

> A chart’s settings beside the chart they drive: type, metric, series order, colour and fill, previewed live and committed with Apply, over a stream with a forecast and anomalies.

Weekly active users split by plan, with the panel that styles them. Four chart types (Line, Bars, Stream, Dots) redraw the same weeks; the metric swaps every figure; the series reorder by dragging a grip and hide behind an eye; a swatch opens a Series colour popover with a palette of 18, a custom colour, Solid, Gradient or Hatch fill, the hex and its opacity. The chart previews the draft as it changes and Apply commits it. The card carries this week’s total, two anomalies with their reasons, a hatched three-week forecast, an overview whose window sets the weeks in view, and a table of each plan’s share. Light and dark.

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

Category: Dashboards.

## Anatomy

1. **Settings panel**: Its header says who edited the chart last; Apply signs the edit with the reader’s name. Reset and Apply sit at its foot.
2. **Chart type**: Four cards as a radio group: Line, Bars, Stream and Dots. The chosen card draws its picture in the series’ colours.
3. **Metric**: A field that opens a listbox of three metrics, each with where its numbers come from. It swaps every figure on the card.
4. **Series row**: A grip to drag or move with the arrow keys, the swatch drawn in its fill, the name, this week’s figure, and the eye.
5. **Colour popover**: Under its row: 18 colours and a custom one, the fill (Solid, Gradient, Hatch), the hex with its opacity, and a dropper.
6. **KPIs**: This week’s total with its change on four weeks ago, the anomalies with dates that open their tooltip, and the forecast with its band.
7. **Plot**: The SVG chart at the box’s own size: textured bands, a dashed Forecast divider with the weeks after it hatched, red anomaly dots.
8. **Tooltip**: A week’s total and its plans, or for an anomaly what it took or added and why. It follows the pointer and the arrow keys.
9. **Overview**: Every week as a small stacked bar, and a window whose handles set the weeks in view; drag the window to pan.
10. **Table**: The plans shown, this week’s figure, the change and the share as a bar, with All plans as its total.

## Properties

### Chart type (`defaultType`)

1. **Stream (default)**: The plans stacked around a centre line: the shape of the whole and how it splits.
2. **Bars**: A stacked bar a week, for reading each week’s total against the next.
3. **Line**: A line a plan on a scale fitted to the values, for comparing the plans’ trends.
4. **Dots**: A dot a plan a week, light enough for a small tile; the forecast becomes rings.

Open with Stream or Bars when the plans make one total and the total matters; open with Line or Dots when each plan’s own trend matters more than the sum. People can still switch it in the panel.

### Forecast (`forecast`)

1. **On (default)**: Three hatched weeks after this one behind a dashed divider, with a KPI and its band.
2. **Off**: The history only: the chart ends this week and the third KPI is the peak week.

Keep it on when the next weeks inform a decision and the forecast is one you trust. Turn it off for reporting on what happened, or when nobody owns the model behind it.

### Settings panel (`settings`)

1. **Shown (default)**: The panel beside the card: type, metric, order and colours, previewed and applied.
2. **Chart only**: The card alone, drawing what is applied, for dashboards people read.

Show the panel to the people who set the chart up, on the page where they do it. Everyone else gets the card alone.

## When to use

- A chart people tune before they share it: the type, the metric, the order of the series and each one’s colour and fill, with the result drawn as they edit.
- A few series that add up to a whole, such as plans, regions or channels, read both as a stack over time and as this week’s split in a table.
- Weekly figures with a short forecast after them and a handful of weeks that broke the pattern, each with its reason.
- A dashboard tile that may need a long range: the overview below the chart picks the weeks in view without leaving the page.

## When not to use

- Read-only reporting where nobody edits the chart. Use the card alone (`settings={false}`) or a plain chart; the panel is weight without a job.
- More than five or six series. The stream and the stacked bars stop reading; rank the largest and fold the rest into Other.
- Series that do not add up, such as a rate beside a count. Stack only parts of one total; plot rates as lines on their own chart.
- Daily or live data. The axis, the forecast and the anomalies are weekly; a live feed wants a time-series chart with zoom and streaming.
- Exact values to compare at a glance across many weeks. Use a table with the weeks as columns; the chart shows shape, the table only this week.

### Choosing a chart type

- **Stream** shows the whole and how it splits, but its centre line is free: only each band’s thickness is data, so nobody reads a value off its edges.
- **Bars** stack each week from a zero baseline, so the totals compare exactly; the parts above the bottom one compare only roughly.
- **Line** gives every plan its own line on a scale fitted to the values, so trends compare well and the total disappears.
- **Dots** draw the same points with no joins: quiet in a small tile, weak at showing a trend.

### Order and colour of the series

- **Order** runs from the top of the chart down, and the legend and the table follow it. Put the plan people ask about most where it is easiest to find, at the top or the bottom, not between two others.
- **Colour**: neighbouring plans want hues far apart. A solid fill also carries its plan’s grain (pinstripes or dots) so bands part without colour.
- **Fill**: Solid for most series, Gradient for a line that needs a soft area under it, Hatch for one series that needs to stand out.
- **Hidden** plans leave the chart, the legend, the totals and the table. The last plan shown can’t be hidden.

### Forecast and anomalies

The forecast is drawn as a different kind of thing: hatched, behind a dashed divider, with dashed edges and ring dots, so nobody reads it as data. Anomalies are for weeks with a known reason; a red dot nobody can explain only adds noise. Keep them few, and name each one in its tooltip.

### Studio vs. chart only

**Studio**
- For the person who sets the chart up.
- Edits a draft, previewed on the card; Apply commits it and calls `onApply`.
- An admin or editing page, one chart at a time.

**Chart only**
- For everyone who reads it.
- `settings={false}`: the applied look, with the tooltip, the overview and the table still live.
- A dashboard tile or a report.

## Do’s and don’ts

- **Do**: Give neighbouring plans hues far apart, so each band reads on its own and its grain backs it up.
- **Don’t**: Colour every plan from one family. Three blues side by side make the legend do all the work.
- **Do**: Let people try a look before it counts: the card draws the draft, says Preview, and nothing is saved until Apply.
- **Caution**: Hatch on a series: the forecast weeks are hatched too, so keep it to one plan and let the dashed divider say where the readings end.
- **Do**: Narrow the weeks with the overview when one stretch matters; the axis and the anomalies follow the range.
- **Don’t**: Keep the stream for a single plan. Its centre line is free, so one band sways in a way that looks like data; switch to Line.

## Content

The words on the card say what is counted, for whom and why a week stands out.

- **The metric’s title** names what is counted and over what period: `Weekly active users`, not `Users` or `WAU trend`.
- **Series names** of one or two words, the same in the panel, the legend, the tooltip and the table.
- **An anomaly’s reason** is what happened, as a short name: `Labor Day`, `Template gallery launch`. Leave a week unmarked rather than guess.
- **Numbers** short where space is tight (`7.8k`) and in full in the tooltip and the table (`18,420`), with a real minus sign on falls.
- **`editor` and `user`** are people’s names as they would sign them, since Apply puts the name in the panel’s header.

## Installation

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

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

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 { ChartStudio, type Config } from './chart-studio';

export function UsageChart() {
  const save = (config: Config) => {
    // Store the chart's look with the dashboard.
    console.log(config.type, config.order);
  };
  return (
    <ChartStudio
      defaultType="stream"
      defaultMetric="wau"
      editor="Mira Holt"
      user="Bruno Delorence"
      onApply={save}
      autoplay={false}
    />
  );
}
```

## States

- **Stream**: The default: three plans stacked around a swaying centre line, the Labor Day anomaly’s tooltip open, three weeks of forecast hatched.
- **Bars**: Stacked bars per week; the forecast weeks are hatched and outlined with a dashed edge.
- **Line**: One line a plan on a scale fitted to the values, dashed after this week. A Gradient or Hatch fill adds a soft area under its line.
- **Dots**: A dot a plan a week; the forecast dots are rings.
- **Series colour**: Growth’s popover open under its row, over the rows below it; the row stays lit while it is open.
- **Unapplied draft**: Bars, and Growth hatched, not applied yet: the chart draws the draft, the title says Preview, and Apply lights up.
- **Four plans shown**: Free shown too: 4 of 4, a fourth band, legend item and table row, and the totals grow with it.
- **Metric list**: The listbox open under the field: weekly active users, sessions and events, each with its source.
- **Week tooltip**: An ordinary week under the pointer: a dashed rule, the week’s total and each plan’s figure.
- **Narrow range**: The overview’s window from Aug 31 to the forecast: the axis and the anomalies follow the weeks in view.
- **Chart only**: With `settings={false}` the card stands alone and draws what is applied.
- **Phone**: Under 760 px of stage the panels stack, the KPIs wrap in two rows, and the table drops its share bars under 440.

## Examples

### Stacked bars

The same plans as a bar a week, stacked in their fills; the three forecast weeks are hatched and outlined with a dashed edge.

```tsx
import { ChartStudio } from './chart-studio';

/** The same plans as stacked bars, the forecast weeks hatched and outlined. */
export function StackedBars() {
  return <ChartStudio defaultType="bars" autoplay={false} />;
}
```

### Lines without forecast

One line a plan on a scale fitted to the values, the history only: the overview ends this week and the third figure becomes the peak week.

```tsx
import { ChartStudio } from './chart-studio';

/** One line a plan, with no forecast: the third figure becomes the peak week. */
export function LinesWithoutForecast() {
  return <ChartStudio defaultType="line" forecast={false} autoplay={false} />;
}
```

### Chart only

The card alone with `settings={false}`, on weekly sessions: the KPIs, the stream, the overview and the table, with no panel.

```tsx
import { ChartStudio } from './chart-studio';

/** The chart card alone, with no settings panel, on weekly sessions. */
export function ChartOnly() {
  return <ChartStudio settings={false} defaultMetric="sessions" autoplay={false} />;
}
```

### Events as dots

Weekly events from the warehouse, a dot a plan a week with rings for the forecast, in light colours whatever the page’s.

```tsx
import { ChartStudio } from './chart-studio';

/** Weekly events as dots, in light colours whatever the page's. */
export function EventsAsDots() {
  return (
    <ChartStudio defaultType="dots" defaultMetric="events" colorScheme="light" autoplay={false} />
  );
}
```

## How it works

- The settings edit a draft of one config: the chart type, the metric, the plans’ order, and each plan’s colour, opacity, fill and visibility. The card draws the draft as it changes and marks its title Preview; Apply copies the draft to the applied config, signs the header with the reader’s name and calls onApply. Reset drops the draft, or with nothing to drop restores the defaults as a draft.
- The chart is SVG drawn at its box’s size in px, read by a ResizeObserver, so the textures keep their grain at any width. The stream stacks the plans around a centre line at half their total; that line is free in a streamgraph (only the bands’ thickness is data), so it sways a little. Bars stack per week; lines and dots use a scale fitted to the values.
- Each fill is an SVG pattern made from the plan’s colour: Solid carries a fine grain (pinstripes, dots) so the bands stay apart without colour, Gradient fades to the bottom, Hatch lays dark diagonal lines. The weeks after this one are a forecast: the same shapes hatched in their colour behind a dashed divider, with dashed edges and ring dots.
- The data is seeded, so it is the same on every load: a wave per plan, scaled so four weeks ago and this week land on their figures, three weeks of forecast after it, and two anomalies (Labor Day across plans, a launch on Growth) laid on top. Their red dots sit on the top of the chart; their week’s tooltip says what they took or added.
- The tooltip follows the pointer or the arrow keys on the focused chart and is placed from the point, above it or below when there is no room. The KPI’s anomaly dates open their tooltip and pan the range to them.
- The overview draws every week as a small stacked bar. Its window’s handles set the first and last week in view (four at least); dragging the window pans it, a press outside moves it there. The axis labels the first week of each month in view.
- The series list reorders live while a grip is dragged: the row under the pointer is where it goes. The colour popover sits under its row in the panel, over it when there is no room, and the + opens the system’s colour picker; the dropper picks from the screen where the browser offers it.
- While on screen and untouched, a demo pointer switches the chart type, opens Growth’s colour, hatches it, applies, and drags the overview’s left handle. Any real input hands it over; it comes back after 9 s of quiet.

## API reference

- **defaultType** (`'line' | 'bars' | 'stream' | 'dots'`, default `'stream'`): The chart type it opens with.
- **defaultMetric** (`'wau' | 'sessions' | 'events'`, default `'wau'`): The metric it opens with: weekly active users, sessions or events.
- **forecast** (`boolean`, default `true`): Draws three weeks of forecast after this week, hatched, with its KPI and band. Without it the third KPI is the peak week.
- **settings** (`boolean`, default `true`): Shows the settings panel beside the chart; without it, the chart card alone.
- **editor** (`string`, default `'Mira Holt'`): Who last edited the chart, in the panel’s header.
- **user** (`string`, default `'Bruno Delorence'`): Who is signed in: Apply signs the edit with this name.
- **onApply** (`(config: Config) => void`): Called with the config Apply commits: type, metric, order, and each plan’s colour, opacity, fill and visibility.
- **defaultState** (`ChartStudioState`): Opens in a moment, for docs and tests: a config, an unapplied draft, an open popover or menu, a tooltip’s week, a range. It keeps 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

### Colour and texture

Colour isn’t the only thing that tells the plans apart (WCAG 1.4.1): a solid fill carries its plan’s grain, the forecast is hatched behind a dashed divider, and every figure is in the table too. Enterprise and Free share the pinstripe grain, so with all four shown, pick their colours far apart. Palette colours aren’t checked against the card: choose ones with 3:1 against it (1.4.11), which the light ones miss on a light card.

### Screen readers

- The chart is a focusable group whose label says in words what it draws: the metric, the type, the weeks in view, each plan this week, the forecast and the anomalies. The SVG itself is hidden.
- Each week’s figures, and every change, apply and copy, are said in a polite live region.
- The table has row headers and a caption, so the numbers are there without the picture (1.1.1).
- The eye is a toggle button with `aria-pressed`; the grip says its position, `2 of 4`.

### Keyboard

On the focused chart the arrow keys, Home and End walk the weeks and move the tooltip. The chart types, the fills and the palette each take one tab stop moved by the arrows; the metric list and Share menu close on Escape with the focus back on their button, as does the colour popover. A grip moves its series with the arrow keys, and the overview’s handles are sliders moved by the arrows, Page Up and Down, Home and End.

### Motion

Under reduced motion nothing fades or slides and the demo pointer never plays; the pointer is decorative and any real input stops it.

### In this build

- The chart is a focusable group whose label says in words what it draws: the metric, the type, the weeks in view, each plan this week, the forecast and the anomalies. The arrow keys, Home and End walk the weeks, and each week’s figures are read in a polite live region; the SVG itself is hidden from assistive technology.
- The chart types and the fills are radio groups and the palette a radio grid, each with one tab stop moved by the arrow keys. The metric is a listbox and Share a menu: arrows, Home and End move, Escape closes with the focus back on the button.
- The colour popover is a dialog that takes the focus to the chosen colour and gives it back to the swatch on Escape. A series moves with the arrow keys on its grip, which says its position; the eye is a toggle button and the last series shown cannot be hidden.
- The overview’s handles are sliders with the week as their value text. The table has row headers and a caption; changes, applies and copies are said in a polite live region.
- Under reduced motion nothing fades or slides and the demo never plays. The demo pointer is decorative.

## Source

### chart-studio/chart-studio.tsx

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

'use client';

import { useEffect, useEffectEvent, useId, useMemo, useRef, useState, type RefObject } from 'react';
import { Brush, MIN_SPAN, Plot, anomalyDelta, downloadSvg, shownPlans, type Tip } from './chart';
import {
  AHEAD,
  ANOMALIES,
  DEFAULT_CONFIG,
  HISTORY,
  METRIC,
  NOW,
  PLAN_NAME,
  SPREAD,
  compact,
  full,
  seriesFor,
  signed,
  signedFull,
  weekLabel,
  type ChartType,
  type Config,
  type MetricId,
  type PlanId,
  type SeriesStyle,
} from './data';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { Icon } from './glyphs';
import { SettingsPanel } from './settings';
import { useAutoplay } from './use-autoplay';
import styles from './chart-studio.module.css';

/*
 * Chart studio: a chart's settings beside the chart they drive.
 *
 * - The settings edit a draft: the chart type, the metric, the order of the plans, and each
 *   plan's colour, fill, opacity and visibility. The chart card draws the draft as it changes and
 *   marks it Preview; Apply commits it (and signs the edit), Reset drops it.
 * - The card: this week's total and its change on four weeks ago, the anomalies (their dates
 *   open their tooltip) and the forecast; the chart, its legend, an overview whose window sets the
 *   weeks in view, and a table of the plans shown with their share.
 * - While on screen and untouched, a demo pointer switches the chart type, opens Growth's colour,
 *   hatches it, applies, and drags the overview's window, in a loop. The reader's first real
 *   input stops it for good (until it mounts again).
 */

export type { ChartType, Config, Fill, MetricId, PlanId, SeriesStyle } from './data';

type StylePatch = Partial<Record<PlanId, Partial<SeriesStyle>>>;
type ConfigPatch = Partial<Omit<Config, 'styles'>> & { styles?: StylePatch };

/** A moment to open in, for the docs; it also keeps the demo off. */
export type ChartStudioState = {
  /** Applied at first (the defaults otherwise). */
  config?: ConfigPatch;
  /** Edits not applied yet, on top: the chart previews them. */
  draft?: ConfigPatch;
  /** The plan whose colour popover is open. */
  popover?: PlanId;
  menu?: 'metric' | 'share';
  /** The week whose tooltip shows (an anomaly's shows what broke); null for none. */
  tip?: number | null;
  /** The first and last week in view. */
  range?: [number, number];
};

const merge = (base: Config, patch?: ConfigPatch): Config => {
  if (!patch) return base;
  const styles = { ...base.styles };
  for (const [id, style] of Object.entries(patch.styles ?? {}) as [PlanId, SeriesStyle][])
    styles[id] = { ...styles[id], ...style };
  return { ...base, ...patch, styles };
};

const same = (a: Config, b: Config) => JSON.stringify(a) === JSON.stringify(b);

/** The first anomaly's week: its tooltip shows when the chart opens. */
const FIRST_TIP = ANOMALIES[0].index;

export function ChartStudio({
  defaultType = 'stream',
  defaultMetric = 'wau',
  forecast = true,
  settings = true,
  editor = 'Mira Holt',
  user = 'Bruno Delorence',
  onApply,
  defaultState,
  autoplay = true,
  colorScheme,
  className = '',
}: {
  /** The chart type it opens with. */
  defaultType?: ChartType;
  /** The metric it opens with. */
  defaultMetric?: MetricId;
  /** Draws three weeks of forecast after this week, with its KPI. */
  forecast?: boolean;
  /** Shows the settings panel beside the chart; without it, the chart card alone. */
  settings?: boolean;
  /** Who last edited the chart, in the panel's header. */
  editor?: string;
  /** Who is signed in: Apply signs the edit with this name. */
  user?: string;
  /** Called with the config Apply commits. */
  onApply?: (config: Config) => void;
  /** Opens locked in a moment (docs); it also keeps the demo off. */
  defaultState?: ChartStudioState;
  autoplay?: boolean;
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const uid = useId().replace(/[^a-zA-Z0-9_-]/g, '');
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>();
  const pointer = useRef<HTMLSpanElement>(null);
  const shareButton = useRef<HTMLButtonElement>(null);

  const count = forecast ? HISTORY + AHEAD : HISTORY;
  const initial = useMemo(
    () =>
      merge({ ...DEFAULT_CONFIG, type: defaultType, metric: defaultMetric }, defaultState?.config),
    // Only the first values count, as with any default.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );
  const firstRange = (): [number, number] => {
    const [a, b] = defaultState?.range ?? [3, count - 1];
    const to = Math.min(count - 1, b);
    return [Math.max(0, Math.min(a, to - MIN_SPAN + 1)), to];
  };

  const [applied, setApplied] = useState(initial);
  const [draft, setDraft] = useState(() => merge(initial, defaultState?.draft));
  const [editedBy, setEditedBy] = useState(editor);
  const [popover, setPopover] = useState<{ plan: PlanId; byReader: boolean } | null>(
    defaultState?.popover ? { plan: defaultState.popover, byReader: false } : null,
  );
  const [menu, setMenu] = useState<'metric' | 'share' | null>(defaultState?.menu ?? null);
  const [tip, setTip] = useState<Tip | null>(() => {
    const at = defaultState && 'tip' in defaultState ? defaultState.tip : FIRST_TIP;
    return at === null || at === undefined ? null : { index: at };
  });
  const [range, setRange] = useState(firstRange);
  const [focus, setFocus] = useState<PlanId | null>(null);
  const [said, setSaid] = useState({ n: 0, text: '' });
  const [copied, setCopied] = useState(false);

  // Without the panel, the chart draws what is applied (nothing else can change it).
  const config = settings ? draft : applied;
  const dirty = settings && !same(draft, applied);
  const metric = METRIC[config.metric];
  const data = seriesFor(config.metric);
  const plans = shownPlans(config);
  const last = count - 1;

  const say = (text: string) => setSaid((now) => ({ n: now.n + 1, text }));

  useEffect(() => {
    if (!copied) return;
    const timer = window.setTimeout(() => setCopied(false), 1600);
    return () => window.clearTimeout(timer);
  }, [copied]);

  // ---- Figures ----------------------------------------------------------------------------------

  const valueNow = (id: PlanId) => data[id].values[NOW];
  const valueBefore = (id: PlanId) => data[id].values[NOW - 4];
  const totalNow = plans.reduce((sum, id) => sum + valueNow(id), 0);
  const totalBefore = plans.reduce((sum, id) => sum + valueBefore(id), 0);
  const change = (now: number, before: number) => (before ? (now / before - 1) * 100 : 0);
  const totalChange = change(totalNow, totalBefore);
  const anomalies = ANOMALIES.filter((a) => anomalyDelta(a.index, plans, data) !== 0);
  const ahead = plans.reduce((sum, id) => sum + data[id].values[last], 0);
  const totals = Array.from({ length: HISTORY }, (_, i) =>
    plans.reduce((sum, id) => sum + data[id].values[i], 0),
  );
  const peak = totals.indexOf(Math.max(...totals));
  const values = Object.fromEntries(config.order.map((id) => [id, data[id].values[NOW]])) as Record<
    PlanId,
    number
  >;

  const describe = () => {
    const parts = plans.map((id) => `${PLAN_NAME[id]} ${full(valueNow(id))}`).join(', ');
    const notes = anomalies
      .map(
        (a) =>
          `${weekLabel(a.index)} ${signedFull(anomalyDelta(a.index, plans, data))} ${metric.unit} (${a.title})`,
      )
      .join('; ');
    return `${metric.title} by plan, ${config.type} chart, ${weekLabel(range[0])} to ${weekLabel(
      range[1],
    )}. This week ${full(totalNow)}: ${parts}.${
      forecast ? ` Forecast ${compact(ahead)} by ${weekLabel(last)}.` : ''
    }${notes ? ` Anomalies: ${notes}.` : ''} Arrow keys read the weeks.`;
  };

  const onTip = (next: Tip | null, byKeyboard = false) => {
    setTip(next);
    if (!byKeyboard || !next) return;
    const i = next.index;
    const a = ANOMALIES.find((x) => x.index === i);
    const delta = a ? anomalyDelta(i, plans, data) : 0;
    const sum = plans.reduce((s, id) => s + data[id].values[i], 0);
    say(
      a && delta
        ? `${weekLabel(i)}: ${signedFull(delta)} ${metric.unit}, ${a.title}, ${a.plans}`
        : `${weekLabel(i)}${i > NOW ? ', forecast' : ''}: ${full(sum)} ${metric.unit}; ${plans
            .map((id) => `${PLAN_NAME[id]} ${full(data[id].values[i])}`)
            .join(', ')}`,
    );
  };

  // ---- Actions ----------------------------------------------------------------------------------

  const apply = () => {
    setApplied(draft);
    setEditedBy(user);
    setPopover(null);
    setMenu(null);
    onApply?.(draft);
    say('Changes applied');
  };

  const reset = () => {
    setPopover(null);
    if (dirty) {
      setDraft(applied);
      say('Changes discarded');
    } else {
      setDraft(initial);
      say(same(initial, applied) ? 'Already at the defaults' : 'Defaults restored, not applied');
    }
  };

  const tsv = () =>
    [
      ['Plan', metric.short, 'Change', 'Share'].join('\t'),
      ...plans.map((id) =>
        [
          PLAN_NAME[id],
          valueNow(id),
          signed(change(valueNow(id), valueBefore(id))),
          `${Math.round((valueNow(id) / totalNow) * 100)}%`,
        ].join('\t'),
      ),
      ['All plans', totalNow, signed(totalChange), '100%'].join('\t'),
    ].join('\n');

  const copy = () => {
    const done = () => {
      setCopied(true);
      say(`Copied ${plans.length} plans as a table`);
    };
    navigator.clipboard?.writeText(tsv()).then(done, done);
  };

  const downloadCsv = () => {
    const head = ['Week', ...plans.map((id) => PLAN_NAME[id]), 'Forecast'];
    const rows = Array.from({ length: range[1] - range[0] + 1 }, (_, k) => {
      const i = range[0] + k;
      return [weekLabel(i), ...plans.map((id) => data[id].values[i]), i > NOW ? 'yes' : ''];
    });
    const blob = new Blob([[head, ...rows].map((r) => r.join(',')).join('\n')], {
      type: 'text/csv',
    });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `${metric.id}-by-plan.csv`;
    link.click();
    URL.revokeObjectURL(link.href);
    say('Saved the weeks in view as CSV');
  };

  const showAnomaly = (index: number) => {
    if (index < range[0] || index > range[1]) {
      const width = range[1] - range[0];
      const from = Math.max(0, Math.min(count - 1 - width, index - Math.floor(width / 2)));
      setRange([from, from + width]);
    }
    setTip({ index });
    const delta = anomalyDelta(index, plans, data);
    const a = ANOMALIES.find((x) => x.index === index);
    say(`${weekLabel(index)}: ${signedFull(delta)} ${metric.unit}, ${a?.title}, ${a?.plans}`);
  };

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

  const demo = autoplay && !defaultState && playing;
  const demoState = useEffectEvent(() => ({
    dirty:
      !same(draft, initial) ||
      !same(applied, initial) ||
      range[0] !== 3 ||
      range[1] !== count - 1 ||
      popover !== null,
  }));
  const demoReset = useEffectEvent(() => {
    setApplied(initial);
    setDraft(initial);
    setEditedBy(editor);
    setPopover(null);
    setMenu(null);
    setTip({ index: FIRST_TIP });
    setRange([3, count - 1]);
    setFocus(null);
  });
  const demoRange = useEffectEvent((next: [number, number]) => setRange(next));
  const demoClear = useEffectEvent(() => {
    setPopover(null);
    setMenu(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);
      };
      for (;;) {
        if (demoState().dirty) {
          demoReset();
          await wait(500);
        }
        await wait(900);
        // The same weeks, three ways.
        await press('type-bars', 760, 1500);
        await press('type-dots', 520, 1300);
        await press('type-stream', 520, 1000);
        // Growth's colour: hatched, then applied.
        await press('swatch-growth', 700, 900);
        await press('fill-hatch', 650, 1300, 0.5);
        await press('apply', 760, 1400, 0.4);
        // Narrow the weeks in view from the overview's left handle.
        const handle = find('brush-from');
        if (handle) {
          glyph('arrow');
          await glide(on(handle), 760);
          glyph('hand');
          await wait(260);
          for (let k = 4; k <= 9; k += 1) {
            demoRange([k, count - 1]);
            await wait(40);
            await glide(on(find('brush-from')), 150);
          }
          await wait(500);
          for (let k = 8; k >= 6; k -= 1) {
            demoRange([k, count - 1]);
            await wait(40);
            await glide(on(find('brush-from')), 160);
          }
        }
        glyph('arrow');
        await glide(on(stage, 0.86, 0.94), 800);
        await wait(2200);
      }
    });
    return () => {
      stop();
      if (over) delete over.dataset.over;
      demoClear();
    };
  }, [demo, root, count]);

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

  const plot = (
    <Plot
      uid={uid}
      config={config}
      data={data}
      metric={metric}
      range={range}
      forecast={forecast}
      tip={tip}
      onTip={onTip}
      focus={focus}
      label={describe()}
    />
  );

  const maxShare = Math.max(0.01, ...plans.map((id) => valueNow(id) / (totalNow || 1)));

  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.studio} data-settings={settings || undefined}>
        {settings && (
          <SettingsPanel
            draft={draft}
            values={values}
            editedBy={editedBy}
            popover={popover}
            onPopover={setPopover}
            menuOpen={menu === 'metric'}
            onMenu={(open) => setMenu(open ? 'metric' : null)}
            dirty={dirty}
            onChange={(next, text) => {
              setDraft(next);
              if (text) say(`${text}. Preview, not applied`);
            }}
            onReset={reset}
            onApply={apply}
          />
        )}

        <section className={styles.card} data-part="chart-card" aria-label={metric.title}>
          <header className={styles.panelHead} data-part="chart-head">
            <Icon name="chart" className={styles.headIcon} />
            <div className={styles.titles}>
              <h3 className={styles.panelTitle}>
                {metric.title}
                {dirty && (
                  <span className={styles.preview} data-part="preview-badge">
                    Preview
                  </span>
                )}
              </h3>
              <p className={styles.subtitle}>Split by plan · 3-week smoothing</p>
            </div>
            <button
              type="button"
              className={styles.headButton}
              aria-label={copied ? 'Copied' : 'Copy the table'}
              data-done={copied || undefined}
              onClick={copy}
            >
              <Icon name={copied ? 'check' : 'copy'} />
            </button>
            <div className={styles.menuWrap}>
              <button
                ref={shareButton}
                type="button"
                className={styles.headButton}
                aria-label="Share"
                aria-haspopup="menu"
                aria-expanded={menu === 'share'}
                onClick={() => setMenu(menu === 'share' ? null : 'share')}
              >
                <Icon name="share" />
              </button>
              {menu === 'share' && (
                <ShareMenu
                  anchor={shareButton}
                  onClose={(back) => {
                    setMenu(null);
                    if (back) shareButton.current?.focus();
                  }}
                  onSvg={() => {
                    downloadSvg(root.current, `${metric.id}-by-plan.svg`);
                    say('Saved the chart as SVG');
                  }}
                  onCsv={downloadCsv}
                />
              )}
            </div>
          </header>

          <div className={styles.cardBody}>
            <dl className={styles.kpis} data-part="kpis">
              <div className={styles.kpi}>
                <dt className={styles.srOnly}>{metric.short} this week</dt>
                <dd className={styles.kpiValue}>{full(totalNow)}</dd>
                <dd className={styles.kpiNote}>
                  {metric.short} this week{' '}
                  <span data-tone={totalChange < 0 ? 'down' : 'up'}>{signed(totalChange)}</span>
                </dd>
              </div>
              <div className={styles.kpi}>
                <dt className={styles.srOnly}>Anomalies</dt>
                <dd className={styles.kpiValue}>{anomalies.length}</dd>
                <dd className={styles.kpiNote}>
                  {anomalies.length === 1 ? 'Anomaly' : 'Anomalies'}{' '}
                  <span className={styles.anomalyDates}>
                    {anomalies.map((a, i) => (
                      <button
                        key={a.index}
                        type="button"
                        className={styles.anomalyDate}
                        aria-label={`Show the ${weekLabel(a.index)} anomaly`}
                        onClick={() => showAnomaly(a.index)}
                      >
                        {weekLabel(a.index)}
                        {i < anomalies.length - 1 ? ',' : ''}
                      </button>
                    ))}
                  </span>
                </dd>
              </div>
              <div className={styles.kpi}>
                {forecast ? (
                  <>
                    <dt className={styles.srOnly}>Forecast</dt>
                    <dd className={styles.kpiValue}>{compact(ahead)}</dd>
                    <dd className={styles.kpiNote}>
                      Forecast {weekLabel(last)}{' '}
                      <span className={styles.kpiPlain}>±{compact(ahead * SPREAD)}</span>
                    </dd>
                  </>
                ) : (
                  <>
                    <dt className={styles.srOnly}>Peak week</dt>
                    <dd className={styles.kpiValue}>{compact(totals[peak])}</dd>
                    <dd className={styles.kpiNote}>
                      Peak week <span className={styles.kpiPlain}>{weekLabel(peak)}</span>
                    </dd>
                  </>
                )}
              </div>
            </dl>

            {plot}

            <ul className={styles.legend} data-part="legend" aria-label="Legend">
              {plans.map((id) => (
                <li
                  key={id}
                  className={styles.legendItem}
                  data-dim={(focus && focus !== id) || undefined}
                  onPointerEnter={() => setFocus(id)}
                  onPointerLeave={() => setFocus(null)}
                >
                  <i style={{ background: config.styles[id].color }} />
                  {PLAN_NAME[id]}
                </li>
              ))}
              <li className={styles.legendItem} data-anomaly="">
                <i />
                Anomaly
              </li>
            </ul>

            <Brush config={config} data={data} count={count} range={range} onRange={setRange} />

            <div className={styles.tableBox}>
              <table className={styles.table} data-part="table">
                <caption className={styles.srOnly}>
                  {metric.title} this week by plan, with the change on four weeks ago
                </caption>
                <thead>
                  <tr>
                    <th scope="col">Plan</th>
                    <th scope="col" className={styles.num}>
                      {metric.short}
                    </th>
                    <th scope="col" className={styles.num}>
                      Change
                    </th>
                    <th scope="col" className={styles.shareHead}>
                      Share
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {plans.map((id) => {
                    const share = valueNow(id) / (totalNow || 1);
                    const delta = change(valueNow(id), valueBefore(id));
                    return (
                      <tr
                        key={id}
                        data-dim={(focus && focus !== id) || undefined}
                        onPointerEnter={() => setFocus(id)}
                        onPointerLeave={() => setFocus(null)}
                      >
                        <th scope="row">
                          <i style={{ background: config.styles[id].color }} />
                          {PLAN_NAME[id]}
                        </th>
                        <td className={styles.num}>{full(valueNow(id))}</td>
                        <td className={styles.num} data-tone={delta < 0 ? 'down' : 'up'}>
                          {signed(delta)}
                        </td>
                        <td className={styles.shareCell}>
                          <span className={styles.sharePct}>{Math.round(share * 100)}%</span>
                          <span className={styles.shareTrack} aria-hidden="true">
                            <span
                              className={styles.shareBar}
                              style={{
                                width: `${(share / maxShare) * 86}%`,
                                background: config.styles[id].color,
                              }}
                            />
                          </span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
                <tfoot>
                  <tr>
                    <th scope="row">All plans</th>
                    <td className={styles.num}>{full(totalNow)}</td>
                    <td className={styles.num} data-tone={totalChange < 0 ? 'down' : 'up'}>
                      {signed(totalChange)}
                    </td>
                    <td />
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </section>
      </div>

      <span className={styles.srOnly} aria-live="polite" key={said.n}>
        {said.text}
      </span>

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

function ShareMenu({
  anchor,
  onClose,
  onSvg,
  onCsv,
}: {
  anchor: RefObject<HTMLButtonElement | null>;
  onClose: (back: boolean) => void;
  onSvg: () => void;
  onCsv: () => void;
}) {
  const box = useRef<HTMLDivElement>(null);

  useEffect(() => {
    box.current?.querySelector<HTMLElement>('[role="menuitem"]')?.focus({ preventScroll: true });
  }, []);

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

  const item = (label: string, act: () => void) => (
    <button
      type="button"
      role="menuitem"
      tabIndex={-1}
      className={styles.menuItem}
      onClick={() => {
        act();
        onClose(true);
      }}
    >
      <Icon name="download" />
      {label}
    </button>
  );

  return (
    <div
      ref={box}
      role="menu"
      tabIndex={-1}
      aria-label="Share"
      className={styles.shareMenu}
      data-part="share-menu"
      onKeyDown={(event) => {
        const items = [...(box.current?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [])];
        const at = items.indexOf(document.activeElement as HTMLElement);
        const go = (i: number) => {
          event.preventDefault();
          items[(i + items.length) % items.length]?.focus();
        };
        if (event.key === 'ArrowDown') go(at + 1);
        else if (event.key === 'ArrowUp') go(at - 1);
        else if (event.key === 'Home') go(0);
        else if (event.key === 'End') go(items.length - 1);
        else if (event.key === 'Escape') {
          event.preventDefault();
          event.stopPropagation();
          onClose(true);
        } else if (event.key === 'Tab') onClose(false);
      }}
    >
      {item('Download SVG', onSvg)}
      {item('Download CSV', onCsv)}
    </div>
  );
}
```

### chart-studio/chart.tsx

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

'use client';

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type PointerEvent as ReactPointerEvent,
} from 'react';
import {
  AHEAD,
  ANOMALIES,
  NOW,
  PLANS,
  PLAN_NAME,
  SPREAD,
  compact,
  full,
  monthOf,
  signedFull,
  weekLabel,
  type Config,
  type Metric,
  type PlanId,
  type Series,
  type SeriesStyle,
} from './data';
import styles from './chart-studio.module.css';

/*
 * The chart and its overview, drawn in SVG at the box's own size in px (a ResizeObserver reads
 * it), so the textures keep their grain at any width.
 *
 * - Stream: the plans stacked around a centre line that follows half their total, the first plan
 *   on top. Bars: stacked per week. Line: one line a plan. Dots: one dot a plan a week.
 * - Each plan's fill is a pattern: its colour with a fine grain (Solid), a fade (Gradient) or
 *   dark diagonal hatching (Hatch). The weeks after this one are the forecast: the same shapes
 *   hatched in their colour behind a dashed divider, with dashed edges.
 * - The anomalies are red dots on the top of the chart; their week's tooltip says what broke.
 * - Hovering or the arrow keys pick a week; its tooltip lists the plans, placed above the point.
 */

export type Tip = { index: number };

/** The plot's inner margins, in px: room for the Forecast label above. */
const TOP = 34;
const BOTTOM = 8;
const AXIS = 26;

export const shownPlans = (config: Config) =>
  config.order.filter((id) => !config.styles[id].hidden);

export const anomalyAt = (index: number) => ANOMALIES.find((a) => a.index === index);

/** What an anomaly took or added across the plans shown. */
export function anomalyDelta(index: number, plans: PlanId[], data: Record<PlanId, Series>) {
  return plans.reduce((sum, id) => sum + (data[id].bumps[index] ?? 0), 0);
}

/** A smooth path through the points (Catmull-Rom as cubic Béziers); `join` starts with L. */
function curve(points: [number, number][], join = false) {
  if (!points.length) return '';
  const [first] = points;
  let d = `${join ? 'L' : 'M'}${first[0].toFixed(1)},${first[1].toFixed(1)}`;
  for (let i = 0; i < points.length - 1; i += 1) {
    const p0 = points[i - 1] ?? points[i];
    const p1 = points[i];
    const p2 = points[i + 1];
    const p3 = points[i + 2] ?? p2;
    const c1 = [p1[0] + (p2[0] - p0[0]) / 6, p1[1] + (p2[1] - p0[1]) / 6];
    const c2 = [p2[0] - (p3[0] - p1[0]) / 6, p2[1] - (p3[1] - p1[1]) / 6];
    d += `C${c1[0].toFixed(1)},${c1[1].toFixed(1)} ${c2[0].toFixed(1)},${c2[1].toFixed(1)} ${p2[0].toFixed(1)},${p2[1].toFixed(1)}`;
  }
  return d;
}

/** The box's size in its own px (not the scaled one a gallery card shows). */
function useSize<T extends HTMLElement>() {
  const ref = useRef<T>(null);
  const [size, setSize] = useState({ width: 0, height: 0 });
  useLayoutEffect(() => {
    const element = ref.current;
    if (!element) return;
    const read = () =>
      setSize((now) =>
        now.width === element.clientWidth && now.height === element.clientHeight
          ? now
          : { width: element.clientWidth, height: element.clientHeight },
      );
    read();
    const observer = new ResizeObserver(read);
    observer.observe(element);
    return () => observer.disconnect();
  }, []);
  return [ref, size] as const;
}

/** The patterns and gradients behind one plan's fill, and its forecast hatching. */
function PlanFills({ id, plan, style }: { id: string; plan: PlanId; style: SeriesStyle }) {
  const grain = PLANS.find((p) => p.id === plan)?.grain;
  return (
    <>
      <pattern id={`${id}-solid`} width="4" height="4" patternUnits="userSpaceOnUse">
        <rect width="4" height="4" fill={style.color} />
        {grain === 'lines' && <rect width="4" height="1" className={styles.grain} />}
        {grain === 'dots' && <circle cx="2" cy="2" r="0.75" className={styles.grain} />}
      </pattern>
      <linearGradient id={`${id}-gradient`} x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stopColor={style.color} />
        <stop offset="1" stopColor={style.color} stopOpacity="0.28" />
      </linearGradient>
      <pattern
        id={`${id}-hatch`}
        width="5"
        height="5"
        patternUnits="userSpaceOnUse"
        patternTransform="rotate(45)"
      >
        <rect width="5" height="5" fill={style.color} />
        <rect width="1.3" height="5" className={styles.grain} />
      </pattern>
      <pattern
        id={`${id}-ahead`}
        width="6"
        height="6"
        patternUnits="userSpaceOnUse"
        patternTransform="rotate(45)"
      >
        <rect width="6" height="6" fill={style.color} opacity="0.1" />
        <rect width="1.4" height="6" fill={style.color} opacity="0.85" />
      </pattern>
    </>
  );
}

export function Plot({
  uid,
  config,
  data,
  metric,
  range,
  forecast,
  tip,
  onTip,
  focus,
  label,
}: {
  uid: string;
  config: Config;
  data: Record<PlanId, Series>;
  metric: Metric;
  /** The first and last week in view, by index. */
  range: [number, number];
  forecast: boolean;
  tip: Tip | null;
  onTip: (tip: Tip | null, byKeyboard?: boolean) => void;
  /** A plan to bring forward (the legend or the table is hovered). */
  focus: PlanId | null;
  label: string;
}) {
  const [box, { width: W, height: boxH }] = useSize<HTMLDivElement>();
  const tipBox = useRef<HTMLDivElement>(null);
  const [tipSize, setTipSize] = useState({ w: 0, h: 0 });
  const H = Math.max(0, boxH - AXIS);
  const plans = shownPlans(config);
  const shownKey = plans.join();
  const type = config.type;
  const [lo, hiRaw] = range;
  const hi = forecast ? hiRaw : Math.min(hiRaw, NOW);
  const span = Math.max(1, hi - lo);
  const slotted = type === 'bars' || type === 'dots';
  const step = W / (hi - lo + 1);
  const x = (i: number) =>
    slotted ? step * (i - lo + 0.5) : 2 + ((i - lo) / span) * Math.max(0, W - 4);
  const indices = Array.from({ length: hi - lo + 1 }, (_, k) => lo + k);
  const value = (id: PlanId, i: number) => data[id].values[i];
  const total = (i: number) => plans.reduce((sum, id) => sum + value(id, i), 0);

  // ---- Scales -----------------------------------------------------------------------------------

  const maxTotal = Math.max(1, ...indices.map(total));
  const sway = maxTotal * 0.09;
  const all = plans.flatMap((id) => indices.map((i) => value(id, i)));
  const minValue = all.length ? Math.min(...all) : 0;
  const maxValue = all.length ? Math.max(...all) : 1;
  const plotH = Math.max(1, H - TOP - BOTTOM);
  /** Stream: centred on the middle; bars: from the bottom; line and dots: fitted to the values. */
  const y = (v: number) => {
    if (type === 'stream') return TOP + plotH * 0.56 - (v / (maxTotal * 1.3)) * plotH;
    if (type === 'bars') return TOP + plotH - (v / (maxTotal * 1.04)) * plotH;
    const low = minValue * 0.86;
    const high = maxValue * 1.04;
    return TOP + plotH - ((v - low) / Math.max(1, high - low)) * plotH;
  };
  /** Where a plan's band starts and ends in a week, in values (stream and bars). */
  const band = (id: PlanId, i: number) => {
    const k = plans.indexOf(id);
    const below = plans.slice(k + 1).reduce((sum, p) => sum + value(p, i), 0);
    // A stream's centre line is free (only the bands' thickness is data): it sways a little.
    const base = type === 'stream' ? -total(i) / 2 + sway * Math.sin(i * 0.42 + 0.6) : 0;
    return { from: base + below, to: base + below + value(id, i) };
  };
  /** The top of the chart in a week, where its anomaly dot sits. */
  const topAt = (i: number) => {
    if (!plans.length) return y(0);
    if (type === 'stream' || type === 'bars') return y(band(plans[0], i).to);
    return Math.min(...plans.map((id) => y(value(id, i))));
  };

  const xNow = x(NOW);
  const ahead = forecast && hi > NOW;
  const fill = (id: PlanId) => `url(#${uid}-${id}-${config.styles[id].fill})`;
  const dim = (id: PlanId) => (focus && focus !== id ? 0.28 : 1);

  // ---- The tooltip ------------------------------------------------------------------------------

  const tipIndex = tip && tip.index >= lo && tip.index <= hi ? tip.index : null;
  const anomaly = tipIndex !== null ? anomalyAt(tipIndex) : undefined;
  const delta = anomaly ? anomalyDelta(anomaly.index, plans, data) : 0;
  const showAnomaly = !!anomaly && delta !== 0;

  useLayoutEffect(() => {
    const element = tipBox.current;
    if (!element) return;
    setTipSize((now) =>
      now.w === element.offsetWidth && now.h === element.offsetHeight
        ? now
        : { w: element.offsetWidth, h: element.offsetHeight },
    );
    // The tooltip's words change with the week, the anomaly and the plans shown.
  }, [tipIndex, showAnomaly, shownKey, metric.id, W]);

  const pick = (event: ReactPointerEvent<HTMLDivElement>) => {
    const frame = event.currentTarget.getBoundingClientRect();
    const scale = frame.width / event.currentTarget.offsetWidth || 1;
    const px = (event.clientX - frame.left) / scale;
    let best = lo;
    for (const i of indices) if (Math.abs(x(i) - px) < Math.abs(x(best) - px)) best = i;
    if (tip?.index !== best) onTip({ index: best });
  };

  const onKeyDown = (event: ReactKeyboardEvent) => {
    const at = tipIndex ?? Math.min(NOW, hi);
    const go = (i: number) => {
      event.preventDefault();
      onTip({ index: Math.max(lo, Math.min(hi, i)) }, true);
    };
    if (event.key === 'ArrowRight') go(at + 1);
    else if (event.key === 'ArrowLeft') go(at - 1);
    else if (event.key === 'Home') go(lo);
    else if (event.key === 'End') go(hi);
    else if (event.key === 'Escape' && tip) {
      event.preventDefault();
      onTip(null, true);
    }
  };

  let tipLeft = 0;
  let tipTop = 0;
  let tipBelow = false;
  if (tipIndex !== null) {
    const px = x(tipIndex);
    const py = topAt(tipIndex);
    tipLeft = Math.max(0, Math.min(W - tipSize.w, px - tipSize.w / 2));
    tipTop = py - tipSize.h - 16;
    if (tipTop < -2) {
      tipTop = py + 16;
      tipBelow = true;
    }
  }

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

  const historyEnd = Math.min(hi, NOW);
  const histIdx = indices.filter((i) => i <= historyEnd);
  const aheadIdx = indices.filter((i) => i >= NOW);
  const stacked = (id: PlanId, list: number[]) => {
    const upper = list.map((i) => [x(i), y(band(id, i).to)] as [number, number]);
    const lower = list.map((i) => [x(i), y(band(id, i).from)] as [number, number]).reverse();
    return { area: `${curve(upper)}${curve(lower, true)}Z`, edge: curve(upper) };
  };
  const lineOf = (id: PlanId, list: number[]) =>
    curve(list.map((i) => [x(i), y(value(id, i))] as [number, number]));
  const areaUnder = (id: PlanId, list: number[]) =>
    `${lineOf(id, list)}L${x(list[list.length - 1]).toFixed(1)},${TOP + plotH}L${x(list[0]).toFixed(1)},${TOP + plotH}Z`;
  const reversed = [...plans].reverse();

  const body = () => {
    if (!W || !H || !plans.length) return null;
    if (type === 'stream')
      return reversed.map((id) => {
        const past = histIdx.length > 1 ? stacked(id, histIdx) : null;
        const next = ahead && aheadIdx.length > 1 ? stacked(id, aheadIdx) : null;
        return (
          <g
            key={id}
            className={styles.layer}
            opacity={(config.styles[id].opacity / 100) * dim(id)}
          >
            {past && <path d={past.area} fill={fill(id)} />}
            {past && <path d={past.edge} className={styles.bandEdge} />}
            {next && <path d={next.area} fill={`url(#${uid}-${id}-ahead)`} />}
            {next && (
              <path
                d={next.edge}
                fill="none"
                stroke={config.styles[id].color}
                strokeWidth="1.4"
                strokeDasharray="3 3"
              />
            )}
          </g>
        );
      });
    if (type === 'bars') {
      const w = Math.min(26, step * 0.62);
      return reversed.map((id) => (
        <g key={id} className={styles.layer} opacity={(config.styles[id].opacity / 100) * dim(id)}>
          {indices.map((i) => {
            const { from, to } = band(id, i);
            const top = y(to);
            const h = Math.max(0, y(from) - top - 1.5);
            const future = i > NOW;
            return (
              <rect
                key={i}
                x={x(i) - w / 2}
                y={top}
                width={w}
                height={h}
                rx={Math.min(3, w / 4)}
                fill={future ? `url(#${uid}-${id}-ahead)` : fill(id)}
                stroke={future ? config.styles[id].color : undefined}
                strokeDasharray={future ? '2.5 2.5' : undefined}
                strokeWidth={future ? 1 : undefined}
              />
            );
          })}
        </g>
      ));
    }
    if (type === 'line')
      return reversed.map((id) => {
        const style = config.styles[id];
        return (
          <g key={id} className={styles.layer} opacity={(style.opacity / 100) * dim(id)}>
            {style.fill !== 'solid' && histIdx.length > 1 && (
              <path
                d={areaUnder(id, histIdx)}
                fill={fill(id)}
                opacity={style.fill === 'hatch' ? 0.32 : 0.22}
              />
            )}
            {histIdx.length > 1 && (
              <path d={lineOf(id, histIdx)} fill="none" stroke={style.color} strokeWidth="2.2" />
            )}
            {ahead && aheadIdx.length > 1 && (
              <path
                d={lineOf(id, aheadIdx)}
                fill="none"
                stroke={style.color}
                strokeWidth="2"
                strokeDasharray="4 4"
              />
            )}
          </g>
        );
      });
    return reversed.map((id) => {
      const style = config.styles[id];
      return (
        <g key={id} className={styles.layer} opacity={(style.opacity / 100) * dim(id)}>
          {indices.map((i) =>
            i > NOW ? (
              <circle
                key={i}
                cx={x(i)}
                cy={y(value(id, i))}
                r="3.2"
                fill="none"
                stroke={style.color}
                strokeWidth="1.5"
              />
            ) : (
              <circle key={i} cx={x(i)} cy={y(value(id, i))} r="3.6" fill={style.color} />
            ),
          )}
        </g>
      );
    });
  };

  // The month labels: under the first week of each month in view, if there is room.
  const ticks: { i: number; at: number }[] = [];
  for (const i of indices) {
    if (i !== lo && monthOf(i) === monthOf(i - 1)) continue;
    const at = i === lo ? Math.max(x(i), 0) : x(i);
    const last = ticks[ticks.length - 1];
    if (last && at - last.at < 40) continue;
    ticks.push({ i, at });
  }

  const tipTotal = tipIndex !== null ? total(tipIndex) : 0;

  return (
    <div
      ref={box}
      className={styles.plot}
      data-part="plot"
      tabIndex={0}
      role="group"
      aria-roledescription="chart"
      aria-label={label}
      onPointerMove={(event) => {
        if (event.pointerType === 'touch') return;
        pick(event);
      }}
      onPointerDown={pick}
      onPointerLeave={(event) => {
        if (event.pointerType !== 'touch') onTip(null);
      }}
      onKeyDown={onKeyDown}
      onBlur={() => onTip(null)}
    >
      {W > 0 && H > 0 && (
        <svg
          width={W}
          height={boxH}
          style={{ width: W, height: boxH }}
          className={styles.plotSvg}
          aria-hidden="true"
        >
          <defs>
            {plans.map((id) => (
              <PlanFills key={id} id={`${uid}-${id}`} plan={id} style={config.styles[id]} />
            ))}
          </defs>
          {ahead && (
            <g className={styles.divider}>
              <line x1={xNow} x2={xNow} y1={TOP - 12} y2={TOP + plotH + 2} />
              <text
                x={W - xNow > 90 ? (xNow + W) / 2 : W}
                y={TOP - 18}
                textAnchor={W - xNow > 90 ? 'middle' : 'end'}
              >
                Forecast
              </text>
            </g>
          )}
          {tipIndex !== null && !showAnomaly && (
            <line
              className={styles.crosshair}
              x1={x(tipIndex)}
              x2={x(tipIndex)}
              y1={TOP - 6}
              y2={TOP + plotH}
            />
          )}
          {body()}
          {tipIndex !== null &&
            !showAnomaly &&
            (type === 'line' || type === 'dots') &&
            plans.map((id) => (
              <circle
                key={id}
                cx={x(tipIndex)}
                cy={y(value(id, tipIndex))}
                r="4.5"
                fill={config.styles[id].color}
                className={styles.hoverDot}
              />
            ))}
          {ANOMALIES.map((a) => {
            if (a.index < lo || a.index > hi || !anomalyDelta(a.index, plans, data)) return null;
            const ay = topAt(a.index);
            return (
              <g key={a.index}>
                {showAnomaly && anomaly?.index === a.index && (
                  <line
                    className={styles.anomalyStem}
                    x1={x(a.index)}
                    x2={x(a.index)}
                    y1={tipBelow ? ay + 6 : ay - 16}
                    y2={tipBelow ? ay + 16 : ay - 6}
                  />
                )}
                <circle cx={x(a.index)} cy={ay} r="5" className={styles.anomalyDot} />
              </g>
            );
          })}
          <g className={styles.axis}>
            {ticks.map(({ i, at }) => (
              <text
                key={i}
                x={at}
                y={H + 18}
                textAnchor={i === lo ? 'start' : 'middle'}
                data-ahead={i > NOW || undefined}
              >
                {monthOf(i)}
              </text>
            ))}
          </g>
        </svg>
      )}
      {tipIndex !== null && (
        <div
          ref={tipBox}
          className={styles.tooltip}
          data-part="tooltip"
          style={{ transform: `translate(${tipLeft}px, ${tipTop}px)` }}
          aria-hidden="true"
        >
          {showAnomaly && anomaly ? (
            <>
              <strong>
                {weekLabel(tipIndex)} · {signedFull(delta)} {metric.unit}
              </strong>
              <span className={styles.tipNote}>
                {anomaly.title}, {anomaly.plans}
              </span>
            </>
          ) : (
            <>
              <strong>
                {weekLabel(tipIndex)} ·{' '}
                {tipIndex > NOW
                  ? `${compact(tipTotal)} ±${compact(tipTotal * SPREAD * ((tipIndex - NOW) / AHEAD))}`
                  : `${full(tipTotal)} ${metric.unit}`}
              </strong>
              {tipIndex > NOW && <span className={styles.tipNote}>Forecast</span>}
              <span className={styles.tipRows}>
                {plans.map((id) => (
                  <span key={id} className={styles.tipRow}>
                    <i style={{ background: config.styles[id].color }} />
                    {PLAN_NAME[id]}
                    <b>{full(value(id, tipIndex))}</b>
                  </span>
                ))}
              </span>
            </>
          )}
        </div>
      )}
    </div>
  );
}

// ---- The overview ---------------------------------------------------------------------------------

/** The fewest weeks the window can hold. */
export const MIN_SPAN = 4;

export function Brush({
  config,
  data,
  count,
  range,
  onRange,
}: {
  config: Config;
  data: Record<PlanId, Series>;
  /** How many weeks it covers: the history, and the forecast when it is drawn. */
  count: number;
  range: [number, number];
  onRange: (range: [number, number]) => void;
}) {
  const [box, { width: W }] = useSize<HTMLDivElement>();
  const plans = shownPlans(config);
  const [from, to] = range;
  const slot = W / count;
  const totals = Array.from({ length: count }, (_, i) =>
    plans.reduce((sum, id) => sum + data[id].values[i], 0),
  );
  const max = Math.max(1, ...totals);
  const drag = useRef<{ kind: 'from' | 'to' | 'window'; grab: number; range: [number, number] }>(
    null,
  );

  const clamp = (next: [number, number]): [number, number] => {
    let [a, b] = next;
    a = Math.max(0, Math.min(a, count - MIN_SPAN));
    b = Math.min(count - 1, Math.max(b, a + MIN_SPAN - 1));
    return [a, b];
  };

  const toSlot = (event: { clientX: number }, element: HTMLElement) => {
    const frame = element.getBoundingClientRect();
    const scale = frame.width / element.offsetWidth || 1;
    return (event.clientX - frame.left) / scale / (slot || 1);
  };

  /** A press on a handle or on the window: which one is in its data-kind. */
  const start = (event: ReactPointerEvent<HTMLElement>) => {
    const frame = event.currentTarget.parentElement;
    if (!frame) return;
    event.stopPropagation();
    event.preventDefault();
    frame.setPointerCapture(event.pointerId);
    const kind = event.currentTarget.dataset.kind as 'from' | 'to' | 'window';
    drag.current = { kind, grab: toSlot(event, frame), range };
  };

  const move = (event: ReactPointerEvent<HTMLDivElement>) => {
    const now = drag.current;
    if (!now) return;
    const at = toSlot(event, event.currentTarget);
    const [a, b] = now.range;
    if (now.kind === 'from') onRange(clamp([Math.min(Math.round(at), b - MIN_SPAN + 1), b]));
    else if (now.kind === 'to') onRange(clamp([a, Math.max(Math.round(at) - 1, a + MIN_SPAN - 1)]));
    else {
      const shift = Math.round(at - now.grab);
      const width = b - a;
      const nextFrom = Math.max(0, Math.min(count - 1 - width, a + shift));
      onRange([nextFrom, nextFrom + width]);
    }
  };

  /** A press on the track outside the window moves the window there. */
  const jump = (event: ReactPointerEvent<HTMLDivElement>) => {
    const at = Math.floor(toSlot(event, event.currentTarget));
    if (at >= from && at <= to) return;
    const width = to - from;
    const nextFrom = Math.max(0, Math.min(count - 1 - width, at - Math.floor(width / 2)));
    onRange([nextFrom, nextFrom + width]);
  };

  const keys = (kind: 'from' | 'to') => (event: ReactKeyboardEvent) => {
    const delta =
      event.key === 'ArrowLeft' || event.key === 'ArrowDown'
        ? -1
        : event.key === 'ArrowRight' || event.key === 'ArrowUp'
          ? 1
          : event.key === 'PageDown'
            ? -4
            : event.key === 'PageUp'
              ? 4
              : 0;
    let next: [number, number] | null = null;
    if (delta) next = kind === 'from' ? [from + delta, to] : [from, to + delta];
    if (event.key === 'Home') next = kind === 'from' ? [0, to] : [from, from + MIN_SPAN - 1];
    if (event.key === 'End') next = kind === 'from' ? [to - MIN_SPAN + 1, to] : [from, count - 1];
    if (!next) return;
    event.preventDefault();
    if (kind === 'from') next[0] = Math.min(next[0], to - MIN_SPAN + 1);
    else next[1] = Math.max(next[1], from + MIN_SPAN - 1);
    onRange(clamp(next));
  };

  const barW = Math.max(2, Math.min(6, slot * 0.36));
  const left = from * slot;
  const right = (to + 1) * slot;

  return (
    <div
      ref={box}
      className={styles.brush}
      data-part="brush"
      onPointerDown={jump}
      onPointerMove={move}
      onPointerUp={() => (drag.current = null)}
      onPointerCancel={() => (drag.current = null)}
    >
      {W > 0 && (
        <svg
          width={W}
          height="40"
          style={{ width: W, height: 40 }}
          className={styles.brushSvg}
          aria-hidden="true"
        >
          {totals.map((_, i) => {
            let y = 34;
            const inside = i >= from && i <= to;
            return (
              <g key={i} opacity={(inside ? 1 : 0.42) * (i > NOW ? 0.55 : 1)}>
                {[...plans].reverse().map((id) => {
                  const h = Math.max(2, (data[id].values[i] / max) * 24 - 1.5);
                  y -= h + 1.5;
                  return (
                    <rect
                      key={id}
                      x={(i + 0.5) * slot - barW / 2}
                      y={y + 1.5}
                      width={barW}
                      height={h}
                      rx={Math.min(1.5, barW / 2)}
                      fill={config.styles[id].color}
                    />
                  );
                })}
              </g>
            );
          })}
        </svg>
      )}
      <div
        className={styles.window}
        style={{ transform: `translateX(${left}px)`, width: Math.max(0, right - left) }}
        data-kind="window"
        onPointerDown={start}
        data-demo="brush-window"
      />
      <span
        role="slider"
        tabIndex={0}
        className={styles.handle}
        style={{ transform: `translateX(${left}px)` }}
        aria-label="Start of the range"
        aria-valuemin={0}
        aria-valuemax={to - MIN_SPAN + 1}
        aria-valuenow={from}
        aria-valuetext={weekLabel(from)}
        data-kind="from"
        onPointerDown={start}
        onKeyDown={keys('from')}
        data-demo="brush-from"
      />
      <span
        role="slider"
        tabIndex={0}
        className={styles.handle}
        style={{ transform: `translateX(${right}px)` }}
        aria-label="End of the range"
        aria-valuemin={from + MIN_SPAN - 1}
        aria-valuemax={count - 1}
        aria-valuenow={to}
        aria-valuetext={`${weekLabel(to)}${to > NOW ? ', forecast' : ''}`}
        data-kind="to"
        onPointerDown={start}
        onKeyDown={keys('to')}
        data-demo="brush-to"
      />
    </div>
  );
}

/** Saves the chart's picture: the plot's SVG with its colours resolved. */
export function downloadSvg(root: HTMLElement | null, name: string) {
  const svg = root?.querySelector<SVGSVGElement>('[data-part="plot"] svg');
  if (!svg) return;
  const copy = svg.cloneNode(true) as SVGSVGElement;
  copy.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  // Classes carry their colours from the stylesheet: write them on the copy.
  const source = svg.querySelectorAll<SVGElement>('*');
  copy.querySelectorAll<SVGElement>('*').forEach((element, i) => {
    const computed = getComputedStyle(source[i]);
    for (const key of ['fill', 'stroke', 'stroke-width', 'stroke-dasharray', 'opacity']) {
      if (!element.getAttribute(key)) element.setAttribute(key, computed.getPropertyValue(key));
    }
    if (element.tagName === 'text') {
      element.setAttribute('font-family', computed.fontFamily);
      element.setAttribute('font-size', computed.fontSize);
    }
    element.removeAttribute('class');
  });
  const blob = new Blob([new XMLSerializer().serializeToString(copy)], {
    type: 'image/svg+xml',
  });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = name;
  link.click();
  URL.revokeObjectURL(link.href);
}

/** Clears a timer when the component goes. */
export function useTimeout() {
  const timer = useRef(0);
  useEffect(() => () => window.clearTimeout(timer.current), []);
  return (fn: () => void, ms: number) => {
    window.clearTimeout(timer.current);
    timer.current = window.setTimeout(fn, ms);
  };
}
```

### chart-studio/settings.tsx

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

'use client';

import {
  useEffect,
  useId,
  useLayoutEffect,
  useRef,
  useState,
  type CSSProperties,
  type KeyboardEvent as ReactKeyboardEvent,
  type PointerEvent as ReactPointerEvent,
  type RefObject,
} from 'react';
import {
  METRICS,
  PALETTE,
  PLAN_NAME,
  compact,
  type ChartType,
  type Config,
  type Fill,
  type MetricId,
  type PlanId,
  type SeriesStyle,
} from './data';
import { Icon, TypeGlyph, type IconName } from './glyphs';
import styles from './chart-studio.module.css';

/*
 * The settings panel: it edits a draft of the chart's config, which the chart draws as it changes;
 * Apply commits it, Reset drops it (or, with nothing to drop, goes back to the defaults).
 *
 * - The chart type is a radio group of cards. The metric is a listbox under its field.
 * - The series list reorders by dragging a row's grip, or by the arrow keys on it; the eye hides a
 *   series (one at least stays shown); the swatch opens the Series colour popover under its row.
 * - The popover: a palette of 18 as a radio grid, a + that opens the system's colour picker, the
 *   fill, the hex with its opacity, and a dropper that picks from the screen where the browser
 *   can, or else opens the picker.
 */

const TYPES: { id: ChartType; label: string }[] = [
  { id: 'line', label: 'Line' },
  { id: 'bars', label: 'Bars' },
  { id: 'stream', label: 'Stream' },
  { id: 'dots', label: 'Dots' },
];

const FILLS: { id: Fill; label: string }[] = [
  { id: 'solid', label: 'Solid' },
  { id: 'gradient', label: 'Gradient' },
  { id: 'hatch', label: 'Hatch' },
];

const METRIC_ICON: Record<MetricId, IconName> = {
  wau: 'user',
  sessions: 'pulse',
  events: 'database',
};

/** Moves the focus in a radio group by the arrow keys and checks what it lands on. */
function roving(
  event: ReactKeyboardEvent<HTMLElement>,
  count: number,
  index: number,
  pick: (i: number) => void,
  columns = count,
) {
  const keys: Record<string, number> = {
    ArrowRight: 1,
    ArrowLeft: -1,
    ArrowDown: columns,
    ArrowUp: -columns,
  };
  let next: number | null = null;
  if (event.key in keys) next = (index + keys[event.key] + count) % count;
  else if (event.key === 'Home') next = 0;
  else if (event.key === 'End') next = count - 1;
  if (next === null) return;
  event.preventDefault();
  pick(next);
  const group = event.currentTarget.closest('[role="radiogroup"]');
  requestAnimationFrame(() =>
    group?.querySelectorAll<HTMLElement>('[role="radio"]')[next]?.focus(),
  );
}

const HEX = /^#?([0-9a-f]{6})$/i;

export function SettingsPanel({
  draft,
  values,
  editedBy,
  popover,
  onPopover,
  menuOpen,
  onMenu,
  dirty,
  onChange,
  onReset,
  onApply,
}: {
  draft: Config;
  /** Each plan's figure this week, beside its name. */
  values: Record<PlanId, number>;
  editedBy: string;
  /** The plan whose colour popover is open; `byReader` moves the focus into it. */
  popover: { plan: PlanId; byReader: boolean } | null;
  onPopover: (next: { plan: PlanId; byReader: boolean } | null) => void;
  menuOpen: boolean;
  onMenu: (open: boolean) => void;
  dirty: boolean;
  /** A new draft, and what changed in words for the live region. */
  onChange: (next: Config, said?: string) => void;
  onReset: () => void;
  onApply: () => void;
}) {
  const uid = useId();
  const body = useRef<HTMLDivElement>(null);
  const metricButton = useRef<HTMLButtonElement>(null);
  const shown = draft.order.filter((id) => !draft.styles[id].hidden);
  const colors = shown.map((id) => draft.styles[id].color);

  const setStyle = (plan: PlanId, patch: Partial<SeriesStyle>, said?: string) =>
    onChange(
      { ...draft, styles: { ...draft.styles, [plan]: { ...draft.styles[plan], ...patch } } },
      said,
    );

  const move = (plan: PlanId, to: number) => {
    const from = draft.order.indexOf(plan);
    if (to < 0 || to >= draft.order.length || to === from) return;
    const order = [...draft.order];
    order.splice(from, 1);
    order.splice(to, 0, plan);
    onChange(
      { ...draft, order },
      `${PLAN_NAME[plan]} moved to position ${to + 1} of ${order.length}`,
    );
  };

  // ---- Dragging a row by its grip -------------------------------------------------------------

  const [dragging, setDragging] = useState<PlanId | null>(null);
  const onGripDown = (plan: PlanId) => (event: ReactPointerEvent<HTMLButtonElement>) => {
    if (event.button !== 0) return;
    event.currentTarget.setPointerCapture(event.pointerId);
    setDragging(plan);
  };
  const onGripMove = (plan: PlanId) => (event: ReactPointerEvent<HTMLButtonElement>) => {
    if (dragging !== plan || !body.current) return;
    const rows = [...body.current.querySelectorAll<HTMLElement>('[data-row]')];
    const over = rows.findIndex((row) => {
      const r = row.getBoundingClientRect();
      return event.clientY >= r.top && event.clientY < r.bottom;
    });
    if (over >= 0) move(plan, over);
  };
  const onGripUp = () => setDragging(null);

  return (
    <section className={styles.settings} data-part="settings" aria-label="Chart settings">
      <header className={styles.panelHead}>
        <Icon name="settings" className={styles.headIcon} />
        <h3 className={styles.panelTitle}>Chart settings</h3>
        <span className={styles.editedBy}>Edited by {editedBy}</span>
      </header>

      <div ref={body} className={styles.settingsBody}>
        <div className={styles.group}>
          <span className={styles.label}>Chart type</span>
          <div className={styles.types} role="radiogroup" aria-label="Chart type" data-part="types">
            {TYPES.map((t, i) => {
              const on = draft.type === t.id;
              return (
                <button
                  key={t.id}
                  type="button"
                  role="radio"
                  aria-checked={on}
                  tabIndex={on ? 0 : -1}
                  className={styles.typeCard}
                  data-demo={`type-${t.id}`}
                  onClick={() => onChange({ ...draft, type: t.id }, `${t.label} chart`)}
                  onKeyDown={(event) =>
                    roving(event, TYPES.length, i, (k) =>
                      onChange({ ...draft, type: TYPES[k].id }, `${TYPES[k].label} chart`),
                    )
                  }
                >
                  <span className={styles.typeGlyph}>
                    <TypeGlyph type={t.id} colors={on ? colors : undefined} />
                  </span>
                  {t.label}
                </button>
              );
            })}
          </div>
        </div>

        <div className={styles.group}>
          <span className={styles.label}>Metric</span>
          <div className={styles.selectWrap}>
            <button
              ref={metricButton}
              type="button"
              className={styles.select}
              aria-haspopup="listbox"
              aria-expanded={menuOpen}
              aria-label={`Metric: ${METRICS.find((m) => m.id === draft.metric)?.title}`}
              data-demo="metric"
              data-part="metric"
              onClick={() => onMenu(!menuOpen)}
            >
              <Icon name={METRIC_ICON[draft.metric]} className={styles.selectIcon} />
              <span className={styles.selectText}>
                {METRICS.find((m) => m.id === draft.metric)?.title}
              </span>
              <span className={styles.selectSource}>
                {METRICS.find((m) => m.id === draft.metric)?.source}
              </span>
              <Icon name="chevron" className={styles.chevron} />
            </button>
            {menuOpen && (
              <MetricList
                uid={uid}
                value={draft.metric}
                anchor={metricButton}
                onPick={(id) => {
                  onChange({ ...draft, metric: id }, METRICS.find((m) => m.id === id)?.title ?? '');
                  onMenu(false);
                  metricButton.current?.focus();
                }}
                onClose={(back) => {
                  onMenu(false);
                  if (back) metricButton.current?.focus();
                }}
              />
            )}
          </div>
        </div>

        <div className={styles.group}>
          <div className={styles.labelRow}>
            <span className={styles.label}>Series</span>
            <span className={styles.labelNote} aria-live="polite">
              {shown.length} of {draft.order.length} shown
            </span>
          </div>
          <ul className={styles.seriesList} aria-label="Series, from the top of the chart">
            {draft.order.map((plan, i) => {
              const style = draft.styles[plan];
              const open = popover?.plan === plan;
              return (
                <li
                  key={plan}
                  data-row={plan}
                  className={styles.seriesRow}
                  data-open={open || undefined}
                  data-dragging={dragging === plan || undefined}
                  data-hidden={style.hidden || undefined}
                  data-part="series-row"
                >
                  <button
                    type="button"
                    className={styles.grip}
                    aria-label={`Reorder ${PLAN_NAME[plan]}, position ${i + 1} of ${draft.order.length}. Arrow keys move it.`}
                    onPointerDown={onGripDown(plan)}
                    onPointerMove={onGripMove(plan)}
                    onPointerUp={onGripUp}
                    onPointerCancel={onGripUp}
                    onKeyDown={(event) => {
                      if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;
                      event.preventDefault();
                      move(plan, i + (event.key === 'ArrowUp' ? -1 : 1));
                    }}
                  >
                    <Icon name="grip" />
                  </button>
                  <button
                    type="button"
                    className={styles.swatchButton}
                    aria-label={`${PLAN_NAME[plan]} colour, ${style.color}, ${style.fill}`}
                    aria-haspopup="dialog"
                    aria-expanded={open}
                    data-demo={`swatch-${plan}`}
                    data-part="swatch"
                    onClick={() => onPopover(open ? null : { plan, byReader: true })}
                  >
                    <FillSwatch style={style} plan={plan} />
                  </button>
                  <span className={styles.seriesName}>{PLAN_NAME[plan]}</span>
                  <span className={styles.seriesValue}>{compact(values[plan])}</span>
                  <button
                    type="button"
                    className={styles.eye}
                    aria-pressed={!style.hidden}
                    aria-label={`Show ${PLAN_NAME[plan]}`}
                    disabled={!style.hidden && shown.length === 1}
                    data-demo={`eye-${plan}`}
                    onClick={() =>
                      setStyle(
                        plan,
                        { hidden: !style.hidden },
                        `${PLAN_NAME[plan]} ${style.hidden ? 'shown' : 'hidden'}`,
                      )
                    }
                  >
                    <Icon name={style.hidden ? 'eyeOff' : 'eye'} />
                  </button>
                </li>
              );
            })}
          </ul>
        </div>

        {popover && (
          <ColourPopover
            key={popover.plan}
            uid={uid}
            plan={popover.plan}
            style={draft.styles[popover.plan]}
            body={body}
            takeFocus={popover.byReader}
            onStyle={(patch, said) => setStyle(popover.plan, patch, said)}
            onClose={(back) => {
              const plan = popover.plan;
              onPopover(null);
              if (back)
                body.current?.querySelector<HTMLElement>(`[data-demo="swatch-${plan}"]`)?.focus();
            }}
          />
        )}
      </div>

      <footer className={styles.panelFoot}>
        <button type="button" className={styles.reset} data-demo="reset" onClick={onReset}>
          Reset
        </button>
        <button
          type="button"
          className={styles.apply}
          data-demo="apply"
          data-part="apply"
          aria-disabled={!dirty}
          onClick={() => dirty && onApply()}
        >
          Apply
        </button>
      </footer>
    </section>
  );
}

/** A series' swatch as its fill draws it. */
function FillSwatch({ style, plan, fill }: { style: SeriesStyle; plan?: PlanId; fill?: Fill }) {
  const kind = fill ?? style.fill;
  const grain = plan === 'growth' ? 'dots' : plan === 'starter' ? '' : 'lines';
  return (
    <span
      className={styles.fillSwatch}
      data-fill={kind}
      data-grain={kind === 'solid' ? grain : undefined}
      style={{ '--c': style.color, opacity: style.opacity / 100 } as CSSProperties}
    />
  );
}

function MetricList({
  uid,
  value,
  anchor,
  onPick,
  onClose,
}: {
  uid: string;
  value: MetricId;
  anchor: RefObject<HTMLButtonElement | null>;
  onPick: (id: MetricId) => void;
  onClose: (back: boolean) => void;
}) {
  const list = useRef<HTMLUListElement>(null);
  const [active, setActive] = useState(
    Math.max(
      0,
      METRICS.findIndex((m) => m.id === value),
    ),
  );

  useEffect(() => {
    list.current?.focus({ preventScroll: true });
  }, []);

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

  const onKeyDown = (event: ReactKeyboardEvent) => {
    const go = (i: number) => {
      event.preventDefault();
      setActive((i + METRICS.length) % METRICS.length);
    };
    if (event.key === 'ArrowDown') go(active + 1);
    else if (event.key === 'ArrowUp') go(active - 1);
    else if (event.key === 'Home') go(0);
    else if (event.key === 'End') go(METRICS.length - 1);
    else if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault();
      onPick(METRICS[active].id);
    } else if (event.key === 'Escape') {
      event.preventDefault();
      event.stopPropagation();
      onClose(true);
    } else if (event.key === 'Tab') onClose(false);
  };

  return (
    <ul
      ref={list}
      role="listbox"
      tabIndex={-1}
      aria-label="Metric"
      aria-activedescendant={`${uid}-metric-${METRICS[active].id}`}
      className={styles.listbox}
      data-part="metric-list"
      onKeyDown={onKeyDown}
    >
      {METRICS.map((m, i) => (
        <li
          key={m.id}
          id={`${uid}-metric-${m.id}`}
          role="option"
          aria-selected={m.id === value}
          className={styles.option}
          data-active={i === active || undefined}
          data-demo={`metric-${m.id}`}
          onPointerEnter={() => setActive(i)}
          onClick={() => onPick(m.id)}
        >
          <Icon name={METRIC_ICON[m.id]} className={styles.selectIcon} />
          <span className={styles.selectText}>{m.title}</span>
          <span className={styles.selectSource}>{m.source}</span>
          {m.id === value && <Icon name="check" className={styles.optionCheck} width={2} />}
        </li>
      ))}
    </ul>
  );
}

type EyeDropperApi = new () => { open: () => Promise<{ sRGBHex: string }> };

function ColourPopover({
  uid,
  plan,
  style,
  body,
  takeFocus,
  onStyle,
  onClose,
}: {
  uid: string;
  plan: PlanId;
  style: SeriesStyle;
  body: RefObject<HTMLDivElement | null>;
  takeFocus: boolean;
  onStyle: (patch: Partial<SeriesStyle>, said?: string) => void;
  onClose: (back: boolean) => void;
}) {
  const box = useRef<HTMLDivElement>(null);
  const picker = useRef<HTMLInputElement>(null);
  const [top, setTop] = useState<number | null>(null);
  const [hex, setHex] = useState(style.color.toUpperCase());
  const [opacity, setOpacity] = useState(String(style.opacity));
  const [custom, setCustom] = useState<string | null>(
    PALETTE.some((p) => p.hex === style.color.toUpperCase()) ? null : style.color.toUpperCase(),
  );

  // The fields follow the colour when it changes from elsewhere (a swatch, the picker).
  const [seen, setSeen] = useState(style);
  if (seen !== style) {
    setSeen(style);
    setHex(style.color.toUpperCase());
    setOpacity(String(style.opacity));
  }

  // Under its row, or over it when the panel has no room below.
  useLayoutEffect(() => {
    const panel = body.current;
    const pop = box.current;
    const row = panel?.querySelector<HTMLElement>(`[data-row="${plan}"]`);
    if (!panel || !pop || !row) return;
    const place = () => {
      const below = row.offsetTop + row.offsetHeight + 6;
      const h = pop.offsetHeight;
      const room = panel.clientHeight;
      setTop(
        below + h <= room || row.offsetTop - h - 6 < 0
          ? Math.min(below, Math.max(0, room - h))
          : row.offsetTop - h - 6,
      );
    };
    place();
    const observer = new ResizeObserver(place);
    observer.observe(panel);
    return () => observer.disconnect();
  }, [body, plan]);

  useEffect(() => {
    if (!takeFocus || top === null) return;
    const radios = box.current?.querySelectorAll<HTMLElement>('[role="radio"]');
    const first = [...(radios ?? [])].find((r) => r.getAttribute('aria-checked') === 'true');
    (first ?? radios?.[0])?.focus({ preventScroll: true });
    // Only when it first shows.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [takeFocus, top === null]);

  useEffect(() => {
    const away = (event: PointerEvent) => {
      const target = event.target as HTMLElement;
      if (box.current?.contains(target)) return;
      if (target.closest?.(`[data-demo="swatch-${plan}"]`)) return;
      onClose(false);
    };
    document.addEventListener('pointerdown', away);
    return () => document.removeEventListener('pointerdown', away);
  }, [plan, onClose]);

  const swatches = [...PALETTE, ...(custom ? [{ hex: custom, name: 'Custom' }] : [])];
  const checked = swatches.findIndex((s) => s.hex === style.color.toUpperCase());
  const pickColor = (next: string, name?: string) =>
    onStyle({ color: next.toUpperCase() }, `${PLAN_NAME[plan]} colour ${name ?? next}`);

  const commitHex = () => {
    const match = HEX.exec(hex.trim());
    if (!match) return setHex(style.color.toUpperCase());
    const next = `#${match[1].toUpperCase()}`;
    if (!PALETTE.some((p) => p.hex === next)) setCustom(next);
    pickColor(next);
  };
  const commitOpacity = (raw = opacity) => {
    const n = Math.round(Number(raw.replace('%', '')));
    if (!Number.isFinite(n)) return setOpacity(String(style.opacity));
    const next = Math.max(10, Math.min(100, n));
    setOpacity(String(next));
    onStyle({ opacity: next }, `${PLAN_NAME[plan]} opacity ${next}%`);
  };

  const fromPicker = (value: string) => {
    const next = value.toUpperCase();
    if (!PALETTE.some((p) => p.hex === next)) setCustom(next);
    pickColor(next);
  };

  const dropper = async () => {
    const Api = (window as unknown as { EyeDropper?: EyeDropperApi }).EyeDropper;
    if (!Api) return picker.current?.click();
    try {
      const { sRGBHex } = await new Api().open();
      fromPicker(sRGBHex);
    } catch {
      // Escape closes the dropper: nothing to pick.
    }
  };

  const fillIndex = FILLS.findIndex((f) => f.id === style.fill);

  return (
    <div
      ref={box}
      role="dialog"
      aria-label={`${PLAN_NAME[plan]} series colour`}
      className={styles.popover}
      data-part="colour-popover"
      style={{ top: top ?? 0, visibility: top === null ? 'hidden' : undefined }}
      onKeyDown={(event) => {
        if (event.key === 'Escape') {
          event.preventDefault();
          event.stopPropagation();
          onClose(true);
        }
      }}
    >
      <div className={styles.popHead}>
        <span className={styles.popDot} style={{ background: style.color }} />
        <span className={styles.popName}>{PLAN_NAME[plan]}</span>
        <span className={styles.popCaption}>Series colour</span>
        <button
          type="button"
          className={styles.iconButton}
          aria-label="Close"
          onClick={() => onClose(true)}
        >
          <Icon name="close" />
        </button>
      </div>

      <div className={styles.palette} role="radiogroup" aria-label="Palette" data-part="palette">
        {swatches.map((s, i) => (
          <button
            key={s.hex + i}
            type="button"
            role="radio"
            aria-checked={i === checked}
            aria-label={`${s.name} ${s.hex}`}
            tabIndex={i === (checked < 0 ? 0 : checked) ? 0 : -1}
            className={styles.paletteSwatch}
            style={{ '--c': s.hex } as CSSProperties}
            data-demo={`colour-${s.hex.slice(1)}`}
            onClick={() => pickColor(s.hex, s.name)}
            onKeyDown={(event) =>
              roving(
                event,
                swatches.length,
                i,
                (k) => pickColor(swatches[k].hex, swatches[k].name),
                10,
              )
            }
          />
        ))}
        <label className={styles.addColour} aria-label="Custom colour">
          <Icon name="plus" />
          <input
            ref={picker}
            type="color"
            className={styles.srOnly}
            value={style.color.toLowerCase()}
            onChange={(event) => fromPicker(event.target.value)}
          />
        </label>
      </div>

      <div className={styles.fillRow}>
        <span className={styles.fillLabel} id={`${uid}-fill`}>
          Fill
        </span>
        <div
          className={styles.segmented}
          role="radiogroup"
          aria-labelledby={`${uid}-fill`}
          data-part="fill"
        >
          {FILLS.map((f, i) => (
            <button
              key={f.id}
              type="button"
              role="radio"
              aria-checked={style.fill === f.id}
              tabIndex={style.fill === f.id ? 0 : -1}
              className={styles.segment}
              data-demo={`fill-${f.id}`}
              onClick={() => onStyle({ fill: f.id }, `${PLAN_NAME[plan]} fill ${f.label}`)}
              onKeyDown={(event) =>
                roving(event, FILLS.length, fillIndex < 0 ? i : fillIndex, (k) =>
                  onStyle({ fill: FILLS[k].id }, `${PLAN_NAME[plan]} fill ${FILLS[k].label}`),
                )
              }
            >
              <FillSwatch style={{ ...style, opacity: 100 }} fill={f.id} />
              {f.label}
            </button>
          ))}
        </div>
      </div>

      <div className={styles.hexRow}>
        <div className={styles.hexField}>
          <span className={styles.hexSwatch} style={{ background: style.color }} />
          <input
            className={styles.hexInput}
            value={hex}
            aria-label="Hex colour"
            spellCheck={false}
            maxLength={7}
            onChange={(event) => setHex(event.target.value.toUpperCase())}
            onBlur={commitHex}
            onKeyDown={(event) => {
              if (event.key === 'Enter') commitHex();
            }}
          />
          <input
            className={styles.opacityInput}
            value={`${opacity}%`}
            aria-label="Opacity, percent"
            inputMode="numeric"
            onChange={(event) => setOpacity(event.target.value.replace(/[^0-9]/g, ''))}
            onBlur={() => commitOpacity()}
            onKeyDown={(event) => {
              if (event.key === 'Enter') commitOpacity();
              if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
                event.preventDefault();
                const n = Number(opacity) || 0;
                commitOpacity(String(n + (event.key === 'ArrowUp' ? 5 : -5)));
              }
            }}
          />
        </div>
        <button
          type="button"
          className={styles.dropper}
          aria-label="Pick a colour from the screen"
          onClick={dropper}
        >
          <Icon name="picker" />
        </button>
      </div>
    </div>
  );
}
```

### chart-studio/chart-studio.module.css

```css
/* Chart studio (chart-studio.tsx): two panels on a grey stage, the settings beside the chart card,
   near-black by night and white by day. Each panel has a header and an inset card; the settings'
   card holds the type cards, the metric, the series and the colour popover, the chart's holds
   the KPIs, the plot, the legend, the overview and the table.

   From 720 px of stage down, the panels stack, settings first. 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). The series' own colours
   are data: they come from the config, not from here. */

.root {
  --stage: #e8e8eb;
  --panel: #ffffff;
  --card: #f7f7f8;
  --edge: #e4e4e8;
  --line: #ececef;
  --ink: #17171a;
  --ink-2: #4f4f56;
  --ink-3: #6e6e73;
  --control: #ffffff;
  --control-edge: #e2e2e7;
  --hover: #f1f1f4;
  --chosen: #eef3ff;
  --chosen-edge: #4f7cf7;
  --up: #2d69d8;
  --down: #cf3a3f;
  --anomaly: #cc3f39;
  --tooltip: #ffffff;
  --tooltip-edge: #e2e2e7;
  --grain: rgb(0 0 0 / 0.2);
  --band-edge: rgb(255 255 255 / 0.75);
  --track: #ebebee;
  --window: rgb(79 124 247 / 0.07);
  --handle: #ffffff;
  --handle-edge: #87878c;
  --apply: #17171a;
  --apply-ink: #ffffff;
  --shadow: rgb(20 20 30 / 0.12);
  --preview: #fff4dc;
  --preview-ink: #8a5a00;
  --focus: #637fe7;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.3);
  --sans: var(--body, Inter, ui-sans-serif, system-ui, sans-serif);
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --stage: light-dark(#e8e8eb, #2a2a2d);
    --panel: light-dark(#ffffff, #141415);
    --card: light-dark(#f7f7f8, #1b1b1d);
    --edge: light-dark(#e4e4e8, #2a2a2d);
    --line: light-dark(#ececef, #29292c);
    --ink: light-dark(#17171a, #ececee);
    --ink-2: light-dark(#4f4f56, #b0b0b6);
    --ink-3: light-dark(#6e6e73, #88888d);
    --control: light-dark(#ffffff, #18181a);
    --control-edge: light-dark(#e2e2e7, #2e2e31);
    --hover: light-dark(#f1f1f4, #222225);
    --chosen: light-dark(#eef3ff, #1b2232);
    --chosen-edge: light-dark(#4f7cf7, #5b8def);
    --up: light-dark(#2d69d8, #5e9bf7);
    --down: light-dark(#cf3a3f, #f2665a);
    --anomaly: light-dark(#cc3f39, #f2665a);
    --tooltip: light-dark(#ffffff, #202022);
    --tooltip-edge: light-dark(#e2e2e7, #333336);
    --grain: light-dark(rgb(0 0 0 / 0.2), rgb(0 0 0 / 0.32));
    --band-edge: light-dark(rgb(255 255 255 / 0.75), rgb(10 10 12 / 0.7));
    --track: light-dark(#ebebee, #29292c);
    --window: light-dark(rgb(79 124 247 / 0.07), rgb(91 141 239 / 0.09));
    --handle: light-dark(#ffffff, #f2f2f3);
    --handle-edge: light-dark(#87878c, #f2f2f3);
    --apply: light-dark(#17171a, #f2f2f3);
    --apply-ink: light-dark(#ffffff, #111113);
    --shadow: light-dark(rgb(20 20 30 / 0.12), rgb(0 0 0 / 0.55));
    --preview: light-dark(#fff4dc, #3a2c10);
    --preview-ink: light-dark(#8a5a00, #f3c766);
    --focus: light-dark(#637fe7, #6d8cff);
  }
}
.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%;
  padding: 28px;
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background: var(--stage);
  color: var(--ink);
  font-family: var(--sans);
  font-size: 13px;
  line-height: 1.35;
  font-variant-numeric: tabular-nums;
  -webkit-tap-highlight-color: transparent;
}
:where(.root) :where(button, input) {
  font: inherit;
  color: inherit;
}
:where(.root) button {
  cursor: pointer;
}
.root :focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}
.root svg {
  flex: none;
  display: block;
}
.srOnly {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.studio {
  display: grid;
  grid-template-columns: minmax(0, 1fr);
  gap: 16px;
  max-width: 1120px;
  margin: 0 auto;
}
.studio[data-settings] {
  grid-template-columns: 320px minmax(0, 1fr);
}

/* ---- The panels ------------------------------------------------------------------------------- */

.settings,
.card {
  display: flex;
  flex-direction: column;
  min-width: 0;
  padding: 0 4px 4px;
  border: 1px solid var(--edge);
  border-radius: 18px;
  background: var(--panel);
  box-shadow: 0 1px 2px var(--shadow);
}
.panelHead {
  display: flex;
  align-items: center;
  gap: 10px;
  min-height: 54px;
  padding: 10px 12px 10px 14px;
}
.headIcon {
  width: 18px;
  height: 18px;
  color: var(--ink-2);
}
.panelTitle {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  letter-spacing: -0.01em;
  white-space: nowrap;
}
.editedBy {
  margin-left: auto;
  overflow: hidden;
  color: var(--ink-2);
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* ---- Settings --------------------------------------------------------------------------------- */

.settingsBody {
  position: relative;
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 18px;
  padding: 14px 12px 16px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--card);
}
.group {
  display: flex;
  flex-direction: column;
  gap: 9px;
}
.label {
  color: var(--ink-2);
  font-weight: 500;
}
.labelRow {
  display: flex;
  justify-content: space-between;
}
.labelNote {
  color: var(--ink-3);
}

.types {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 8px;
}
.typeCard {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  padding: 11px 4px 8px;
  border: 1px solid var(--control-edge);
  border-radius: 11px;
  background: var(--control);
  color: var(--ink-2);
  font-weight: 500;
  transition:
    border-color 0.15s ease,
    background-color 0.15s ease,
    color 0.15s ease;
}
.typeCard:hover,
.typeCard[data-over] {
  background: var(--hover);
}
.typeCard[aria-checked='true'] {
  border-color: var(--chosen-edge);
  background: var(--chosen);
  box-shadow: inset 0 0 0 0.5px var(--chosen-edge);
  color: var(--ink);
}
.typeGlyph {
  display: block;
  width: 40px;
  height: 20px;
}
.typeGlyph svg {
  width: 100%;
  height: 100%;
}

.selectWrap {
  position: relative;
}
.select {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  height: 40px;
  padding: 0 12px;
  border: 1px solid var(--control-edge);
  border-radius: 10px;
  background: var(--control);
  text-align: left;
}
.select:hover,
.select[data-over] {
  background: var(--hover);
}
.selectIcon {
  width: 17px;
  height: 17px;
  color: var(--ink-2);
}
.selectText {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  font-size: 14px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.selectSource {
  color: var(--ink-3);
}
.chevron {
  width: 15px;
  height: 15px;
  color: var(--ink-2);
}
.listbox,
.shareMenu {
  position: absolute;
  z-index: 5;
  margin: 0;
  padding: 4px;
  list-style: none;
  border: 1px solid var(--control-edge);
  border-radius: 11px;
  background: var(--tooltip);
  box-shadow: 0 12px 32px var(--shadow);
  animation: rise 0.16s ease;
}
.listbox {
  top: calc(100% + 6px);
  right: 0;
  left: 0;
}
.listbox:focus {
  outline: none;
}
.option {
  display: flex;
  align-items: center;
  gap: 10px;
  height: 36px;
  padding: 0 10px;
  border-radius: 7px;
  cursor: pointer;
}
.option[data-active],
.option[data-over] {
  background: var(--hover);
}
.listbox:focus-visible .option[data-active] {
  box-shadow: inset 0 0 0 1.5px var(--focus);
}
.optionCheck {
  width: 15px;
  height: 15px;
  color: var(--up);
}

.seriesList {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.seriesRow {
  display: flex;
  align-items: center;
  gap: 8px;
  height: 40px;
  padding: 0 8px 0 2px;
  border: 1px solid transparent;
  border-radius: 10px;
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}
.seriesRow:hover {
  background: var(--hover);
}
.seriesRow[data-open],
.seriesRow[data-dragging] {
  border-color: var(--control-edge);
  background: var(--control);
}
.seriesRow[data-dragging] {
  box-shadow: 0 6px 16px var(--shadow);
}
.seriesRow[data-hidden] .seriesName,
.seriesRow[data-hidden] .seriesValue,
.seriesRow[data-hidden] .swatchButton {
  opacity: 0.4;
}
.grip {
  display: grid;
  place-items: center;
  width: 20px;
  height: 30px;
  padding: 0;
  border: 0;
  border-radius: 6px;
  background: none;
  color: var(--ink-3);
  cursor: grab;
  touch-action: none;
}
.grip svg {
  width: 16px;
  height: 16px;
}
.seriesRow[data-dragging] .grip {
  cursor: grabbing;
}
.swatchButton {
  display: grid;
  place-items: center;
  width: 28px;
  height: 28px;
  padding: 0;
  border: 0;
  border-radius: 8px;
  background: none;
}
.swatchButton:hover .fillSwatch,
.swatchButton[data-over] .fillSwatch,
.swatchButton[aria-expanded='true'] .fillSwatch {
  box-shadow:
    0 0 0 2px var(--panel),
    0 0 0 3.5px var(--ink-2);
}
.fillSwatch {
  display: block;
  width: 20px;
  height: 20px;
  border-radius: 6px;
  background-color: var(--c);
}
.fillSwatch[data-grain='lines'] {
  background-image: repeating-linear-gradient(to bottom, var(--grain) 0 1px, transparent 1px 4px);
}
.fillSwatch[data-grain='dots'] {
  background-image: radial-gradient(circle, var(--grain) 0.8px, transparent 1.2px);
  background-size: 4px 4px;
}
.fillSwatch[data-fill='gradient'] {
  background-image: linear-gradient(
    to bottom,
    var(--c),
    color-mix(in srgb, var(--c) 28%, transparent)
  );
  background-color: transparent;
}
.fillSwatch[data-fill='hatch'] {
  background-image: repeating-linear-gradient(45deg, var(--grain) 0 1.3px, transparent 1.3px 3.6px);
}
.seriesName {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  font-size: 15px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.seriesValue {
  color: var(--ink-2);
}
.eye {
  display: grid;
  place-items: center;
  width: 30px;
  height: 30px;
  padding: 0;
  border: 0;
  border-radius: 7px;
  background: none;
  color: var(--ink-2);
}
.eye:hover:not(:disabled),
.eye[data-over] {
  background: var(--hover);
  color: var(--ink);
}
.eye:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}
.eye svg {
  width: 18px;
  height: 18px;
}

/* The colour popover, over the rows under the one it belongs to. */
.popover {
  position: absolute;
  z-index: 4;
  right: 6px;
  left: 6px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 12px;
  border: 1px solid var(--control-edge);
  border-radius: 14px;
  background: var(--tooltip);
  box-shadow: 0 18px 40px var(--shadow);
  animation: rise 0.18s ease;
}
.popHead {
  display: flex;
  align-items: center;
  gap: 8px;
}
.popDot {
  width: 10px;
  height: 10px;
  border-radius: 3px;
}
.popName {
  font-size: 14px;
  font-weight: 500;
}
.popCaption {
  flex: 1;
  color: var(--ink-3);
}
.iconButton {
  display: grid;
  place-items: center;
  width: 26px;
  height: 26px;
  padding: 0;
  border: 0;
  border-radius: 7px;
  background: none;
  color: var(--ink-2);
}
.iconButton:hover {
  background: var(--hover);
}
.iconButton svg {
  width: 15px;
  height: 15px;
}
.palette {
  display: grid;
  grid-template-columns: repeat(10, minmax(0, 1fr));
  gap: 6px;
}
.paletteSwatch,
.addColour {
  aspect-ratio: 1;
  min-width: 0;
  padding: 0;
  border: 0;
  border-radius: 7px;
  background: var(--c);
  box-shadow: inset 0 0 0 1px rgb(0 0 0 / 0.08);
}
.paletteSwatch:hover,
.paletteSwatch[data-over] {
  transform: scale(1.08);
}
.paletteSwatch[aria-checked='true'] {
  box-shadow:
    0 0 0 2px var(--tooltip),
    0 0 0 3.5px var(--ink);
}
.addColour {
  position: relative;
  display: grid;
  place-items: center;
  border: 1px dashed var(--ink-3);
  background: none;
  box-shadow: none;
  color: var(--ink-2);
  cursor: pointer;
}
.addColour:hover {
  background: var(--hover);
}
.addColour:focus-within {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}
.addColour svg {
  width: 14px;
  height: 14px;
}
.fillRow {
  display: flex;
  align-items: center;
  gap: 10px;
}
.fillLabel {
  color: var(--ink-2);
}
.segmented {
  display: grid;
  flex: 1;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 2px;
  padding: 3px;
  border: 1px solid var(--control-edge);
  border-radius: 10px;
  background: var(--card);
}
.segment {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  min-width: 0;
  height: 30px;
  padding: 0 4px;
  font-size: 12.5px;
  border: 0;
  border-radius: 7px;
  background: none;
  color: var(--ink-2);
  white-space: nowrap;
}
.segment .fillSwatch {
  flex: none;
  width: 12px;
  height: 12px;
  border-radius: 3.5px;
}
.segment:hover,
.segment[data-over] {
  color: var(--ink);
}
.segment[aria-checked='true'] {
  background: var(--control);
  box-shadow:
    0 0 0 1px var(--control-edge),
    0 1px 2px var(--shadow);
  color: var(--ink);
}
.hexRow {
  display: flex;
  gap: 8px;
}
.hexField {
  display: flex;
  flex: 1;
  align-items: center;
  gap: 8px;
  min-width: 0;
  height: 38px;
  padding: 0 10px;
  border: 1px solid var(--control-edge);
  border-radius: 10px;
  background: var(--card);
}
.hexField:focus-within {
  border-color: var(--focus);
}
.hexSwatch {
  flex: none;
  width: 18px;
  height: 18px;
  border-radius: 5px;
}
.hexInput,
.opacityInput {
  min-width: 0;
  padding: 0;
  border: 0;
  background: none;
  outline: none;
}
.hexInput {
  flex: 1;
  font-size: 14px;
  letter-spacing: 0.01em;
}
.opacityInput {
  width: 46px;
  color: var(--ink-2) !important;
  text-align: right;
}
.root .hexInput:focus-visible,
.root .opacityInput:focus-visible {
  outline: none;
}
.dropper {
  display: grid;
  flex: none;
  place-items: center;
  width: 38px;
  height: 38px;
  padding: 0;
  border: 1px solid var(--control-edge);
  border-radius: 10px;
  background: var(--card);
  color: var(--ink-2);
}
.dropper:hover {
  background: var(--hover);
  color: var(--ink);
}
.dropper svg {
  width: 17px;
  height: 17px;
}

.panelFoot {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  padding: 14px 10px 10px;
}
.reset,
.apply {
  height: 40px;
  border-radius: 10px;
  font-size: 14px !important;
  font-weight: 500 !important;
  transition:
    background-color 0.15s ease,
    opacity 0.15s ease;
}
.reset {
  border: 1px solid var(--control-edge);
  background: var(--card);
}
.reset:hover,
.reset[data-over] {
  background: var(--hover);
}
.apply {
  border: 0;
  background: var(--apply);
  color: var(--apply-ink) !important;
}
.apply[aria-disabled='true'] {
  cursor: default;
  opacity: 0.45;
}
.apply[data-over] {
  opacity: 0.88;
}

/* ---- The chart card --------------------------------------------------------------------------- */

.titles {
  flex: 1;
  min-width: 0;
}
.subtitle {
  margin: 1px 0 0;
  overflow: hidden;
  color: var(--ink-2);
  text-overflow: ellipsis;
  white-space: nowrap;
}
.preview {
  padding: 2px 7px;
  border-radius: 6px;
  background: var(--preview);
  color: var(--preview-ink);
  font-size: 11px;
  font-weight: 500;
  letter-spacing: 0;
}
.headButton {
  display: grid;
  flex: none;
  place-items: center;
  width: 34px;
  height: 32px;
  padding: 0;
  border: 1px solid var(--control-edge);
  border-radius: 9px;
  background: var(--card);
  color: var(--ink-2);
}
.headButton:hover {
  background: var(--hover);
  color: var(--ink);
}
.headButton[data-done] {
  color: var(--up);
}
.headButton svg {
  width: 16px;
  height: 16px;
}
.menuWrap {
  position: relative;
}
.shareMenu {
  top: calc(100% + 6px);
  right: 0;
  width: 172px;
}
.menuItem {
  display: flex;
  align-items: center;
  gap: 9px;
  width: 100%;
  height: 34px;
  padding: 0 10px;
  border: 0;
  border-radius: 7px;
  background: none;
  text-align: left;
}
.menuItem:hover,
.menuItem:focus-visible {
  background: var(--hover);
  outline: none;
}
.menuItem svg {
  width: 15px;
  height: 15px;
  color: var(--ink-2);
}

.cardBody {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-width: 0;
  padding: 16px 16px 6px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--card);
}
.kpis {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, auto));
  justify-content: space-between;
  gap: 8px 20px;
  margin: 0;
}
.kpi {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}
.kpi dd {
  margin: 0;
}
.kpiValue {
  font-size: 26px;
  font-weight: 600;
  letter-spacing: -0.03em;
  line-height: 1.15;
}
.kpiNote {
  color: var(--ink-2);
  font-size: 13.5px;
  white-space: nowrap;
}
.kpiNote [data-tone='up'],
.root [data-tone='up'] {
  color: var(--up);
}
.kpiNote [data-tone='down'],
.root [data-tone='down'] {
  color: var(--down);
}
.kpiPlain {
  margin-left: 4px;
  color: var(--ink-2);
}
.anomalyDates {
  display: inline-flex;
  gap: 4px;
  margin-left: 4px;
}
.anomalyDate {
  padding: 0;
  border: 0;
  border-radius: 3px;
  background: none;
  color: var(--anomaly) !important;
}
.anomalyDate:hover {
  text-decoration: underline;
  text-underline-offset: 3px;
}

/* The plot: an SVG at the box's size, with the tooltip over it. */
.plot {
  position: relative;
  height: 280px;
  margin: 8px -4px 0;
  border-radius: 8px;
  touch-action: pan-y;
}
.plotSvg {
  overflow: visible;
}
.grain {
  fill: var(--grain);
}
.layer {
  transition: opacity 0.2s ease;
}
.bandEdge {
  fill: none;
  stroke: var(--band-edge);
  stroke-width: 1.3;
}
.divider line {
  stroke: var(--ink-3);
  stroke-dasharray: 2 3;
  stroke-width: 1.2;
}
.divider text {
  fill: var(--ink-2);
  font-size: 13px;
  font-weight: 500;
}
.crosshair {
  stroke: var(--ink-3);
  stroke-dasharray: 2 3;
}
.hoverDot {
  stroke: var(--card);
  stroke-width: 2;
}
.anomalyStem {
  stroke: var(--ink-3);
  stroke-dasharray: 2 2;
}
.anomalyDot {
  fill: var(--anomaly);
  stroke: var(--card);
  stroke-width: 2;
  filter: drop-shadow(0 0 3px color-mix(in srgb, var(--anomaly) 60%, transparent));
}
.axis text {
  fill: var(--ink-2);
  font-size: 13px;
}
.axis text[data-ahead] {
  fill: var(--ink-3);
}
.tooltip {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  display: flex;
  flex-direction: column;
  gap: 2px;
  max-width: 240px;
  padding: 7px 11px 8px;
  border: 1px solid var(--tooltip-edge);
  border-radius: 9px;
  background: var(--tooltip);
  box-shadow: 0 8px 24px var(--shadow);
  pointer-events: none;
  white-space: nowrap;
}
.tooltip strong {
  font-size: 13.5px;
  font-weight: 500;
}
.tipNote {
  color: var(--ink-2);
}
.tipRows {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-top: 4px;
}
.tipRow {
  display: flex;
  align-items: center;
  gap: 7px;
  color: var(--ink-2);
}
.tipRow i {
  width: 8px;
  height: 8px;
  border-radius: 2px;
}
.tipRow b {
  margin-left: auto;
  padding-left: 14px;
  color: var(--ink);
  font-weight: 500;
}

.legend {
  display: flex;
  flex-wrap: wrap;
  gap: 6px 18px;
  margin: 14px 0 0;
  padding: 0;
  list-style: none;
}
.legendItem {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--ink-2);
  font-size: 13.5px;
  transition: opacity 0.15s ease;
}
.legendItem[data-dim] {
  opacity: 0.45;
}
.legendItem i {
  width: 9px;
  height: 9px;
  border-radius: 2.5px;
}
.legendItem[data-anomaly] {
  margin-left: auto;
}
.legendItem[data-anomaly] i {
  border-radius: 50%;
  background: var(--anomaly);
}

/* The overview: small stacked bars, and a window with a handle at each end. */
.brush {
  position: relative;
  height: 42px;
  margin-top: 14px;
  touch-action: none;
  user-select: none;
}
.brushSvg {
  position: absolute;
  inset: 0;
}
.window {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  border: 1px solid color-mix(in srgb, var(--chosen-edge) 55%, transparent);
  border-radius: 9px;
  background: var(--window);
  cursor: grab;
}
.window:active {
  cursor: grabbing;
}
.handle {
  position: absolute;
  top: 50%;
  left: -4px;
  width: 8px;
  height: 26px;
  margin-top: -13px;
  border: 1px solid var(--handle-edge);
  border-radius: 4px;
  background: var(--handle);
  box-shadow: 0 1px 3px var(--shadow);
  cursor: ew-resize;
  touch-action: none;
}
.handle::before {
  position: absolute;
  inset: -8px -10px;
  content: '';
}
.handle[data-over] {
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--chosen-edge) 40%, transparent);
}

.tableBox {
  margin-top: 14px;
  overflow-x: auto;
}
.table {
  width: 100%;
  min-width: 340px;
  border-collapse: collapse;
}
.table th,
.table td {
  height: 38px;
  padding: 0 8px;
  border-bottom: 1px solid var(--line);
  font-weight: 400;
  text-align: left;
  white-space: nowrap;
}
.table th:first-child,
.table td:first-child {
  padding-left: 0;
}
.table th:last-child,
.table td:last-child {
  padding-right: 0;
}
.table thead th {
  height: 34px;
  color: var(--ink-2);
}
.table tbody th {
  font-size: 15px;
}
.table tbody th i {
  display: inline-block;
  width: 9px;
  height: 9px;
  margin-right: 10px;
  border-radius: 2.5px;
  vertical-align: 1px;
}
.table tbody tr {
  transition: opacity 0.15s ease;
}
.table tbody tr[data-dim] {
  opacity: 0.45;
}
.table tfoot th,
.table tfoot td {
  border-bottom: 0;
  font-size: 15px;
}
.table tfoot th {
  color: var(--ink-2);
}
.num {
  text-align: right !important;
}
.table td.num {
  font-size: 15px;
}
.shareHead {
  width: 42%;
  text-align: right !important;
}
.shareCell {
  width: 42%;
}
.sharePct {
  display: inline-block;
  width: 3.2em;
  color: var(--ink-2);
}
.shareTrack {
  display: inline-block;
  width: calc(100% - 3.6em);
  height: 4px;
  overflow: hidden;
  border-radius: 2px;
  background: var(--track);
  vertical-align: middle;
}
.shareBar {
  display: block;
  height: 100%;
  border-radius: 2px;
  transition: width 0.3s ease;
}

@keyframes rise {
  from {
    opacity: 0;
    transform: translateY(-4px);
  }
}

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

@container (max-width: 1080px) {
  .studio[data-settings] {
    grid-template-columns: 300px minmax(0, 1fr);
  }
  .plot {
    height: 230px;
  }
}

@container (max-width: 760px) {
  .root {
    padding: 14px;
  }
  .studio[data-settings] {
    grid-template-columns: minmax(0, 1fr);
  }
  .kpis {
    grid-template-columns: repeat(2, minmax(0, 1fr));
    justify-content: stretch;
  }
  .kpis > :last-child {
    grid-column: 1 / -1;
  }
  .plot {
    height: 220px;
  }
}

@container (max-width: 440px) {
  .root {
    padding: 8px;
  }
  .cardBody {
    padding: 12px 12px 4px;
  }
  .kpiValue {
    font-size: 22px;
  }
  .kpiNote {
    white-space: normal;
  }
  .legendItem[data-anomaly] {
    margin-left: 0;
  }
  .table {
    min-width: 0;
  }
  .table th,
  .table td {
    padding: 0 5px;
  }
  .shareHead,
  .shareCell {
    width: auto;
  }
  .sharePct {
    width: auto;
  }
  .titles .panelTitle {
    flex-wrap: wrap;
    white-space: normal;
  }
  .shareTrack {
    display: none;
  }
}

/* ---- 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) {
  .typeCard,
  .seriesRow,
  .layer,
  .legendItem,
  .table tbody tr,
  .shareBar,
  .reset,
  .apply {
    transition: none;
  }
  .listbox,
  .shareMenu,
  .popover {
    animation: none;
  }
}
```

### chart-studio/data.ts

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

/*
 * The chart studio's data: eighteen weeks of a product's usage split by plan, three weeks of
 * forecast after them, and the two weeks that broke the pattern. Every series is computed from a
 * seed, so it is the same on every load: a smooth wave, bent so that this week and four weeks ago
 * land on the figures below, then the anomalies laid on top.
 */

export type PlanId = 'enterprise' | 'growth' | 'starter' | 'free';
export type MetricId = 'wau' | 'sessions' | 'events';
export type ChartType = 'line' | 'bars' | 'stream' | 'dots';
export type Fill = 'solid' | 'gradient' | 'hatch';

/** How a series is drawn: its colour, opacity (0–100), fill, and whether it is shown. */
export type SeriesStyle = { color: string; opacity: number; fill: Fill; hidden: boolean };

/** What the settings set: Apply commits a draft of this. */
export type Config = {
  type: ChartType;
  metric: MetricId;
  /** The plans from the top of the stack down: the legend and the table follow it. */
  order: PlanId[];
  styles: Record<PlanId, SeriesStyle>;
};

export type Plan = {
  id: PlanId;
  name: string;
  /** The fine texture a solid fill carries, so bands stay apart without their colour. */
  grain: 'lines' | 'dots' | 'none';
};

export const PLANS: Plan[] = [
  { id: 'enterprise', name: 'Enterprise', grain: 'lines' },
  { id: 'growth', name: 'Growth', grain: 'dots' },
  { id: 'starter', name: 'Starter', grain: 'none' },
  { id: 'free', name: 'Free', grain: 'lines' },
];

export const PLAN_NAME = Object.fromEntries(PLANS.map((p) => [p.id, p.name])) as Record<
  PlanId,
  string
>;

export type Metric = {
  id: MetricId;
  title: string;
  /** In the KPI and the table's header. */
  short: string;
  /** What one unit is, in the tooltips. */
  unit: string;
  /** Where the numbers come from, at the right of the select. */
  source: string;
  /** This week and its change on four weeks ago, per plan. */
  now: Record<PlanId, { value: number; change: number }>;
};

export const METRICS: Metric[] = [
  {
    id: 'wau',
    title: 'Weekly active users',
    short: 'WAU',
    unit: 'users',
    source: 'events',
    now: {
      enterprise: { value: 7840, change: 9.1 },
      growth: { value: 6120, change: 4.8 },
      starter: { value: 4460, change: 3.2 },
      free: { value: 9310, change: 1.4 },
    },
  },
  {
    id: 'sessions',
    title: 'Weekly sessions',
    short: 'Sessions',
    unit: 'sessions',
    source: 'web + app',
    now: {
      enterprise: { value: 32150, change: 7.4 },
      growth: { value: 20190, change: 5.6 },
      starter: { value: 11600, change: 2.1 },
      free: { value: 16760, change: -0.8 },
    },
  },
  {
    id: 'events',
    title: 'Weekly events',
    short: 'Events',
    unit: 'events',
    source: 'warehouse',
    now: {
      enterprise: { value: 407700, change: 11.2 },
      growth: { value: 232600, change: 6.9 },
      starter: { value: 120400, change: 2.7 },
      free: { value: 111700, change: 0.6 },
    },
  },
];

export const METRIC = Object.fromEntries(METRICS.map((m) => [m.id, m])) as Record<MetricId, Metric>;

/** The 18 colours of the palette, in two rows, with the names a screen reader says. */
export const PALETTE: { hex: string; name: string }[] = [
  { hex: '#6B5CF6', name: 'Indigo' },
  { hex: '#9B7BFA', name: 'Violet' },
  { hex: '#C78BF8', name: 'Lilac' },
  { hex: '#F472C0', name: 'Pink' },
  { hex: '#F2655A', name: 'Coral' },
  { hex: '#F98A54', name: 'Orange' },
  { hex: '#F2B43C', name: 'Amber' },
  { hex: '#E6D55A', name: 'Yellow' },
  { hex: '#B5D65A', name: 'Lime' },
  { hex: '#3DD6A0', name: 'Green' },
  { hex: '#2EC4B6', name: 'Teal' },
  { hex: '#3CC4EC', name: 'Sky' },
  { hex: '#4A9BF8', name: 'Blue' },
  { hex: '#7B8CFB', name: 'Periwinkle' },
  { hex: '#8F8F94', name: 'Grey' },
  { hex: '#5C5C61', name: 'Graphite' },
  { hex: '#F0F0F2', name: 'White' },
  { hex: '#E8A0BF', name: 'Rose' },
];

export const DEFAULT_CONFIG: Config = {
  type: 'stream',
  metric: 'wau',
  order: ['enterprise', 'growth', 'starter', 'free'],
  styles: {
    enterprise: { color: '#9B7BFA', opacity: 100, fill: 'solid', hidden: false },
    growth: { color: '#3DD6A0', opacity: 100, fill: 'solid', hidden: false },
    starter: { color: '#F2B43C', opacity: 100, fill: 'hatch', hidden: false },
    free: { color: '#4A9BF8', opacity: 100, fill: 'solid', hidden: true },
  },
};

// ---- The weeks ------------------------------------------------------------------------------------

const DAY = 86_400_000;
/** The Monday the first week starts on. */
const FIRST = Date.UTC(2026, 5, 29);
/** Weeks with readings; this week is the last of them. */
export const HISTORY = 18;
/** Weeks of forecast after them. */
export const AHEAD = 3;
export const WEEKS = Array.from({ length: HISTORY + AHEAD }, (_, i) => FIRST + i * 7 * DAY);
/** The index of this week. */
export const NOW = HISTORY - 1;
/** Compared with this week in the Change column. */
const BEFORE = NOW - 4;

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
export const monthOf = (i: number) => MONTHS[new Date(WEEKS[i]).getUTCMonth()];
/** "Sep 7". */
export const weekLabel = (i: number) => `${monthOf(i)} ${new Date(WEEKS[i]).getUTCDate()}`;

export type Anomaly = {
  index: number;
  /** What it took or added, as a share of each plan's week. */
  share: Partial<Record<PlanId, number>>;
  title: string;
  plans: string;
};

/** The weeks that broke the pattern: users lost or gained against the expected line, by plan. */
export const ANOMALIES: Anomaly[] = [
  {
    index: 10,
    share: { enterprise: -0.15, growth: -0.16, starter: -0.17, free: -0.07 },
    title: 'Labor Day',
    plans: 'all plans',
  },
  {
    index: 15,
    share: { growth: 0.27 },
    title: 'Template gallery launch',
    plans: 'Growth',
  },
];

/** Weekly growth of the forecast, per plan: the fourth quarter's planning season. */
const AHEAD_RATE: Record<PlanId, number> = {
  enterprise: 0.062,
  growth: 0.051,
  starter: 0.043,
  free: 0.012,
};
/** The forecast's band, as a share of its value at the end. */
export const SPREAD = 0.065;

/** A seeded wave, so the same plan draws the same line on every load. */
function wave(seed: number, i: number) {
  return (
    1 +
    0.085 * Math.sin(i * 0.5 + seed * 1.7) +
    0.045 * Math.sin(i * 1.05 + seed * 2.9) +
    0.015 * Math.sin(i * 2.3 + seed)
  );
}

export type Series = {
  plan: PlanId;
  /** HISTORY readings, then AHEAD forecast points. */
  values: number[];
  /** What each anomaly took or added this plan, by week index. */
  bumps: Record<number, number>;
};

const cache = new Map<MetricId, Record<PlanId, Series>>();

/** Every plan's weeks for a metric. */
export function seriesFor(metric: MetricId): Record<PlanId, Series> {
  const hit = cache.get(metric);
  if (hit) return hit;
  const m = METRIC[metric];
  const out = {} as Record<PlanId, Series>;
  PLANS.forEach((plan, p) => {
    const { value, change } = m.now[plan.id];
    const before = value / (1 + change / 100);
    // A wave around a gentle climb, scaled to land on four weeks ago, then eased onto this week.
    const raw = Array.from(
      { length: HISTORY },
      (_, i) => before * (0.9 + (0.1 * i) / NOW) * wave(p + metric.length, i),
    );
    const from = before / raw[BEFORE];
    const to = value / raw[NOW];
    const values = raw.map((v, i) =>
      Math.round(v * (i <= BEFORE ? from : from + ((to - from) * (i - BEFORE)) / (NOW - BEFORE))),
    );
    const bumps: Record<number, number> = {};
    // The anomalies are sized on the metric's own scale against this plan's level.
    for (const anomaly of ANOMALIES) {
      const share = anomaly.share[plan.id];
      if (!share) continue;
      const bump = Math.round(values[anomaly.index] * share);
      bumps[anomaly.index] = bump;
      values[anomaly.index] += bump;
    }
    for (let k = 1; k <= AHEAD; k += 1) {
      values.push(Math.round(value * (1 + AHEAD_RATE[plan.id]) ** k));
    }
    out[plan.id] = { plan: plan.id, values, bumps };
  });
  cache.set(metric, out);
  return out;
}

// ---- Numbers ------------------------------------------------------------------------------------

const whole = new Intl.NumberFormat('en-US');
/** 18,420. */
export const full = (n: number) => whole.format(Math.round(n));
/** 7.8k, 1.2M. */
export function compact(n: number) {
  const a = Math.abs(n);
  if (a >= 999_500) return `${(n / 1e6).toFixed(a >= 1e7 ? 0 : 1)}M`;
  if (a >= 1000) return `${(n / 1000).toFixed(a >= 99_950 ? 0 : 1)}k`;
  return String(Math.round(n));
}
/** +6.2%, using a real minus sign. */
export const signed = (n: number, digits = 1) =>
  `${n < 0 ? '−' : '+'}${Math.abs(n).toFixed(digits)}%`;
/** −2,640 with a real minus sign. */
export const signedFull = (n: number) => `${n < 0 ? '−' : '+'}${full(Math.abs(n))}`;
```

### chart-studio/glyphs.tsx

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

/*
 * The chart studio's icons: strokes on a 20-unit grid in the current colour, decorative. The chart
 * type cards draw their own small charts (TypeGlyph), in the series' colours when chosen.
 */

import type { ChartType } from './data';

export type IconName =
  | 'settings'
  | 'chart'
  | 'copy'
  | 'share'
  | 'user'
  | 'pulse'
  | 'database'
  | 'chevron'
  | 'grip'
  | 'eye'
  | 'eyeOff'
  | 'close'
  | 'plus'
  | 'picker'
  | 'check'
  | 'download';

const PATHS: Record<IconName, string> = {
  settings: 'M3 5.5h14M5.5 10h9M8 14.5h4',
  chart: 'M3.5 3.5v13h13M7 13.5v-4M10 13.5v-7M13 13.5v-5M16 13.5V11',
  copy: 'M7 7V4.8c0-.7.6-1.3 1.3-1.3h6.9c.7 0 1.3.6 1.3 1.3v6.9c0 .7-.6 1.3-1.3 1.3H13M4.8 7h6.9c.7 0 1.3.6 1.3 1.3v6.9c0 .7-.6 1.3-1.3 1.3H4.8c-.7 0-1.3-.6-1.3-1.3V8.3C3.5 7.6 4.1 7 4.8 7z',
  share: 'M10 12.5V3.5M6.5 7 10 3.5 13.5 7M4 11v4.2c0 .7.6 1.3 1.3 1.3h9.4c.7 0 1.3-.6 1.3-1.3V11',
  user: 'M10 9.5a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM4 16.5c.6-3 3-4.5 6-4.5s5.4 1.5 6 4.5',
  pulse: 'M2.5 10h3.2l1.8-4.5 3 9 2-6 1.3 1.5h3.7',
  database:
    'M16 5.5c0 1.4-2.7 2.5-6 2.5S4 6.9 4 5.5 6.7 3 10 3s6 1.1 6 2.5zM4 5.5v9C4 15.9 6.7 17 10 17s6-1.1 6-2.5v-9M4 10c0 1.4 2.7 2.5 6 2.5s6-1.1 6-2.5',
  chevron: 'M6 8l4 4 4-4',
  grip: 'M7.5 5h0M12.5 5h0M7.5 10h0M12.5 10h0M7.5 15h0M12.5 15h0',
  eye: 'M2.5 10s2.7-5 7.5-5 7.5 5 7.5 5-2.7 5-7.5 5-7.5-5-7.5-5zM10 12.3a2.3 2.3 0 1 0 0-4.6 2.3 2.3 0 0 0 0 4.6z',
  eyeOff:
    'M8.2 5.2A7.6 7.6 0 0 1 10 5c4.8 0 7.5 5 7.5 5a12.8 12.8 0 0 1-2 2.6M12 12a2.6 2.6 0 0 1-4-3.4M5.3 6.6C3.5 7.9 2.5 10 2.5 10s2.7 5 7.5 5c1.4 0 2.6-.4 3.6-1M3.5 3.5l13 13',
  close: 'M5.5 5.5l9 9M14.5 5.5l-9 9',
  plus: 'M10 4.5v11M4.5 10h11',
  picker:
    'M12.6 4.2l3.2 3.2M14.6 2.9c.6-.6 1.6-.6 2.2 0l.3.3c.6.6.6 1.6 0 2.2l-2 2-2.5-2.5zM12.4 5.1 4.6 12.9 3.5 16.5l3.6-1.1 7.8-7.8',
  check: 'M4.5 10.5l3.5 3.5 7.5-8',
  download:
    'M10 3.5v9M6.5 9 10 12.5 13.5 9M4 13.5v1.7c0 .7.6 1.3 1.3 1.3h9.4c.7 0 1.3-.6 1.3-1.3v-1.7',
};

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

/** A chart type's card picture; `colors` (top band first) when the card is chosen. */
export function TypeGlyph({ type, colors }: { type: ChartType; colors?: string[] }) {
  const c = (i: number) => colors?.[i] ?? 'currentColor';
  if (type === 'line')
    return (
      <svg viewBox="0 0 44 22" aria-hidden="true" fill="none" strokeLinecap="round">
        <path
          d="M2 18 9 11l6 4 8-9 7 6 6-4 6 2"
          stroke={c(0)}
          strokeWidth="2.2"
          strokeLinejoin="round"
        />
      </svg>
    );
  if (type === 'bars')
    return (
      <svg viewBox="0 0 44 22" aria-hidden="true">
        {[
          [5, 8],
          [14, 2],
          [23, 10],
          [32, 6],
        ].map(([x, y], i) => (
          <g key={x}>
            <rect x={x} y={y} width="6" height={20 - y} rx="1.5" fill={c(2)} opacity={0.9} />
            <rect x={x} y={y} width="6" height={(20 - y) * 0.5} rx="1.5" fill={c(i % 2)} />
          </g>
        ))}
      </svg>
    );
  if (type === 'stream')
    return (
      <svg viewBox="0 0 44 22" aria-hidden="true">
        <path d="M2 6c8-4 14 2 22-1s12-4 18-2v5H2z" fill={c(0)} />
        <path d="M2 11c8-2 14 2 22 0s12-3 18-3v5c-6 0-10 3-18 3s-14-3-22-1z" fill={c(1)} />
        <path
          d="M2 15c8-2 14 1 22 1s12-3 18-3v4c-6 0-10 2-18 2s-14-2-22-1z"
          fill={c(2)}
          opacity={colors ? 1 : 0.6}
        />
      </svg>
    );
  return (
    <svg viewBox="0 0 44 22" aria-hidden="true">
      {[
        [4, 15],
        [9, 9],
        [14, 13],
        [19, 6],
        [24, 11],
        [29, 4],
        [34, 9],
        [39, 6],
        [12, 18],
        [27, 16],
      ].map(([x, y], i) => (
        <circle key={i} cx={x} cy={y} r="2" fill={c(i % 3)} />
      ))}
    </svg>
  );
}
```

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

### chart-studio/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 };
}
```