# Cohort retention

> A retention card: weekly or monthly cohorts as a textured stream from oldest to newest, a tooltip with a leader to the band, week 1 by cohort and the best one flagged.

A product’s signups grouped by the week (or month) they joined, read in one card. The headline is the share of the oldest cohort still active at its latest period, beside everyone active today. Below it, every cohort’s active users stack day by day, oldest at the bottom, each band a colour from violet to orange under a texture of its own: dots, fine dots, level lines or diagonals. Hover or walk the bands with the arrow keys to read a cohort’s period; hover a swatch in the legend to see one cohort alone, press it to hold it. Week 1 by cohort lines them up at their first week, the best in lime, the current one dashed while its week 1 runs. W / M reads it all again by the month. Light and dark.

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

Category: Dashboards.

## Anatomy

1. **Header**: The chart’s mark, the title and the cadence (Weekly or Monthly cohorts).
2. **Switch**: W and M as a radio group: the whole card is read again from the other matrix.
3. **Headline**: The share of the oldest cohort still active at its latest period; with a cohort held, that cohort’s.
4. **Total**: Everyone active today across the cohorts, or the held cohort alone.
5. **Stream**: Every cohort’s active users day by day, oldest at the bottom, each band a colour under a texture. Arrow keys walk cohorts and periods.
6. **Tooltip**: The cohort, its period and the share retained, with a dotted leader to a ring on the band.
7. **Axis**: The first cohort’s date, the middle one’s and the newest, each placed where its band starts.
8. **Legend**: Oldest to Newest, a swatch per cohort: hover to see one alone, press to hold it.
9. **Week 1 bars**: Each cohort’s first-week share as a bar, the best in lime, the current cohort dashed while its week 1 is in progress.
10. **Rows**: The week 1 average and the best cohort, with its swatch.

## Properties

### Palette (`palette`)

1. **Spectrum (default)**: Violet through blue and green to orange, oldest to newest: neighbours stay far apart.
2. **Ember**: Wine through red to amber: one warm family, for a card where low retention is the point.

Leave it on spectrum, which keeps the most distance between neighbouring bands. The best cohort’s bar is lime on both, so it stands out either way.

### Opens on (`defaultPeriod`)

1. **Weekly (default)**: Cohorts by the week they joined; the headline and the bars read weeks.
2. **Monthly**: Cohorts by the month; fewer, thicker bands over a longer history.

Open on the cadence people use the product at. A cadence missing from `data` is ignored, and the card opens on the one it has.

### Cadences (`data`)

1. **Weekly and monthly (default)**: Both matrices: the W / M switch reads the card again from the other.
2. **One cadence**: Only `week` (or only `month`): the switch is left out of the header.

Pass both once there are enough months to make a monthly view worth reading; until then, one cadence and no switch.

## When to use

- A product’s signups grouped by the week or month they joined, where the question is how many stay and whether newer cohorts stay better.
- A dashboard tile that has to carry one figure (the share still active at the oldest cohort’s age) with the shape behind it a hover away.
- Comparing cohorts at the same age: the week 1 bars line every cohort up at its first week, with the best one flagged.
- Up to a dozen cohorts. Each gets its own colour and texture, so bands stay apart in print, for colour-blind readers and when isolated.

## When not to use

- A full retention table with every cohort at every age. Use a triangle heatmap; the stream shows people over time, not shares by age.
- More than a dozen cohorts. The bands get too thin to point at; switch to monthly, or show the latest dozen.
- Revenue retention, where expansion can push a cohort over 100%. The bands only shrink; use a line per cohort instead.
- A single number for a status bar. Show the headline as a stat with its change; the chart needs about 300 px to read.
- Live counts that change by the minute. The card reads a settled matrix, one value per cohort and period.

### Reading the headline

- **The figure** is the share of the oldest cohort still active at its latest period: `24% still active at week 8`. Cohorts that have reached the same period are averaged in by size.
- **The total under it** is everyone active today, across every cohort.
- **With a cohort hovered or held**, both read that cohort alone, and the line says which: `of Sep 29 still active at week 4`.
- **The period in progress** reads `so far` in the tooltip, and a cohort still in its week 1 has a dashed bar and no week 1 figure.

### Weekly or monthly

Weekly cohorts show a change in onboarding within days, but each band is a week of signups and twelve weeks is about the most the stream holds. Monthly cohorts carry half a year in six bands. When both are passed, W / M reads the headline, the stream, the bars and the rows again from the other matrix, and lets go of any cohort held.

### Stream vs. week 1 bars

**Stream**
- How many people each cohort still has, day by day, stacked into today’s total.
- Read a cohort at any period from the tooltip.
- Answers: is the active base growing, and which cohorts make it up?

**Week 1 bars**
- Every cohort’s share at the same age, side by side.
- The best in lime; hover or press one to read it alone.
- Answers: are newer cohorts staying better than older ones?

## Do’s and don’ts

- **Do**: Set `metric` to the one word that means staying, so the headline and the total read it: `still paying at week 8`.
- **Don’t**: Put a definition into `metric`. It is written into the headline and the total, and a phrase crowds both; explain the rule elsewhere.
- **Do**: Keep to a dozen cohorts or fewer, so every band is thick enough to point at and every swatch can be told apart.
- **Don’t**: Pass every week since launch. Sixteen bands turn into slivers; switch to monthly, or show the latest dozen.
- **Caution**: Ember draws every cohort in reds. Keep it for a card about poor retention, and say so in the title, so the colour isn’t read as an alarm on a healthy product.
- **Don’t**: Open the card with a cohort held. The big figure then belongs to one cohort, and a glance reads it as everyone’s.

## Content

The card writes most of its own words from the data: the cohorts’ dates, the shares and the counts. What you pass is the title and the metric.

- **A title of a word or two**, in sentence case: `Retention`, `Paid retention`. The subtitle already says Weekly or Monthly cohorts, so leave the cadence out.
- **A metric of one word** that fits `still … at week 8` and after the total: `active`, `paying`, `posting`.
- **Shares are whole percentages** and counts have thousands separators; don’t round the data for the card, it rounds when it writes.
- **Cohorts are named by their start**: Aug 25 for a week, Apr for a month.

## Installation

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

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

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 { CohortRetention, makeSeries } from './cohort-retention';

const week = makeSeries({
  period: 'week',
  first: '2026-08-25',
  count: 8,
  size: [1250, 1600],
  week1: 0.66,
  floor: 0.055,
  decay: 0.16,
  seed: 11,
});

export function RetentionTile() {
  return (
    <CohortRetention
      data={{ week }}
      title="Retention"
      metric="active"
      onCohortPin={(start) => console.log('Cohort', start)}
      autoplay={false}
    />
  );
}
```

## States

- **Weekly**: The default: eight weekly cohorts from Aug 25, 24% of the oldest still active at week 8.
- **Reading a band**: The Sep 8 cohort at week 4: the tooltip, its leader and ring; the other bands fade a little.
- **Signup week**: Period 0 of a cohort reads how many joined, not a share.
- **Monthly**: The `M` side: six monthly cohorts from April; the headline, total, bars and rows are read again.
- **Legend hover**: A swatch under the pointer shows its cohort alone and the headline reads it, until the pointer leaves.
- **Cohort held**: A pressed swatch (or bar) holds its cohort alone; pressing it again lets go.
- **Poor retention**: With `palette="ember"`, wine to amber: most people leave in week 1, and the best cohort stays lime against the reds.
- **Four cohorts**: A product a month old: only weekly data, so the switch is left out, and the newest is still in week 1.
- **No cohorts yet**: Before the first full period: a dashed box says when the first cohort appears.
- **Light**: With `colorScheme="light"` the card turns white and the band edges white; the cohorts keep their colours.
- **Dark**: With `colorScheme="dark"`: a near-black card with a lifted inner panel.
- **Narrow**: At 320 px the stage’s padding shrinks and the chart redraws at its width; the textures keep their size.

## Examples

### Monthly cohorts

The same product opened on M: six monthly cohorts from April, the headline at month 6, month 1 by cohort.

```tsx
import { CohortRetention } from './cohort-retention';
import { DATA } from './data';

/** Six months of cohorts, opened on M: the headline reads month 6. */
export function MonthlyCohorts() {
  return <CohortRetention autoplay={false} data={DATA} defaultPeriod="month" />;
}
```

### Poor retention

A product most people leave in week 1, on the ember palette: 6% still active at week 8, and the one cohort that did better flagged in lime.

```tsx
import { CohortRetention } from './cohort-retention';
import { LEAKY } from './data';

/** A product most people leave in the first week: wine to amber, the one good cohort in lime. */
export function PoorRetention() {
  return <CohortRetention autoplay={false} data={LEAKY} palette="ember" />;
}
```

### Short history

Four weeks since launch: only weekly cohorts, so no switch, and the newest still in its first week.

```tsx
import { CohortRetention } from './cohort-retention';
import { LAUNCH } from './data';

/** Four weeks since launch: no monthly view yet, so no switch. */
export function ShortHistory() {
  return <CohortRetention autoplay={false} data={LAUNCH} title="Launch retention" />;
}
```

### Paying subscribers

Paid plans by the week they converted, with the metric set to paying: a high, slow curve and a smaller total.

```tsx
import { CohortRetention } from './cohort-retention';
import { PAID } from './data';

/** Who is still paying, by the week they converted. */
export function PayingSubscribers() {
  return <CohortRetention autoplay={false} data={PAID} title="Paid retention" metric="paying" />;
}
```

## How it works

- The data is a cohort matrix: each cohort’s start, its size and the share still active in each period since, the last one in progress. makeSeries grows a plausible one from a seed (a share left after period 1, an exponential fall to a floor, a lift per cohort and a little noise), so the card is the same on every load.
- readSeries turns it into a stack sampled day by day: a cohort ramps up through its signup period, then follows its shares through the middle of each period with a smoothstep, times a weekday rhythm and a seeded wobble that make the ragged top. Bands stack oldest at the bottom.
- The chart is SVG drawn in px at the box’s own width (a ResizeObserver), so the textures never stretch. Each band is filled with a pattern: a rect in the cohort’s colour under dots, fine dots, level lines or rotated stripes in a translucent dark, with a hairline top edge in the card’s colour. Colours run along eight stops, mixed for any other count.
- The pointer picks the band under it from the stack on that day, or the top band when just over it, and snaps to that cohort’s period. The ring sits mid-band at the period’s middle; the tooltip goes beside it on the side with more room, above when it fits, and a dotted leader runs from its nearest corner.
- The legend’s swatches and the week 1 bars both isolate a cohort: hovering fades the others hard and reads the headline and total for that cohort alone; pressing holds it (aria-pressed) until pressed again. A hovered band only fades the others a little.
- Week 1 bars scale between just under the lowest share and the highest, so the differences show; the best is lime on any palette and the cohort whose week 1 is still running is a dashed outline. The rows give the average and the best cohort.
- W / M is a radio group; switching reads the other matrix again and the stream redraws with a clip-path reveal. With one cadence in the data the switch is left out.
- While on screen and untouched, a demo pointer reads a cohort along its weeks and two others, switches to monthly and back, peeks at two swatches and holds one. Any real input hands it over; it comes back after 8 s of quiet.

## API reference

- **data** (`{ week?: CohortSeries; month?: CohortSeries }`, default `eight weekly and six monthly cohorts`): The cohort matrices, each with its period, today’s date and its cohorts: start, size and the share retained per period, the last one in progress. With one of the two, the switch is left out.
- **defaultPeriod** (`'week' | 'month'`, default `'week'`): The cadence it opens on.
- **title** (`string`, default `'Retention'`): The card’s title; the subtitle says the cadence.
- **metric** (`string`, default `'active'`): What staying means, in the headline and the total: “still paying at week 8”.
- **palette** (`'spectrum' | 'ember'`, default `'spectrum'`): The bands’ colours, oldest to newest: violet to orange, or wine to amber. The best cohort is lime on both.
- **onPeriodChange** (`(period: 'week' | 'month') => void`): Called when W / M is switched.
- **onCohortPin** (`(start: string | null) => void`): Called with a cohort’s start date when it is held from the legend or the bars, and null when let go.
- **defaultState** (`CohortRetentionState`): Opens in a moment: a cadence, a cohort and period under the tooltip, a held or hovered cohort. It also 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

### Keyboard

- **W / M** is one tab stop; the arrow keys move the choice.
- **The chart** is one tab stop and, on focus, opens the oldest cohort at its latest period. Left and right walk periods, Home and End jump to the first and the latest, up and down move to the newer or older cohort, and Escape closes the tooltip, as does leaving the chart.
- **Swatches and bars** are buttons: Enter or Space holds a cohort and lets it go, and focus shows it alone as hover does.

### Not by colour alone

Each band has a texture as well as a colour, the best cohort is named in its bar’s label and in the Best cohort row as well as drawn in lime, and a week 1 in progress is a dashed outline whose label says `in progress` (WCAG 1.4.1, Use of color).

### Announcements

Switching cadence, holding or letting go of a cohort, and every reading made with the arrow keys are said in a polite live region, so they never interrupt (WCAG 4.1.3, Status messages). Pointer hovers are not announced.

### Target size

The W and M segments are 34 × 28 px. The legend’s swatches are 14 × 24 px targets round an 11 × 8 drawing and sit edge to edge, narrower than the 24 px minimum; the week 1 bars hold and show the same cohorts as 34 px tall buttons, about 28 px wide with eight cohorts at the card’s full width, which meets WCAG 2.5.8 (Target size, minimum) by its equivalent-control exception. With more cohorts, or on a narrower card, the bars narrow too, and under 24 px the exception no longer holds.

### Contrast and the demo

Every text colour reaches 4.5:1 on the panel and the card in both schemes, and the focus ring, the held segment’s edge and the dashed outline of a week 1 in progress reach 3:1 (WCAG 1.4.3 and 1.4.11). The demo pointer stops at the reader’s first input and doesn’t come back until the card remounts (WCAG 2.2.2); `autoplay={false}` turns it off, and under reduced motion it never plays.

### In this build

- The chart is a focusable application with a roledescription of chart and a label that says what it draws: how many cohorts, from when to when, oldest at the bottom, and the total today. Focus opens a cohort’s period; the arrow keys walk periods (left, right, Home, End) and cohorts (up, down), Escape closes the tooltip, and each reading is said in a polite live region.
- W / M is a radiogroup of two radios moved with the arrow keys; a switch announces the new headline and total.
- The legend’s swatches and the week 1 bars are buttons with aria-pressed, named by their cohort and, for the bars, the week 1 share, “the best” or “week 1 in progress”. Focus works as hover: the cohort shows alone.
- The bands keep a texture each, so they stay apart without colour. The summary rows are a description list.
- Under reduced motion nothing fades, grows or reveals and the demo never plays. The demo pointer is decorative.

## Source

### cohort-retention/cohort-retention.tsx

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

'use client';

import {
  useEffect,
  useEffectEvent,
  useId,
  useMemo,
  useRef,
  useState,
  type KeyboardEvent,
} from 'react';
import { StreamChart, spotPoint, type Spot } from './chart';
import {
  BEST,
  DATA,
  count,
  percent,
  readSeries,
  type CohortData,
  type Palette,
  type Period,
} from './data';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { useAutoplay } from './use-autoplay';
import styles from './cohort-retention.module.css';

/*
 * Cohort retention: a card that reads a product's signups by the week (or month) they joined.
 *
 * - W / M switches weekly and monthly cohorts; everything below is read again from that matrix.
 * - The headline is the share of the oldest cohort(s) still active at their latest period, and the
 *   total is everyone active today.
 * - The stream stacks every cohort's active users day by day, oldest at the bottom, each band in its
 *   colour and texture. Hover or focus it to read a cohort's period; arrows walk cohorts and periods.
 * - The legend's swatches and the week 1 bars isolate a cohort while hovered, and hold it pressed;
 *   the headline then reads that cohort alone.
 * - While on screen and untouched, a demo pointer reads a few bands, switches to monthly and back,
 *   and isolates a cohort from the legend, in a loop. The reader's first input stops it for good
 *   (until the component remounts).
 */

export type { Cohort, CohortData, CohortSeries, Palette, Period } from './data';
export { makeSeries } from './data';

/** A moment to open in, for the docs: it also keeps the demo off. */
export type CohortRetentionState = {
  period?: Period;
  /** The cohort and period the tooltip reads. */
  spot?: Spot;
  /** A cohort held from the legend. */
  pinned?: number;
  /** A cohort hovered in the legend or the bars. */
  peek?: number;
};

const UNIT: Record<Period, string> = { week: 'week', month: 'month' };
const CADENCE: Record<Period, string> = { week: 'Weekly', month: 'Monthly' };

function ChartIcon() {
  return (
    <svg viewBox="0 0 18 18" width="18" height="18" aria-hidden="true">
      <path
        d="M2.5 2.5v13h13"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
      />
      <path
        d="M6 12.5V9.5M8.6 12.5V6.5M11.2 12.5v-4M13.8 12.5V5"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
      />
    </svg>
  );
}

export function CohortRetention({
  data = DATA,
  defaultPeriod,
  title = 'Retention',
  metric = 'active',
  palette = 'spectrum',
  onPeriodChange,
  onCohortPin,
  defaultState,
  autoplay = true,
  colorScheme,
  className = '',
}: {
  /** The weekly and monthly cohorts; with only one, the switch is left out. */
  data?: CohortData;
  defaultPeriod?: Period;
  title?: string;
  /** What staying means: "active", "paying", "posting"… */
  metric?: string;
  /** The bands' colours, oldest to newest: violet to orange, or wine to amber. */
  palette?: Palette;
  onPeriodChange?: (period: Period) => void;
  /** Called with the cohort's start date when one is held from the legend or the bars, or null. */
  onCohortPin?: (start: string | null) => void;
  defaultState?: CohortRetentionState;
  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 periods = (['week', 'month'] as Period[]).filter((p) => data[p]);
  const firstPeriod =
    defaultState?.period ?? (defaultPeriod && data[defaultPeriod] ? defaultPeriod : periods[0]);
  const [period, setPeriod] = useState<Period>(firstPeriod ?? 'week');
  const [spot, setSpot] = useState<Spot | null>(defaultState?.spot ?? null);
  const [pinned, setPinned] = useState<number | null>(defaultState?.pinned ?? null);
  const [peek, setPeek] = useState<number | null>(defaultState?.peek ?? null);
  const [said, setSaid] = useState('');

  const series = data[period];
  const reading = useMemo(
    () => readSeries(series ?? { period, now: '2026-10-23', cohorts: [] }, palette),
    [series, period, palette],
  );
  const { cohorts } = reading;
  const unit = UNIT[period];
  const Unit = unit[0].toUpperCase() + unit.slice(1);

  // ---- What is read --------------------------------------------------------------------------------

  const held = peek ?? pinned;
  const heldCohort = held !== null ? cohorts[held] : undefined;
  const activeNow = (i: number) => {
    const [low, high] = reading.stack[i][reading.span];
    return high - low;
  };
  const headline = heldCohort
    ? {
        share: heldCohort.retained[heldCohort.latest],
        text: `of ${heldCohort.label} still ${metric} at ${unit} ${heldCohort.latest}`,
        total: `${count(activeNow(heldCohort.index))} ${metric}`,
      }
    : {
        share: reading.headline,
        text:
          reading.headline === null
            ? `no ${unit} 1 yet`
            : `still ${metric} at ${unit} ${reading.horizon}`,
        total: `${count(reading.total)} ${metric}`,
      };

  const tipOf = (s: Spot | null) => {
    const cohort = s && cohorts[s.cohort];
    if (!s || !cohort) return null;
    const share = cohort.retained[s.period];
    const going = s.period === cohort.latest ? ' so far' : '';
    return {
      title: `${cohort.label} cohort · ${unit} ${s.period}`,
      value: s.period === 0 ? `${count(cohort.size)} joined` : `${percent(share)} retained${going}`,
    };
  };
  const tip = tipOf(spot);

  const first = cohorts[0];
  const last = cohorts[cohorts.length - 1];
  const chartLabel = cohorts.length
    ? `Stacked area chart of ${cohorts.length} ${CADENCE[period].toLowerCase()} cohorts from ${first.label} to ${last.label}, oldest at the bottom. ${headline.total} today. Arrow keys read each cohort by ${unit}.`
    : 'No cohorts yet.';

  // ---- Acting ------------------------------------------------------------------------------------

  const choosePeriod = (next: Period) => {
    if (next === period || !data[next]) return;
    setPeriod(next);
    setSpot(null);
    setPinned(null);
    setPeek(null);
    onPeriodChange?.(next);
    const read = readSeries(data[next]!, palette);
    setSaid(
      `${CADENCE[next]} cohorts: ${
        read.headline === null
          ? 'no figure yet'
          : `${percent(read.headline)} still ${metric} at ${UNIT[next]} ${read.horizon}`
      }, ${count(read.total)} ${metric}.`,
    );
  };

  const pin = (i: number) => {
    const next = pinned === i ? null : i;
    setPinned(next);
    onCohortPin?.(next === null ? null : cohorts[next].start);
    setSaid(
      next === null
        ? 'All cohorts shown.'
        : `${cohorts[next].label} cohort alone: ${percent(cohorts[next].retained[cohorts[next].latest])} still ${metric} at ${unit} ${cohorts[next].latest}.`,
    );
  };

  const onSwitchKey = (event: KeyboardEvent<HTMLButtonElement>) => {
    if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) return;
    event.preventDefault();
    const at = periods.indexOf(period);
    const step = event.key === 'ArrowLeft' || event.key === 'ArrowUp' ? -1 : 1;
    const next = periods[(at + step + periods.length) % periods.length];
    choosePeriod(next);
    root.current?.querySelector<HTMLElement>(`[data-period="${next}"]`)?.focus();
  };

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

  const demo = autoplay && !defaultState && playing;
  const dirty = useEffectEvent(
    () => period !== (firstPeriod ?? 'week') || pinned !== null || peek !== null || spot !== null,
  );
  const reset = useEffectEvent(() => {
    setPeriod(firstPeriod ?? 'week');
    setSpot(null);
    setPinned(null);
    setPeek(null);
  });
  /** Where a cohort's period is, in the stage's px, in the reading on screen. */
  const spotAt = useEffectEvent((s: Spot, stage: HTMLElement): Point | null => {
    const box = stage.querySelector<HTMLElement>('[data-part="chart"] [role="application"]');
    if (!box || !cohorts[s.cohort]) return null;
    const frame = stage.getBoundingClientRect();
    const scale = frame.width / stage.offsetWidth || 1;
    const rect = box.getBoundingClientRect();
    const at = spotPoint(reading, box.clientWidth, {
      cohort: s.cohort,
      period: Math.min(s.period, cohorts[s.cohort].latest),
    });
    return { x: (rect.left - frame.left) / scale + at.x, y: (rect.top - frame.top) / scale + at.y };
  });
  const demoClear = useEffectEvent(() => {
    setSpot(null);
    setPeek(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,
      };
    };
    const stop = runDemo(stage, arrow, async ({ wait, glide, glyph }) => {
      /** Moves over a band and reads it, as a hover would. */
      const read = async (s: Spot, ms: number, after: number) => {
        const to = spotAt(s, stage);
        if (!to) return;
        glyph('arrow');
        await glide({ x: to.x + 2, y: to.y + 2 }, ms);
        setSpot(s);
        await wait(after);
      };
      const press = async (name: string, ms: number, after: number) => {
        const element = find(name);
        if (!element) return;
        glyph('arrow');
        await glide(on(element), ms);
        glyph('hand');
        element.dataset.over = '';
        await wait(260);
        delete element.dataset.over;
        (find(name) ?? element).click();
        await wait(after);
      };
      /** Hovers a swatch: its cohort alone while the pointer is on it. */
      const hover = async (name: string, i: number | null, ms: number, after: number) => {
        const element = find(name);
        if (!element) return;
        glyph('hand');
        await glide(on(element), ms);
        setPeek(i);
        await wait(after);
      };
      for (;;) {
        if (dirty()) {
          reset();
          await wait(500);
        }
        await wait(900);
        // One cohort, read along its weeks, then two others.
        await read({ cohort: 2, period: 1 }, 900, 500);
        await read({ cohort: 2, period: 2 }, 380, 380);
        await read({ cohort: 2, period: 4 }, 520, 1500);
        await read({ cohort: 5, period: 2 }, 650, 1400);
        await read({ cohort: 0, period: 8 }, 650, 1400);
        setSpot(null);
        // The same people by the month, and back.
        await press('period-month', 750, 1300);
        await read({ cohort: 2, period: 2 }, 700, 1500);
        setSpot(null);
        await press('period-week', 700, 1100);
        // One cohort alone from the legend: peeked, held, let go.
        await hover('swatch-1', 1, 750, 900);
        await hover('swatch-5', 5, 420, 600);
        await press('swatch-5', 200, 1800);
        setPeek(null);
        await press('swatch-5', 400, 700);
        glyph('arrow');
        await glide(on(stage, 0.84, 0.94), 800);
        await wait(1600);
      }
    });
    return () => {
      stop();
      stage.querySelectorAll<HTMLElement>('[data-over]').forEach((el) => delete el.dataset.over);
      demoClear();
    };
  }, [demo, root]);

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

  const week1s = cohorts.map((cohort) => cohort.week1).filter((v): v is number => v !== null);
  const lo = week1s.length ? Math.min(...week1s) - 0.08 : 0;
  const hi = week1s.length ? Math.max(...week1s) : 1;
  const barHeight = (v: number) => 7 + ((v - lo) / (hi - lo || 1)) * 21;

  // The dates under the chart: the first cohort, the middle one (past four) and the newest.
  const ticks = cohorts.length
    ? [
        ...new Set(
          cohorts.length > 4
            ? [0, Math.floor((cohorts.length - 1) / 2), cohorts.length - 1]
            : [0, cohorts.length - 1],
        ),
      ].map((i) => ({
        i,
        at: cohorts[i].from / reading.span,
      }))
    : [];

  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();
      }}
    >
      <section className={styles.card} aria-labelledby={`${uid}-title`} data-part="card">
        <header className={styles.header} data-part="header">
          <span className={styles.icon}>
            <ChartIcon />
          </span>
          <div className={styles.heading}>
            <h2 id={`${uid}-title`} className={styles.title}>
              {title}
            </h2>
            <p className={styles.subtitle}>{CADENCE[period]} cohorts</p>
          </div>
          {periods.length > 1 && (
            <div
              className={styles.switch}
              role="radiogroup"
              aria-label="Cohorts by"
              data-part="switch"
            >
              {periods.map((p) => (
                <button
                  key={p}
                  type="button"
                  role="radio"
                  aria-checked={p === period}
                  aria-label={`${CADENCE[p]} cohorts`}
                  tabIndex={p === period ? 0 : -1}
                  className={styles.segment}
                  data-period={p}
                  data-demo={`period-${p}`}
                  onClick={() => choosePeriod(p)}
                  onKeyDown={onSwitchKey}
                >
                  {p === 'week' ? 'W' : 'M'}
                </button>
              ))}
            </div>
          )}
        </header>

        <div className={styles.panel} data-part="panel">
          <p className={styles.headline} data-part="headline">
            <strong>{headline.share === null ? '—' : percent(headline.share)}</strong>
            <span>{headline.text}</span>
          </p>

          {cohorts.length ? (
            <StreamChart
              reading={reading}
              uid={uid}
              spot={spot}
              isolated={held ?? spot?.cohort ?? null}
              soft={held === null}
              tip={tip}
              label={chartLabel}
              total={headline.total}
              onSpot={(next, by) => {
                setSpot(next);
                if (by === 'key') {
                  const words = tipOf(next);
                  setSaid(words ? `${words.title}: ${words.value}.` : '');
                }
              }}
              onLeave={() => setSpot(null)}
            />
          ) : (
            <div className={styles.empty} data-part="chart">
              <span>No cohorts yet</span>
              <span>The first one appears a {unit} after signups start.</span>
            </div>
          )}

          <div className={styles.axis} aria-hidden="true" data-part="axis">
            {ticks.map(({ i, at }, n) => (
              <span
                key={i}
                style={{
                  left: `${at * 100}%`,
                  translate: n === 0 ? '0' : n === ticks.length - 1 && at > 0.8 ? '-100%' : '-50%',
                }}
              >
                {cohorts[i].label}
              </span>
            ))}
          </div>

          {cohorts.length > 0 && (
            <div className={styles.legend} data-part="legend">
              <span>Oldest</span>
              <div
                className={styles.swatches}
                role="group"
                aria-label="Show one cohort alone"
                onPointerLeave={() => setPeek(null)}
              >
                {cohorts.map((cohort) => (
                  <button
                    key={cohort.index}
                    type="button"
                    className={styles.swatch}
                    aria-label={`${cohort.label} cohort`}
                    aria-pressed={pinned === cohort.index}
                    data-demo={`swatch-${cohort.index}`}
                    data-part="swatch"
                    data-dim={held !== null && held !== cohort.index ? '' : undefined}
                    style={{ ['--c' as string]: cohort.colour }}
                    onPointerEnter={() => setPeek(cohort.index)}
                    onFocus={() => setPeek(cohort.index)}
                    onBlur={() => setPeek(null)}
                    onClick={() => pin(cohort.index)}
                  />
                ))}
              </div>
              <span>Newest</span>
            </div>
          )}

          {cohorts.length > 0 && (
            <div className={styles.firsts} data-part="week1">
              <div className={styles.firstsHead}>
                <span>{Unit} 1 by cohort</span>
                <span>avg {reading.average === null ? '—' : percent(reading.average)}</span>
              </div>
              <div
                className={styles.bars}
                role="group"
                aria-label={`${Unit} 1 retention by cohort`}
                onPointerLeave={() => setPeek(null)}
              >
                {cohorts.map((cohort) => {
                  const best = cohort.index === reading.best;
                  return (
                    <button
                      key={cohort.index}
                      type="button"
                      className={styles.bar}
                      aria-label={
                        cohort.week1 === null
                          ? `${cohort.label}: ${unit} 1 in progress`
                          : `${cohort.label}: ${percent(cohort.week1)} in ${unit} 1${best ? ', the best' : ''}`
                      }
                      aria-pressed={pinned === cohort.index}
                      data-part="bar"
                      data-best={best ? '' : undefined}
                      data-open={cohort.week1 === null ? '' : undefined}
                      data-dim={held !== null && held !== cohort.index ? '' : undefined}
                      style={{
                        ['--c' as string]: best ? BEST : cohort.colour,
                        ['--h' as string]: `${cohort.week1 === null ? 8 : barHeight(cohort.week1)}px`,
                      }}
                      onPointerEnter={() => setPeek(cohort.index)}
                      onFocus={() => setPeek(cohort.index)}
                      onBlur={() => setPeek(null)}
                      onClick={() => pin(cohort.index)}
                    >
                      <span />
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          <dl className={styles.rows} data-part="rows">
            <div>
              <dt>{Unit} 1 average</dt>
              <dd>{reading.average === null ? '—' : percent(reading.average)}</dd>
            </div>
            <div>
              <dt>Best cohort</dt>
              <dd>
                {reading.best === null ? (
                  '—'
                ) : (
                  <>
                    {cohorts[reading.best].label}
                    <i className={styles.bestDot} aria-hidden="true" />
                  </>
                )}
              </dd>
            </div>
          </dl>
        </div>
        <p className={styles.srOnly} aria-live="polite">
          {said}
        </p>
      </section>

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

### cohort-retention/chart.tsx

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

'use client';

import { useLayoutEffect, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react';
import { anchorDay, PERIOD_DAYS, type Reading, type Texture } from './data';
import styles from './cohort-retention.module.css';

/*
 * The stream of cohorts: one band per cohort stacked oldest at the bottom, each filled with its
 * colour under a texture of its own (an SVG pattern), drawn in px at the box's own width so the
 * textures never stretch. The pointer picks the band under it and snaps to that cohort's period;
 * the arrow keys walk the same points. The tooltip sits beside the point, a dotted leader back to
 * a ring on the band.
 */

/** The chart's height in px; its width is the box's. */
export const CHART_HEIGHT = 148;
/** Headroom over the tallest day, so the ragged top never touches the total. */
const HEADROOM = 1.18;

export type Spot = { cohort: number; period: number };

/** Where a cohort's period sits in the chart: its band's middle on the day it is read. */
export function spotPoint(reading: Reading, width: number, { cohort, period }: Spot) {
  const day = anchorDay(reading, cohort, period);
  const d = Math.round(day);
  const [low, high] = reading.stack[cohort][d] ?? [0, 0];
  const y = (v: number) => CHART_HEIGHT - (v / (reading.peak * HEADROOM)) * CHART_HEIGHT;
  return { x: (day / reading.span) * width, y: (y(low) + y(high)) / 2 };
}

/** The pattern laid over a band's colour: dots, fine dots, level lines or diagonals. */
function Pattern({ id, colour, texture }: { id: string; colour: string; texture: Texture }) {
  const ink = 'rgb(0 0 0 / 0.34)';
  switch (texture) {
    case 'dots':
      return (
        <pattern id={id} width="5" height="5" patternUnits="userSpaceOnUse">
          <rect width="5" height="5" fill={colour} />
          <circle cx="1.25" cy="1.25" r="0.85" fill={ink} />
          <circle cx="3.75" cy="3.75" r="0.85" fill={ink} />
        </pattern>
      );
    case 'fine':
      return (
        <pattern id={id} width="3.5" height="3.5" patternUnits="userSpaceOnUse">
          <rect width="3.5" height="3.5" fill={colour} />
          <circle cx="1.75" cy="1.75" r="0.7" fill={ink} />
        </pattern>
      );
    case 'lines':
      return (
        <pattern id={id} width="4" height="3.4" patternUnits="userSpaceOnUse">
          <rect width="4" height="3.4" fill={colour} />
          <rect y="2.4" width="4" height="1" fill={ink} />
        </pattern>
      );
    case 'diagonal':
      return (
        <pattern
          id={id}
          width="4"
          height="4"
          patternUnits="userSpaceOnUse"
          patternTransform="rotate(-38)"
        >
          <rect width="4" height="4" fill={colour} />
          <rect width="1.2" height="4" fill={ink} />
        </pattern>
      );
  }
}

export function StreamChart({
  reading,
  uid,
  spot,
  isolated,
  soft,
  tip,
  label,
  total,
  onSpot,
  onLeave,
}: {
  reading: Reading;
  /** A prefix for the pattern ids, unique to the card. */
  uid: string;
  spot: Spot | null;
  /** The cohort drawn alone, the others faded. */
  isolated: number | null;
  /** A light fade, as a hover gives, instead of the legend's strong one. */
  soft: boolean;
  tip: { title: string; value: string } | null;
  /** The chart in words. */
  label: string;
  /** "5,204 active", over the top right. */
  total: string;
  onSpot: (spot: Spot | null, by: 'pointer' | 'key') => void;
  onLeave: () => void;
}) {
  const box = useRef<HTMLDivElement>(null);
  const tipBox = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(280);
  const [tipSize, setTipSize] = useState({ w: 150, h: 46 });

  useLayoutEffect(() => {
    const element = box.current;
    if (!element) return;
    const read = () => setWidth(Math.max(120, element.clientWidth));
    read();
    const observer = new ResizeObserver(read);
    observer.observe(element);
    return () => observer.disconnect();
  }, []);

  useLayoutEffect(() => {
    const element = tipBox.current;
    if (!element) return;
    const w = element.offsetWidth;
    const h = element.offsetHeight;
    setTipSize((now) => (now.w === w && now.h === h ? now : { w, h }));
  }, [tip?.title, tip?.value]);

  const { cohorts, stack, span, peak } = reading;
  const x = (d: number) => (d / span) * width;
  const y = (v: number) => CHART_HEIGHT - (v / (peak * HEADROOM || 1)) * CHART_HEIGHT;
  const f = (n: number) => Math.round(n * 10) / 10;

  // Each band from the day its cohort starts: the top edge forward, the bottom edge back.
  const bands = cohorts.map((cohort, i) => {
    const from = Math.max(0, Math.floor(cohort.from));
    const top: string[] = [];
    const bottom: string[] = [];
    for (let d = from; d <= span; d += 1) {
      const [low, high] = stack[i][d];
      top.push(`${f(x(d))},${f(y(high))}`);
      bottom.unshift(`${f(x(d))},${f(y(low))}`);
    }
    return {
      area: `M${top.join('L')}L${bottom.join('L')}Z`,
      edge: `M${top.join('L')}`,
    };
  });

  /** The cohort under a point of the chart, and the period it is in on that day. */
  const pick = (px: number, py: number): Spot | null => {
    const d = Math.max(0, Math.min(span, Math.round((px / width) * span)));
    let found = -1;
    for (let i = cohorts.length - 1; i >= 0; i -= 1) {
      const [low, high] = stack[i][d];
      if (high - low < 0.5) continue;
      if (found === -1 && py < y(high)) {
        // Over the top of the stack: the band just under, when near enough.
        if (y(high) - py <= 18) found = i;
        break;
      }
      if (py >= y(high) && py <= y(low)) {
        found = i;
        break;
      }
    }
    if (found === -1) return null;
    const cohort = cohorts[found];
    const age = (d - cohort.from) / PERIOD_DAYS[reading.period];
    return { cohort: found, period: Math.max(0, Math.min(cohort.latest, Math.floor(age))) };
  };

  const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
    const rect = event.currentTarget.getBoundingClientRect();
    const scale = rect.width / event.currentTarget.offsetWidth || 1;
    onSpot(
      pick((event.clientX - rect.left) / scale, (event.clientY - rect.top) / scale),
      'pointer',
    );
  };

  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (!cohorts.length) return;
    const now = spot ?? { cohort: 0, period: cohorts[0].latest };
    const at = cohorts[now.cohort];
    let next: Spot | null = now;
    switch (event.key) {
      case 'ArrowRight':
        next = { ...now, period: Math.min(at.latest, now.period + 1) };
        break;
      case 'ArrowLeft':
        next = { ...now, period: Math.max(0, now.period - 1) };
        break;
      case 'ArrowUp':
      case 'ArrowDown': {
        const step = event.key === 'ArrowUp' ? 1 : -1;
        const c = Math.max(0, Math.min(cohorts.length - 1, now.cohort + step));
        next = { cohort: c, period: Math.min(cohorts[c].latest, now.period) };
        break;
      }
      case 'Home':
        next = { ...now, period: 0 };
        break;
      case 'End':
        next = { ...now, period: at.latest };
        break;
      case 'Escape':
        next = null;
        break;
      default:
        return;
    }
    event.preventDefault();
    onSpot(next, 'key');
  };

  const point = spot && cohorts[spot.cohort] ? spotPoint(reading, width, spot) : null;
  // The tooltip beside the point, on the side with more room; above it when it fits.
  let place: { left: number; top: number; cx: number; cy: number } | null = null;
  if (point) {
    const { w, h } = tipSize;
    const gap = 26;
    const leftSide = point.x > width / 2;
    const left = Math.max(0, Math.min(width - w, leftSide ? point.x - w - gap : point.x + gap));
    // Above: at the top of the chart, so the leader runs up to it; else just under the point.
    const above = point.y - h - 18 >= 0;
    const top = above ? 0 : point.y + 18;
    place = {
      left,
      top,
      cx: leftSide ? left + w - 8 : left + 8,
      cy: above ? top + h : top,
    };
  }

  return (
    <div className={styles.chartWrap} data-part="chart">
      <span className={styles.total} data-part="total">
        {total}
      </span>
      {/* An application: screen readers hand it the arrow keys, which walk cohorts and periods. */}
      {/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */}
      <div
        ref={box}
        className={styles.chart}
        role="application"
        aria-roledescription="chart"
        aria-label={label}
        // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex
        tabIndex={0}
        style={{ height: CHART_HEIGHT }}
        onPointerMove={onPointerMove}
        onPointerLeave={onLeave}
        onKeyDown={onKeyDown}
        onFocus={() => {
          // Focus opens the oldest cohort at its latest period, where the arrow keys start too.
          if (spot || !cohorts.length) return;
          onSpot({ cohort: 0, period: cohorts[0].latest }, 'key');
        }}
        onBlur={onLeave}
      >
        <svg
          key={`${reading.period}-${cohorts.length}`}
          className={styles.stream}
          width={width}
          height={CHART_HEIGHT}
          aria-hidden="true"
        >
          <defs>
            {cohorts.map((cohort) => (
              <Pattern
                key={cohort.index}
                id={`${uid}-tex-${cohort.index}`}
                colour={cohort.colour}
                texture={cohort.texture}
              />
            ))}
          </defs>
          {bands.map((band, i) => (
            <g
              key={i}
              className={styles.band}
              data-part="band"
              data-cohort={i}
              data-dim={isolated !== null && isolated !== i ? (soft ? 'soft' : 'hard') : undefined}
            >
              <path d={band.area} fill={`url(#${uid}-tex-${i})`} />
              <path d={band.edge} className={styles.edge} />
            </g>
          ))}
          {point && place && (
            <g className={styles.marker} data-part="ring">
              <line
                x1={place.cx}
                y1={place.cy}
                x2={point.x}
                y2={point.y}
                className={styles.leader}
              />
              <circle cx={point.x} cy={point.y} r="6.5" className={styles.ring} />
            </g>
          )}
        </svg>
        {tip && place && spot && (
          <div
            ref={tipBox}
            className={styles.tooltip}
            data-part="tooltip"
            style={{ left: place.left, top: place.top }}
          >
            <span className={styles.tipTitle}>{tip.title}</span>
            <span className={styles.tipValue}>
              <i style={{ background: cohorts[spot.cohort].colour }} aria-hidden="true" />
              {tip.value}
            </span>
          </div>
        )}
      </div>
    </div>
  );
}
```

### cohort-retention/cohort-retention.module.css

```css
/* Cohort retention (cohort-retention.tsx): a card on a grey stage, near-black by night and white by
   day. A header with the chart's mark, the title and the W / M switch; an inset panel holds the
   headline, the stream of cohorts (chart.tsx), the legend, week 1 by cohort and two rows.

   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 cohorts' own colours come from data.ts, the same on both. Text tokens
   reach 4.5:1 on the panel, and the focus ring, the held segment's edge and the dashed outline
   3:1, in both schemes. */

.root {
  --stage: #e9e9ec;
  --card: #ffffff;
  --card-edge: #e2e2e6;
  --panel: #f7f7f8;
  --panel-edge: #ebebee;
  --line: #e8e8eb;
  --ink: #18181b;
  --ink-2: #6e6e76;
  --ink-3: #717177;
  --seg: #ffffff;
  --seg-edge: #949498;
  --tip: #ffffff;
  --tip-edge: #e4e4e8;
  --ring: #18181b;
  --edge: rgb(255 255 255 / 0.75);
  --dashed: #8f8f94;
  --shadow: rgb(0 0 0 / 0.08);
  --tip-shadow: rgb(0 0 0 / 0.14);
  --best: #8fbf1f;
  --focus: #637fe8;
  /* The same on both schemes. */
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.3);
  --sans: var(--body, Inter, ui-sans-serif, system-ui, sans-serif);
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --stage: light-dark(#e9e9ec, #2a2a2d);
    --card: light-dark(#ffffff, #121213);
    --card-edge: light-dark(#e2e2e6, #2a2a2c);
    --panel: light-dark(#f7f7f8, #1a1a1b);
    --panel-edge: light-dark(#ebebee, #29292b);
    --line: light-dark(#e8e8eb, #29292b);
    --ink: light-dark(#18181b, #f0f0f2);
    --ink-2: light-dark(#6e6e76, #a2a2a8);
    --ink-3: light-dark(#717177, #828289);
    --seg: light-dark(#ffffff, #262628);
    --seg-edge: light-dark(#949498, #6f6f71);
    --tip: light-dark(#ffffff, #2a2a2c);
    --tip-edge: light-dark(#e4e4e8, #3a3a3d);
    --ring: light-dark(#18181b, #ffffff);
    --edge: light-dark(rgb(255 255 255 / 0.75), rgb(14 14 15 / 0.85));
    --dashed: light-dark(#8f8f94, #66666a);
    --shadow: light-dark(rgb(0 0 0 / 0.08), rgb(0 0 0 / 0.5));
    --tip-shadow: light-dark(rgb(0 0 0 / 0.14), rgb(0 0 0 / 0.55));
    --best: light-dark(#8fbf1f, #c3e64f);
    --focus: light-dark(#637fe8, #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;
  display: grid;
  place-items: center;
  width: 100%;
  padding: clamp(16px, 8%, 48px) clamp(12px, 5%, 24px);
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background: var(--stage);
  color: var(--ink);
  font-family: var(--sans);
  font-size: 13px;
  line-height: 1.35;
  -webkit-tap-highlight-color: transparent;
}
.root :where(button) {
  font: inherit;
  color: inherit;
  cursor: pointer;
}
.root :focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}
.root svg {
  display: block;
  flex: none;
}
.srOnly {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

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

.card {
  width: 100%;
  max-width: 336px;
  padding: 4px;
  border: 1px solid var(--card-edge);
  border-radius: 18px;
  background: var(--card);
  box-shadow: 0 22px 44px -22px var(--shadow);
}

.header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 12px 14px 16px;
}
.icon {
  display: grid;
  place-items: center;
  color: var(--ink-2);
}
.heading {
  flex: 1;
  min-width: 0;
}
.title {
  margin: 0;
  font-size: 15px;
  font-weight: 560;
  line-height: 1.25;
  letter-spacing: -0.005em;
}
.subtitle {
  margin: 1px 0 0;
  color: var(--ink-2);
  font-size: 13px;
}

.switch {
  display: flex;
  gap: 4px;
}
.segment {
  width: 34px;
  height: 28px;
  padding: 0;
  border: 1px solid transparent;
  border-radius: 8px;
  background: none;
  color: var(--ink-2);
  font-size: 13px;
  font-weight: 600;
  transition:
    background-color 0.15s ease,
    color 0.15s ease;
}
.segment:hover,
.segment[data-over] {
  color: var(--ink);
}
.segment[aria-checked='true'] {
  border-color: var(--seg-edge);
  background: var(--seg);
  color: var(--ink);
  box-shadow: 0 1px 2px var(--shadow);
}

.panel {
  padding: 16px 14px 4px;
  border: 1px solid var(--panel-edge);
  border-radius: 14px;
  background: var(--panel);
}

.headline {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
  gap: 4px 9px;
  margin: 0 0 6px;
}
.headline strong {
  font-size: 28px;
  font-weight: 560;
  line-height: 1.1;
  letter-spacing: -0.03em;
  font-variant-numeric: tabular-nums;
}
.headline span {
  color: var(--ink-2);
  font-size: 13px;
}

/* ---- The stream ------------------------------------------------------------------------------- */

.chartWrap {
  position: relative;
  padding-top: 22px;
}
.total {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 13px;
  font-weight: 520;
  font-variant-numeric: tabular-nums;
}
.chart {
  position: relative;
  border-radius: 2px;
  touch-action: pan-y;
}
.chart:focus-visible {
  outline-offset: 4px;
}
.stream {
  overflow: visible;
  animation: reveal 0.7s cubic-bezier(0.3, 0, 0.2, 1);
}
@keyframes reveal {
  from {
    clip-path: inset(0 100% 0 0);
  }
  to {
    clip-path: inset(0 0 0 0);
  }
}
.band {
  transition: opacity 0.2s ease;
}
.band[data-dim='soft'] {
  opacity: 0.6;
}
.band[data-dim='hard'] {
  opacity: 0.16;
}
.edge {
  fill: none;
  stroke: var(--edge);
  stroke-width: 1;
  stroke-linejoin: round;
}
.marker {
  pointer-events: none;
}
.leader {
  stroke: var(--ring);
  stroke-width: 1.2;
  stroke-dasharray: 1.2 3;
  stroke-linecap: round;
  opacity: 0.7;
}
.ring {
  fill: rgb(0 0 0 / 0.12);
  stroke: var(--ring);
  stroke-width: 1.6;
}
.tooltip {
  position: absolute;
  display: grid;
  gap: 2px;
  padding: 7px 10px 7px 9px;
  border: 1px solid var(--tip-edge);
  border-radius: 9px;
  background: var(--tip);
  box-shadow: 0 10px 24px -8px var(--tip-shadow);
  white-space: nowrap;
  pointer-events: none;
}
.tipTitle {
  color: var(--ink-2);
  font-size: 12px;
}
.tipValue {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  font-weight: 540;
}
.tipValue i {
  width: 8px;
  height: 8px;
  border-radius: 2px;
}

.empty {
  display: grid;
  place-content: center;
  gap: 4px;
  height: 170px;
  border: 1px dashed var(--dashed);
  border-radius: 10px;
  color: var(--ink-2);
  text-align: center;
}
.empty span:first-child {
  color: var(--ink);
  font-weight: 540;
}

.axis {
  position: relative;
  height: 18px;
  margin: 12px 0 14px;
  color: var(--ink-3);
  font-size: 12.5px;
}
.axis span {
  position: absolute;
  top: 0;
  white-space: nowrap;
}

/* ---- Legend and week 1 ------------------------------------------------------------------------ */

.legend {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--ink-3);
  font-size: 12.5px;
}
.swatches {
  display: flex;
}
.swatch {
  position: relative;
  width: 14px;
  /* 24 px tall for the hit area (WCAG 2.5.8), the 3 px each way taken back by the margins, so the
     row keeps its height; the drawn swatch stays 11 × 8. */
  height: 24px;
  margin-block: -3px;
  padding: 0;
  border: 0;
  background: none;
}
.swatch::before {
  content: '';
  position: absolute;
  inset: 8px 1.5px;
  border-radius: 2px;
  background: var(--c);
  transition:
    opacity 0.15s ease,
    transform 0.15s ease;
}
.swatch:hover::before,
.swatch[data-over]::before,
.swatch[aria-pressed='true']::before {
  transform: scaleY(1.45);
}
.swatch[aria-pressed='true']::after {
  content: '';
  position: absolute;
  left: 4px;
  right: 4px;
  bottom: 2px;
  height: 2px;
  border-radius: 1px;
  background: var(--ink);
}
.swatch[data-dim]::before {
  opacity: 0.3;
}

.firsts {
  margin-top: 14px;
}
.firstsHead {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  color: var(--ink-2);
}
.firstsHead span:last-child {
  color: var(--ink);
  font-variant-numeric: tabular-nums;
}
.bars {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  height: 34px;
  margin-top: 10px;
}
.bar {
  flex: 1;
  display: flex;
  align-items: flex-end;
  height: 100%;
  min-width: 0;
  padding: 0;
  border: 0;
  background: none;
}
.bar span {
  display: block;
  width: 100%;
  height: var(--h);
  border-radius: 3px;
  background: color-mix(in oklab, var(--c) 62%, var(--panel));
  transition:
    opacity 0.15s ease,
    background-color 0.15s ease,
    height 0.4s cubic-bezier(0.3, 0, 0.2, 1);
}
.bar[data-best] span {
  background: var(--best);
}
.bar:hover span,
.bar[aria-pressed='true'] span {
  background: var(--c);
}
.bar[data-best]:hover span {
  background: var(--best);
}
.bar[data-open] span {
  border: 1px dashed var(--dashed);
  background: none;
}
.bar[data-dim] span {
  opacity: 0.35;
}

.rows {
  margin: 12px 0 0;
}
.rows div {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  padding: 11px 0;
  border-top: 1px solid var(--line);
}
.rows dt {
  color: var(--ink-2);
}
.rows dd {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-variant-numeric: tabular-nums;
}
.bestDot {
  width: 9px;
  height: 9px;
  border-radius: 2px;
  background: var(--best);
}

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

@container (max-width: 360px) {
  .header {
    padding-left: 12px;
  }
  .panel {
    padding-inline: 12px;
  }
  .headline strong {
    font-size: 25px;
  }
  .bars {
    gap: 7px;
  }
}

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

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

@media (prefers-reduced-motion: reduce) {
  .segment,
  .band,
  .swatch::before,
  .bar span {
    transition: none;
  }
  .stream {
    animation: none;
  }
}
```

### cohort-retention/data.ts

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

/*
 * The cohorts the card opens with, and what it reads from them.
 *
 * A cohort is everyone who signed up in one week (or month): its size, and the share of it still
 * active in each period since, period 0 being the one it signed up in. The last share is the
 * period in progress. makeSeries grows a plausible matrix from a seed, so the card looks the same
 * on every load; readSeries turns one into what the card draws: a day-by-day stack of every
 * cohort's active users, the headline at the oldest cohort's age, week 1 by cohort, the best.
 */

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

export type Cohort = {
  /** The first day of its period, YYYY-MM-DD. */
  start: string;
  /** How many signed up. */
  size: number;
  /** The share still active in each period since; [0] is 1, the last is in progress. */
  retained: number[];
};

export type CohortSeries = { period: Period; now: string; cohorts: Cohort[] };

export type CohortData = Partial<Record<Period, CohortSeries>>;

export type Palette = 'spectrum' | 'ember';

const DAY = 86_400_000;
/** A period's length in days. */
export const PERIOD_DAYS: Record<Period, number> = { week: 7, month: 30.44 };

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

const dayOf = (iso: string) => Math.round(Date.parse(`${iso}T00:00:00Z`) / DAY);
const isoOf = (day: number) => new Date(day * DAY).toISOString().slice(0, 10);

/** "Sep 8" for a week, "Sep" for a month. */
export function cohortLabel(iso: string, period: Period) {
  const date = new Date(`${iso}T00:00:00Z`);
  const month = MONTHS[date.getUTCMonth()];
  return period === 'week' ? `${month} ${date.getUTCDate()}` : month;
}

export const count = (n: number) => Math.round(n).toLocaleString('en-US');
export const percent = (share: number) => `${Math.round(share * 100)}%`;

// ---- A seeded matrix -----------------------------------------------------------------------------

/** A small seeded generator: the same seed, the same numbers. */
function seeded(seed: number) {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

/** A number in [-1, 1] for a cohort and a day, the same every time. */
function wobble(cohort: number, day: number, seed: number) {
  let h = Math.imul(cohort + 1, 374761393) ^ Math.imul(day + 7, 668265263) ^ seed;
  h = Math.imul(h ^ (h >>> 13), 1274126177);
  return (((h ^ (h >>> 16)) >>> 0) / 4294967295) * 2 - 1;
}

export type SeriesOptions = {
  period: Period;
  /** The first cohort's start, YYYY-MM-DD. */
  first: string;
  count: number;
  /** How far into the newest cohort's second period today is, in periods. */
  into?: number;
  /** The smallest and largest signups; later cohorts lean larger. */
  size: [number, number];
  /** The share left in period 1, on average. */
  week1: number;
  /** Where the curve settles, and how fast it gets there (per period, exponential). */
  floor: number;
  decay: number;
  /** Each cohort's lift over week1 (or drop, below 0); seeded when left out. */
  quality?: number[];
  seed: number;
};

/** A plausible cohort matrix: each curve falls fast and settles, with a little noise. */
export function makeSeries({
  period,
  first,
  count: n,
  into = 1.4,
  size,
  week1,
  floor,
  decay,
  quality,
  seed,
}: SeriesOptions): CohortSeries {
  const random = seeded(seed);
  const firstDay = dayOf(first);
  const startOf = (i: number) => {
    if (period === 'week') return firstDay + i * 7;
    const date = new Date(firstDay * DAY);
    return Math.round(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + i, 1) / DAY);
  };
  const nowDay = Math.round(startOf(n - 1) + into * PERIOD_DAYS[period]);
  const cohorts = Array.from({ length: n }, (_, i): Cohort => {
    const start = startOf(i);
    const lift = quality?.[i] ?? (random() - 0.5) * 0.08;
    const grown = size[0] + (size[1] - size[0]) * (n > 1 ? i / (n - 1) : 0);
    const age = Math.floor((nowDay - start) / PERIOD_DAYS[period]);
    const retained = [1];
    for (let k = 1; k <= age; k += 1) {
      const curve = floor + (week1 + lift - floor) * Math.exp(-decay * (k - 1));
      const noisy = curve + (random() - 0.5) * 0.025;
      retained.push(Math.max(0.01, Math.min(retained[k - 1], noisy)));
    }
    return {
      start: isoOf(start),
      size: Math.round(grown * (0.92 + random() * 0.16)),
      retained: retained.map((share) => Math.round(share * 1000) / 1000),
    };
  });
  return { period, now: isoOf(nowDay), cohorts };
}

/** Eight weekly cohorts from Aug 25, the Sep 29 one the stickiest. */
export const WEEKLY = makeSeries({
  period: 'week',
  first: '2026-08-25',
  count: 8,
  size: [1250, 1600],
  week1: 0.66,
  floor: 0.055,
  decay: 0.16,
  quality: [-0.035, -0.02, -0.01, 0.01, 0.02, 0.08, 0.04, 0],
  seed: 11,
});

/** Six monthly cohorts from April. */
export const MONTHLY = makeSeries({
  period: 'month',
  first: '2026-04-01',
  count: 6,
  into: 1.75,
  size: [6100, 8300],
  week1: 0.52,
  floor: 0.12,
  decay: 0.3,
  quality: [-0.04, -0.01, 0.02, 0.06, 0.01, 0.03],
  seed: 23,
});

export const DATA: CohortData = { week: WEEKLY, month: MONTHLY };

// ---- Other products, for the examples and the docs ----------------------------------------------

/** A product most people leave in its first week; one cohort did better. */
export const LEAKY: CohortData = {
  week: makeSeries({
    period: 'week',
    first: '2026-08-25',
    count: 8,
    size: [2400, 2100],
    week1: 0.36,
    floor: 0.02,
    decay: 0.3,
    quality: [0.01, -0.02, -0.04, 0.0, 0.11, -0.03, -0.05, 0],
    seed: 41,
  }),
  month: makeSeries({
    period: 'month',
    first: '2026-04-01',
    count: 6,
    into: 1.75,
    size: [9800, 8600],
    week1: 0.24,
    floor: 0.02,
    decay: 0.55,
    quality: [0.02, -0.01, 0.0, 0.05, -0.02, -0.03],
    seed: 43,
  }),
};

/** Four weeks since launch: no monthly view yet, so no switch. */
export const LAUNCH: CohortData = {
  week: makeSeries({
    period: 'week',
    first: '2026-09-22',
    count: 4,
    size: [640, 1180],
    week1: 0.71,
    floor: 0.1,
    decay: 0.2,
    quality: [-0.02, 0.03, 0.05, 0],
    seed: 5,
  }),
};

/** Retention of paid plans: who is still paying, by the week they converted. */
export const PAID: CohortData = {
  week: makeSeries({
    period: 'week',
    first: '2026-08-25',
    count: 8,
    size: [212, 286],
    week1: 0.91,
    floor: 0.55,
    decay: 0.12,
    quality: [-0.02, 0.0, 0.01, 0.03, -0.01, 0.02, 0.04, 0],
    seed: 77,
  }),
  month: makeSeries({
    period: 'month',
    first: '2026-04-01',
    count: 6,
    into: 1.75,
    size: [840, 1120],
    week1: 0.86,
    floor: 0.5,
    decay: 0.2,
    quality: [-0.03, 0.01, 0.02, 0.0, 0.03, 0],
    seed: 79,
  }),
};

// ---- Colours and textures ------------------------------------------------------------------------

/** Oldest to newest. A cohort takes the colour at its place along the stops. */
const STOPS: Record<Palette, string[]> = {
  spectrum: [
    '#6a4cf2',
    '#8b5cf6',
    '#3d7ff0',
    '#25a6d6',
    '#2bbd8c',
    '#a6d24a',
    '#e9b23e',
    '#f2774a',
  ],
  ember: ['#6f2348', '#9a2c47', '#c43b43', '#de5a3c', '#ec7c3a', '#f2a043', '#f5c25a'],
};

/** The best cohort's colour in the week 1 bars, on any palette. */
export const BEST = '#c3e64f';

const mixHex = (a: string, b: string, t: number) => {
  const pa = [1, 3, 5].map((i) => parseInt(a.slice(i, i + 2), 16));
  const pb = [1, 3, 5].map((i) => parseInt(b.slice(i, i + 2), 16));
  return `#${pa
    .map((v, i) =>
      Math.round(v + (pb[i] - v) * t)
        .toString(16)
        .padStart(2, '0'),
    )
    .join('')}`;
};

export function colourAt(palette: Palette, i: number, n: number) {
  const stops = STOPS[palette];
  if (n === stops.length) return stops[i];
  const at = n > 1 ? (i / (n - 1)) * (stops.length - 1) : 0;
  const low = Math.floor(at);
  return mixHex(stops[low], stops[Math.min(low + 1, stops.length - 1)], at - low);
}

export type Texture = 'dots' | 'diagonal' | 'lines' | 'fine';
const TEXTURES: Texture[] = [
  'dots',
  'fine',
  'lines',
  'diagonal',
  'dots',
  'lines',
  'diagonal',
  'fine',
];
export const textureAt = (i: number) => TEXTURES[i % TEXTURES.length];

// ---- What the card draws -------------------------------------------------------------------------

export type ReadCohort = Cohort & {
  index: number;
  label: string;
  colour: string;
  texture: Texture;
  /** Days from the first cohort's start. */
  from: number;
  /** The period in progress. */
  latest: number;
  /** Week 1's share, or null while week 1 is in progress or ahead. */
  week1: number | null;
};

export type Reading = {
  period: Period;
  cohorts: ReadCohort[];
  /** Days from the first start to today. */
  span: number;
  /** stack[i][d]: cohort i's band on day d, as [bottom, top] in people. */
  stack: [number, number][][];
  peak: number;
  /** Everyone active today. */
  total: number;
  /** The oldest cohort's period in progress, and the share of those that reached it. */
  horizon: number;
  headline: number | null;
  average: number | null;
  best: number | null;
};

/** The day (from the first start) a cohort's period k is read at: its middle, or today. */
export const anchorDay = (reading: Reading, i: number, k: number) => {
  const cohort = reading.cohorts[i];
  const days = PERIOD_DAYS[reading.period];
  return Math.min(cohort.from + (k === 0 ? 0.6 : k + 0.5) * days, reading.span);
};

const smooth = (t: number) => t * t * (3 - 2 * t);

/** A cohort's active users at an age in periods: joining through period 0, then its curve. */
function activeAt(cohort: Cohort, age: number) {
  if (age <= 0) return 0;
  if (age < 0.9) return cohort.size * smooth(age / 0.9);
  const anchors: [number, number][] = [[0.9, 1]];
  cohort.retained.forEach((share, k) => k > 0 && anchors.push([k + 0.5, share]));
  for (let j = 1; j < anchors.length; j += 1) {
    const [a0, s0] = anchors[j - 1];
    const [a1, s1] = anchors[j];
    if (age <= a1) return cohort.size * (s0 + (s1 - s0) * smooth((age - a0) / (a1 - a0)));
  }
  return cohort.size * anchors[anchors.length - 1][1];
}

export function readSeries(series: CohortSeries, palette: Palette = 'spectrum'): Reading {
  const { period } = series;
  const days = PERIOD_DAYS[period];
  const firstDay = series.cohorts.length ? dayOf(series.cohorts[0].start) : dayOf(series.now);
  const span = Math.max(1, dayOf(series.now) - firstDay);
  const n = series.cohorts.length;
  const cohorts = series.cohorts.map((cohort, index): ReadCohort => {
    const latest = cohort.retained.length - 1;
    return {
      ...cohort,
      index,
      label: cohortLabel(cohort.start, period),
      colour: colourAt(palette, index, n),
      texture: textureAt(index),
      from: dayOf(cohort.start) - firstDay,
      latest,
      week1: latest > 1 ? cohort.retained[1] : null,
    };
  });

  // Day by day, oldest at the bottom; a little weekday rhythm and noise make the ragged top.
  const stack = cohorts.map(() => [] as [number, number][]);
  let peak = 0;
  for (let d = 0; d <= span; d += 1) {
    let floor = 0;
    cohorts.forEach((cohort, i) => {
      const age = (d - cohort.from) / days;
      let value = activeAt(cohort, age);
      if (value > 0 && age > 0.9) {
        const weekday = (firstDay + d + 4) % 7;
        const rest = 1 + 0.035 * Math.sin(((weekday - 1) / 7) * Math.PI * 2);
        value *= rest * (1 + 0.018 * wobble(i, d, 7));
      }
      stack[i].push([floor, floor + value]);
      floor += value;
    });
    peak = Math.max(peak, floor);
  }
  const total = cohorts.reduce((sum, _, i) => sum + (stack[i][span]?.[1] - stack[i][span]?.[0]), 0);

  const horizon = n ? cohorts[0].latest : 0;
  const reached = cohorts.filter((cohort) => cohort.latest >= horizon && horizon > 0);
  const people = reached.reduce((sum, cohort) => sum + cohort.size, 0);
  const headline = people
    ? reached.reduce((sum, cohort) => sum + cohort.size * cohort.retained[horizon], 0) / people
    : null;

  const firsts = cohorts.filter((cohort) => cohort.week1 !== null);
  const average = firsts.length
    ? firsts.reduce((sum, cohort) => sum + cohort.week1!, 0) / firsts.length
    : null;
  const best = firsts.length
    ? firsts.reduce((top, cohort) => (cohort.week1! > top.week1! ? cohort : top)).index
    : null;

  return { period, cohorts, span, stack, peak, total, horizon, headline, average, best };
}
```

### cohort-retention/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 (cohort-retention.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 card 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>
  );
}
```

### cohort-retention/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 them for
 * good, until the component remounts (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 };
}
```