# View switcher

> The saved views of a records page: a menu that scales from its button with a band that glides between rows, each view a table, a board or a chart of its own.

The People page of a CRM, with its saved views behind one button. The menu lists them with a coloured tile for their type, the active one in blue, and a grey band that glides to the row under the pointer or the focus. Picking one changes what is below: Activity is a table of everyone added, newest first, under seven rules; Strong connection keeps the people you were in touch with this month; Slipping away is a board of who has gone quiet, in lanes by how long; Contact overview is a chart of the same buckets. Each row’s ⋮ menu renames it in place (F2 too), duplicates it or deletes it with an undo, and Create new names a view and picks its type without leaving the menu. Filter lists the view’s rules to remove or add, and Sort orders it. Light and dark.

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

Category: Navigation.

## Anatomy

1. **Page head**: The page’s title, an info button whose tooltip says where the records come from, and a tinted Beta badge.
2. **Views button**: A menu button with the active view’s type tile, its name and a chevron that turns over; open, it takes a soft blue ring.
3. **Filter count**: How many rules the active view filters by, in a tinted badge; it rolls when the view or its rules change.
4. **Views menu**: Captioned Views, it scales and fades from its button and lists every saved view, then Create new.
5. **View row**: The view’s type tile and name, the active one in the accent; a grey band glides under the row the pointer or the focus is on.
6. **Type tile**: White marks on the type’s colour: a list for a table, cards for a board, bars for a chart.
7. **Options button**: The ⋮ at the end of each row, which opens that view’s own menu: Rename, Duplicate, Delete.
8. **Create new**: The last row, in grey: it turns into a field for the name and a choice of type.
9. **Record row**: A checkbox, a round initial in the person’s tint, the name, and the view’s date on a tinted column.

## Properties

### View type (`views[].type`)

1. **Table (default)**: Rows with a checkbox each, for reading names and acting on a few. Create new starts on it.
2. **Board**: Cards in lanes by how long since the last contact, for seeing who sits where.
3. **Chart**: A bar for each of the same lanes, for how many, not who.

Pick the type from what people do with the view: act on records in a table, sort them by time in a board, count them in a chart. Rows are the only type with a selection.

### Date column (`views[].column`)

1. **Contact added (default)**: When each person was added. A new table starts on it.
2. **Last contact**: When you were last in touch, or Never.

Show the date the view is about, since the view sorts by it too: added for what’s new, last contact for who needs a word. Boards and charts always group by the last contact.

## When to use

- A records page in a CRM, a tracker or an admin tool where people keep a few saved ways of looking at the same list: a filter, a sort and a layout under one name.
- Views that differ in kind, not only in filters: the same people as rows, as cards grouped by a status, or as a chart of the groups.
- Lists people return to every day, where switching between “mine”, “recent” and “needs attention” should take one press and the keyboard.
- Teams that name their own views: rename, duplicate and delete them in place, with an undo, without a settings page.

## When not to use

- Two or three fixed layouts nobody renames. Use a segmented control or tabs; a menu hides choices that could all show.
- One-off filtering. Use filter chips over the list; a saved view is worth its name only when people come back to it.
- Moving between different pages or records. Use navigation; views change how one list is drawn, not where you are.
- Dozens of views. Add search to the menu, or group them by owner; a flat menu stops scanning well past ten or so.

### Saving views

- A view is a `name`, a `type`, filter `rules`, a date `column` and a `sort`. The component keeps its own list, starting from `views`, which only counts the first time.
- `onViewsChange` gets every view after each create, rename, duplicate, delete, undo, or change of rules or sort. Save the list from there.
- `onViewChange` hears the view that opens, also when a deletion moves to its neighbour or Undo brings it back. Store its id and pass it as `defaultView` next time.
- A new view is named in place; left blank, it is called `Untitled table` (or board, or chart). A duplicate is called `… copy` and opens in rename.

### Deleting and undo

- **Delete sits last in a view’s ⋮ menu**, in red after a rule. It is off while only one view is left, so the page always has one.
- **The view goes at once**, and its neighbour opens if it was the active one. A dark toast offers Undo: its six seconds wait while the views menu is still open and while the pointer or the focus is on the toast. Undo, or ⌘Z or Ctrl+Z from anywhere in the component, puts the view back in its place.
- **`onViewsChange` fires the moment a view is deleted, before the undo’s time is up, and again on Undo** with the view back in the list. Nothing tells you when the toast has gone, so if a deletion on your server can’t be taken back, keep it soft or delay it until Undo can no longer come.

### Views menu vs. view tabs

**Views menu**
- Only the active view shows; the rest wait one press away.
- Holds as many views as people save, and lets them rename, duplicate, delete and create in place.
- Each view can draw the list its own way: a table, a board or a chart.

**View tabs**
- Every view shows at once, and switching is a single press.
- Fits a handful of views the team sets up and rarely renames.
- Runs out of room as views pile up; past what the row holds, move to a menu.

## Do’s and don’ts

- **Do**: Name a view in a word or three for who is in it: `Slipping away`, `Strong connection`.
- **Don’t**: Write the rules into the name. The views button cuts a long name short, and the Filter button already lists the rules.
- **Do**: Give each view its own question and let its type follow: rows to act on, lanes to group, bars to count.
- **Don’t**: Name views after their layout: `Table`, `Table 2`, `Board`. The type tile already shows the layout; the name should say who is in the list.
- **Caution**: Treat the delete in `onViewsChange` as final. It comes at once, while Undo is still on offer, and an Undo then sends the list back with the view in it.

## Content

The page title says what the records are; each view’s name says which of them.

- **The page title** (`title`): the records, plural, in a word: `People`, `Contacts`. It also names the info button, “About People”.
- **View names**: sentence case, no full stop, a word or three for who is in the list. The button leaves about 130 px for the name, near the width of `Strong connection`; longer names end in an ellipsis.
- **Not the rules, not the layout**: the Filter button counts and lists the rules, and the type tile shows table, board or chart.
- **Rows and lanes** use the data’s own words: full names, and dates as people say them, like `Yesterday, 4:00 pm` or `3 weeks ago`.

## Installation

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

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

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 { ViewSwitcher } from './view-switcher';

export function PeoplePage() {
  return (
    <ViewSwitcher
      title="People"
      defaultView="activity"
      onViewChange={(view) => console.log('Showing', view.name)}
      onViewsChange={(views) => console.log('Saved views', views)}
      autoplay={false}
    />
  );
}
```

## States

- **Activity**: The table of everyone you added, newest first, under seven rules.
- **Views menu**: Open from its button, the band on Strong connection and Activity in the accent.
- **Strong connection**: Three rules: strong connections you were in touch with this month, by last contact.
- **Slipping away**: A board of everyone quiet for two weeks, in lanes by how long ago, the longest first.
- **Contact overview**: Bars of everyone by last contact, from this week to never.
- **Row options**: The ⋮ menu of Slipping away: Rename with its F2 key, Duplicate, and Delete in red.
- **Renaming**: F2 or Rename turns the name into a field in place; Enter keeps it, Escape puts it back.
- **Create new**: A name typed in and Board picked; Create view adds it at the end and opens it.
- **Filter panel**: The rules of the active view, each with ×, and the rules it can add.
- **Sort**: Newest first, oldest first or by name, a radio set of the active view.
- **Deleted, with undo**: Slipping away is gone from the menu; the toast brings it back where it was.
- **Phone**: Under 560 px Filter and Sort keep their icons, the menu spans the card and the table tightens.

## Examples

### Opened on the board

The same page opened on Slipping away: everyone quiet for two weeks, in lanes by how long, the longest first.

```tsx
import { ViewSwitcher } from './view-switcher';

export function OpenOnTheBoard() {
  return <ViewSwitcher autoplay={false} defaultView="slipping" />;
}
```

### Your own views

A Contacts page with four views of its own, open on a Directory table sorted by name, with a board of who to reach out to and a chart of the whole team.

```tsx
import { ViewSwitcher, type View } from './view-switcher';

const CONTACT_VIEWS: View[] = [
  {
    id: 'recent',
    name: 'Recently added',
    type: 'table',
    rules: ['active', 'year'],
    column: 'added',
    sort: 'recent',
  },
  {
    id: 'reach-out',
    name: 'Reach out this week',
    type: 'board',
    rules: ['active', 'mine', 'quiet'],
    column: 'contact',
    sort: 'oldest',
  },
  {
    id: 'directory',
    name: 'Directory',
    type: 'table',
    rules: ['email'],
    column: 'contact',
    sort: 'name',
  },
  {
    id: 'pulse',
    name: 'Team pulse',
    type: 'chart',
    rules: [],
    column: 'contact',
    sort: 'recent',
  },
];

export function YourOwnViews() {
  return (
    <ViewSwitcher autoplay={false} title="Contacts" views={CONTACT_VIEWS} defaultView="directory" />
  );
}
```

### Renaming in place

The menu open with Strong connection being renamed to Close circle in its row.

```tsx
import { ViewSwitcher } from './view-switcher';

export function RenamingInPlace() {
  return (
    <ViewSwitcher
      autoplay={false}
      defaultState={{
        menu: 'views',
        hot: 'strong',
        renaming: { id: 'strong', name: 'Close circle' },
      }}
    />
  );
}
```

### Selection and filters

Strong connection with two people checked and its Filter panel open on its three rules.

```tsx
import { ViewSwitcher } from './view-switcher';

export function SelectionAndFilters() {
  return (
    <ViewSwitcher
      autoplay={false}
      defaultState={{ view: 'strong', menu: 'filter', selected: ['maren', 'leila'] }}
    />
  );
}
```

## How it works

- A view is data: a name, a type (table, board or chart), the rules that filter the people, the date it shows and its sort. The body is drawn from the active view each time, so picking a view, removing a rule or changing the sort all redraw the same way, and the Filter badge counts the active view’s rules.
- The menu stays mounted and hidden, so it can animate both ways: it scales up from the corner under its button on a spring, fades out faster than it came, and its chevron turns over. Hidden, it is out of the accessibility tree and the tab order.
- One band sits under the rows and moves with the `translate` property to the row the pointer or the focus is on, measured from the row’s own offset, so it glides instead of jumping and stays right inside a scaled-down card. When nothing is under it, it fades where it was and glides from there next time.
- The views button follows the menu button pattern: Enter, Space or ↓ open on the active view, ↑ on the last row; ↑ ↓ Home and End move, letters jump to the next name that starts with them, F2 renames, → or Shift+F10 opens the row’s ⋮ menu, Escape closes and gives the focus back.
- Renaming lays a field over the name in its row; Enter or leaving it keeps the name, Escape puts the old one back. Duplicate adds “… copy” under the original with its name already selected. Delete removes the view and, if it was open, opens its neighbour; Undo puts it back in its place for six seconds.
- Create new turns its row into a name field, a radio group of the three types and Create view. The new view starts with one rule and opens at once.
- The table’s rows, the board’s cards and the chart’s bars come in one after the other when the view changes, staggered from a custom property; the Filter count rolls to its new number.
- While on screen and untouched, a demo pointer opens the menu, glides past Activity to Strong connection and picks it, opens Slipping away and Contact overview, then creates a board named Weekly check-ins. Any real input hands it over; it comes back after 8 s of quiet.

## API reference

- **title** (`string`, default `'People'`): The page’s title, in the head.
- **views** (`View[]`, default `four views`): The saved views at first: an id, a name, a type (table, board or chart), filter rules, the date column (added or last contact) and the sort.
- **people** (`Person[]`, default `sixteen people`): The records the views filter: a name, a tint, when they were added and last contacted, connection strength, owner, email, archive and source.
- **defaultView** (`string`): The id of the view open at first; the first view when left out.
- **defaultSelected** (`string[]`, default `[]`): Ids of the people checked at first.
- **defaultState** (`ViewSwitcherState`): Opens locked in a moment, with the demo off: the view, a popover open, the row under the band, a ⋮ menu, a rename or a new view in progress, or a view just deleted.
- **onViewChange** (`(view: View) => void`): Called with the view picked, created, or opened after a delete.
- **onViewsChange** (`(views: View[]) => void`): Called with every view when one is created, renamed, duplicated, deleted, restored or has its rules or sort changed.
- **onSelectionChange** (`(ids: string[]) => void`): Called with the checked people’s ids when they change.
- **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

The views button opens its menu with Enter, Space or Down, and Up opens it on the last row. In the menu, Up and Down move and wrap round, Home and End jump to the ends, typing jumps to a name, and Enter opens the view. F2 renames in place; Right, Shift+F10 or the Menu key opens the row’s ⋮ menu, and Left or Escape comes back. Escape closes the menu and puts focus back on its button; Tab closes it. After a delete, ⌘Z or Ctrl+Z undoes it from anywhere in the component (not inside a text field), and the toast’s Undo button is also in the Tab order. Focus shows as a blue ring, or as a blue bar at the start of a views menu row.

### Screen readers

- The views button is a menu button that names the view and its type: “View: Activity, Table”. The rows are radio items, the active one checked, and each ⋮ is “Options for Activity”.
- Filter and Sort say their state in their names: “Filter, 7 rules”, “Sort, newest first”. The count badge itself is hidden.
- A polite live region says what changed: the view opened with its type and count, a rename, a duplicate, a deletion with how to undo it (“Undo with Command Z or Control Z”), a restore, a sort or a filter.

### Undo timing

The undo toast’s six seconds only start once the views menu has closed, and stop while the pointer or the focus is on the toast; they go on from where they stopped when it leaves. That way nobody loses Undo while reaching for it (WCAG 2.2.1 Timing Adjustable, A). Focus stays in the menu after a delete, so ⌘Z or Ctrl+Z is the keyboard’s way back.

### Colour

Text meets 4.5:1 and icons, checkbox edges and focus rings 3:1 against what they sit on, in light and dark (WCAG 1.4.3 and 1.4.11, AA). The avatars’ initials and the bars’ fills only repeat a name or a number written beside them.

### Motion

Under reduced motion the menu, the band and the chevron change at once, the rows, cards, bars, counts and toast don’t animate in, and the demo never plays.

### In this build

- The views button is a menu button (aria-haspopup, aria-expanded, aria-controls) labelled with the active view and its type. The views are menuitemradio items, the open one checked; each ⋮ is a menuitem with its own menu, reached with → or Shift+F10 as well as the pointer.
- In the menu ↑ ↓ Home and End move the focus, typed letters jump to a name, Enter or Space picks, F2 renames, and Escape closes with the focus back on the button. The ⋮ menu closes with Escape or ← back to its row. The band follows the focus as well as the pointer, and a focused row also shows an accent edge.
- Filter opens a non-modal dialog whose remove buttons name their rule; Sort is a menu of radio items. The info button’s tooltip is tied to it with aria-describedby and shows on hover and focus; Escape hides it.
- Create new is a group: a labelled name field and a radio group of types moved with the arrow keys. The rename field is labelled with the view it renames.
- The table has column headers and each name is its row’s header; checkboxes are role="checkbox" buttons, the header one mixed while some are checked. The board is a labelled group of lanes, and on a phone it scrolls sideways and takes the focus. Each chart bar says its bucket and count in words.
- A polite live region says which view opened and how many people it shows, renames, duplicates, deletes and their undo, and rule and sort changes. Under reduced motion nothing scales, glides or rolls and the demo never plays; the demo pointer is decorative.

## Source

### view-switcher/view-switcher.tsx

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

'use client';

import {
  useEffect,
  useEffectEvent,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
} from 'react';
import {
  PEOPLE,
  RULES,
  RULE_IDS,
  SORT_LABEL,
  TYPE_LABEL,
  VIEWS,
  peopleFor,
  type Person,
  type RuleId,
  type SortOrder,
  type View,
  type ViewType,
} from './data';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { Icon, TypeTile } from './glyphs';
import { useAutoplay } from './use-autoplay';
import { BoardView, ChartView, TableView, count } from './views';
import styles from './view-switcher.module.css';

/*
 * View switcher: the saved views of a records page, People, in a CRM.
 *
 * - The views button shows the active view's type tile and name. Its menu lists the saved views,
 *   each with a ⋮ button for its own menu (Rename, Duplicate, Delete with an undo: a toast whose
 *   six seconds wait while the views menu is open or the toast is hovered or focused, and ⌘Z or
 *   Ctrl+Z from anywhere in the component), and Create new,
 *   which names a view inline and picks its type: a table, a board or a chart.
 * - Picking a view changes what is below it: its filters (the Filter button counts them and lists
 *   them to remove or add), its sort (the Sort button), the date it shows, and how it draws the
 *   people: rows, cards grouped by how long since you were in touch, or bars of the same.
 * - The menu scales from its button, a grey band glides between the rows under the pointer or the
 *   focus, and the keyboard follows the menu button pattern, with typeahead and F2 to rename.
 * - While on screen and untouched, a demo pointer picks Strong connection, then the board and the
 *   chart, then creates a view, in a loop.
 */

export type { DateColumn, Person, RuleId, SortOrder, View, ViewType } from './data';

type Popover = 'views' | 'filter' | 'sort';
type Draft = { name: string; type: ViewType };

/** A moment to open in, locked: the demo stays off. Used by the docs. */
export type ViewSwitcherState = {
  /** The active view's id. */
  view?: string;
  /** A popover held open. */
  menu?: Popover;
  /** The views menu's row under the band. */
  hot?: string;
  /** The view whose ⋮ menu is open. */
  options?: string;
  /** The view being renamed, and the name typed so far. */
  renaming?: { id: string; name: string };
  /** Create new, filled in so far. */
  creating?: Draft;
  /** A view just deleted: it is gone and the undo shows. */
  deleted?: string;
  selected?: string[];
};

const TYPES: ViewType[] = ['table', 'board', 'chart'];
const TYPEAHEAD_MS = 600;
const UNDO_MS = 6000;

export function ViewSwitcher({
  title = 'People',
  views: initialViews = VIEWS,
  people = PEOPLE,
  defaultView,
  defaultSelected = [],
  defaultState,
  onViewChange,
  onViewsChange,
  onSelectionChange,
  autoplay = true,
  colorScheme,
  className = '',
}: {
  /** The page's title. */
  title?: string;
  /** The saved views at first: a name, a type, filter rules, the date shown and the sort. */
  views?: View[];
  /** The records the views filter. */
  people?: Person[];
  /** The view open at first; the first one when left out. */
  defaultView?: string;
  defaultSelected?: string[];
  /** Opens locked in a moment, with the demo off. */
  defaultState?: ViewSwitcherState;
  /** Called with the view picked. */
  onViewChange?: (view: View) => void;
  /**
   * Called with every view when one is created, renamed, duplicated, deleted or edited. A delete
   * calls it at once, while Undo is still on offer, and Undo calls it again with the view back.
   */
  onViewsChange?: (views: View[]) => void;
  onSelectionChange?: (ids: string[]) => void;
  autoplay?: boolean;
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const uid = useId();
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>(8000);
  const pointer = useRef<HTMLSpanElement>(null);
  const viewsButton = useRef<HTMLButtonElement>(null);
  const filterButton = useRef<HTMLButtonElement>(null);
  const sortButton = useRef<HTMLButtonElement>(null);
  const viewsMenu = useRef<HTMLDivElement>(null);
  const list = useRef<HTMLDivElement>(null);
  const popover = useRef<HTMLDivElement>(null);
  const locked = defaultState !== undefined;
  const s = defaultState ?? {};

  const start = useMemo(
    () => ({ views: initialViews, view: defaultView ?? initialViews[0]?.id ?? '' }),
    // Only the first values count.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  const [views, setViews] = useState<View[]>(() =>
    s.deleted ? start.views.filter((v) => v.id !== s.deleted) : start.views,
  );
  const [activeId, setActiveId] = useState(() => {
    const id = s.view ?? start.view;
    return id === s.deleted ? (start.views.find((v) => v.id !== id)?.id ?? '') : id;
  });
  const [open, setOpen] = useState<Popover | null>(s.menu ?? null);
  const [hot, setHot] = useState<string | null>(s.hot ?? null);
  const [options, setOptions] = useState<string | null>(s.options ?? null);
  const [renaming, setRenaming] = useState<{ id: string; name: string } | null>(s.renaming ?? null);
  const [creating, setCreating] = useState<Draft | null>(s.creating ?? null);
  const [selected, setSelected] = useState<Set<string>>(
    () => new Set(s.selected ?? defaultSelected),
  );
  const [undo, setUndo] = useState<{ view: View; index: number; wasActive: boolean } | null>(() => {
    const index = start.views.findIndex((v) => v.id === s.deleted);
    return index < 0
      ? null
      : { view: start.views[index], index, wasActive: (s.view ?? start.view) === s.deleted };
  });
  /** Whether the pointer or the focus is on the undo toast: its time waits meanwhile. */
  const [toastHover, setToastHover] = useState(false);
  const [toastFocus, setToastFocus] = useState(false);
  /** What is left of an undo's time, once it has waited. */
  const undoLeft = useRef<{ view: View | null; ms: number }>({ view: null, ms: UNDO_MS });
  const toast = useRef<HTMLDivElement>(null);
  const [tip, setTip] = useState(false);
  const [band, setBand] = useState<{ top: number; height: number; on: boolean } | null>(null);
  const [optionsTop, setOptionsTop] = useState(0);
  const [live, setLive] = useState('');
  /** Who opened the open popover: the reader's focus moves into it, the demo's does not. */
  const byReader = useRef(false);
  const demoing = useRef(false);
  const typed = useRef({ text: '', at: 0 });
  const renameDone = useRef<string | null>(null);

  const active = views.find((v) => v.id === activeId) ?? views[0];
  const shown = useMemo(() => (active ? peopleFor(active, people) : []), [active, people]);

  const say = (text: string) => setLive((was) => (was === text ? `${text} ` : text));

  // ---- Views -------------------------------------------------------------------------------------

  const commit = (next: View[]) => {
    setViews(next);
    onViewsChange?.(next);
  };

  const close = (back?: Popover) => {
    setOpen(null);
    setOptions(null);
    setRenaming(null);
    setCreating(null);
    setHot(null);
    if (back && !demoing.current) {
      const button = { views: viewsButton, filter: filterButton, sort: sortButton }[back];
      button.current?.focus({ preventScroll: true });
    }
  };

  const openPopover = (which: Popover, focus: 'active' | 'last' = 'active') => {
    byReader.current = !demoing.current;
    focusOnOpen.current = focus;
    setOptions(null);
    setRenaming(null);
    setCreating(null);
    setHot(which === 'views' && demoing.current ? null : which === 'views' ? activeId : null);
    setOpen(which);
  };
  const focusOnOpen = useRef<'active' | 'last'>('active');

  const pick = (view: View) => {
    close('views');
    if (view.id === activeId) return;
    setActiveId(view.id);
    onViewChange?.(view);
    const n = peopleFor(view, people).length;
    say(`${view.name}: ${TYPE_LABEL[view.type].toLowerCase()} of ${count(n)}`);
  };

  const patch = (id: string, change: Partial<View>) =>
    commit(views.map((v) => (v.id === id ? { ...v, ...change } : v)));

  const freshId = (base: string) => {
    let n = 1;
    const slug = base.toLowerCase().replace(/[^a-z0-9]+/g, '-') || 'view';
    while (views.some((v) => v.id === (n === 1 ? slug : `${slug}-${n}`))) n += 1;
    return n === 1 ? slug : `${slug}-${n}`;
  };

  const finishRename = (keep: boolean) => {
    // Enter, then the blur of the input going away: only the first one counts.
    if (!renaming || renameDone.current === renaming.id) return;
    renameDone.current = renaming.id;
    const name = renaming.name.trim();
    const view = views.find((v) => v.id === renaming.id);
    setRenaming(null);
    if (keep && view && name && name !== view.name) {
      patch(view.id, { name });
      say(`Renamed ${view.name} to ${name}`);
    }
    focusRow(renaming.id);
  };

  const duplicate = (view: View) => {
    const name = `${view.name} copy`;
    const copy = { ...view, id: freshId(name), name, rules: [...view.rules] };
    const index = views.indexOf(view);
    commit([...views.slice(0, index + 1), copy, ...views.slice(index + 1)]);
    setOptions(null);
    setHot(copy.id);
    setRenaming({ id: copy.id, name });
    say(`Duplicated ${view.name}`);
  };

  const remove = (view: View) => {
    if (views.length < 2) return;
    const index = views.indexOf(view);
    const next = views.filter((v) => v.id !== view.id);
    commit(next);
    setOptions(null);
    const wasActive = view.id === activeId;
    if (wasActive) {
      const to = next[Math.min(index, next.length - 1)];
      setActiveId(to.id);
      onViewChange?.(to);
    }
    setToastHover(false);
    setToastFocus(false);
    setUndo({ view, index, wasActive });
    const neighbour = next[Math.min(index, next.length - 1)];
    setHot(neighbour.id);
    focusRow(neighbour.id);
    say(`Deleted ${view.name}. Undo with Command Z or Control Z.`);
  };

  const restore = () => {
    if (!undo) return;
    // The toast goes away: a focus on it moves to the restored row, or the views button.
    if (toast.current?.contains(document.activeElement)) {
      if (open === 'views') focusRow(undo.view.id);
      else viewsButton.current?.focus({ preventScroll: true });
    }
    const next = [...views];
    next.splice(Math.min(undo.index, next.length), 0, undo.view);
    commit(next);
    if (undo.wasActive) {
      setActiveId(undo.view.id);
      onViewChange?.(undo.view);
    }
    setUndo(null);
    say(`Restored ${undo.view.name}`);
  };

  const create = () => {
    if (!creating) return;
    const name = creating.name.trim() || `Untitled ${TYPE_LABEL[creating.type].toLowerCase()}`;
    const view: View = {
      id: freshId(name),
      name,
      type: creating.type,
      rules: ['active'],
      column: creating.type === 'table' ? 'added' : 'contact',
      sort: 'recent',
    };
    commit([...views, view]);
    setActiveId(view.id);
    onViewChange?.(view);
    close('views');
    say(
      `Created ${name}, a ${TYPE_LABEL[view.type].toLowerCase()} of ${count(peopleFor(view, people).length)}`,
    );
  };

  // An undo lasts six seconds, unless the docs hold it. The time waits while the views menu is
  // still open, and while the pointer or the focus is on the toast (WCAG 2.2.1), then goes on
  // from where it stopped.
  const undoHeld = open === 'views' || toastHover || toastFocus;
  useEffect(() => {
    if (!undo || locked || undoHeld) return;
    const left = undoLeft.current;
    if (left.view !== undo.view) Object.assign(left, { view: undo.view, ms: UNDO_MS });
    const started = Date.now();
    const timer = window.setTimeout(() => setUndo(null), Math.max(left.ms, 0));
    return () => {
      window.clearTimeout(timer);
      left.ms -= Date.now() - started;
    };
  }, [undo, locked, undoHeld]);

  // ---- Focus and the band ------------------------------------------------------------------------

  const rowButton = (id: string) =>
    list.current?.querySelector<HTMLElement>(`[data-item="${CSS.escape(id)}"]`) ?? null;
  const pendingFocus = useRef<string | null>(null);
  const focusRow = (id: string) => {
    if (!demoing.current) pendingFocus.current = id;
  };

  // Moves the focus once the menu shows what it should be on.
  useEffect(() => {
    if (open !== 'views') return;
    if (byReader.current && focusOnOpen.current) {
      const items = [...(list.current?.querySelectorAll<HTMLElement>('[data-item]') ?? [])];
      const target =
        focusOnOpen.current === 'last'
          ? items.at(-1)
          : (list.current?.querySelector<HTMLElement>('[aria-checked="true"]') ?? items[0]);
      target?.focus({ preventScroll: true });
      if (target?.dataset.item) setHot(target.dataset.item);
    }
    focusOnOpen.current = 'active';
    byReader.current = false;
    // Only as it opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  useEffect(() => {
    const id = pendingFocus.current;
    if (!id || renaming || options) return;
    pendingFocus.current = null;
    rowButton(id)?.focus({ preventScroll: true });
  });

  // The band sits under the hot row: measured in the list's own px, so a scaled stage is fine.
  useLayoutEffect(() => {
    const row = hot
      ? list.current?.querySelector<HTMLElement>(`[data-row="${CSS.escape(hot)}"]`)
      : null;
    // Off, it stays where it was, so it fades out there and glides from there next time.
    setBand((was) =>
      row
        ? { top: row.offsetTop, height: row.offsetHeight, on: true }
        : was && { ...was, on: false },
    );
    // The ⋮ menu hangs under its row, in the views menu's px.
    const owner = options
      ? list.current?.querySelector<HTMLElement>(`[data-row="${CSS.escape(options)}"]`)
      : null;
    if (owner && list.current)
      setOptionsTop(list.current.offsetTop + owner.offsetTop + owner.offsetHeight - 4);
  }, [hot, views, creating, open, options]);

  // Filter and Sort: the reader's focus goes into them; they stay inside the card.
  useLayoutEffect(() => {
    const box = popover.current;
    const frame = root.current;
    if (!box || !frame || (open !== 'filter' && open !== 'sort')) return;
    box.style.translate = '';
    const scale = frame.getBoundingClientRect().width / frame.offsetWidth || 1;
    const f = frame.getBoundingClientRect();
    // Its layout box, not its drawn one: it opens slightly scaled down.
    const left = (box.offsetParent as HTMLElement).getBoundingClientRect().left / scale;
    const x = left + box.offsetLeft;
    const over = x + box.offsetWidth - f.right / scale + 12;
    const under = f.left / scale - x + 12;
    box.style.translate = over > 0 ? `${-over}px 0` : under > 0 ? `${under}px 0` : '';
    if (byReader.current) {
      box
        .querySelector<HTMLElement>('[aria-checked="true"], button, [role^="menuitem"]')
        ?.focus({ preventScroll: true });
    }
    byReader.current = false;
  }, [open, root]);

  // A press elsewhere closes what is open.
  useEffect(() => {
    if (!open) return;
    const away = (event: PointerEvent) => {
      const target = event.target as Node;
      const inside = [viewsMenu, popover, viewsButton, filterButton, sortButton].some((r) =>
        r.current?.contains(target),
      );
      if (!inside) close();
    };
    document.addEventListener('pointerdown', away);
    return () => document.removeEventListener('pointerdown', away);
  });

  // ---- Keyboard ----------------------------------------------------------------------------------

  const onButtonKey = (which: Popover) => (event: ReactKeyboardEvent) => {
    if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
      event.preventDefault();
      openPopover(which, event.key === 'ArrowUp' ? 'last' : 'active');
    }
  };

  const onMenuKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
    const target = event.target as HTMLElement;
    if (target.closest('[data-field]')) return;
    const items = [...(list.current?.querySelectorAll<HTMLElement>('[data-item]') ?? [])];
    const index = items.indexOf(document.activeElement as HTMLElement);
    const current = items[index]?.dataset.item;
    const view = views.find((v) => v.id === current);
    const move = (to: number) => {
      event.preventDefault();
      const item = items[(to + items.length) % items.length];
      item?.focus();
      setHot(item?.dataset.item ?? null);
    };
    if (event.key === 'ArrowDown') move(index + 1);
    else if (event.key === 'ArrowUp') move(index < 0 ? items.length - 1 : index - 1);
    else if (event.key === 'Home') move(0);
    else if (event.key === 'End') move(items.length - 1);
    else if (event.key === 'Escape') {
      event.preventDefault();
      event.stopPropagation();
      close('views');
    } else if (event.key === 'Tab') close();
    else if (event.key === 'F2' && view) {
      event.preventDefault();
      setRenaming({ id: view.id, name: view.name });
    } else if (
      view &&
      (event.key === 'ArrowRight' ||
        event.key === 'ContextMenu' ||
        (event.key === 'F10' && event.shiftKey))
    ) {
      event.preventDefault();
      setOptions(view.id);
    } else if (event.key.length === 1 && /\S/.test(event.key) && !event.metaKey && !event.ctrlKey) {
      // Typeahead: the next row whose name starts with what was typed.
      const now = Date.now();
      const text = (now - typed.current.at < TYPEAHEAD_MS ? typed.current.text : '') + event.key;
      typed.current = { text, at: now };
      const names = items.map((item) => (item.textContent ?? '').trim().toLowerCase());
      const from = text.length === 1 ? index + 1 : Math.max(index, 0);
      for (let k = 0; k < items.length; k += 1) {
        const i = (from + k) % items.length;
        if (names[i].startsWith(text.toLowerCase())) {
          move(i);
          break;
        }
      }
    }
  };

  const onOptionsKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
    const items = [
      ...event.currentTarget.querySelectorAll<HTMLElement>(
        '[role="menuitem"]:not([aria-disabled])',
      ),
    ];
    const index = items.indexOf(document.activeElement as HTMLElement);
    const move = (to: number) => {
      event.preventDefault();
      items[(to + items.length) % items.length]?.focus();
    };
    event.stopPropagation();
    const id = options;
    const view = views.find((v) => v.id === id);
    if (event.key === 'ArrowDown') move(index + 1);
    else if (event.key === 'ArrowUp') move(index - 1);
    else if (event.key === 'Home') move(0);
    else if (event.key === 'End') move(items.length - 1);
    else if (event.key === 'Escape' || event.key === 'ArrowLeft') {
      event.preventDefault();
      setOptions(null);
      if (id) focusRow(id);
    } else if (event.key === 'Tab') close();
    else if (event.key === 'F2' && view) {
      event.preventDefault();
      setOptions(null);
      setRenaming({ id: view.id, name: view.name });
    }
  };

  // The ⋮ menu takes the focus when it opens, unless the demo opened it.
  const optionsBox = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!options || demoing.current || locked) return;
    optionsBox.current?.querySelector<HTMLElement>('[role="menuitem"]')?.focus();
  }, [options, locked]);

  const onPopoverKey =
    (which: 'filter' | 'sort') => (event: ReactKeyboardEvent<HTMLDivElement>) => {
      if (event.key === 'Escape') {
        event.preventDefault();
        event.stopPropagation();
        close(which);
        return;
      }
      if (which !== 'sort') return;
      const items = [
        ...event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitemradio"]'),
      ];
      const index = items.indexOf(document.activeElement as HTMLElement);
      const move = (to: number) => {
        event.preventDefault();
        items[(to + items.length) % items.length]?.focus();
      };
      if (event.key === 'ArrowDown') move(index + 1);
      else if (event.key === 'ArrowUp') move(index - 1);
      else if (event.key === 'Home') move(0);
      else if (event.key === 'End') move(items.length - 1);
      else if (event.key === 'Tab') close();
    };

  // ---- Selection, filters, sort ------------------------------------------------------------------

  const choose = (next: Set<string>) => {
    setSelected(next);
    onSelectionChange?.([...next]);
  };
  const toggle = (id: string) => {
    const next = new Set(selected);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    choose(next);
  };
  const toggleAll = () => {
    const all = shown.every((person) => selected.has(person.id));
    const next = new Set(selected);
    shown.forEach((person) => (all ? next.delete(person.id) : next.add(person.id)));
    choose(next);
    say(all ? 'Cleared the selection' : `Selected ${count(shown.length)}`);
  };

  const setRules = (rules: RuleId[], change: string) => {
    if (!active) return;
    patch(active.id, { rules });
    const n = peopleFor({ ...active, rules }, people).length;
    say(`${change}. ${count(n)} in view.`);
  };
  const setSort = (sort: SortOrder) => {
    if (!active) return;
    patch(active.id, { sort });
    close('sort');
    say(`Sorted ${SORT_LABEL[sort].toLowerCase()}`);
  };

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

  const demo = autoplay && !locked && playing;
  const dirty = useEffectEvent(
    () => activeId !== start.view || views !== start.views || selected.size > 0 || open !== null,
  );
  const reset = useEffectEvent(() => {
    setViews(start.views);
    setActiveId(start.view);
    setSelected(new Set());
    setUndo(null);
    close();
  });
  const typeName = useEffectEvent((name: string) =>
    setCreating((draft) => (draft ? { ...draft, name } : draft)),
  );
  const demoClear = useEffectEvent(() => close());

  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    if (!demo || !stage || !arrow) return;
    demoing.current = true;
    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 }) => {
      /** Glides over a row of the views menu, the band following. */
      const hover = async (id: string, ms: number) => {
        glyph('arrow');
        await glide(on(find(`view-${id}`), 0.42), ms);
        setHot(id);
        glyph('hand');
      };
      const press = async (name: string, ms: number, after: number, fx = 0.5) => {
        const element = find(name);
        if (!element) return;
        glyph('arrow');
        await glide(on(element, fx), ms);
        glyph('hand');
        element.dataset.over = '';
        await wait(220);
        delete element.dataset.over;
        (find(name) ?? element).click();
        await wait(after);
      };
      const pickView = async (id: string, after: number) => {
        await press('views', 700, 520, 0.3);
        await hover(id, 520);
        await wait(380);
        await press(`view-${id}`, 120, after, 0.42);
      };
      for (;;) {
        if (dirty()) {
          reset();
          await wait(500);
        }
        await wait(900);
        // Open the menu, glide down past Activity to Strong connection, and pick it.
        await press('views', 760, 560, 0.3);
        await hover(start.view, 460);
        await wait(320);
        await hover('strong', 380);
        await wait(420);
        await press('view-strong', 120, 2600, 0.42);
        // The board of who is slipping away, then the chart.
        await pickView('slipping', 2700);
        await pickView('overview', 2400);
        // A new view: named inline, a board.
        await press('views', 700, 480, 0.3);
        await press('create', 640, 420, 0.3);
        const name = 'Weekly check-ins';
        for (let i = 1; i <= name.length; i += 1) {
          typeName(name.slice(0, i));
          await wait(55);
        }
        await wait(300);
        await press('type-board', 560, 380);
        await press('create-submit', 480, 2600);
        // Back to where it started.
        await pickView(start.view, 1500);
        glyph('arrow');
        await glide(on(stage, 0.84, 0.92), 800);
        await wait(1600);
      }
    });
    return () => {
      stop();
      demoing.current = false;
      stage.querySelectorAll<HTMLElement>('[data-over]').forEach((el) => delete el.dataset.over);
      demoClear();
    };
  }, [demo, root, start]);

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

  const optionsView = views.find((v) => v.id === options) ?? null;
  const unused = RULE_IDS.filter((rule) => !active?.rules.includes(rule));
  const ruleCount = active?.rules.length ?? 0;

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="stage"
      data-color-scheme={colorScheme}
      onPointerDownCapture={take}
      onKeyDownCapture={(event) => {
        take();
        // ⌘Z or Ctrl+Z undoes a delete from anywhere in the component, text fields aside.
        const target = event.target as HTMLElement;
        if (
          undo &&
          (event.metaKey || event.ctrlKey) &&
          !event.altKey &&
          !event.shiftKey &&
          event.key.toLowerCase() === 'z' &&
          !target.closest('input, textarea, [contenteditable="true"]')
        ) {
          event.preventDefault();
          event.stopPropagation();
          restore();
        }
      }}
      onWheel={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') take();
      }}
    >
      <section className={styles.app} aria-labelledby={`${uid}-title`} data-part="app">
        <header className={styles.head} data-part="head">
          <h2 id={`${uid}-title`} className={styles.title}>
            {title}
          </h2>
          <span className={styles.tipWrap}>
            <button
              type="button"
              className={styles.info}
              aria-label={`About ${title}`}
              aria-describedby={`${uid}-tip`}
              onPointerEnter={() => setTip(true)}
              onPointerLeave={() => setTip(false)}
              onFocus={() => setTip(true)}
              onBlur={() => setTip(false)}
              onClick={() => setTip((was) => !was)}
              onKeyDown={(event) => {
                if (event.key === 'Escape') setTip(false);
              }}
            >
              <Icon name="info" />
            </button>
            <span
              id={`${uid}-tip`}
              role="tooltip"
              className={styles.tip}
              data-open={tip || undefined}
              data-part="tooltip"
            >
              Everyone you’ve emailed or met, kept up to date from your inbox and calendar.
            </span>
          </span>
          <span className={styles.beta} data-part="beta">
            Beta
          </span>
        </header>

        <div className={styles.toolbar} data-part="toolbar">
          <div className={styles.anchor}>
            <button
              ref={viewsButton}
              type="button"
              className={styles.viewsButton}
              aria-haspopup="menu"
              aria-expanded={open === 'views'}
              aria-controls={`${uid}-views`}
              aria-label={active ? `View: ${active.name}, ${TYPE_LABEL[active.type]}` : 'Views'}
              data-open={open === 'views' || undefined}
              data-part="views-button"
              data-demo="views"
              onClick={() => (open === 'views' ? close() : openPopover('views'))}
              onKeyDown={onButtonKey('views')}
            >
              {active && (
                <TypeTile key={`t-${active.id}`} type={active.type} className={styles.swap} />
              )}
              <span key={`n-${active?.id}`} className={`${styles.viewsName} ${styles.swap}`}>
                {active?.name ?? 'No view'}
              </span>
              <Icon name="chevron" className={styles.chevron} />
            </button>

            <div
              ref={viewsMenu}
              id={`${uid}-views`}
              role="menu"
              aria-label="Views"
              className={styles.menu}
              data-open={open === 'views' || undefined}
              data-part="menu"
              onKeyDown={onMenuKey}
            >
              <div className={styles.caption} role="presentation">
                Views
              </div>
              <div
                ref={list}
                className={styles.list}
                role="none"
                onPointerLeave={() => {
                  if (!demoing.current && !options) {
                    const focused = (document.activeElement as HTMLElement | null)?.dataset.item;
                    setHot(focused ?? null);
                  }
                }}
              >
                <span
                  className={styles.band}
                  aria-hidden="true"
                  data-on={band?.on ? '' : undefined}
                  style={band ? { translate: `0 ${band.top}px`, height: band.height } : undefined}
                />
                {views.map((view) => {
                  const isActive = view.id === active?.id;
                  const isRenaming = renaming?.id === view.id;
                  return (
                    <div
                      key={view.id}
                      role="none"
                      className={styles.row}
                      data-row={view.id}
                      data-part="view-item"
                      data-hot={hot === view.id || undefined}
                    >
                      <button
                        type="button"
                        role="menuitemradio"
                        aria-checked={isActive}
                        tabIndex={-1}
                        className={styles.item}
                        data-item={view.id}
                        data-active={isActive || undefined}
                        data-demo={`view-${view.id}`}
                        aria-keyshortcuts="F2"
                        onClick={() => pick(view)}
                        onFocus={() => setHot(view.id)}
                        onPointerEnter={() => {
                          if (!options) setHot(view.id);
                        }}
                      >
                        <TypeTile type={view.type} />
                        <span className={styles.itemName} data-hidden={isRenaming || undefined}>
                          {view.name}
                        </span>
                        <span className={styles.srOnly}>, {TYPE_LABEL[view.type]}</span>
                      </button>
                      {isRenaming && renaming && (
                        <input
                          className={styles.rename}
                          aria-label={`Rename ${view.name}`}
                          value={renaming.name}
                          data-field=""
                          data-part="rename"
                          autoFocus={!locked}
                          onFocus={(event) => {
                            renameDone.current = null;
                            event.currentTarget.select();
                          }}
                          onChange={(event) =>
                            setRenaming({ id: view.id, name: event.currentTarget.value })
                          }
                          onBlur={() => finishRename(true)}
                          onKeyDown={(event) => {
                            event.stopPropagation();
                            if (event.key === 'Enter') {
                              event.preventDefault();
                              finishRename(true);
                            } else if (event.key === 'Escape') {
                              event.preventDefault();
                              finishRename(false);
                            }
                          }}
                        />
                      )}
                      <button
                        type="button"
                        role="menuitem"
                        tabIndex={-1}
                        aria-haspopup="menu"
                        aria-expanded={options === view.id}
                        aria-label={`Options for ${view.name}`}
                        className={styles.more}
                        data-open={options === view.id || undefined}
                        data-part="more"
                        data-demo={`more-${view.id}`}
                        onPointerEnter={() => {
                          if (!options) setHot(view.id);
                        }}
                        onClick={() => {
                          setRenaming(null);
                          setHot(view.id);
                          setOptions(options === view.id ? null : view.id);
                        }}
                      >
                        <Icon name="more" />
                      </button>
                    </div>
                  );
                })}

                {creating ? (
                  <div
                    role="group"
                    aria-label="New view"
                    className={styles.create}
                    data-field=""
                    data-part="create-form"
                    onKeyDown={(event) => {
                      if (event.key === 'Escape') {
                        event.preventDefault();
                        event.stopPropagation();
                        setCreating(null);
                        focusRow('create');
                      }
                    }}
                  >
                    <input
                      className={styles.createName}
                      aria-label="Name the new view"
                      placeholder="Name the view"
                      value={creating.name}
                      autoFocus={!locked && !demoing.current}
                      onChange={(event) =>
                        setCreating({ ...creating, name: event.currentTarget.value })
                      }
                      onKeyDown={(event) => {
                        if (event.key === 'Enter') {
                          event.preventDefault();
                          create();
                        }
                      }}
                    />
                    <div role="radiogroup" aria-label="Type" className={styles.types}>
                      {TYPES.map((type, i) => {
                        const on = creating.type === type;
                        return (
                          <button
                            key={type}
                            type="button"
                            role="radio"
                            aria-checked={on}
                            tabIndex={on ? 0 : -1}
                            className={styles.type}
                            data-demo={`type-${type}`}
                            onClick={() => setCreating({ ...creating, type })}
                            onKeyDown={(event) => {
                              const step =
                                event.key === 'ArrowRight' || event.key === 'ArrowDown'
                                  ? 1
                                  : event.key === 'ArrowLeft' || event.key === 'ArrowUp'
                                    ? -1
                                    : 0;
                              if (!step) return;
                              event.preventDefault();
                              const to = TYPES[(i + step + TYPES.length) % TYPES.length];
                              setCreating({ ...creating, type: to });
                              const group = event.currentTarget.parentElement;
                              group
                                ?.querySelector<HTMLElement>(`[data-demo="type-${to}"]`)
                                ?.focus();
                            }}
                          >
                            <TypeTile type={type} />
                            {TYPE_LABEL[type]}
                          </button>
                        );
                      })}
                    </div>
                    <div className={styles.createEnd}>
                      <button
                        type="button"
                        className={styles.ghost}
                        onClick={() => {
                          setCreating(null);
                          focusRow('create');
                        }}
                      >
                        Cancel
                      </button>
                      <button
                        type="button"
                        className={styles.primary}
                        data-demo="create-submit"
                        onClick={create}
                      >
                        Create view
                      </button>
                    </div>
                  </div>
                ) : (
                  <div role="none" className={styles.row} data-row="create">
                    <button
                      type="button"
                      role="menuitem"
                      tabIndex={-1}
                      className={`${styles.item} ${styles.createItem}`}
                      data-item="create"
                      data-part="create"
                      data-demo="create"
                      onFocus={() => setHot('create')}
                      onPointerEnter={() => {
                        if (!options) setHot('create');
                      }}
                      onClick={() => {
                        setOptions(null);
                        setRenaming(null);
                        setHot(null);
                        setCreating({ name: '', type: 'table' });
                      }}
                    >
                      <Icon name="plus" className={styles.plus} />
                      Create new
                    </button>
                  </div>
                )}
              </div>

              {optionsView && (
                <div
                  ref={optionsBox}
                  role="menu"
                  aria-label={`Options for ${optionsView.name}`}
                  className={styles.options}
                  data-part="options"
                  style={{ top: optionsTop }}
                  onKeyDown={onOptionsKey}
                >
                  <button
                    type="button"
                    role="menuitem"
                    tabIndex={-1}
                    className={styles.optionItem}
                    aria-keyshortcuts="F2"
                    data-demo="option-rename"
                    onClick={() => {
                      setOptions(null);
                      setRenaming({ id: optionsView.id, name: optionsView.name });
                    }}
                  >
                    <Icon name="pencil" />
                    <span>Rename</span>
                    <kbd className={styles.kbd} aria-hidden="true">
                      F2
                    </kbd>
                  </button>
                  <button
                    type="button"
                    role="menuitem"
                    tabIndex={-1}
                    className={styles.optionItem}
                    data-demo="option-duplicate"
                    onClick={() => duplicate(optionsView)}
                  >
                    <Icon name="copy" />
                    <span>Duplicate</span>
                  </button>
                  <div role="separator" className={styles.separator} />
                  <button
                    type="button"
                    role="menuitem"
                    tabIndex={-1}
                    className={styles.optionItem}
                    data-tone="danger"
                    aria-disabled={views.length < 2 || undefined}
                    data-demo="option-delete"
                    onClick={() => remove(optionsView)}
                  >
                    <Icon name="trash" />
                    <span>Delete</span>
                  </button>
                </div>
              )}
            </div>
          </div>

          <div className={styles.anchor}>
            <button
              ref={filterButton}
              type="button"
              className={styles.tool}
              aria-haspopup="dialog"
              aria-expanded={open === 'filter'}
              aria-label={`Filter, ${ruleCount} ${ruleCount === 1 ? 'rule' : 'rules'}`}
              data-open={open === 'filter' || undefined}
              data-part="filter"
              data-demo="filter"
              onClick={() => (open === 'filter' ? close() : openPopover('filter'))}
              onKeyDown={onButtonKey('filter')}
            >
              <Icon name="filter" />
              <span className={styles.toolLabel}>Filter</span>
              <span className={styles.count} data-part="count" aria-hidden="true">
                <span key={ruleCount} className={styles.digit}>
                  {ruleCount}
                </span>
              </span>
            </button>
            {open === 'filter' && active && (
              <div
                ref={popover}
                role="dialog"
                aria-label={`Filters of ${active.name}`}
                className={`${styles.popover} ${styles.filters}`}
                data-part="filter-panel"
                onKeyDown={onPopoverKey('filter')}
              >
                <p className={styles.popHead}>
                  {count(shown.length)} match {ruleCount === 1 ? 'this rule' : 'these rules'}
                </p>
                <ul className={styles.rules}>
                  {active.rules.map((rule) => (
                    <li key={rule} className={styles.rule}>
                      <span>{RULES[rule].label}</span>
                      <button
                        type="button"
                        className={styles.ruleX}
                        aria-label={`Remove ${RULES[rule].label}`}
                        onClick={() =>
                          setRules(
                            active.rules.filter((r) => r !== rule),
                            `Removed ${RULES[rule].label}`,
                          )
                        }
                      >
                        <Icon name="close" />
                      </button>
                    </li>
                  ))}
                  {active.rules.length === 0 && (
                    <li className={styles.noRules}>No rules: everyone shows.</li>
                  )}
                </ul>
                {unused.length > 0 && (
                  <>
                    <p className={styles.popSub}>Add a rule</p>
                    <div className={styles.adds}>
                      {unused.map((rule) => (
                        <button
                          key={rule}
                          type="button"
                          className={styles.add}
                          onClick={() =>
                            setRules([...active.rules, rule], `Added ${RULES[rule].label}`)
                          }
                        >
                          <Icon name="plus" />
                          {RULES[rule].label}
                        </button>
                      ))}
                    </div>
                  </>
                )}
              </div>
            )}
          </div>

          <div className={styles.anchor}>
            <button
              ref={sortButton}
              type="button"
              className={styles.tool}
              aria-haspopup="menu"
              aria-expanded={open === 'sort'}
              aria-label={active ? `Sort, ${SORT_LABEL[active.sort].toLowerCase()}` : 'Sort'}
              data-open={open === 'sort' || undefined}
              data-part="sort"
              data-demo="sort"
              onClick={() => (open === 'sort' ? close() : openPopover('sort'))}
              onKeyDown={onButtonKey('sort')}
            >
              <Icon name="sort" />
              <span className={styles.toolLabel}>Sort</span>
            </button>
            {open === 'sort' && active && (
              <div
                ref={popover}
                role="menu"
                aria-label="Sort"
                className={`${styles.popover} ${styles.sortMenu}`}
                data-part="sort-menu"
                onKeyDown={onPopoverKey('sort')}
              >
                {(Object.keys(SORT_LABEL) as SortOrder[]).map((order) => {
                  const off = order === 'name' && active.type === 'chart';
                  return (
                    <button
                      key={order}
                      type="button"
                      role="menuitemradio"
                      aria-checked={active.sort === order}
                      aria-disabled={off || undefined}
                      tabIndex={-1}
                      className={styles.optionItem}
                      onClick={() => {
                        if (!off) setSort(order);
                      }}
                    >
                      <span>{SORT_LABEL[order]}</span>
                      <Icon name="check" className={styles.tick} />
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        </div>

        <div className={styles.body} data-type={active?.type} data-part="body">
          {active && (
            <div key={`${active.id}-${active.type}`} className={styles.content}>
              {active.type === 'table' && (
                <TableView
                  view={active}
                  people={shown}
                  selected={selected}
                  onToggle={toggle}
                  onToggleAll={toggleAll}
                />
              )}
              {active.type === 'board' && <BoardView view={active} people={shown} />}
              {active.type === 'chart' && <ChartView view={active} people={shown} />}
            </div>
          )}
        </div>

        {undo && (
          <div
            ref={toast}
            className={styles.toast}
            data-part="toast"
            onPointerEnter={() => setToastHover(true)}
            onPointerLeave={() => setToastHover(false)}
            onFocus={() => setToastFocus(true)}
            onBlur={(event) => {
              if (!event.currentTarget.contains(event.relatedTarget as Node | null))
                setToastFocus(false);
            }}
          >
            <span>
              Deleted <b>{undo.view.name}</b>
            </span>
            <button
              type="button"
              className={styles.undo}
              aria-keyshortcuts="Meta+Z Control+Z"
              onClick={restore}
            >
              Undo
            </button>
          </div>
        )}
      </section>

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

### view-switcher/views.tsx

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

'use client';

import type { CSSProperties } from 'react';
import { BUCKETS, COLUMN_LABEL, ago, bucketOf, when, type Person, type View } from './data';
import { Avatar, Sparkle } from './glyphs';
import styles from './view-switcher.module.css';

/*
 * What a view draws under the toolbar: the people as a table, as a board of cards grouped by how
 * long since you were in touch, or as bars of the same buckets. Each mounts afresh when the view
 * changes, so its rows come in one after the other (--i staggers them).
 */

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

export function TableView({
  view,
  people,
  selected,
  onToggle,
  onToggleAll,
}: {
  view: View;
  people: Person[];
  selected: Set<string>;
  onToggle: (id: string) => void;
  onToggleAll: () => void;
}) {
  const all = people.length > 0 && people.every((person) => selected.has(person.id));
  const some = people.some((person) => selected.has(person.id));
  return (
    <table className={styles.table} aria-label={`${view.name}, ${count(people.length)}`}>
      <thead>
        <tr>
          <th className={styles.checkCell} scope="col">
            <button
              type="button"
              role="checkbox"
              aria-checked={all ? true : some ? 'mixed' : false}
              aria-label="Select everyone in view"
              className={styles.check}
              disabled={people.length === 0}
              onClick={onToggleAll}
            />
          </th>
          <th scope="col" className={styles.nameHead}>
            Name<span className={styles.narrowOnly}> · {COLUMN_LABEL[view.column]}</span>
          </th>
          <th scope="col" className={styles.dateHead} data-part="date-head">
            <span>{COLUMN_LABEL[view.column]}</span>
            <Sparkle className={styles.sparkle} />
            <span className={styles.srOnly}>, filled in from your email and calendar</span>
          </th>
        </tr>
      </thead>
      <tbody>
        {people.map((person, i) => {
          const on = selected.has(person.id);
          return (
            <tr
              key={person.id}
              className={styles.tr}
              style={nth(i)}
              data-selected={on || undefined}
              data-part="row"
            >
              <td className={styles.checkCell}>
                <button
                  type="button"
                  role="checkbox"
                  aria-checked={on}
                  aria-label={`Select ${person.name}`}
                  className={styles.check}
                  onClick={() => onToggle(person.id)}
                />
              </td>
              <th scope="row" className={styles.nameCell}>
                <span className={styles.person}>
                  <Avatar name={person.name} tint={person.tint} />
                  <span className={styles.personText}>
                    <span className={styles.personName}>{person.name}</span>
                    {/* On a phone the date sits under the name, in place of its column. */}
                    <span className={styles.narrowOnly} aria-hidden="true">
                      {when(person[view.column])}
                    </span>
                  </span>
                </span>
              </th>
              <td className={styles.dateCell}>{when(person[view.column])}</td>
            </tr>
          );
        })}
        {people.length === 0 && (
          <tr>
            <td colSpan={3} className={styles.empty}>
              No one matches these filters.
            </td>
          </tr>
        )}
      </tbody>
    </table>
  );
}

export function BoardView({ view, people }: { view: View; people: Person[] }) {
  const columns = BUCKETS.map((bucket) => ({
    ...bucket,
    people: people.filter((person) => bucketOf(person) === bucket.id),
  })).filter((column) => column.people.length > 0);
  let i = 0;
  return (
    <div
      className={styles.board}
      role="group"
      aria-label={`${view.name}, ${count(people.length)}, by last contact`}
      // On a phone the lanes scroll sideways: the keyboard can scroll them too.
      tabIndex={0}
      data-part="board"
    >
      {columns.map((column) => (
        <section key={column.id} className={styles.lane} aria-label={column.label}>
          <h3 className={styles.laneHead}>
            <span className={styles.laneDot} data-bucket={column.id} aria-hidden="true" />
            {column.label}
            <span className={styles.laneCount}>{column.people.length}</span>
          </h3>
          <ul className={styles.cards}>
            {column.people.map((person) => (
              <li key={person.id} className={styles.card} style={nth(i++)} data-part="card">
                <Avatar name={person.name} tint={person.tint} />
                <span className={styles.cardText}>
                  <span className={styles.personName}>{person.name}</span>
                  <span className={styles.cardMeta}>Last contact {ago(person.contact)}</span>
                </span>
              </li>
            ))}
          </ul>
        </section>
      ))}
      {columns.length === 0 && <p className={styles.empty}>No one matches these filters.</p>}
    </div>
  );
}

export function ChartView({ view, people }: { view: View; people: Person[] }) {
  const bars = BUCKETS.map((bucket) => ({
    ...bucket,
    n: people.filter((person) => bucketOf(person) === bucket.id).length,
  }));
  if (view.sort === 'oldest') bars.reverse();
  const max = Math.max(1, ...bars.map((bar) => bar.n));
  return (
    <figure className={styles.chart} data-part="chart">
      <figcaption className={styles.chartHead}>
        <span className={styles.chartTotal}>{people.length}</span>
        <span className={styles.chartLabel}>people, by last contact</span>
      </figcaption>
      <ul className={styles.bars}>
        {bars.map((bar, i) => (
          <li key={bar.id} className={styles.bar} style={nth(i)} data-part="bar">
            <span className={styles.barValue} aria-hidden="true">
              {bar.n}
            </span>
            <span className={styles.barTrack} aria-hidden="true">
              <span
                className={styles.barFill}
                data-bucket={bar.id}
                style={{ '--h': bar.n / max } as CSSProperties}
              />
            </span>
            <span className={styles.barLabel}>
              <span aria-hidden="true">{bar.short}</span>
              <span className={styles.srOnly}>
                {bar.label}: {count(bar.n)}
              </span>
            </span>
          </li>
        ))}
      </ul>
    </figure>
  );
}

export const count = (n: number) => `${n} ${n === 1 ? 'person' : 'people'}`;
```

### view-switcher/data.ts

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

/*
 * The view switcher's data: the people of a records page, the rules a view filters them by, the
 * views saved by default, and how dates are written. Dates are counted from a fixed "now", in UTC,
 * so the server and the browser write the same words.
 */

export type ViewType = 'table' | 'board' | 'chart';
export type Strength = 'strong' | 'good' | 'weak';
export type Tint = 'amber' | 'green' | 'pink' | 'blue' | 'violet' | 'teal' | 'orange' | 'red';

export type Person = {
  id: string;
  name: string;
  tint: Tint;
  /** When the contact was added, `YYYY-MM-DDTHH:MM` (UTC). */
  added: string;
  /** When you were last in touch, or null if never. */
  contact: string | null;
  strength: Strength;
  owner: 'me' | 'team';
  email: boolean;
  bounced: boolean;
  archived: boolean;
  source: 'manual' | 'calendar' | 'import';
};

export type RuleId =
  | 'mine'
  | 'email'
  | 'delivered'
  | 'active'
  | 'year'
  | 'contacted'
  | 'manual'
  | 'strong'
  | 'recent'
  | 'quiet';

/** The date a view shows and sorts by. */
export type DateColumn = 'added' | 'contact';
export type SortOrder = 'recent' | 'oldest' | 'name';

export type View = {
  id: string;
  name: string;
  type: ViewType;
  rules: RuleId[];
  column: DateColumn;
  sort: SortOrder;
};

/** The moment the dates are counted from. */
export const NOW = Date.UTC(2026, 9, 30, 15, 20);
const DAY = 86_400_000;

export const time = (stamp: string) => {
  const [date, clock = '12:00'] = stamp.split('T');
  const [y, m, d] = date.split('-').map(Number);
  const [h, min] = clock.split(':').map(Number);
  return Date.UTC(y, m - 1, d, h, min);
};

/** Whole days since a date; Infinity for never. */
export const daysSince = (stamp: string | null) =>
  stamp === null ? Infinity : Math.floor((NOW - time(stamp)) / DAY);

export const PEOPLE: Person[] = [
  p('maren', 'Maren Okafor', 'amber', '2026-10-30T13:05', '2026-10-30T12:40', 'strong'),
  p('theo', 'Theo Lindqvist', 'green', '2026-10-29T00:41', '2026-10-28T10:00', 'good'),
  p('priya', 'Priya Raman', 'pink', '2026-10-29T13:32', '2026-10-29T16:00', 'strong'),
  p('caio', 'Caio Mendes', 'blue', '2026-03-27T10:14', '2026-10-02T09:30', 'good'),
  p('ines', 'Ines Valtonen', 'violet', '2026-03-21T16:02', '2026-08-14T11:00', 'good'),
  p('rafael', 'Rafael Duarte', 'orange', '2026-03-21T09:10', '2026-10-24T14:45', 'strong'),
  p('hana', 'Hana Kowal', 'green', '2026-02-21T08:30', '2026-06-02T10:20', 'weak'),
  p('oskar', 'Oskar Brandt', 'pink', '2026-02-21T17:48', '2026-10-12T13:10', 'strong'),
  p('leila', 'Leila Haddad', 'teal', '2026-10-27T11:25', '2026-10-27T15:00', 'strong', {
    owner: 'team',
  }),
  p('tomas', 'Tomás Ferreira', 'orange', '2025-06-11T10:00', '2026-09-15T09:00', 'good'),
  p('yuki', 'Yuki Morimoto', 'blue', '2026-09-03T12:12', null, 'weak', { source: 'import' }),
  p('nadia', 'Nadia Petrov', 'violet', '2026-07-19T14:40', '2026-08-31T10:30', 'good', {
    bounced: true,
  }),
  p('felix', 'Felix Aubert', 'teal', '2026-05-08T09:55', '2026-05-20T16:15', 'weak', {
    owner: 'team',
  }),
  p('sana', 'Sana Qureshi', 'red', '2026-01-14T10:05', '2026-10-20T09:40', 'strong', {
    archived: true,
  }),
  p('elio', 'Elio Marchetti', 'green', '2026-08-02T18:20', null, 'weak', { email: false }),
  p('greta', 'Greta Holm', 'amber', '2024-11-05T08:00', '2025-12-01T11:30', 'weak', {
    owner: 'team',
    source: 'import',
  }),
];

function p(
  id: string,
  name: string,
  tint: Tint,
  added: string,
  contact: string | null,
  strength: Strength,
  more: Partial<Person> = {},
): Person {
  return {
    id,
    name,
    tint,
    added,
    contact,
    strength,
    owner: 'me',
    email: true,
    bounced: false,
    archived: false,
    source: 'calendar',
    ...more,
  };
}

/** Each rule: how it reads in the Filter panel, and the people it keeps. */
export const RULES: Record<RuleId, { label: string; test: (person: Person) => boolean }> = {
  mine: { label: 'Owner is me', test: (x) => x.owner === 'me' },
  email: { label: 'Email is set', test: (x) => x.email },
  delivered: { label: 'Email hasn’t bounced', test: (x) => !x.bounced },
  active: { label: 'Not archived', test: (x) => !x.archived },
  year: { label: 'Added in the last year', test: (x) => daysSince(x.added) < 365 },
  contacted: { label: 'Contacted at least once', test: (x) => x.contact !== null },
  manual: { label: 'Not from a bulk import', test: (x) => x.source !== 'import' },
  strong: { label: 'Connection is strong', test: (x) => x.strength === 'strong' },
  recent: { label: 'Last contact within 30 days', test: (x) => daysSince(x.contact) <= 30 },
  quiet: {
    label: 'No contact for 2 weeks',
    test: (x) => x.contact !== null && daysSince(x.contact) > 14,
  },
};
export const RULE_IDS = Object.keys(RULES) as RuleId[];

export const VIEWS: View[] = [
  {
    id: 'activity',
    name: 'Activity',
    type: 'table',
    rules: ['mine', 'email', 'delivered', 'active', 'year', 'contacted', 'manual'],
    column: 'added',
    sort: 'recent',
  },
  {
    id: 'strong',
    name: 'Strong connection',
    type: 'table',
    rules: ['active', 'strong', 'recent'],
    column: 'contact',
    sort: 'recent',
  },
  {
    id: 'slipping',
    name: 'Slipping away',
    type: 'board',
    rules: ['active', 'quiet'],
    column: 'contact',
    sort: 'oldest',
  },
  {
    id: 'overview',
    name: 'Contact overview',
    type: 'chart',
    rules: ['active'],
    column: 'contact',
    sort: 'recent',
  },
];

export const TYPE_LABEL: Record<ViewType, string> = {
  table: 'Table',
  board: 'Board',
  chart: 'Chart',
};

export const COLUMN_LABEL: Record<DateColumn, string> = {
  added: 'Contact added',
  contact: 'Last contact',
};

export const SORT_LABEL: Record<SortOrder, string> = {
  recent: 'Newest first',
  oldest: 'Oldest first',
  name: 'Name, A to Z',
};

/** The people a view keeps, in its order. */
export function peopleFor(view: View, people: Person[]) {
  const kept = people.filter((person) => view.rules.every((rule) => RULES[rule].test(person)));
  const at = (person: Person) => {
    const stamp = person[view.column];
    return stamp === null ? null : time(stamp);
  };
  return kept.sort((a, b) => {
    if (view.sort === 'name') return a.name.localeCompare(b.name);
    const x = at(a);
    const y = at(b);
    if (x === null || y === null) return x === y ? 0 : x === null ? 1 : -1;
    return view.sort === 'recent' ? y - x : x - y;
  });
}

/** How long since you were last in touch, in buckets: the board's columns, the chart's bars. */
export const BUCKETS = [
  { id: 'week', label: 'This week', short: 'Week', test: (d: number) => d < 7 },
  { id: 'month', label: '1–4 weeks ago', short: '1–4 wk', test: (d: number) => d >= 7 && d <= 30 },
  {
    id: 'quarter',
    label: '1–3 months ago',
    short: '1–3 mo',
    test: (d: number) => d > 30 && d <= 90,
  },
  {
    id: 'older',
    label: 'Over 3 months',
    short: '3 mo+',
    test: (d: number) => d > 90 && d !== Infinity,
  },
  { id: 'never', label: 'Never contacted', short: 'Never', test: (d: number) => d === Infinity },
] as const;

export const bucketOf = (person: Person) =>
  BUCKETS.find((bucket) => bucket.test(daysSince(person.contact)))?.id ?? 'never';

const MONTHS = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December',
];
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

const clock = (at: Date) => {
  const h = at.getUTCHours();
  const m = String(at.getUTCMinutes()).padStart(2, '0');
  return `${h % 12 || 12}:${m} ${h < 12 ? 'am' : 'pm'}`;
};

/** A date as the table writes it: 2 hours ago, Yesterday, 12:41 am, March 27, 2025. */
export function when(stamp: string | null) {
  if (stamp === null) return 'Never';
  const at = new Date(time(stamp));
  const minutes = Math.round((NOW - at.getTime()) / 60_000);
  const today = new Date(NOW);
  const dayStart = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
  if (minutes < 60) return minutes <= 1 ? 'Just now' : `${minutes} minutes ago`;
  if (at.getTime() >= dayStart) {
    const hours = Math.round(minutes / 60);
    return hours === 1 ? '1 hour ago' : `${hours} hours ago`;
  }
  if (at.getTime() >= dayStart - DAY) return `Yesterday, ${clock(at)}`;
  if (at.getTime() >= dayStart - 6 * DAY) return `${WEEKDAYS[at.getUTCDay()]}, ${clock(at)}`;
  const date = `${MONTHS[at.getUTCMonth()]} ${at.getUTCDate()}`;
  return at.getUTCFullYear() === today.getUTCFullYear() ? date : `${date}, ${at.getUTCFullYear()}`;
}

/** How long ago, in round words: 3 days ago, 4 weeks ago, 5 months ago. */
export function ago(stamp: string | null) {
  const days = daysSince(stamp);
  if (days === Infinity) return 'Never';
  if (days < 1) return 'Today';
  if (days < 2) return 'Yesterday';
  if (days < 14) return `${days} days ago`;
  if (days < 60) return `${Math.round(days / 7)} weeks ago`;
  if (days < 365) return `${Math.round(days / 30)} months ago`;
  const years = Math.round(days / 365);
  return years === 1 ? 'A year ago' : `${years} years ago`;
}
```

### view-switcher/view-switcher.module.css

```css
/* View switcher (view-switcher.tsx): a records page, People, on a grey stage. The head names the
   page; the toolbar holds the views button, Filter and Sort; the body draws the active view as a
   table, a board or a chart. The views menu hangs from its button over the body.

   Under 560 px of stage, Filter and Sort keep their icons only, the views button takes the rest of
   the row, and the table's columns tighten.

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

.root {
  --stage: #ececee;
  --surface: #ffffff;
  --surface-2: #f6f6f7;
  --line: #ebebed;
  --edge: #e3e3e6;
  --ink: #141416;
  --ink-2: #66666e;
  --ink-3: #6e6e76;
  --accent: #1b67d8;
  --accent-ink: #ffffff;
  --accent-soft: #edf3fe;
  --halo: #d6e5fc;
  --ring: #5890e8;
  --band: #f3f3f4;
  --column: #f9f8fc;
  --selected: #f3f7fe;
  --menu: #ffffff;
  --menu-edge: #e8e8eb;
  --shadow: rgb(20 20 30 / 0.16);
  --shadow-near: rgb(20 20 30 / 0.06);
  --count: #e6effd;
  --count-ink: #1b67d8;
  --beta: #d4f1fb;
  --beta-ink: #0b5675;
  --sparkle: #9b6cf2;
  --danger: #c83428;
  --tip: #1d1d21;
  --tip-ink: #f4f4f5;
  --toast: #1d1d21;
  --toast-ink: #f4f4f5;
  --toast-accent: #8db7ff;
  --check-edge: #8a8a92;
  /* The view types' tiles and the avatars' tints: the same on both schemes. */
  --table: #1fa463;
  --board: #e2283c;
  --chart: #7b4ff0;
  --amber: #e2a10b;
  --green: #22a565;
  --pink: #e8457f;
  --blue: #3d7ee8;
  --violet: #8a5cf0;
  --teal: #16a3a3;
  --orange: #ec7a28;
  --red: #dc3f3a;
  /* The buckets of last contact. */
  --b-week: #22a565;
  --b-month: #3d7ee8;
  --b-quarter: #e2a10b;
  --b-older: #e2283c;
  --b-never: #b5b5bc;
  --focus: #4282ec;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.3);
  --sans: var(--body, Inter, ui-sans-serif, system-ui, sans-serif);
  --mono: var(--code, ui-monospace, 'SF Mono', Menlo, monospace);
  --spring: linear(
    0,
    0.009,
    0.035 2.1%,
    0.141 4.4%,
    0.723 15.5%,
    0.938 20.7%,
    1.017 24.3%,
    1.061 28%,
    1.074 31.2%,
    1.067 34.7%,
    1.036 40.4%,
    1.004 47.3%,
    0.993 53.3%,
    0.998 70%,
    1
  );
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --stage: light-dark(#ececee, #232326);
    --surface: light-dark(#ffffff, #141416);
    --surface-2: light-dark(#f6f6f7, #1b1b1e);
    --line: light-dark(#ebebed, #26262a);
    --edge: light-dark(#e3e3e6, #303035);
    --ink: light-dark(#141416, #f2f2f3);
    --ink-2: light-dark(#66666e, #a3a3ab);
    --ink-3: light-dark(#6e6e76, #8e8e96);
    --accent: light-dark(#1b67d8, #5b9bff);
    --accent-ink: light-dark(#ffffff, #0b1426);
    --accent-soft: light-dark(#edf3fe, #17243b);
    --halo: light-dark(#d6e5fc, #1d3358);
    --ring: light-dark(#5890e8, #4f8cf0);
    --band: light-dark(#f3f3f4, #26262b);
    --column: light-dark(#f9f8fc, #18171d);
    --selected: light-dark(#f3f7fe, #172030);
    --menu: light-dark(#ffffff, #1e1e22);
    --menu-edge: light-dark(#e8e8eb, #34343a);
    --shadow: light-dark(rgb(20 20 30 / 0.16), rgb(0 0 0 / 0.6));
    --shadow-near: light-dark(rgb(20 20 30 / 0.06), rgb(0 0 0 / 0.3));
    --count: light-dark(#e6effd, #1a2a47);
    --count-ink: light-dark(#1b67d8, #8db7ff);
    --beta: light-dark(#d4f1fb, #0e3343);
    --beta-ink: light-dark(#0b5675, #7fd3f0);
    --sparkle: light-dark(#9b6cf2, #b18eff);
    --danger: light-dark(#c83428, #ff6b5f);
    --tip: light-dark(#1d1d21, #f2f2f3);
    --tip-ink: light-dark(#f4f4f5, #141416);
    --toast: light-dark(#1d1d21, #2a2a30);
    --toast-accent: light-dark(#8db7ff, #8db7ff);
    --check-edge: light-dark(#8a8a92, #707078);
    --focus: light-dark(#4282ec, #4f8cf0);
    --b-never: light-dark(#b5b5bc, #55555d);
  }
}
.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: clamp(14px, 4.5%, 36px) clamp(12px, 4%, 32px);
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background: var(--stage);
  color: var(--ink);
  font-family: var(--sans);
  font-size: 14px;
  line-height: 1.35;
  -webkit-tap-highlight-color: transparent;
}
.root :where(button, input) {
  font: inherit;
  color: inherit;
}
.root button {
  cursor: pointer;
}
.root button[aria-disabled='true'],
.root button:disabled {
  cursor: default;
}
.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;
}
.icon {
  width: 18px;
  height: 18px;
}

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

.app {
  position: relative;
  max-width: 780px;
  margin: 0 auto;
  border: 1px solid var(--edge);
  border-radius: 14px;
  background: var(--surface);
  box-shadow:
    0 1px 2px var(--shadow-near),
    0 24px 48px -30px var(--shadow);
}
.head {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 18px 24px 17px;
  border-bottom: 1px solid var(--line);
}
.title {
  margin: 0;
  font-size: 22px;
  font-weight: 650;
  line-height: 1.2;
  letter-spacing: -0.02em;
}
.tipWrap {
  position: relative;
  display: flex;
}
.info {
  display: grid;
  place-items: center;
  width: 26px;
  height: 26px;
  padding: 0;
  border: 0;
  border-radius: 50%;
  background: none;
  color: var(--ink-3) !important;
  transition: color 0.15s ease;
}
.info:hover {
  color: var(--ink-2) !important;
}
.info svg {
  width: 20px;
  height: 20px;
}
.tip {
  position: absolute;
  top: calc(100% + 8px);
  left: 50%;
  z-index: 12;
  width: 228px;
  padding: 8px 10px;
  border-radius: 8px;
  background: var(--tip);
  color: var(--tip-ink);
  font-size: 12.5px;
  line-height: 1.4;
  translate: -50% -3px;
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
  transition:
    opacity 0.14s ease,
    translate 0.14s ease,
    visibility 0s linear 0.14s;
}
.tip[data-open] {
  translate: -50% 0;
  opacity: 1;
  visibility: visible;
  transition:
    opacity 0.16s ease 0.12s,
    translate 0.3s var(--spring) 0.12s,
    visibility 0s;
}
.beta {
  padding: 3px 7px 2px;
  border-radius: 6px;
  background: var(--beta);
  color: var(--beta-ink);
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 0.05em;
  text-transform: uppercase;
}

/* ---- The toolbar ------------------------------------------------------------------------------ */

.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 14px 24px;
}
.anchor {
  position: relative;
  display: flex;
}
.viewsButton,
.tool {
  display: flex;
  align-items: center;
  height: 38px;
  border: 1px solid var(--edge);
  border-radius: 10px;
  background: var(--surface);
  font-size: 15px;
  font-weight: 500;
  white-space: nowrap;
  transition:
    border-color 0.18s ease,
    box-shadow 0.18s ease,
    background-color 0.15s ease;
}
.viewsButton:hover,
.tool:hover {
  background: var(--surface-2);
}
.viewsButton[data-open],
.tool[data-open] {
  border-color: var(--ring);
  background: var(--surface);
  box-shadow: 0 0 0 3px var(--halo);
}
.viewsButton {
  gap: 9px;
  width: 210px;
  padding: 0 10px 0 9px;
}
.viewsName {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-align: left;
  text-overflow: ellipsis;
}
.swap {
  animation: swap 0.32s var(--spring);
}
@keyframes swap {
  from {
    opacity: 0;
    translate: 0 5px;
  }
}
.chevron {
  width: 17px;
  height: 17px;
  color: var(--ink-2);
  transition: rotate 0.3s var(--spring);
}
.viewsButton[data-open] .chevron {
  rotate: 180deg;
}
.tool {
  gap: 8px;
  padding: 0 12px;
}
.tool > svg {
  width: 18px;
  height: 18px;
}
.count {
  display: grid;
  min-width: 22px;
  height: 22px;
  padding: 0 5px;
  overflow: hidden;
  border-radius: 6px;
  background: var(--count);
  color: var(--count-ink);
  font-size: 13px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
  place-items: center;
}
.digit {
  animation: roll 0.42s var(--spring);
}
@keyframes roll {
  from {
    opacity: 0;
    translate: 0 70%;
  }
}

/* The type tiles: white marks on the type's colour. */
.tile {
  display: grid;
  flex: none;
  width: 20px;
  height: 20px;
  border-radius: 5px;
  background: var(--table);
  color: #fff;
  place-items: center;
}
.tile[data-type='board'] {
  background: var(--board);
}
.tile[data-type='chart'] {
  background: var(--chart);
}
.tile svg {
  width: 17px;
  height: 17px;
}

/* ---- The views menu --------------------------------------------------------------------------- */

.menu {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  z-index: 10;
  width: min(330px, calc(100cqw - 40px));
  padding: 4px 0 6px;
  border: 1px solid var(--menu-edge);
  border-radius: 12px;
  background: var(--menu);
  box-shadow:
    0 2px 6px var(--shadow-near),
    0 18px 40px -14px var(--shadow);
  transform-origin: 30px 0;
  scale: 0.94;
  translate: 0 -4px;
  opacity: 0;
  visibility: hidden;
  transition:
    opacity 0.12s ease,
    scale 0.14s ease,
    translate 0.14s ease,
    visibility 0s linear 0.14s;
}
.menu[data-open] {
  scale: 1;
  translate: 0 0;
  opacity: 1;
  visibility: visible;
  transition:
    opacity 0.14s ease-out,
    scale 0.42s var(--spring),
    translate 0.42s var(--spring),
    visibility 0s;
}
.caption {
  padding: 9px 16px 5px;
  color: var(--ink-2);
  font-size: 13.5px;
}
.list {
  position: relative;
}
.band {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  height: 40px;
  background: var(--band);
  opacity: 0;
  pointer-events: none;
  transition:
    translate 0.3s var(--spring),
    height 0.2s ease,
    opacity 0.12s ease;
}
.band[data-on] {
  opacity: 1;
}
.row {
  position: relative;
  display: flex;
  align-items: center;
  height: 41px;
}
.item {
  display: flex;
  flex: 1;
  align-items: center;
  gap: 12px;
  min-width: 0;
  height: 100%;
  padding: 0 6px 0 16px;
  border: 0;
  background: none;
  font-size: 15.5px;
  font-weight: 500;
  text-align: left;
}
.root .item:focus-visible {
  outline: none;
  box-shadow: inset 2px 0 0 var(--accent);
}
.itemName {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: color 0.2s ease;
}
.item[data-active] .itemName {
  color: var(--accent);
}
.itemName[data-hidden] {
  visibility: hidden;
}
.rename {
  position: absolute;
  top: 6px;
  right: 46px;
  left: 42px;
  height: 29px;
  padding: 0 7px;
  border: 1px solid var(--ring);
  border-radius: 7px;
  outline: none;
  background: var(--surface);
  box-shadow: 0 0 0 3px var(--halo);
  font-size: 15.5px !important;
  font-weight: 500 !important;
}
.more {
  display: grid;
  flex: none;
  width: 30px;
  height: 30px;
  margin-right: 10px;
  padding: 0;
  border: 0;
  border-radius: 7px;
  background: none;
  color: var(--ink-3) !important;
  place-items: center;
  transition:
    background-color 0.15s ease,
    color 0.15s ease;
}
.more:hover,
.more[data-open] {
  background: var(--menu);
  color: var(--ink) !important;
}
.more svg {
  width: 18px;
  height: 18px;
}
.createItem {
  color: var(--ink-2) !important;
  font-weight: 450;
}
.plus {
  width: 20px;
  height: 20px;
}

/* Create new, filled in inside the menu. */
.create {
  display: grid;
  gap: 9px;
  margin: 4px 0 0;
  padding: 10px 12px 6px;
  border-top: 1px solid var(--line);
  animation: unfold 0.32s var(--spring);
}
@keyframes unfold {
  from {
    opacity: 0;
    translate: 0 -4px;
  }
}
.createName {
  height: 36px;
  padding: 0 10px;
  border: 1px solid var(--edge);
  border-radius: 8px;
  outline: none;
  background: var(--surface);
  font-size: 15px !important;
  transition:
    border-color 0.15s ease,
    box-shadow 0.15s ease;
}
.createName::placeholder {
  color: var(--ink-3);
}
.createName:focus {
  border-color: var(--ring);
  box-shadow: 0 0 0 3px var(--halo);
}
.types {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 6px;
}
.type {
  display: flex;
  align-items: center;
  gap: 7px;
  height: 34px;
  padding: 0 8px;
  border: 1px solid var(--edge);
  border-radius: 8px;
  background: var(--surface);
  font-size: 13.5px;
  font-weight: 500;
  transition:
    border-color 0.15s ease,
    background-color 0.15s ease,
    color 0.15s ease;
}
.type .tile {
  width: 18px;
  height: 18px;
}
.type[aria-checked='true'] {
  border-color: var(--ring);
  background: var(--accent-soft);
  color: var(--accent) !important;
}
.createEnd {
  display: flex;
  justify-content: flex-end;
  gap: 6px;
}
.ghost,
.primary {
  height: 31px;
  padding: 0 12px;
  border: 0;
  border-radius: 8px;
  font-size: 13.5px;
  font-weight: 550;
}
.ghost {
  background: none;
  color: var(--ink-2) !important;
}
.ghost:hover {
  background: var(--band);
}
.primary {
  background: var(--accent);
  color: var(--accent-ink) !important;
}

/* A view's ⋮ menu, under its row. */
.options {
  position: absolute;
  right: 10px;
  z-index: 2;
  width: 188px;
  padding: 5px;
  border: 1px solid var(--menu-edge);
  border-radius: 10px;
  background: var(--menu);
  box-shadow:
    0 2px 6px var(--shadow-near),
    0 16px 32px -12px var(--shadow);
  transform-origin: 85% 0;
  animation: pop 0.36s var(--spring);
}
@keyframes pop {
  from {
    opacity: 0;
    scale: 0.92;
  }
}
.optionItem {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  height: 33px;
  padding: 0 9px;
  border: 0;
  border-radius: 7px;
  background: none;
  font-size: 14px;
  text-align: left;
}
.optionItem:hover,
.root .optionItem:focus-visible {
  background: var(--band);
}
.root .optionItem:focus-visible {
  outline-offset: -2px;
}
.optionItem svg {
  width: 17px;
  height: 17px;
  color: var(--ink-2);
}
.optionItem[data-tone='danger'],
.optionItem[data-tone='danger'] svg {
  color: var(--danger) !important;
}
.optionItem[aria-disabled='true'] {
  opacity: 0.45;
}
.optionItem[aria-disabled='true']:hover {
  background: none;
}
.kbd {
  margin-left: auto;
  padding: 1px 5px;
  border: 1px solid var(--line);
  border-radius: 5px;
  color: var(--ink-3);
  font-family: var(--mono);
  font-size: 11px;
}
.separator {
  height: 1px;
  margin: 4px 6px;
  background: var(--line);
}

/* ---- Filter and Sort -------------------------------------------------------------------------- */

.popover {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  z-index: 10;
  padding: 5px;
  border: 1px solid var(--menu-edge);
  border-radius: 12px;
  background: var(--menu);
  box-shadow:
    0 2px 6px var(--shadow-near),
    0 18px 40px -14px var(--shadow);
  transform-origin: 20px 0;
  animation: pop 0.38s var(--spring);
}
.sortMenu {
  right: 0;
  left: auto;
  width: 196px;
  transform-origin: calc(100% - 20px) 0;
}
.tick {
  width: 17px;
  height: 17px;
  margin-left: auto;
  color: var(--accent) !important;
  visibility: hidden;
}
[aria-checked='true'] > .tick {
  visibility: visible;
}
.filters {
  width: 292px;
  padding: 10px;
}
.popHead {
  margin: 2px 4px 8px;
  color: var(--ink-2);
  font-size: 13px;
}
.rules {
  display: grid;
  gap: 3px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.rule {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 31px;
  padding: 0 4px 0 10px;
  border-radius: 7px;
  background: var(--surface-2);
  font-size: 13.5px;
  animation: unfold 0.3s var(--spring);
}
.ruleX {
  display: grid;
  width: 25px;
  height: 25px;
  padding: 0;
  border: 0;
  border-radius: 6px;
  background: none;
  color: var(--ink-3) !important;
  place-items: center;
}
.ruleX:hover {
  background: var(--band);
  color: var(--ink) !important;
}
.ruleX svg {
  width: 15px;
  height: 15px;
}
.noRules {
  padding: 6px 4px;
  color: var(--ink-3);
  font-size: 13px;
}
.popSub {
  margin: 12px 4px 6px;
  color: var(--ink-2);
  font-size: 12.5px;
}
.adds {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
.add {
  display: flex;
  align-items: center;
  gap: 4px;
  height: 27px;
  padding: 0 8px 0 6px;
  border: 1px dashed var(--check-edge);
  border-radius: 7px;
  background: none;
  color: var(--ink-2) !important;
  font-size: 12.5px;
}
.add:hover {
  border-style: solid;
  color: var(--ink) !important;
}
.add svg {
  width: 13px;
  height: 13px;
}

/* ---- The body: a table, a board or a chart ---------------------------------------------------- */

.body {
  position: relative;
  min-height: 386px;
  overflow: hidden;
  overflow: clip;
  border-top: 1px solid var(--line);
  border-radius: 0 0 13px 13px;
}
.content {
  animation: fade 0.25s ease;
}
@keyframes fade {
  from {
    opacity: 0;
  }
}
.table {
  width: 100%;
  border-collapse: collapse;
  font-size: 15px;
}
.table th,
.table td {
  height: 47px;
  padding: 0 12px;
  border-bottom: 1px solid var(--line);
  text-align: left;
  white-space: nowrap;
}
.table thead th {
  height: 46px;
  color: var(--ink-2);
  font-weight: 450;
}
.checkCell {
  width: 52px;
  padding-left: 24px !important;
  padding-right: 4px !important;
}
.nameCell {
  font-weight: 500;
}
.dateHead,
.dateCell {
  width: 42%;
  padding: 0 20px !important;
  border-left: 1px solid var(--line);
  background: var(--column);
}
.dateHead {
  position: relative;
}
.dateCell {
  color: var(--ink-2);
  font-variant-numeric: tabular-nums;
}
.sparkle {
  position: absolute;
  top: 50%;
  right: 16px;
  width: 17px;
  height: 17px;
  color: var(--sparkle);
  translate: 0 -50%;
}
.tr[data-selected] td,
.tr[data-selected] th {
  background: var(--selected);
}
.table tbody tr {
  animation: enter 0.38s var(--spring) backwards;
  animation-delay: calc(var(--i, 0) * 26ms);
}
@keyframes enter {
  from {
    opacity: 0;
    translate: 0 6px;
  }
}
.person {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
}
.personText {
  display: grid;
  min-width: 0;
}
.narrowOnly {
  display: none;
}
.personName {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.avatar {
  display: grid;
  flex: none;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background: var(--amber);
  color: #fff;
  font-size: 11.5px;
  font-weight: 600;
  place-items: center;
}
.avatar[data-tint='green'] {
  background: var(--green);
}
.avatar[data-tint='pink'] {
  background: var(--pink);
}
.avatar[data-tint='blue'] {
  background: var(--blue);
}
.avatar[data-tint='violet'] {
  background: var(--violet);
}
.avatar[data-tint='teal'] {
  background: var(--teal);
}
.avatar[data-tint='orange'] {
  background: var(--orange);
}
.avatar[data-tint='red'] {
  background: var(--red);
}
.check {
  position: relative;
  display: block;
  width: 19px;
  height: 19px;
  padding: 0;
  border: 1.5px solid var(--check-edge);
  border-radius: 5px;
  background: var(--surface);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}
.check:disabled {
  opacity: 0.5;
}
.check[aria-checked='true'],
.check[aria-checked='mixed'] {
  border-color: var(--accent);
  background: var(--accent);
}
.check[aria-checked='true']::after {
  content: '';
  position: absolute;
  top: 2px;
  left: 5px;
  width: 5px;
  height: 9px;
  border: solid var(--accent-ink);
  border-width: 0 2px 2px 0;
  rotate: 45deg;
}
.check[aria-checked='mixed']::after {
  content: '';
  position: absolute;
  top: 7px;
  left: 3px;
  width: 10px;
  height: 2px;
  border-radius: 1px;
  background: var(--accent-ink);
}
.empty {
  padding: 48px 24px !important;
  color: var(--ink-3);
  text-align: center !important;
}

/* The board: a lane per bucket of last contact. */
.board {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  align-items: start;
  gap: 12px;
  padding: 18px 24px 22px;
}
.lane {
  padding: 10px;
  border-radius: 11px;
  background: var(--surface-2);
}
.laneHead {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 2px 4px 10px;
  font-size: 13.5px;
  font-weight: 600;
}
.laneDot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--b-week);
}
.laneCount {
  margin-left: auto;
  color: var(--ink-3);
  font-weight: 500;
}
.cards {
  display: grid;
  gap: 6px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.card {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
  padding: 9px 10px;
  border: 1px solid var(--line);
  border-radius: 9px;
  background: var(--surface);
  box-shadow: 0 1px 2px var(--shadow-near);
  animation: enter 0.4s var(--spring) backwards;
  animation-delay: calc(var(--i, 0) * 34ms);
}
.cardText {
  display: grid;
  min-width: 0;
  font-weight: 500;
}
.cardMeta {
  overflow: hidden;
  color: var(--ink-2);
  font-size: 12.5px;
  font-weight: 400;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.root [data-bucket='month'] {
  --bucket: var(--b-month);
}
.root [data-bucket='quarter'] {
  --bucket: var(--b-quarter);
}
.root [data-bucket='older'] {
  --bucket: var(--b-older);
}
.root [data-bucket='never'] {
  --bucket: var(--b-never);
}
.laneDot[data-bucket] {
  background: var(--bucket, var(--b-week));
}

/* The chart: bars of the same buckets. */
.chart {
  margin: 0;
  padding: 20px 24px 22px;
}
.chartHead {
  display: flex;
  align-items: baseline;
  gap: 8px;
}
.chartTotal {
  font-size: 28px;
  font-weight: 650;
  letter-spacing: -0.02em;
  font-variant-numeric: tabular-nums;
}
.chartLabel {
  color: var(--ink-2);
  font-size: 14px;
}
.bars {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 14px;
  height: 250px;
  margin: 16px 0 0;
  padding: 0;
  border-bottom: 1px solid var(--line);
  list-style: none;
}
.bar {
  display: grid;
  grid-template-rows: auto 1fr;
  justify-items: center;
  gap: 6px;
  min-width: 0;
  height: 100%;
  position: relative;
  padding-bottom: 0;
}
.barValue {
  font-size: 13.5px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}
.barTrack {
  display: flex;
  align-items: flex-end;
  width: 100%;
  max-width: 64px;
  height: 100%;
}
.barFill {
  width: 100%;
  height: calc(var(--h, 0) * 100%);
  min-height: 3px;
  border-radius: 7px 7px 2px 2px;
  background: var(--chart);
  transform-origin: 50% 100%;
  animation: grow 0.6s var(--spring) backwards;
  animation-delay: calc(var(--i, 0) * 50ms);
}
.barFill[data-bucket='never'] {
  background: var(--b-never);
}
@keyframes grow {
  from {
    scale: 1 0;
  }
}
.barLabel {
  position: absolute;
  top: calc(100% + 8px);
  color: var(--ink-2);
  font-size: 12.5px;
  white-space: nowrap;
}
.chart {
  padding-bottom: 40px;
}

/* ---- The undo --------------------------------------------------------------------------------- */

.toast {
  position: absolute;
  bottom: 16px;
  left: 50%;
  z-index: 11;
  display: flex;
  align-items: center;
  gap: 14px;
  max-width: calc(100% - 32px);
  padding: 7px 7px 7px 14px;
  border-radius: 10px;
  background: var(--toast);
  color: var(--toast-ink);
  font-size: 13.5px;
  white-space: nowrap;
  box-shadow: 0 16px 32px -12px var(--shadow);
  translate: -50% 0;
  animation: rise 0.42s var(--spring);
}
.toast b {
  font-weight: 600;
}
.toast > span {
  overflow: hidden;
  text-overflow: ellipsis;
}
@keyframes rise {
  from {
    opacity: 0;
    translate: -50% 12px;
  }
}
.undo {
  height: 28px;
  padding: 0 9px;
  border: 0;
  border-radius: 6px;
  background: none;
  color: var(--toast-accent) !important;
  font-weight: 600;
}
.undo:hover {
  background: rgb(255 255 255 / 0.08);
}

/* ---- Phones ----------------------------------------------------------------------------------- */

@container (max-width: 560px) {
  .root {
    padding: 10px 8px;
  }
  .head {
    padding: 14px 16px 13px;
  }
  .title {
    font-size: 19px;
  }
  .toolbar {
    gap: 6px;
    padding: 12px 14px;
  }
  .viewsButton {
    flex: 1;
    width: auto;
    min-width: 0;
  }
  .anchor:first-child {
    flex: 1;
    min-width: 0;
  }
  .tool {
    padding: 0 9px;
  }
  .filters {
    width: min(292px, calc(100cqw - 24px));
  }
  .toolLabel {
    position: absolute;
    width: 1px;
    height: 1px;
    overflow: hidden;
    clip-path: inset(50%);
  }
  .menu {
    width: calc(100cqw - 34px);
  }
  .body {
    min-height: 300px;
  }
  /* The date moves under the name: two lines a row, no third column. */
  .table {
    table-layout: fixed;
    font-size: 14.5px;
  }
  .table th,
  .table td {
    height: 54px;
  }
  .checkCell {
    width: 42px;
    padding-left: 14px !important;
  }
  .nameCell,
  .nameHead {
    padding: 0 14px 0 6px !important;
    overflow: hidden;
  }
  .dateHead,
  .dateCell {
    display: none;
  }
  .narrowOnly {
    display: inline;
  }
  .personText .narrowOnly {
    display: block;
    overflow: hidden;
    color: var(--ink-2);
    font-size: 12.5px;
    font-weight: 400;
    text-overflow: ellipsis;
  }
  .sparkle {
    display: none;
  }
  /* Lanes side by side, as wide as a card needs: the board scrolls sideways in its own box. */
  .board {
    grid-template-columns: none;
    grid-auto-columns: 208px;
    grid-auto-flow: column;
    padding: 14px 14px 18px;
    overflow-x: auto;
    overscroll-behavior-x: contain;
    scrollbar-width: none;
  }
  .chart {
    padding: 16px 16px 40px;
  }
  .bars {
    gap: 8px;
    height: 210px;
  }
  .barLabel {
    font-size: 11.5px;
  }
}

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

.pointerLayer {
  position: absolute;
  inset: 0;
  z-index: 20;
  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;
}
[data-over].viewsButton,
[data-over].tool {
  background: var(--surface-2);
}
[data-over].type,
[data-over].primary {
  filter: brightness(0.96);
}

@media (prefers-reduced-motion: reduce) {
  .menu,
  .menu[data-open],
  .band,
  .tip,
  .tip[data-open],
  .chevron,
  .viewsButton,
  .tool {
    transition: none;
  }
  .swap,
  .digit,
  .create,
  .options,
  .popover,
  .rule,
  .content,
  .table tbody tr,
  .card,
  .barFill,
  .toast {
    animation: none;
  }
}
```

### view-switcher/glyphs.tsx

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

import type { ReactNode } from 'react';
import type { Tint, ViewType } from './data';
import styles from './view-switcher.module.css';

/*
 * The drawings: line icons on a 20-unit grid in the text's colour, the view types' coloured tiles,
 * and the people's initials. All of them are decorative; the buttons around them carry the words.
 */

const PATHS = {
  chevron: <path d="m6 8 4 4 4-4" />,
  filter: <path d="M3.5 4.5h13l-5 6.2v4.8l-3 1.5v-6.3z" />,
  sort: <path d="M6.5 15.5v-11m0 0L4 7m2.5-2.5L9 7m4.5-2.5v11m0 0L11 13m2.5 2.5L16 13" />,
  info: (
    <>
      <circle cx="10" cy="10" r="7" />
      <path d="M10 9v4.5" />
      <path d="M10 6.4v.1" strokeWidth="2.2" />
    </>
  ),
  more: (
    <>
      <path d="M10 4.6v.1M10 10v.1M10 15.4v.1" strokeWidth="2.4" />
    </>
  ),
  plus: <path d="M10 4v12M4 10h12" />,
  pencil: <path d="m12.5 4.5 3 3L7.5 15.5H4.5v-3zM11 6l3 3" />,
  copy: (
    <>
      <rect x="7" y="7" width="9" height="9" rx="2" />
      <path d="M13 7V5.5A1.5 1.5 0 0 0 11.5 4h-6A1.5 1.5 0 0 0 4 5.5v6A1.5 1.5 0 0 0 5.5 13H7" />
    </>
  ),
  trash: (
    <path d="M4 6h12M8 6V4.5h4V6m-6.5 0 .7 9.2a1.5 1.5 0 0 0 1.5 1.3h4.6a1.5 1.5 0 0 0 1.5-1.3L14.5 6M8.5 9v4.5M11.5 9v4.5" />
  ),
  check: <path d="m5 10.5 3.2 3L15 6.5" />,
  close: <path d="m6 6 8 8m0-8-8 8" />,
};
export type IconName = keyof typeof PATHS;

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

/** The twin-star mark of a column filled in on its own. */
export function Sparkle({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 20 20" className={className} fill="currentColor" aria-hidden="true">
      <path d="M12.5 2.5c.4 2.7 1.6 3.9 4.3 4.3-2.7.4-3.9 1.6-4.3 4.3-.4-2.7-1.6-3.9-4.3-4.3 2.7-.4 3.9-1.6 4.3-4.3z" />
      <path d="M6 10.5c.3 1.8 1 2.6 2.9 2.9-1.8.3-2.6 1-2.9 2.9-.3-1.9-1.1-2.6-2.9-2.9 1.8-.3 2.6-1.1 2.9-2.9z" />
    </svg>
  );
}

const TILE: Record<ViewType, ReactNode> = {
  // Three rows of a list: a dot and a line each.
  table: (
    <>
      <path d="M5.2 6h.1M5.2 10h.1M5.2 14h.1" strokeWidth="2.2" />
      <path d="M8.2 6h6.6M8.2 10h6.6M8.2 14h6.6" />
    </>
  ),
  // Two columns of cards, the left one taller.
  board: (
    <>
      <rect x="4.2" y="4.2" width="4.9" height="11.6" rx="1.2" fill="currentColor" stroke="none" />
      <rect x="10.9" y="4.2" width="4.9" height="6.4" rx="1.2" fill="currentColor" stroke="none" />
    </>
  ),
  // Three bars.
  chart: <path d="M6 14.5v-4M10 14.5v-9M14 14.5V8" strokeWidth="2.1" />,
};

/** A view type's tile: white marks on its colour. */
export function TypeTile({ type, className }: { type: ViewType; className?: string }) {
  return (
    <span className={`${styles.tile} ${className ?? ''}`} data-type={type} data-part="tile">
      <svg
        viewBox="0 0 20 20"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        aria-hidden="true"
      >
        {TILE[type]}
      </svg>
    </span>
  );
}

/** A round initial in the person's tint. */
export function Avatar({ name, tint }: { name: string; tint: Tint }) {
  return (
    <span className={styles.avatar} data-tint={tint} data-part="avatar" aria-hidden="true">
      {name.charAt(0)}
    </span>
  );
}
```

### view-switcher/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 (view-switcher.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 page 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>
  );
}
```

### view-switcher/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 not while the reader is using it. `take()` hands it to the reader; it
 * takes back over `idle` ms after their last input.
 */
export function useAutoplay<T extends HTMLElement>(idle = 6000) {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);
  const timer = useRef(0);

  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);
    window.clearTimeout(timer.current);
    timer.current = window.setTimeout(() => setTaken(false), idle);
  }, [idle]);
  useEffect(() => () => window.clearTimeout(timer.current), []);

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