# Filter builder

> A table’s Filters popover with nested groups: conditions joined by an And/Or pill, subgroups in tinted panels, values fitted to each field, and rows you drag between groups.

A sales team’s Opportunities table and the popover that narrows it. Each condition is a row: a handle, a field, an operator that fits the field (is, is any of, when, before, is over) and a value picked from a list that fits too: a person with their initials, a health status with its coloured square, a date preset, several stages as pills that fold into +1. The rows of a group are joined on a bracket by one pill, And or Or, that flips the group when pressed; a subgroup sits in a tinted panel with its own pill, Add condition and Add subgroup. Rows move by their handle, within a group or into another, and the table behind filters as you go, with the count on the Filters button and an empty state. View tabs keep a filter each; the toolbar groups, hides fields, sets the row height and the lines. Light and dark.

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

Category: Data.

## Anatomy

1. **Header**: The table’s icon tile and its name.
2. **View tabs**: Saved views as a tablist, each with its own conditions; + Add starts a view with none.
3. **Filters button**: Opens the popover; its badge counts the conditions with a value, rolling as it changes.
4. **Popover**: A non-modal dialog under the button: the conditions, the subgroups and a foot with Add condition, Add group and Clear all.
5. **Condition**: A handle, then field, operator and value in one outlined row, and a bin to remove it. The handle drags the row, and a click on it opens Move up and Move down.
6. **Conjunction pill**: And or Or on the bracket that joins a group’s rows; pressing it flips the group.
7. **Subgroup**: A tinted panel captioned “Any of the following are true:” with its own rows, pill and Add condition, and Add subgroup unless it is already at the deepest level.
8. **Value picker**: A listbox fitted to the field: people with their initials, statuses with a square, stages as pills, date presets.
9. **Table**: The rows that pass the filter, with a sticky header, the name held at the left, and a count and sum in the foot.

## Properties

### Saved views (`views`)

1. **One view**: A single tab: one question people tune as they go. + Add still lets them save another.
2. **Several views (default)**: A tab per question the team asks again, each with its own conditions. The built-in sample has three.

Give a view to each question people come back to, and name it by what it shows. Start with one when nobody has settled on those questions yet.

### Top-level conjunction (`views[].filter.conj`)

1. **And (default)**: A deal must pass every part. Each condition narrows the table further.
2. **Or**: One passing part is enough. Each condition widens the table.

Start the top group with And, as new views do, and put the alternatives in an Or subgroup inside it. A top-level Or suits views that gather several unrelated lists.

## When to use

- A table of records people narrow with questions that mix all and any: the owner is me, and the deal is critical or has no meeting booked.
- Saved views a team returns to, each a tab with its own conditions, where the count on the Filters button says at a glance how narrowed a view is.
- Fields of different kinds in one place: people, statuses, stages, amounts and dates, each with the operators and values that make sense for it.
- Power users who build a filter once and rearrange it later: dragging a condition into a subgroup is quicker than deleting and adding it again.

## When not to use

- One or two simple filters. Use filter chips in the toolbar; a popover of nested groups is more than a status and an owner need.
- Free-text search across records. Use a search field; conditions test known fields with known values.
- Queries people type or share as text. Use a query editor with completion; this builds the tree with pointer and keyboard.
- Deep logic. The popover nests two levels of subgroups; anything deeper reads better as a saved segment with a name.

### How conditions combine

- **One conjunction per group**: every row in a group is joined by the same And or Or, and its pill flips them all at once.
- **A subgroup is one part** of the group around it: “Owner is Imani, and any of these three”. New subgroups start with Or, the usual reason to make one.
- **Two levels deep**: the top group, its subgroups and theirs. The deepest ones offer no Add subgroup.
- **Unfinished parts are left out**: a condition without a value and an empty group test nothing, so adding a row never empties the table by surprise.

### Views and the count

Each tab keeps its own conditions, and switching tabs keeps your edits to the others. The badge on Filters counts the conditions that have a value, so a glance tells how narrowed the view is; with none, it goes. `onFilterChange` hands over the filter and the rows that pass it, to save the view or fetch from a server.

### Filter builder vs. status chips

**Filter builder**
- Several fields at once, mixing all and any.
- Conditions live in a popover; the count shows on the button.
- For people who build a view once and come back to it.

**Status chips**
- One field, one value at a time, always in view.
- A single press, no popover to open.
- For a short list narrowed by its status.

## Do’s and don’ts

- **Do**: Put the alternatives in an Or subgroup, under an And at the top, so the rest still narrows.
- **Don’t**: Flip the whole filter to Or to let one alternative in. Every other condition stops narrowing.
- **Do**: Name each view by the question it answers, so the tabs read as a list of choices.
- **Don’t**: Leave views as View 1, View 2: people have to open each one to know what it holds.
- **Caution**: A new condition tests nothing until it has a value: fine while building, puzzling if left, since the badge leaves it out.
- **Don’t**: Nest subgroups to the limit to spell out a long rule. Past one level, save it as a segment with a name.

## Content

The fields, operators and captions come with the component; the words you supply are the title, the view names and the records.

- **Title**: the records the table holds, plural: `Opportunities`, `Accounts`.
- **View names**: two or three words saying what the view shows, in sentence case: `Best case`, `This quarter`, `My deals`. No “View” or “Filter” in the name.
- **People and companies**: names are cut short with an ellipsis in the value, so the part that tells them apart goes first.
- **At most six views**: + Add stops at six, and more tabs than that crowd the row on a phone.

## Installation

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

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

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 { FilterBuilder, type Group } from './filter-builder';

const mine: Group = {
  type: 'group',
  id: 'root',
  conj: 'and',
  items: [
    { type: 'condition', id: 'owner', field: 'owner', op: 'is', value: ['imani'] },
    { type: 'condition', id: 'stage', field: 'stage', op: 'anyOf', value: ['proposal'] },
  ],
};

export function Pipeline() {
  return (
    <FilterBuilder
      views={[{ id: 'mine', label: 'My deals', filter: mine }]}
      onFilterChange={(filter, rows) => console.log(filter, rows.length)}
      autoplay={false}
    />
  );
}
```

## States

- **All opportunities**: Five conditions narrow eighteen deals to eight; the badge says 5.
- **Filters open**: Owner, then a subgroup where any of three is enough, then Stage, all joined by And.
- **Joined by Or**: The top group flipped to Or: any one of its parts lets a deal through, so fifteen show.
- **Field picker**: The fields a condition can test; picking another resets its operator and value.
- **Several stages**: `is any of` takes several values: ticked stages stay in the list, and the row shows the first with +1.
- **Date presets**: `when` offers No meeting, This week, Next week and This month; `before` and `after` offer days from today.
- **A new condition**: Added with Add condition, it waits for a value and tests nothing meanwhile; the badge leaves it out.
- **Dragging a row**: Stage held by its handle over the top of the subgroup: the accent line shows where it lands.
- **Grouped by stage**: Group by draws a header per stage with its count and sum; each one collapses.
- **Fields menu**: Checkboxes for the columns; Owner and the two dates start hidden.
- **No matches**: Conditions that leave nothing: Edit filters opens the popover, Clear filters empties it.
- **Phone**: Under 440 px of popover the pill sits between the rows and each condition takes two lines.

## Examples

### Stalled deals

A view joined by Or: no recent interaction, no meeting booked, or a large deal at risk, the last as an And subgroup.

```tsx
import { FilterBuilder, type Group } from './filter-builder';

const STALLED: Group = {
  type: 'group',
  id: 'root',
  conj: 'or',
  items: [
    { type: 'condition', id: 's-touch', field: 'lastInteraction', op: 'before', value: ['ago7'] },
    { type: 'condition', id: 's-meeting', field: 'nextMeeting', op: 'when', value: ['none'] },
    {
      type: 'group',
      id: 's-big',
      conj: 'and',
      items: [
        { type: 'condition', id: 's-amount', field: 'amount', op: 'over', value: ['150000'] },
        {
          type: 'condition',
          id: 's-health',
          field: 'health',
          op: 'anyOf',
          value: ['critical', 'risk'],
        },
      ],
    },
  ],
};

export function StalledDeals() {
  return (
    <FilterBuilder
      autoplay={false}
      title="Stalled deals"
      views={[{ id: 'stalled', label: 'Stalled', filter: STALLED }]}
      defaultState={{ open: true }}
    />
  );
}
```

### Grouped by stage

The Best case view in compact rows, grouped by stage with each group’s count and sum; Company hidden, Owner and Next meeting shown.

```tsx
import { FilterBuilder } from './filter-builder';

export function GroupedByStage() {
  return (
    <FilterBuilder
      autoplay={false}
      defaultView="best"
      defaultState={{
        view: 'best',
        groupBy: 'stage',
        rowHeight: 'compact',
        hidden: ['company', 'lastInteraction'],
      }}
    />
  );
}
```

### Picking stages

This quarter’s filter open on the Stage value: a multi-select listbox of pills with two ticked.

```tsx
import { FilterBuilder } from './filter-builder';

export function PickingStages() {
  return (
    <FilterBuilder
      autoplay={false}
      defaultState={{ view: 'quarter', open: true, picker: 'value:q-stage' }}
    />
  );
}
```

### No matches

One person’s view whose conditions leave nothing, with grid lines: the empty state offers Edit filters and Clear filters.

```tsx
import { FilterBuilder, type Group } from './filter-builder';

const NOTHING: Group = {
  type: 'group',
  id: 'root',
  conj: 'and',
  items: [
    { type: 'condition', id: 'e-owner', field: 'owner', op: 'is', value: ['hana'] },
    { type: 'condition', id: 'e-stage', field: 'stage', op: 'anyOf', value: ['discovery'] },
  ],
};

export function NoMatches() {
  return (
    <FilterBuilder
      autoplay={false}
      title="Hana’s pipeline"
      views={[{ id: 'mine', label: 'My deals', filter: NOTHING }]}
      defaultState={{ lines: 'grid' }}
    />
  );
}
```

## How it works

- The filter is a tree: a group holds conditions and subgroups and one conjunction. A row passes a group when all (And) or any (Or) of its parts pass; a condition without a value and a group with nothing in it are left out, so a new row changes nothing until it has a value.
- Each field has a kind (person, status, stage, company, amount, date) and each kind its operators. Changing the field resets the operator and value; changing the operator keeps the values that still fit, so is any of keeps every stage and is keeps the first.
- Dates are days from today. when tests a range (No meeting, This week, Next week, This month); before and after compare with a day (Today, In 7 days, 7 days ago), so the table reads the same whenever it opens.
- The value is a listbox fitted to the field: initials on the owner’s colour, a square in the status colour, stages as their pills, companies with their drawn marks. is any of keeps the list open while you tick; the row shows the first value and +1 for the rest.
- Dragging a handle lifts the row and measures every slot in reading order, a subgroup’s own between its parent’s; an accent line shows the nearest one, and letting go moves the row there. ↑ and ↓ on a focused handle step through the same slots, into and out of subgroups.
- Whatever changes the tree, the rows that moved glide from where they were (FLIP on the separate translate property) and new rows grow in; the conjunction’s glyph turns half a circle and its word rolls, and so does the badge’s count.
- Under 440 px of popover the bracket gives way to the pill between the rows, and each condition puts the field over the operator and value. The table scrolls inside its box with the name held at the left.
- While on screen and untouched, a demo pointer opens Filters, flips And to Or and back, adds a condition to the subgroup and picks its value, then drags Stage into the subgroup. Any real input hands it over; it comes back after 8 s of quiet.

## API reference

- **title** (`string`, default `'Opportunities'`): The table’s name, beside its icon.
- **opportunities** (`Opportunity[]`, default `eighteen deals`): The rows: name, amount, company, stage, health, owner, days to the next meeting and days since the last interaction (null for none).
- **people** (`Person[]`, default `five people`): Everyone who can own a deal: an id, a name and a colour for their initials.
- **companies** (`Company[]`, default `six companies`): The companies the deals are with: an id, a name, a mark shape and its colour.
- **views** (`SavedView[]`, default `All opportunities, Best case, This quarter`): The view tabs, each an id, a label and its filter (a Group).
- **defaultView** (`string`): The tab open at first; the first one when left out.
- **defaultState** (`FilterBuilderState`): Opens locked in a moment, with the demo off: the view, the popover open, a filter in place of the view’s, a picker or menu held open, the grouping, row height, lines, hidden columns, or a row held mid-drag.
- **onFilterChange** (`(filter: Group, rows: Opportunity[]) => void`): Called with the view’s filter and the rows that pass it whenever the filter changes.
- **onViewChange** (`(id: string) => void`): Called with a view’s id when its tab is chosen or added.
- **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 view tabs are a tablist: ← and → move between them and choose, Home and End jump to the ends.
- Filters opens the popover and moves the focus into it; Escape closes it and gives the focus back to Filters.
- In a field, operator or value list, ↑ and ↓ move, Home and End jump, Enter or Space picks, Escape closes and returns to the trigger. Tab closes the list.
- ↑ and ↓ on a row’s handle move the row one slot at a time, into and out of subgroups, and the handle keeps the focus.
- Enter or Space on a handle opens its menu, Move up and Move down; the arrows move between them and Escape closes it.

### Screen readers

- Filters is named with its count, “Filters, 5 conditions”, since the badge itself is hidden.
- Each change is announced with the rows left, through a status region (WCAG 4.1.3, AA): “Removed Owner is Imani Okafor”, then how many opportunities show.
- The pill is named by what it does, “Joined by And; switch to Or”, and each subgroup is a group labelled by its caption.
- Handles are named “Move Stage condition” with where the row is, describe the arrow keys, and say they open a menu (`aria-haspopup`, `aria-expanded`).

### Dragging

Dragging has a keyboard way (2.1.1, A) and a single-pointer one (Dragging Movements, 2.5.7, AA): a click on the handle opens Move up and Move down, which take the same one-slot steps as the arrow keys. An item that can’t go further is disabled.

### Contrast

Text is at least 4.5:1 on the surface it sits on in both schemes (1.4.3, AA), the quiet grey of placeholders, counts and the handle included; the handle and the bins are at least 3:1 (1.4.11, AA). The health squares sit beside their names, so the colour is never the only cue.

### Targets and motion

Every control is at least 24 px across (2.5.8, AA): the handle narrows to 24 px wide on a phone, the rest are 28 px or more. With reduced motion, rows jump to their places instead of gliding, and the demo pointer stays off.

### In this build

- The Filters button opens a non-modal dialog (aria-haspopup="dialog", aria-expanded) and its label counts the conditions; Escape closes it with the focus back on the button, and a press outside closes it too.
- Field, operator and value are buttons that open a listbox; the arrows, Home and End move through the options, Enter or Space picks, and a multi-value listbox is aria-multiselectable and stays open. Escape closes it with the focus back on its button.
- Each conjunction pill says what it does: “Joined by And; switch to Or”. A subgroup is a group named by its caption. Every bin names the condition it removes.
- A row’s handle is a button: ↑ and ↓ move the row one slot at a time, into and out of subgroups, and the live region says where it landed (“Stage moved: 1 of 4 in the subgroup”), as it says every change and how many rows remain.
- The views are a tablist moved with the arrow keys; Groups, Group by, Fields, Row height and Layout are menu buttons with radio and checkbox items. The table has column headers, each name is its row’s header, and grouped rows sit in a tbody per group with a disclosure button.
- Under reduced motion nothing slides, rolls or grows and the demo never plays. The demo pointer is decorative.

## Source

### filter-builder/filter-builder.tsx

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

'use client';

import {
  Fragment,
  useCallback,
  useEffect,
  useEffectEvent,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type ReactNode,
} from 'react';
import { Avatar, CompanyMark, HealthChip, HealthSquare, StagePill } from './cells';
import {
  COMPANIES,
  HEALTH,
  OPPORTUNITIES,
  PEOPLE,
  STAGES,
  VIEWS,
  money,
  type Company,
  type HealthId,
  type Opportunity,
  type Person,
  type SavedView,
  type StageId,
} from './data';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import {
  FIELDS,
  FIELD_MENU,
  OP_LABEL,
  changeField,
  changeOp,
  countConditions,
  describe,
  isMulti,
  locate,
  matches,
  stepSlot,
  updateCondition,
  valueOptions,
  type Condition,
  type Group,
  type Slot,
} from './filter';
import { Icon, VaultMark, type IconName } from './glyphs';
import { FilterPanel, type PanelApi, type PickerPart } from './panel';
import { MenuItem, Option, Popup, PopupLabel } from './popup';
import { useAutoplay } from './use-autoplay';
import styles from './filter-builder.module.css';

/*
 * Filter builder: a CRM's Opportunities table with a Filters popover that nests conditions.
 *
 * - Each condition is a field, an operator that fits the field's kind (is, is any of, when,
 *   before, is over…) and a value picked from a list that fits too: a person, a health status, a
 *   date preset, several stages as pills.
 * - Conditions in a group are joined by one conjunction, And or Or, shown as a pill on the group's
 *   bracket: pressing it flips the group. A subgroup sits in a tinted panel with its own pill,
 *   its own Add condition and, above the deepest level, its own Add subgroup.
 * - Rows move by their handle, dragged with the pointer, with the arrow keys, or with Move up and
 *   Move down in the menu a click on the handle opens: within a group or into another.
 * - The table behind filters as the conditions change; the Filters button counts them.
 * - The view tabs keep a filter each; the toolbar groups the rows, hides fields, sets the row
 *   height and the lines.
 * - While on screen and untouched, a demo pointer opens Filters, flips And and back, adds a
 *   condition to the subgroup and picks its value, drags a row into the subgroup.
 */

export type { Company, Opportunity, Person, SavedView } from './data';
export type { Condition, Group, Item, FieldId, OpId, Conj, Slot } from './filter';

export type ColumnId =
  'amount' | 'company' | 'stage' | 'health' | 'owner' | 'nextMeeting' | 'lastInteraction';
export type GroupBy = 'none' | 'stage' | 'health' | 'owner';
export type RowHeight = 'compact' | 'default' | 'tall';
export type Lines = 'grid' | 'rows' | 'stripes';
type ToolMenu = 'groups' | 'groupBy' | 'fields' | 'rowHeight' | 'layout';

/** A moment to open in, locked: the demo stays off. Used by the docs. */
export type FilterBuilderState = {
  /** The view (tab) shown. */
  view?: string;
  /** The Filters popover open. */
  open?: boolean;
  /** The conditions, in place of the view's own. */
  filter?: Group;
  /** A picker held open: `field:<condition id>`, `op:…` or `value:…`. */
  picker?: `${PickerPart}:${string}`;
  /** A toolbar menu held open. */
  menu?: ToolMenu;
  groupBy?: GroupBy;
  rowHeight?: RowHeight;
  lines?: Lines;
  hidden?: ColumnId[];
  /** A row held mid-drag over the slot it would land in. */
  drag?: { id: string; to: Slot };
};

const COLUMNS: { id: ColumnId; label: string }[] = [
  { id: 'amount', label: 'Amount' },
  { id: 'company', label: 'Company' },
  { id: 'stage', label: 'Stage' },
  { id: 'health', label: 'Health score' },
  { id: 'owner', label: 'Owner' },
  { id: 'nextMeeting', label: 'Next meeting' },
  { id: 'lastInteraction', label: 'Last interaction' },
];
const DEFAULT_HIDDEN: ColumnId[] = ['owner', 'nextMeeting', 'lastInteraction'];

const GROUP_BY: { id: GroupBy; label: string }[] = [
  { id: 'none', label: 'No grouping' },
  { id: 'stage', label: 'Stage' },
  { id: 'health', label: 'Health score' },
  { id: 'owner', label: 'Owner' },
];
const ROW_HEIGHTS: { id: RowHeight; label: string }[] = [
  { id: 'compact', label: 'Compact' },
  { id: 'default', label: 'Default' },
  { id: 'tall', label: 'Tall' },
];
const LINES: { id: Lines; label: string }[] = [
  { id: 'grid', label: 'Grid lines' },
  { id: 'rows', label: 'Row lines' },
  { id: 'stripes', label: 'Stripes' },
];
const TOOLS: { id: ToolMenu | 'filters'; label: string; icon: IconName }[] = [
  { id: 'groups', label: 'Groups', icon: 'groups' },
  { id: 'filters', label: 'Filters', icon: 'filter' },
  { id: 'groupBy', label: 'Group by', icon: 'groupBy' },
  { id: 'fields', label: 'Fields', icon: 'fields' },
  { id: 'rowHeight', label: 'Row height', icon: 'rowHeight' },
  { id: 'layout', label: 'Layout', icon: 'layout' },
];

const days = (n: number | null, ahead: boolean) =>
  n === null
    ? '—'
    : n === 0
      ? 'Today'
      : ahead
        ? n === 1
          ? 'Tomorrow'
          : `In ${n} days`
        : n === 1
          ? 'Yesterday'
          : `${n} days ago`;

const cloneViews = (views: SavedView[]) =>
  Object.fromEntries(views.map((v) => [v.id, structuredClone(v.filter)])) as Record<string, Group>;

export function FilterBuilder({
  title = 'Opportunities',
  opportunities = OPPORTUNITIES,
  people = PEOPLE,
  companies = COMPANIES,
  views: savedViews = VIEWS,
  defaultView,
  defaultState,
  onFilterChange,
  onViewChange,
  autoplay = true,
  colorScheme,
  className = '',
}: {
  /** The table's name, beside its icon. */
  title?: string;
  /** The rows the table holds. */
  opportunities?: Opportunity[];
  /** Everyone who can own a deal. */
  people?: Person[];
  /** The companies the deals are with. */
  companies?: Company[];
  /** The view tabs, each with its own filter. */
  views?: SavedView[];
  /** The tab open at first; the first one when left out. */
  defaultView?: string;
  /** Opens locked in a moment, with the demo off. */
  defaultState?: FilterBuilderState;
  /** Called with the view's filter and the rows that pass it, whenever the filter changes. */
  onFilterChange?: (filter: Group, rows: Opportunity[]) => void;
  /** Called with a view's id when its tab is chosen or added. */
  onViewChange?: (id: 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 card = useRef<HTMLDivElement>(null);
  const filtersButton = useRef<HTMLButtonElement>(null);
  const panelApi = useRef<PanelApi | null>(null);
  const counter = useRef(0);
  const locked = defaultState !== undefined;
  const s = defaultState ?? {};
  const firstView = s.view ?? defaultView ?? savedViews[0]?.id ?? 'all';

  const start = useMemo(
    () => ({ views: savedViews, trees: cloneViews(savedViews) }),
    // Only the first values count.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  const [views, setViews] = useState<SavedView[]>(start.views);
  const [view, setView] = useState(firstView);
  const [trees, setTrees] = useState<Record<string, Group>>(() =>
    s.filter ? { ...start.trees, [firstView]: structuredClone(s.filter) } : start.trees,
  );
  const [open, setOpen] = useState(s.open ?? false);
  const [openByReader, setOpenByReader] = useState(false);
  const [picker, setPicker] = useState<{
    id: string;
    part: PickerPart;
    anchor: HTMLElement;
    byReader: boolean;
  } | null>(null);
  const [menu, setMenu] = useState<{ id: ToolMenu; anchor: HTMLElement; byReader: boolean } | null>(
    null,
  );
  const [rowMenu, setRowMenu] = useState<{
    id: string;
    anchor: HTMLElement;
    byReader: boolean;
  } | null>(null);
  const [groupBy, setGroupBy] = useState<GroupBy>(s.groupBy ?? 'none');
  const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
  const [rowHeight, setRowHeight] = useState<RowHeight>(s.rowHeight ?? 'default');
  const [lines, setLines] = useState<Lines>(s.lines ?? 'rows');
  const [hidden, setHidden] = useState<Set<ColumnId>>(new Set(s.hidden ?? DEFAULT_HIDDEN));
  const [live, setLive] = useState('');
  const [popAt, setPopAt] = useState<{ x: number; y: number; w: number; h: number } | null>(null);

  const tree = trees[view] ?? { type: 'group', id: 'root', conj: 'and', items: [] };
  const rows = useMemo(() => opportunities.filter((o) => matches(tree, o)), [opportunities, tree]);
  const count = countConditions(tree);
  const say = useCallback((text: string) => setLive(text), []);
  const newId = useCallback(() => `n${(counter.current += 1)}`, []);
  const demo = autoplay && !locked && playing;

  const change = useCallback(
    (next: Group, message: string) => {
      setTrees((all) => ({ ...all, [view]: next }));
      const n = opportunities.filter((o) => matches(next, o)).length;
      say(`${message}. ${n} ${n === 1 ? 'opportunity' : 'opportunities'}.`);
    },
    [view, opportunities, say],
  );

  // The host hears every change of filter, not the first one.
  const reported = useRef(tree);
  useEffect(() => {
    if (reported.current === tree) return;
    reported.current = tree;
    onFilterChange?.(tree, rows);
  }, [tree, rows, onFilterChange]);

  // ---- The popover and its pickers ---------------------------------------------------------------

  // Under the Filters button, inside the card.
  useLayoutEffect(() => {
    if (!open) return;
    const place = () => {
      const c = card.current;
      const b = filtersButton.current;
      if (!c || !b) return;
      const scale = c.getBoundingClientRect().width / c.offsetWidth || 1;
      const cr = c.getBoundingClientRect();
      const br = b.getBoundingClientRect();
      const w = Math.min(664, c.clientWidth - 16);
      const x = Math.max(8, Math.min((br.left - cr.left) / scale, c.clientWidth - w - 8));
      const y = (br.bottom - cr.top) / scale + 6;
      setPopAt({ x, y, w, h: c.clientHeight - y - 8 });
    };
    place();
    const observer = new ResizeObserver(place);
    if (card.current) observer.observe(card.current);
    return () => observer.disconnect();
  }, [open]);

  // Opened by the reader: the focus goes to the first row's handle, or the first button.
  useEffect(() => {
    if (!open || !openByReader || !popAt) return;
    root.current
      ?.querySelector<HTMLElement>('[data-part="popover"] button')
      ?.focus({ preventScroll: true });
    // Only when it first shows.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, openByReader, popAt === null]);

  const closeFilters = useCallback((back: boolean) => {
    setOpen(false);
    setPicker(null);
    setRowMenu(null);
    setPopAt(null);
    if (back) filtersButton.current?.focus();
  }, []);

  // A press outside the popover (and its pickers) closes it.
  useEffect(() => {
    if (!open || locked) return;
    const away = (event: PointerEvent) => {
      const target = event.target as Element;
      if (
        target.closest?.('[data-part="popover"], [data-popup]') ||
        filtersButton.current?.contains(target)
      )
        return;
      closeFilters(false);
    };
    document.addEventListener('pointerdown', away);
    return () => document.removeEventListener('pointerdown', away);
  }, [open, locked, closeFilters]);

  const toggleFilters = (byReader: boolean) => {
    if (open) closeFilters(false);
    else {
      setMenu(null);
      setOpen(true);
      setOpenByReader(byReader);
      say(`Filters open: ${count} ${count === 1 ? 'condition' : 'conditions'}`);
    }
  };

  // A held picker or menu (docs) opens once its trigger is drawn.
  useLayoutEffect(() => {
    const stage = root.current;
    if (!stage) return;
    if (s.picker && popAt) {
      const [part, id] = s.picker.split(':') as [PickerPart, string];
      const anchor = stage.querySelector<HTMLElement>(`[data-picker="${s.picker}"]`);
      if (anchor) setPicker({ id, part, anchor, byReader: false });
    }
    if (s.menu && !popAt) {
      const anchor = stage.querySelector<HTMLElement>(`[data-tool="${s.menu}"]`);
      if (anchor) setMenu({ id: s.menu, anchor, byReader: false });
    }
    // Once, with the popover drawn.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [popAt !== null]);

  const openPicker = useCallback(
    (id: string, part: PickerPart, anchor: HTMLElement) => {
      setPicker((p) =>
        p && p.id === id && p.part === part ? null : { id, part, anchor, byReader: !demo },
      );
    },
    [demo],
  );
  const openRowMenu = useCallback(
    (id: string, anchor: HTMLElement) => {
      setPicker(null);
      setRowMenu((m) => (m && m.id === id ? null : { id, anchor, byReader: !demo }));
    },
    [demo],
  );
  const closeRowMenu = useCallback((back: boolean) => {
    setRowMenu((m) => {
      if (back) m?.anchor.focus();
      return null;
    });
  }, []);
  const closePicker = useCallback((back: boolean) => {
    setPicker((p) => {
      if (back) p?.anchor.focus();
      return null;
    });
  }, []);
  const closeMenu = useCallback((back: boolean) => {
    setMenu((m) => {
      if (back) m?.anchor.focus();
      return null;
    });
  }, []);

  const pickedCondition = picker ? locate(tree, picker.id)?.item : null;
  const movedCondition = rowMenu ? locate(tree, rowMenu.id)?.item : null;

  const pickerBody = (c: Condition, part: PickerPart): ReactNode => {
    if (part === 'field')
      return FIELD_MENU.map((f) => (
        <Option
          key={f}
          selected={c.field === f}
          demo={`opt-${f}`}
          onSelect={() => {
            closePicker(true);
            if (f !== c.field)
              change(
                updateCondition(tree, c.id, (x) => changeField(x, f)),
                `Field set to ${FIELDS[f].label}; pick a value`,
              );
          }}
        >
          {FIELDS[f].label}
        </Option>
      ));
    if (part === 'op')
      return FIELDS[c.field].ops.map((op) => (
        <Option
          key={op}
          selected={c.op === op}
          demo={`opt-${op}`}
          onSelect={() => {
            closePicker(true);
            if (op !== c.op) {
              const next = changeOp(c, op);
              change(
                updateCondition(tree, c.id, () => next),
                `Now ${describe(next, people, companies)}`,
              );
            }
          }}
        >
          {OP_LABEL[op]}
        </Option>
      ));
    const multi = isMulti(c.op);
    return valueOptions(c.field, c.op, people, companies).map((o) => {
      const selected = c.value.includes(o.value);
      const lead =
        o.kind === 'person' ? (
          <Avatar person={o.person} size={20} />
        ) : o.kind === 'status' ? (
          <HealthSquare health={o.value as HealthId} />
        ) : o.kind === 'company' ? (
          <CompanyMark company={o.company} />
        ) : null;
      return (
        <Option
          key={o.value}
          selected={selected}
          demo={`opt-${o.value}`}
          lead={lead}
          onSelect={() => {
            const value = multi
              ? selected
                ? c.value.filter((v) => v !== o.value)
                : [...c.value, o.value]
              : [o.value];
            if (!multi) closePicker(true);
            const next = { ...c, value };
            change(
              updateCondition(tree, c.id, () => next),
              describe(next, people, companies),
            );
          }}
        >
          {o.kind === 'stage' ? <StagePill stage={o.value as StageId} /> : o.label}
        </Option>
      );
    });
  };

  // ---- Views and toolbar ------------------------------------------------------------------------

  const chooseView = (id: string) => {
    if (id === view) return;
    setView(id);
    setPicker(null);
    setRowMenu(null);
    const label = views.find((v) => v.id === id)?.label;
    const n = opportunities.filter((o) => matches(trees[id], o)).length;
    say(`${label}: ${n} ${n === 1 ? 'opportunity' : 'opportunities'}`);
    onViewChange?.(id);
  };
  const addView = () => {
    const id = `view-${newId()}`;
    const label = `View ${views.length + 1}`;
    setViews((v) => [
      ...v,
      { id, label, filter: { type: 'group', id: 'root', conj: 'and', items: [] } },
    ]);
    setTrees((t) => ({ ...t, [id]: { type: 'group', id: 'root', conj: 'and', items: [] } }));
    setView(id);
    say(`Added ${label}, with no filters`);
    onViewChange?.(id);
  };
  const onTabsKey = (event: ReactKeyboardEvent) => {
    const keys = ['ArrowLeft', 'ArrowRight', 'Home', 'End'];
    if (!keys.includes(event.key)) return;
    event.preventDefault();
    const i = views.findIndex((v) => v.id === view);
    const to =
      event.key === 'Home'
        ? 0
        : event.key === 'End'
          ? views.length - 1
          : (i + (event.key === 'ArrowRight' ? 1 : -1) + views.length) % views.length;
    chooseView(views[to].id);
    root.current?.querySelector<HTMLElement>(`[data-tab="${views[to].id}"]`)?.focus();
  };

  const toggleHidden = (id: ColumnId) => {
    setHidden((h) => {
      const next = new Set(h);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
    const label = COLUMNS.find((c) => c.id === id)?.label;
    say(`${label} ${hidden.has(id) ? 'shown' : 'hidden'}`);
  };

  const menuBody = (id: ToolMenu): ReactNode => {
    if (id === 'groupBy')
      return GROUP_BY.map((g) => (
        <MenuItem
          key={g.id}
          kind="radio"
          checked={groupBy === g.id}
          onSelect={() => {
            setGroupBy(g.id);
            setCollapsed(new Set());
            closeMenu(true);
            say(g.id === 'none' ? 'Rows no longer grouped' : `Rows grouped by ${g.label}`);
          }}
        >
          {g.label}
        </MenuItem>
      ));
    if (id === 'groups') {
      const none = groupBy === 'none';
      return (
        <>
          {none && <PopupLabel>Pick a Group by first</PopupLabel>}
          <MenuItem
            disabled={none}
            onSelect={() => {
              setCollapsed(new Set());
              closeMenu(true);
              say('All groups expanded');
            }}
          >
            Expand all
          </MenuItem>
          <MenuItem
            disabled={none}
            onSelect={() => {
              setCollapsed(new Set(sections.map((sec) => sec.key)));
              closeMenu(true);
              say('All groups collapsed');
            }}
          >
            Collapse all
          </MenuItem>
          {none && (
            <MenuItem
              onSelect={() => {
                setGroupBy('stage');
                closeMenu(true);
                say('Rows grouped by Stage');
              }}
            >
              Group by stage
            </MenuItem>
          )}
        </>
      );
    }
    if (id === 'fields')
      return (
        <>
          <PopupLabel>Shown in the table</PopupLabel>
          {COLUMNS.map((c) => (
            <MenuItem
              key={c.id}
              kind="checkbox"
              checked={!hidden.has(c.id)}
              onSelect={() => toggleHidden(c.id)}
            >
              {c.label}
            </MenuItem>
          ))}
        </>
      );
    if (id === 'rowHeight')
      return ROW_HEIGHTS.map((r) => (
        <MenuItem
          key={r.id}
          kind="radio"
          checked={rowHeight === r.id}
          onSelect={() => {
            setRowHeight(r.id);
            closeMenu(true);
            say(`Row height: ${r.label}`);
          }}
        >
          {r.label}
        </MenuItem>
      ));
    return LINES.map((l) => (
      <MenuItem
        key={l.id}
        kind="radio"
        checked={lines === l.id}
        onSelect={() => {
          setLines(l.id);
          closeMenu(true);
          say(`Layout: ${l.label}`);
        }}
      >
        {l.label}
      </MenuItem>
    ));
  };

  // ---- The table --------------------------------------------------------------------------------

  const shown = COLUMNS.filter((c) => !hidden.has(c.id));
  const sections = useMemo(() => {
    if (groupBy === 'none') return [{ key: 'all', label: '', rows }];
    const keys =
      groupBy === 'stage'
        ? STAGES.map((x) => ({ key: x.id as string, label: x.label }))
        : groupBy === 'health'
          ? HEALTH.map((x) => ({ key: x.id as string, label: x.label }))
          : people.map((p) => ({ key: p.id, label: p.name }));
    return keys
      .map((k) => ({ ...k, rows: rows.filter((r) => String(r[groupBy]) === k.key) }))
      .filter((k) => k.rows.length > 0);
  }, [groupBy, rows, people]);
  const total = rows.reduce((sum, r) => sum + r.amount, 0);

  const cell = (o: Opportunity, id: ColumnId): ReactNode => {
    if (id === 'amount') return money(o.amount);
    if (id === 'company') {
      const co = companies.find((c) => c.id === o.company);
      return (
        co && (
          <span className={styles.companyCell}>
            <CompanyMark company={co} />
            {co.name}
          </span>
        )
      );
    }
    if (id === 'stage') return <StagePill stage={o.stage} />;
    if (id === 'health') return <HealthChip health={o.health} />;
    if (id === 'owner') {
      const p = people.find((x) => x.id === o.owner);
      return (
        p && (
          <span className={styles.ownerCell}>
            <Avatar person={p} size={20} />
            {p.name.replace(/ (\S)\S*$/, ' $1.')}
          </span>
        )
      );
    }
    if (id === 'nextMeeting') return days(o.nextMeeting, true);
    return days(o.lastInteraction, false);
  };

  const clearFilters = () => change({ ...tree, items: [] }, 'Cleared all conditions');

  const table = (
    <div className={styles.tableBox} data-part="table" data-lines={lines} data-height={rowHeight}>
      <table
        className={styles.table}
        aria-labelledby={`${uid}-title`}
        aria-rowcount={rows.length + 1}
      >
        <thead>
          <tr>
            <th scope="col" data-col="name">
              Name
            </th>
            {shown.map((c) => (
              <th key={c.id} scope="col" data-col={c.id}>
                {c.label}
              </th>
            ))}
          </tr>
        </thead>
        {sections.map((sec) => {
          const closed = collapsed.has(sec.key);
          return (
            <tbody key={sec.key}>
              {groupBy !== 'none' && (
                <tr className={styles.sectionRow}>
                  <th scope="rowgroup" colSpan={shown.length + 1}>
                    <button
                      type="button"
                      className={styles.sectionButton}
                      aria-expanded={!closed}
                      onClick={() =>
                        setCollapsed((c) => {
                          const next = new Set(c);
                          if (next.has(sec.key)) next.delete(sec.key);
                          else next.add(sec.key);
                          return next;
                        })
                      }
                    >
                      <Icon name="chevronRight" className={styles.sectionChevron} />
                      {groupBy === 'stage' ? (
                        <StagePill stage={sec.key as StageId} />
                      ) : groupBy === 'health' ? (
                        <HealthChip health={sec.key as HealthId} />
                      ) : (
                        <span className={styles.ownerCell}>
                          <Avatar person={people.find((p) => p.id === sec.key)!} size={20} />
                          {sec.label}
                        </span>
                      )}
                      <span className={styles.sectionCount}>
                        {sec.rows.length} · {money(sec.rows.reduce((n, r) => n + r.amount, 0))}
                      </span>
                    </button>
                  </th>
                </tr>
              )}
              {!closed &&
                sec.rows.map((o) => (
                  <tr key={o.id} className={styles.row} data-part="row">
                    <th scope="row" data-col="name">
                      {o.name}
                    </th>
                    {shown.map((c) => (
                      <td key={c.id} data-col={c.id}>
                        {cell(o, c.id)}
                      </td>
                    ))}
                  </tr>
                ))}
            </tbody>
          );
        })}
        {rows.length > 0 && (
          <tfoot>
            <tr>
              <th scope="row" data-col="name">
                {rows.length} of {opportunities.length}
              </th>
              {shown.map((c) => (
                <td key={c.id} data-col={c.id}>
                  {c.id === 'amount' && (
                    <>
                      <span className={styles.sumLabel}>Sum</span> {money(total)}
                    </>
                  )}
                </td>
              ))}
            </tr>
          </tfoot>
        )}
      </table>
      {rows.length === 0 && (
        <div className={styles.empty} data-part="empty">
          <span className={styles.emptyIcon} aria-hidden="true">
            <Icon name="funnelOff" />
          </span>
          <p className={styles.emptyTitle}>No opportunities match</p>
          <p className={styles.emptyText}>
            {count} {count === 1 ? 'condition leaves' : 'conditions leave'} nothing in{' '}
            {views.find((v) => v.id === view)?.label}.
          </p>
          <div className={styles.emptyActions}>
            <button
              type="button"
              className={styles.emptyButton}
              onClick={() => toggleFilters(true)}
            >
              Edit filters
            </button>
            <button
              type="button"
              className={styles.emptyButton}
              data-tone="accent"
              onClick={clearFilters}
            >
              Clear filters
            </button>
          </div>
        </div>
      )}
    </div>
  );

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

  const dirty = useEffectEvent(
    () => open || view !== firstView || JSON.stringify(trees) !== JSON.stringify(start.trees),
  );
  const reset = useEffectEvent(() => {
    setViews(start.views);
    setView(firstView);
    setTrees(cloneViews(start.views));
    setOpen(false);
    setPopAt(null);
    setPicker(null);
    setMenu(null);
  });
  const demoClear = useEffectEvent(() => {
    setPicker(null);
    setMenu(null);
  });

  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    if (!demo || !stage || !arrow) return;
    // The first one drawn: some pieces exist twice, one for each width.
    const find = (name: string) =>
      [...stage.querySelectorAll<HTMLElement>(`[data-demo="${name}"]`)].find(
        (element) => element.getClientRects().length > 0,
      ) ?? null;
    const on = (element: Element | null, fx = 0.5, fy = 0.5): Point => {
      const frame = stage.getBoundingClientRect();
      const scale = frame.width / stage.offsetWidth || 1;
      const rect = element?.getBoundingClientRect() ?? frame;
      return {
        x: (rect.left + rect.width * fx - frame.left) / scale,
        y: (rect.top + rect.height * fy - frame.top) / scale,
      };
    };
    let over: HTMLElement | null = null;
    const stop = runDemo(stage, arrow, async ({ wait, glide, glyph }) => {
      const press = async (
        target: string | (() => HTMLElement | null),
        ms: number,
        after: number,
        fx = 0.5,
        fy = 0.5,
      ) => {
        const element = typeof target === 'string' ? find(target) : target();
        if (!element) return;
        glyph('arrow');
        await glide(on(element, fx, fy), ms);
        glyph('hand');
        over = element;
        element.dataset.over = '';
        await wait(220);
        delete element.dataset.over;
        over = null;
        element.click();
        await wait(after);
      };
      for (;;) {
        if (dirty()) {
          reset();
          await wait(500);
        }
        await wait(900);
        await press('filters', 760, 900, 0.35);
        // Any condition instead of all, and back.
        await press('conj-root', 700, 1700, 0.3);
        await press('conj-root', 300, 1200, 0.3);
        // A fourth way into the subgroup: a large amount.
        await press('add-g-any', 700, 650, 0.3);
        await press(
          () => {
            const all = stage.querySelectorAll<HTMLElement>(
              '[data-group-id="g-any"] [data-part="value"]',
            );
            return all[all.length - 1] ?? null;
          },
          640,
          550,
          0.4,
        );
        await press('opt-150000', 520, 1700, 0.3);
        // Stage moves into the subgroup: one way among the others now.
        const grip = find('grip-c-stage');
        if (grip) {
          glyph('arrow');
          await glide(on(grip), 700);
          glyph('hand');
          await wait(260);
          const move = panelApi.current?.demoDrag('c-stage', { group: 'g-any', index: 0 });
          if (move) {
            await glide(move.target, 1100, move.follow);
            await wait(160);
            move.drop();
          }
          await wait(2200);
        }
        await press('filters', 700, 1800, 0.35);
        glyph('arrow');
        await glide(on(stage, 0.86, 0.94), 800);
        await wait(1400);
      }
    });
    return () => {
      stop();
      if (over) delete over.dataset.over;
      demoClear();
    };
  }, [demo, root]);

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

  const activeView = views.find((v) => v.id === view);

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="stage"
      data-color-scheme={colorScheme}
      onPointerDownCapture={take}
      onKeyDownCapture={take}
      onWheel={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') take();
      }}
    >
      <section ref={card} className={styles.card} data-part="card" aria-labelledby={`${uid}-title`}>
        <header className={styles.head} data-part="header">
          <span className={styles.tile} aria-hidden="true">
            <VaultMark className={styles.tileMark} />
          </span>
          <h2 id={`${uid}-title`} className={styles.title}>
            {title}
          </h2>
        </header>

        <div className={styles.tabsRow} data-part="view-tabs">
          <div role="tablist" aria-label="Views" className={styles.tabs} onKeyDown={onTabsKey}>
            {views.map((v) => (
              <button
                key={v.id}
                type="button"
                role="tab"
                id={`${uid}-tab-${v.id}`}
                aria-selected={v.id === view}
                aria-controls={`${uid}-panel`}
                tabIndex={v.id === view ? 0 : -1}
                className={styles.tab}
                data-tab={v.id}
                data-demo={`tab-${v.id}`}
                onClick={() => chooseView(v.id)}
              >
                {v.label}
              </button>
            ))}
          </div>
          <span className={styles.tabsRule} aria-hidden="true" />
          <button
            type="button"
            className={styles.addTab}
            disabled={views.length >= 6}
            onClick={addView}
          >
            <Icon name="plus" width={2} />
            Add<span className={styles.srOnly}> a view</span>
          </button>
        </div>

        <div
          id={`${uid}-panel`}
          role="tabpanel"
          aria-labelledby={`${uid}-tab-${view}`}
          className={styles.tabPanel}
        >
          <div className={styles.toolbar} role="toolbar" aria-label="Table" data-part="toolbar">
            {TOOLS.map((t, i) => {
              const isFilters = t.id === 'filters';
              const expanded = isFilters ? open : menu?.id === t.id;
              return (
                <Fragment key={t.id}>
                  {i === 1 && <span className={styles.toolRule} aria-hidden="true" />}
                  <button
                    ref={isFilters ? filtersButton : undefined}
                    type="button"
                    className={styles.tool}
                    data-tool={t.id}
                    data-demo={t.id}
                    data-part={isFilters ? 'filters-button' : undefined}
                    data-on={
                      (isFilters && (open || count > 0)) ||
                      (t.id === 'groupBy' && groupBy !== 'none') ||
                      undefined
                    }
                    aria-haspopup={isFilters ? 'dialog' : 'menu'}
                    aria-expanded={expanded}
                    aria-label={
                      isFilters
                        ? `Filters, ${count} ${count === 1 ? 'condition' : 'conditions'}`
                        : t.label
                    }
                    onClick={(event) => {
                      if (isFilters) toggleFilters(!demo);
                      else {
                        const anchor = event.currentTarget;
                        setMenu((m) =>
                          m?.id === t.id ? null : { id: t.id as ToolMenu, anchor, byReader: !demo },
                        );
                      }
                    }}
                  >
                    <Icon name={t.icon} className={styles.toolIcon} />
                    <span className={styles.toolLabel} data-keep={isFilters || undefined}>
                      {t.label}
                    </span>
                    {isFilters && count > 0 && (
                      <span className={styles.badge} aria-hidden="true" data-part="badge">
                        <span key={count} className={styles.badgeNum}>
                          {count}
                        </span>
                      </span>
                    )}
                  </button>
                </Fragment>
              );
            })}
          </div>
          {table}
        </div>

        {open && (
          <div
            role="dialog"
            aria-label={`Filters for ${activeView?.label ?? title}`}
            className={styles.popover}
            data-part="popover"
            style={{
              translate: popAt ? `${popAt.x}px ${popAt.y}px` : undefined,
              width: popAt?.w,
              ['--pop-max' as string]: popAt ? `${popAt.h}px` : undefined,
              visibility: popAt ? undefined : 'hidden',
            }}
            onKeyDown={(event) => {
              if (event.key === 'Escape') {
                event.preventDefault();
                closeFilters(true);
              }
            }}
          >
            <FilterPanel
              key={view}
              tree={tree}
              change={change}
              say={say}
              picker={picker ? { id: picker.id, part: picker.part } : null}
              openPicker={openPicker}
              rowMenu={rowMenu?.id ?? null}
              openRowMenu={openRowMenu}
              newId={newId}
              people={people}
              companies={companies}
              held={s.drag}
              api={panelApi}
            />
          </div>
        )}
      </section>

      {picker && pickedCondition?.type === 'condition' && (
        <Popup
          key={`${picker.id}-${picker.part}`}
          anchor={picker.anchor}
          role="listbox"
          label={
            picker.part === 'field'
              ? 'Field'
              : picker.part === 'op'
                ? `${FIELDS[pickedCondition.field].label} operator`
                : `${FIELDS[pickedCondition.field].label} value`
          }
          multi={picker.part === 'value' && isMulti(pickedCondition.op)}
          minWidth
          takeFocus={picker.byReader}
          onClose={closePicker}
        >
          {pickerBody(pickedCondition, picker.part)}
        </Popup>
      )}
      {rowMenu && movedCondition?.type === 'condition' && (
        <Popup
          key={`move-${rowMenu.id}`}
          anchor={rowMenu.anchor}
          role="menu"
          label={`Move ${FIELDS[movedCondition.field].label} condition`}
          takeFocus={rowMenu.byReader}
          onClose={closeRowMenu}
        >
          {([-1, 1] as const).map((dir) => (
            <MenuItem
              key={dir}
              disabled={!stepSlot(tree, rowMenu.id, dir)}
              onSelect={() => {
                closeRowMenu(true);
                panelApi.current?.step(rowMenu.id, dir);
              }}
            >
              {dir === -1 ? 'Move up' : 'Move down'}
            </MenuItem>
          ))}
        </Popup>
      )}
      {menu && (
        <Popup
          key={menu.id}
          anchor={menu.anchor}
          role="menu"
          label={TOOLS.find((t) => t.id === menu.id)?.label ?? ''}
          takeFocus={menu.byReader}
          onClose={closeMenu}
        >
          {menuBody(menu.id)}
        </Popup>
      )}

      <p className={styles.srOnly} role="status">
        {live}
      </p>

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

### filter-builder/panel.tsx

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

'use client';

import {
  Fragment,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type PointerEvent as ReactPointerEvent,
  type Ref,
} from 'react';
import { Avatar, CompanyMark, HealthSquare, StagePill } from './cells';
import type { Company, HealthId, Person, StageId } from './data';
import {
  FIELDS,
  OP_LABEL,
  depthOf,
  describe,
  freshCondition,
  locate,
  moveItem,
  nextField,
  removeItem,
  insertItem,
  setConj,
  slots,
  stepSlot,
  valueOptions,
  type Condition,
  type Group,
  type Slot,
} from './filter';
import type { Flight, Point } from './demo-pointer';
import { Grip, Icon } from './glyphs';
import styles from './filter-builder.module.css';

/*
 * The Filters popover's body: the root group's conditions and subgroups, each group's conjunction
 * pill on its bracket, and the foot that adds conditions and groups or clears them all.
 *
 * Rows move by their handle: dragged with the pointer (a line shows where it will land, in any
 * group), or with ↑ and ↓ on the focused handle, one slot at a time, into and out of subgroups.
 * A click (or Enter) on the handle opens its menu, Move up and Move down, which take the same
 * steps without dragging; the menu itself is drawn on the stage by filter-builder.tsx.
 * Whatever changes the tree, the rows that move glide from where they were (FLIP); new rows
 * grow in.
 */

export type PickerPart = 'field' | 'op' | 'value';

/** What the demo uses to drag a row as a person would, and the handle's menu to move one. */
export type PanelApi = {
  /** Moves a row one slot up or down, as ↑ and ↓ on its handle do, and keeps its handle focused. */
  step: (id: string, dir: -1 | 1) => void;
  /** Where `slot` is, in the stage's px, and the row's handle; null when either is gone. */
  demoDrag: (
    id: string,
    to: Slot,
  ) => { target: Point; follow: (flight: Flight) => void; drop: () => void } | null;
};

/** A slot's line: where it is, in the panel's own px. */
type SlotLine = Slot & { x: number; y: number; w: number };

/** The deepest a subgroup goes: the root, its subgroups, theirs. */
const MAX_DEPTH = 2;

export function FilterPanel({
  tree,
  change,
  say,
  picker,
  openPicker,
  rowMenu,
  openRowMenu,
  newId,
  people,
  companies,
  held,
  api,
  onDone,
}: {
  tree: Group;
  /** Sets the tree; `message` goes to the live region. */
  change: (next: Group, message: string) => void;
  say: (message: string) => void;
  /** The picker open now, to mark its trigger. */
  picker: { id: string; part: PickerPart } | null;
  openPicker: (id: string, part: PickerPart, anchor: HTMLElement) => void;
  /** The row whose handle menu is open now, to mark its handle. */
  rowMenu?: string | null;
  /** Opens (or closes) a row's handle menu, Move up and Move down. */
  openRowMenu?: (id: string, anchor: HTMLElement) => void;
  newId: () => string;
  people: Person[];
  companies: Company[];
  /** A row held mid-drag over a slot, locked: for the docs. */
  held?: { id: string; to: Slot };
  api: Ref<PanelApi | null>;
  /** Clear all also closes nothing; Escape is the dialog's. */
  onDone?: () => void;
}) {
  const body = useRef<HTMLDivElement>(null);
  const rects = useRef(new Map<string, DOMRect>());
  const [line, setLine] = useState<SlotLine | null>(null);
  const [dragging, setDragging] = useState<string | null>(held?.id ?? null);
  const drag = useRef<{
    id: string;
    row: HTMLElement;
    startY: number;
    scale: number;
    lines: SlotLine[];
    to: SlotLine | null;
  } | null>(null);
  // A press that became a drag doesn't also open the handle's menu.
  const dragged = useRef(false);

  const scaleOf = () => {
    const el = body.current;
    if (!el) return 1;
    return el.getBoundingClientRect().width / el.offsetWidth || 1;
  };

  /** Every slot's line, measured from the rows where they are now. */
  const measure = (): SlotLine[] => {
    const el = body.current;
    if (!el) return [];
    const frame = el.getBoundingClientRect();
    const scale = scaleOf();
    const local = (r: DOMRect) => ({
      x: (r.left - frame.left) / scale,
      top: (r.top - frame.top) / scale,
      bottom: (r.bottom - frame.top) / scale,
      w: r.width / scale,
    });
    return slots(tree).flatMap((slot) => {
      const items = [...el.querySelectorAll<HTMLElement>(`[data-in="${slot.group}"]`)];
      const box = el.querySelector<HTMLElement>(`[data-group-id="${slot.group}"]`);
      if (!box) return [];
      if (items.length === 0) {
        const r = local(box.getBoundingClientRect());
        return [{ ...slot, x: r.x, y: r.top + 4, w: r.w }];
      }
      const first = local(items[0].getBoundingClientRect());
      if (slot.index < items.length) {
        const r = local(items[slot.index].getBoundingClientRect());
        return [{ ...slot, x: first.x, y: r.top - 4, w: first.w }];
      }
      const r = local(items[items.length - 1].getBoundingClientRect());
      return [{ ...slot, x: first.x, y: r.bottom + 4, w: first.w }];
    });
  };

  // Rows that moved glide from where they were; new rows grow in.
  useLayoutEffect(() => {
    const el = body.current;
    if (!el) return;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const scale = scaleOf();
    const before = rects.current;
    const after = new Map<string, DOMRect>();
    el.querySelectorAll<HTMLElement>('[data-item-id]').forEach((item) => {
      const id = item.dataset.itemId!;
      const now = item.getBoundingClientRect();
      after.set(id, now);
      if (reduced || before.size === 0) return;
      const was = before.get(id);
      if (!was) {
        item.animate(
          [
            { opacity: 0, scale: '0.97' },
            { opacity: 1, scale: '1' },
          ],
          { duration: 260, easing: 'cubic-bezier(0.2, 0.9, 0.3, 1.2)' },
        );
        return;
      }
      const dx = (was.left - now.left) / scale;
      const dy = (was.top - now.top) / scale;
      if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return;
      item.animate([{ translate: `${dx}px ${dy}px` }, { translate: '0 0' }], {
        duration: 420,
        easing: 'cubic-bezier(0.22, 1.18, 0.36, 1)',
      });
    });
    rects.current = after;
  }, [tree]);

  // A held row, for the docs: lifted over the slot it would land in.
  useLayoutEffect(() => {
    if (!held) return;
    const to = measure().find((l) => l.group === held.to.group && l.index === held.to.index);
    const row = body.current?.querySelector<HTMLElement>(`[data-item-id="${held.id}"]`);
    if (!to || !row) return;
    setLine(to);
    const r = row.getBoundingClientRect();
    const frame = body.current!.getBoundingClientRect();
    const scale = scaleOf();
    const top = (r.top - frame.top) / scale;
    row.style.translate = `0 ${to.y - top - r.height / scale / 2 + 6}px`;
    // Measured once, as the docs draw it.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const where = (id: string) => {
    const at = locate(tree, id);
    if (!at) return '';
    const parent = at.parent.id === tree.id ? 'the top group' : 'the subgroup';
    return `${at.index + 1} of ${at.parent.items.length} in ${parent}`;
  };

  const commitMove = (id: string, to: Slot) => {
    const next = moveItem(tree, id, to);
    if (next === tree) return false;
    const c = locate(tree, id)?.item;
    const moved = locate(next, id);
    const parent = moved?.parent.id === next.id ? 'the top group' : 'the subgroup';
    change(
      next,
      `${c?.type === 'condition' ? FIELDS[c.field].label : 'Group'} moved: ${(moved?.index ?? 0) + 1} of ${moved?.parent.items.length} in ${parent}`,
    );
    return true;
  };

  // ---- Dragging with the pointer ---------------------------------------------------------------

  const onGripDown = (event: ReactPointerEvent<HTMLButtonElement>, id: string) => {
    if (event.button !== 0) return;
    const row = event.currentTarget.closest<HTMLElement>('[data-item-id]');
    if (!row) return;
    event.preventDefault();
    event.currentTarget.setPointerCapture(event.pointerId);
    dragged.current = false;
    drag.current = {
      id,
      row,
      startY: event.clientY,
      scale: scaleOf(),
      lines: measure(),
      to: null,
    };
  };
  const onGripMove = (event: ReactPointerEvent<HTMLButtonElement>) => {
    const d = drag.current;
    if (!d) return;
    const dy = (event.clientY - d.startY) / d.scale;
    if (!dragging && Math.abs(dy) < 3) return;
    if (!dragging) setDragging(d.id);
    dragged.current = true;
    d.row.style.translate = `0 ${dy}px`;
    const frame = body.current!.getBoundingClientRect();
    const y = (event.clientY - frame.top) / d.scale;
    let best: SlotLine | null = null;
    for (const l of d.lines) if (!best || Math.abs(l.y - y) < Math.abs(best.y - y)) best = l;
    if (best && (best.group !== d.to?.group || best.index !== d.to?.index)) {
      d.to = best;
      setLine(best);
    }
  };
  const onGripUp = () => {
    const d = drag.current;
    drag.current = null;
    if (!d) return;
    setLine(null);
    setDragging(null);
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    // The row lands from where it was let go.
    rects.current.set(d.id, d.row.getBoundingClientRect());
    d.row.style.translate = '';
    if (d.to && commitMove(d.id, d.to)) return;
    const at = rects.current.get(d.id);
    const now = d.row.getBoundingClientRect();
    if (at && !reduced) {
      d.row.animate([{ translate: `0 ${(at.top - now.top) / d.scale}px` }, { translate: '0 0' }], {
        duration: 320,
        easing: 'cubic-bezier(0.22, 1.18, 0.36, 1)',
      });
    }
  };

  /** One slot up or down, from the keyboard or the handle's menu. */
  const step = (id: string, dir: -1 | 1) => {
    const to = stepSlot(tree, id, dir);
    if (!to) {
      say(dir === -1 ? 'Already first' : 'Already last');
      return;
    }
    commitMove(id, to);
    // The handle keeps the focus when its row changes groups (and so is drawn again).
    requestAnimationFrame(() => {
      const grip = body.current?.querySelector<HTMLElement>(`[data-grip="${id}"]`);
      if (grip && document.activeElement !== grip) grip.focus({ preventScroll: true });
    });
  };

  const onGripKey = (event: ReactKeyboardEvent<HTMLButtonElement>, id: string) => {
    if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;
    event.preventDefault();
    step(id, event.key === 'ArrowUp' ? -1 : 1);
  };

  // ---- The demo's drag -------------------------------------------------------------------------

  useEffect(() => {
    const ref = api as { current: PanelApi | null } | null;
    if (!ref) return;
    ref.current = {
      step,
      demoDrag: (id, to) => {
        const el = body.current;
        const row = el?.querySelector<HTMLElement>(`[data-item-id="${id}"]`);
        const grip = el?.querySelector<HTMLElement>(`[data-grip="${id}"]`);
        const stage = el?.closest<HTMLElement>('[data-part="stage"]');
        const l = measure().find((s) => s.group === to.group && s.index === to.index);
        if (!el || !row || !grip || !stage || !l) return null;
        const scale = scaleOf();
        const s = stage.getBoundingClientRect();
        const b = el.getBoundingClientRect();
        const g = grip.getBoundingClientRect();
        const start = (g.top + g.height / 2 - s.top) / scale;
        const rowX = (row.getBoundingClientRect().left - b.left) / scale;
        const target: Point = {
          x: (g.left + g.width / 2 - s.left) / scale + (l.x - rowX),
          y: (b.top - s.top) / scale + l.y,
        };
        let lift: Animation | null = null;
        return {
          target,
          follow: ({ points, timing }) => {
            setDragging(id);
            setLine(l);
            lift = row.animate(
              points.map((p) => ({ translate: `0 ${p.y - start}px` })),
              { ...timing, fill: 'forwards' },
            );
          },
          drop: () => {
            rects.current.set(id, row.getBoundingClientRect());
            lift?.cancel();
            setLine(null);
            setDragging(null);
            commitMove(id, to);
          },
        };
      },
    };
    return () => {
      ref.current = null;
    };
  });

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

  const valueView = (c: Condition) => {
    if (c.value.length === 0) return <span className={styles.placeholder}>Select value</span>;
    const kind = FIELDS[c.field].kind;
    const more = c.value.length > 1 && (
      <span className={styles.more} aria-hidden="true">
        +{c.value.length - 1}
      </span>
    );
    const one = c.value[0];
    if (kind === 'person') {
      const p = people.find((x) => x.id === one);
      return (
        <>
          {p && <Avatar person={p} size={20} />}
          <span className={styles.valueText}>{p?.name ?? one}</span>
          {more}
        </>
      );
    }
    if (kind === 'status') {
      const label = valueOptions(c.field, c.op).find((o) => o.value === one)?.label;
      return (
        <>
          <HealthSquare health={one as HealthId} />
          <span className={styles.valueText}>{label}</span>
          {more}
        </>
      );
    }
    if (kind === 'stage')
      return (
        <>
          <span className={styles.valuePill}>
            <StagePill stage={one as StageId} />
          </span>
          {more}
        </>
      );
    if (kind === 'company') {
      const co = companies.find((x) => x.id === one);
      return (
        <>
          {co && <CompanyMark company={co} />}
          <span className={styles.valueText}>{co?.name ?? one}</span>
          {more}
        </>
      );
    }
    const label = valueOptions(c.field, c.op).find((o) => o.value === one)?.label ?? one;
    return kind === 'date' ? (
      <span className={styles.preset}>{label}</span>
    ) : (
      <span className={styles.valueText}>{label}</span>
    );
  };

  const trigger = (c: Condition, part: PickerPart) => {
    const open = picker?.id === c.id && picker.part === part;
    const field = FIELDS[c.field].label;
    const text =
      part === 'field'
        ? field
        : part === 'op'
          ? OP_LABEL[c.op]
          : c.value.length
            ? describe(c, people, companies).slice(field.length + OP_LABEL[c.op].length + 2)
            : 'none';
    return (
      <button
        type="button"
        className={styles.select}
        data-slot={part}
        data-part={part === 'value' ? 'value' : undefined}
        data-picker={`${part}:${c.id}`}
        data-demo={`${part}-${c.id}`}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={`${part === 'field' ? 'Field' : part === 'op' ? 'Operator' : 'Value'}: ${text}`}
        onClick={(event) => openPicker(c.id, part, event.currentTarget)}
      >
        <span className={styles.selectBody}>
          {part === 'value' ? (
            valueView(c)
          ) : (
            <span className={styles.valueText}>{part === 'field' ? field : OP_LABEL[c.op]}</span>
          )}
        </span>
        <Icon name="chevronDown" className={styles.chevron} />
      </button>
    );
  };

  const conditionRow = (c: Condition, group: Group, index: number) => (
    <div
      className={styles.condition}
      data-item-id={c.id}
      data-in={group.id}
      data-part="condition"
      data-dragging={dragging === c.id || undefined}
      style={{ gridRow: index + 1 }}
    >
      <div className={styles.rowBox} data-part="row-box">
        <button
          type="button"
          className={styles.grip}
          data-grip={c.id}
          data-demo={`grip-${c.id}`}
          data-part="grip"
          aria-label={`Move ${FIELDS[c.field].label} condition, ${where(c.id)}`}
          aria-describedby={`${group.id}-grip-hint`}
          aria-haspopup={openRowMenu ? 'menu' : undefined}
          aria-expanded={openRowMenu ? rowMenu === c.id : undefined}
          onClick={(event) => {
            if (dragged.current) {
              dragged.current = false;
              return;
            }
            openRowMenu?.(c.id, event.currentTarget);
          }}
          onPointerDown={(event) => onGripDown(event, c.id)}
          onPointerMove={onGripMove}
          onPointerUp={onGripUp}
          onPointerCancel={onGripUp}
          onKeyDown={(event) => onGripKey(event, c.id)}
        >
          <Grip className={styles.gripIcon} />
        </button>
        {trigger(c, 'field')}
        {trigger(c, 'op')}
        {trigger(c, 'value')}
      </div>
      <button
        type="button"
        className={styles.trash}
        aria-label={`Remove ${FIELDS[c.field].label} condition`}
        data-part="trash"
        onClick={() => change(removeItem(tree, c.id), `Removed ${describe(c, people, companies)}`)}
      >
        <Icon name="trash" />
      </button>
    </div>
  );

  const addCondition = (group: Group) => {
    const c = freshCondition(newId(), nextField(group));
    change(
      insertItem(tree, group.id, group.items.length, c),
      `Added ${FIELDS[c.field].label} condition; pick its value`,
    );
  };
  const addGroup = (group: Group) => {
    const c = freshCondition(newId(), 'health');
    const sub: Group = { type: 'group', id: `g-${newId()}`, conj: 'or', items: [c] };
    change(insertItem(tree, group.id, group.items.length, sub), 'Added a subgroup');
  };

  const conjPill = (group: Group) => (
    <button
      type="button"
      className={styles.conj}
      data-part="conjunction"
      data-demo={`conj-${group.id}`}
      data-conj={group.conj}
      aria-label={`Joined by ${group.conj === 'and' ? 'And' : 'Or'}; switch to ${group.conj === 'and' ? 'Or' : 'And'}`}
      onClick={() => {
        const next = group.conj === 'and' ? 'or' : 'and';
        change(
          setConj(tree, group.id, next),
          `${group.id === tree.id ? 'Conditions' : 'Subgroup'} now match ${next === 'and' ? 'all' : 'any'} of their conditions`,
        );
      }}
    >
      <span className={styles.conjText} key={group.conj}>
        {group.conj === 'and' ? 'And' : 'Or'}
      </span>
      <Icon name="swap" className={styles.conjIcon} />
    </button>
  );

  const groupGrid = (group: Group) => (
    <div className={styles.groupGrid} data-group-id={group.id}>
      <p id={`${group.id}-grip-hint`} hidden>
        Up and down arrows move the condition, into and out of subgroups. Enter opens Move up and
        Move down.
      </p>
      {group.items.length === 0 && <p className={styles.emptyGroup}>No conditions yet.</p>}
      {group.items.map((item, index) => (
        <Fragment key={item.id}>
          {index === 0 && (
            <span className={styles.where} aria-hidden="true">
              Where:
            </span>
          )}
          {/* On a narrow popover the pill sits between the rows instead of on the bracket. */}
          {index > 0 && (
            <div className={styles.joiner}>
              {index === 1 ? (
                conjPill(group)
              ) : (
                <span className={styles.joinerText} aria-hidden="true">
                  {group.conj === 'and' ? 'and' : 'or'}
                </span>
              )}
            </div>
          )}
          {item.type === 'condition'
            ? conditionRow(item, group, index)
            : subgroup(item, group, index)}
        </Fragment>
      ))}
      {group.items.length > 1 && (
        <div
          className={styles.bracket}
          data-part="bracket"
          style={{ gridRow: `2 / span ${group.items.length - 1}` }}
        >
          <span className={styles.bracketLine} aria-hidden="true" />
          {conjPill(group)}
        </div>
      )}
    </div>
  );

  const subgroup = (group: Group, parent: Group, index: number) => {
    const depth = depthOf(tree, group.id);
    return (
      <div
        className={styles.subgroup}
        data-item-id={group.id}
        data-in={parent.id}
        data-part="subgroup"
        role="group"
        aria-label={`${group.conj === 'and' ? 'All' : 'Any'} of the following are true`}
        style={{ gridRow: index + 1 }}
      >
        <div className={styles.subHead}>
          <span className={styles.caption}>
            {group.conj === 'and' ? 'All' : 'Any'} of the following are true:
          </span>
          <button
            type="button"
            className={styles.subRemove}
            aria-label="Remove this subgroup"
            onClick={() => change(removeItem(tree, group.id), 'Removed the subgroup')}
          >
            <Icon name="trash" />
          </button>
        </div>
        {groupGrid(group)}
        <div className={styles.foot}>
          <button
            type="button"
            className={styles.addAccent}
            data-demo={`add-${group.id}`}
            onClick={() => addCondition(group)}
          >
            <Icon name="plus" width={2} />
            Add condition
          </button>
          {depth < MAX_DEPTH && (
            <button type="button" className={styles.addPlain} onClick={() => addGroup(group)}>
              <Icon name="plus" width={2} />
              Add subgroup
            </button>
          )}
        </div>
      </div>
    );
  };

  return (
    <div ref={body} className={styles.panelBody} data-dragging={dragging ? '' : undefined}>
      {groupGrid(tree)}
      {line && (
        <span
          className={styles.dropLine}
          aria-hidden="true"
          data-part="drop-line"
          style={{ translate: `${line.x}px ${line.y}px`, width: line.w }}
        />
      )}
      <div className={styles.rootFoot}>
        <button
          type="button"
          className={styles.addAccent}
          data-demo="add-root"
          onClick={() => addCondition(tree)}
        >
          <Icon name="plus" width={2} />
          Add condition
        </button>
        <button type="button" className={styles.addPlain} onClick={() => addGroup(tree)}>
          <Icon name="plus" width={2} />
          Add group
        </button>
        <button
          type="button"
          className={styles.clear}
          disabled={tree.items.length === 0}
          onClick={() => {
            change({ ...tree, items: [] }, 'Cleared all conditions');
            onDone?.();
          }}
        >
          Clear all
        </button>
      </div>
    </div>
  );
}
```

### filter-builder/filter.ts

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

import {
  COMPANIES,
  HEALTH,
  PEOPLE,
  STAGES,
  money,
  type Company,
  type Opportunity,
  type Person,
} from './data';

/*
 * The filter as data: a group of conditions and subgroups joined by And or Or, the fields a
 * condition can test, the operators each kind of field takes, the values each offers, and the
 * pure functions that test a row and rearrange the tree. Nothing here draws.
 */

export type FieldId =
  'owner' | 'health' | 'stage' | 'company' | 'amount' | 'nextMeeting' | 'lastInteraction';
export type OpId =
  'is' | 'isNot' | 'anyOf' | 'noneOf' | 'over' | 'under' | 'when' | 'before' | 'after';
export type Conj = 'and' | 'or';

/** One test on one field. Values are always a list: a single-value operator reads the first. */
export type Condition = {
  type: 'condition';
  id: string;
  field: FieldId;
  op: OpId;
  value: string[];
};
export type Group = { type: 'group'; id: string; conj: Conj; items: Item[] };
export type Item = Condition | Group;

export type FieldKind = 'person' | 'status' | 'stage' | 'company' | 'number' | 'date';

export const FIELDS: Record<FieldId, { label: string; kind: FieldKind; ops: OpId[] }> = {
  owner: { label: 'Owner', kind: 'person', ops: ['is', 'isNot', 'anyOf'] },
  health: { label: 'Health score', kind: 'status', ops: ['is', 'isNot', 'anyOf'] },
  stage: { label: 'Stage', kind: 'stage', ops: ['anyOf', 'noneOf'] },
  company: { label: 'Company', kind: 'company', ops: ['anyOf', 'noneOf'] },
  amount: { label: 'Amount', kind: 'number', ops: ['over', 'under'] },
  nextMeeting: { label: 'Next meeting', kind: 'date', ops: ['when', 'before', 'after'] },
  lastInteraction: { label: 'Last interaction', kind: 'date', ops: ['when', 'before', 'after'] },
};

/** The order fields are listed in; a new condition takes the first its group does not test. */
export const FIELD_ORDER: FieldId[] = [
  'amount',
  'stage',
  'company',
  'owner',
  'health',
  'nextMeeting',
  'lastInteraction',
];
export const FIELD_MENU: FieldId[] = [
  'owner',
  'health',
  'stage',
  'company',
  'amount',
  'nextMeeting',
  'lastInteraction',
];

export const OP_LABEL: Record<OpId, string> = {
  is: 'is',
  isNot: 'is not',
  anyOf: 'is any of',
  noneOf: 'is none of',
  over: 'is over',
  under: 'is under',
  when: 'when',
  before: 'before',
  after: 'after',
};

export const isMulti = (op: OpId) => op === 'anyOf' || op === 'noneOf';

export type ValueOption =
  | { value: string; label: string; kind: 'person'; person: Person }
  | { value: string; label: string; kind: 'status' }
  | { value: string; label: string; kind: 'stage' }
  | { value: string; label: string; kind: 'company'; company: Company }
  | { value: string; label: string; kind: 'plain' };

/** Days from today each date preset covers, inclusive; null for no date at all. */
const MEETING_WHEN: Record<string, [string, [number, number] | null]> = {
  none: ['No meeting', null],
  thisWeek: ['This week', [0, 6]],
  nextWeek: ['Next week', [7, 13]],
  thisMonth: ['This month', [0, 30]],
};
const TOUCH_WHEN: Record<string, [string, [number, number] | null]> = {
  none: ['No interaction', null],
  thisWeek: ['This week', [0, 6]],
  lastWeek: ['Last week', [7, 13]],
  over30: ['Over 30 days ago', [31, 9999]],
};
/** The days a before/after anchor stands for. */
const MEETING_AT: Record<string, [string, number]> = {
  today: ['Today', 0],
  in7: ['In 7 days', 7],
  in14: ['In 14 days', 14],
  in30: ['In 30 days', 30],
};
const TOUCH_AT: Record<string, [string, number]> = {
  today: ['Today', 0],
  ago7: ['7 days ago', 7],
  ago14: ['14 days ago', 14],
  ago30: ['30 days ago', 30],
};
const AMOUNTS = [50000, 100000, 150000, 200000];

/** The values a condition can pick, from its field and operator. */
export function valueOptions(
  field: FieldId,
  op: OpId,
  people: Person[] = PEOPLE,
  companies: Company[] = COMPANIES,
): ValueOption[] {
  const plain = (record: Record<string, [string, unknown]>) =>
    Object.entries(record).map(([value, [label]]) => ({ value, label, kind: 'plain' as const }));
  switch (field) {
    case 'owner':
      return people.map((p) => ({ value: p.id, label: p.name, kind: 'person', person: p }));
    case 'health':
      return HEALTH.map((h) => ({ value: h.id, label: h.label, kind: 'status' }));
    case 'stage':
      return STAGES.map((s) => ({ value: s.id, label: s.label, kind: 'stage' }));
    case 'company':
      return companies.map((c) => ({ value: c.id, label: c.name, kind: 'company', company: c }));
    case 'amount':
      return AMOUNTS.map((n) => ({ value: String(n), label: money(n), kind: 'plain' }));
    case 'nextMeeting':
      return plain(op === 'when' ? MEETING_WHEN : MEETING_AT);
    case 'lastInteraction':
      return plain(op === 'when' ? TOUCH_WHEN : TOUCH_AT);
  }
}

/** Whether a condition has what it needs to test: a value. */
export const complete = (c: Condition) => c.value.length > 0;

function test(c: Condition, o: Opportunity): boolean {
  const v = c.value;
  const one = v[0];
  switch (FIELDS[c.field].kind) {
    case 'person':
    case 'status':
    case 'stage':
    case 'company': {
      const have = String(o[c.field as 'owner' | 'health' | 'stage' | 'company']);
      if (c.op === 'is') return have === one;
      if (c.op === 'isNot') return have !== one;
      if (c.op === 'anyOf') return v.includes(have);
      return !v.includes(have);
    }
    case 'number':
      return c.op === 'over' ? o.amount > Number(one) : o.amount < Number(one);
    case 'date': {
      const meeting = c.field === 'nextMeeting';
      const days = meeting ? o.nextMeeting : o.lastInteraction;
      if (c.op === 'when') {
        const range = (meeting ? MEETING_WHEN : TOUCH_WHEN)[one]?.[1];
        if (range === undefined) return true;
        if (range === null) return days === null;
        return days !== null && days >= range[0] && days <= range[1];
      }
      if (days === null) return false;
      const at = (meeting ? MEETING_AT : TOUCH_AT)[one]?.[1] ?? 0;
      // A meeting is ahead (more days is later); an interaction is behind (more days is earlier).
      const later = meeting ? days > at : days < at;
      const earlier = meeting ? days < at : days > at;
      return c.op === 'after' ? later : earlier;
    }
  }
}

/** Whether a group tests anything: a complete condition somewhere inside it. */
export const active = (item: Item): boolean =>
  item.type === 'condition' ? complete(item) : item.items.some(active);

/** Whether a row passes the group. Unfinished conditions and empty groups are left out. */
export function matches(group: Group, o: Opportunity): boolean {
  const live = group.items.filter(active);
  if (live.length === 0) return true;
  const pass = (item: Item) => (item.type === 'condition' ? test(item, o) : matches(item, o));
  return group.conj === 'and' ? live.every(pass) : live.some(pass);
}

/** How many complete conditions the tree holds: the Filters button's badge. */
export const countConditions = (group: Group): number =>
  group.items.reduce(
    (n, item) => n + (item.type === 'condition' ? (complete(item) ? 1 : 0) : countConditions(item)),
    0,
  );

/** A condition in words, for the live region: “Stage is any of Requirements or Technical win”. */
export function describe(c: Condition, people = PEOPLE, companies = COMPANIES) {
  const field = FIELDS[c.field].label;
  if (!complete(c)) return `${field} ${OP_LABEL[c.op]} (no value yet)`;
  const options = valueOptions(c.field, c.op, people, companies);
  const labels = c.value.map((v) => options.find((o) => o.value === v)?.label ?? v);
  const list =
    labels.length > 1 ? `${labels.slice(0, -1).join(', ')} or ${labels.at(-1)}` : labels[0];
  return `${field} ${OP_LABEL[c.op]} ${list}`;
}

// ---- The tree ------------------------------------------------------------------------------------

/** The item with `id`, and the group that holds it. */
export function locate(
  group: Group,
  id: string,
): { item: Item; parent: Group; index: number } | null {
  for (let index = 0; index < group.items.length; index += 1) {
    const item = group.items[index];
    if (item.id === id) return { item, parent: group, index };
    if (item.type === 'group') {
      const found = locate(item, id);
      if (found) return found;
    }
  }
  return null;
}

export function findGroup(group: Group, id: string): Group | null {
  if (group.id === id) return group;
  for (const item of group.items) {
    if (item.type === 'group') {
      const found = findGroup(item, id);
      if (found) return found;
    }
  }
  return null;
}

/** Depth of a group: the root is 0. */
export function depthOf(root: Group, id: string, depth = 0): number {
  if (root.id === id) return depth;
  for (const item of root.items) {
    if (item.type === 'group') {
      const found = depthOf(item, id, depth + 1);
      if (found >= 0) return found;
    }
  }
  return -1;
}

/** The tree with each group passed through `fn` (the root included). */
function mapGroups(group: Group, fn: (g: Group) => Group): Group {
  const next = fn(group);
  return {
    ...next,
    items: next.items.map((item) => (item.type === 'group' ? mapGroups(item, fn) : item)),
  };
}

export const updateCondition = (root: Group, id: string, fn: (c: Condition) => Condition) =>
  mapGroups(root, (g) => ({
    ...g,
    items: g.items.map((item) => (item.id === id && item.type === 'condition' ? fn(item) : item)),
  }));

export const setConj = (root: Group, id: string, conj: Conj) =>
  mapGroups(root, (g) => (g.id === id ? { ...g, conj } : g));

export const removeItem = (root: Group, id: string) =>
  mapGroups(root, (g) => ({ ...g, items: g.items.filter((item) => item.id !== id) }));

export const insertItem = (root: Group, groupId: string, index: number, item: Item) =>
  mapGroups(root, (g) => {
    if (g.id !== groupId) return g;
    const items = [...g.items];
    items.splice(Math.max(0, Math.min(index, items.length)), 0, item);
    return { ...g, items };
  });

/** A place an item can go: before the `index`th item of a group (its length for the end). */
export type Slot = { group: string; index: number };

/** Every slot in reading order, a subgroup's own slots between its parent's. */
export function slots(group: Group): Slot[] {
  const out: Slot[] = [];
  group.items.forEach((item, index) => {
    out.push({ group: group.id, index });
    if (item.type === 'group') out.push(...slots(item));
  });
  out.push({ group: group.id, index: group.items.length });
  return out;
}

/** Moves an item to a slot. A slot beside the item where it is leaves the tree as it was. */
export function moveItem(root: Group, id: string, to: Slot): Group {
  const from = locate(root, id);
  if (!from) return root;
  // A group never goes inside itself.
  if (from.item.type === 'group' && findGroup(from.item, to.group)) return root;
  let index = to.index;
  if (from.parent.id === to.group) {
    if (index === from.index || index === from.index + 1) return root;
    if (index > from.index) index -= 1;
  }
  return insertItem(removeItem(root, id), to.group, index, from.item);
}

/** The slot one step up or down from where the item is, for the keyboard. */
export function stepSlot(root: Group, id: string, dir: -1 | 1): Slot | null {
  const from = locate(root, id);
  if (!from) return null;
  const all = slots(root).filter(
    (s) => !(from.item.type === 'group' && findGroup(from.item, s.group)),
  );
  const here = all.findIndex(
    (s) => s.group === from.parent.id && s.index === (dir === 1 ? from.index + 1 : from.index),
  );
  return all[here + dir] ?? null;
}

/** What a field’s condition starts as. */
export function freshCondition(id: string, field: FieldId): Condition {
  return { type: 'condition', id, field, op: FIELDS[field].ops[0], value: [] };
}

/** The first field the group does not test yet, for a new condition. */
export function nextField(group: Group): FieldId {
  const used = new Set(
    group.items.filter((i): i is Condition => i.type === 'condition').map((c) => c.field),
  );
  return FIELD_ORDER.find((f) => !used.has(f)) ?? FIELD_ORDER[0];
}

/** A condition moved to another field or operator keeps what still makes sense. */
export function changeField(c: Condition, field: FieldId): Condition {
  return field === c.field ? c : { ...freshCondition(c.id, field) };
}
export function changeOp(c: Condition, op: OpId): Condition {
  const kind = FIELDS[c.field].kind;
  // A date's presets differ between when and before/after.
  const reset = kind === 'date' && (op === 'when') !== (c.op === 'when');
  const value = reset ? [] : isMulti(op) ? c.value : c.value.slice(0, 1);
  return { ...c, op, value };
}
```

### filter-builder/popup.tsx

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

'use client';

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

/*
 * The small popups: a listbox for a condition's field, operator or value, and a menu for the
 * toolbar's buttons. Both sit on the stage under their trigger (over it when there is no room
 * below), in the stage's own px, since a gallery card may scale the whole stage. The arrows, Home
 * and End move between items; Escape closes and gives the focus back; a press elsewhere closes.
 * A multi-select listbox stays open while you tick.
 */

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

export function Popup({
  anchor,
  role,
  label,
  multi,
  takeFocus,
  onClose,
  minWidth,
  children,
}: {
  anchor: HTMLElement;
  role: 'listbox' | 'menu';
  label: string;
  multi?: boolean;
  /** Moves the focus to the chosen or first item: when the reader opened it, not the demo. */
  takeFocus: boolean;
  /** `back`: give the focus back to the trigger. */
  onClose: (back: boolean) => void;
  /** At least the trigger's width when true. */
  minWidth?: boolean;
  children: ReactNode;
}) {
  const box = useRef<HTMLDivElement>(null);
  const [at, setAt] = useState<{ x: number; y: number; w: number; up: boolean } | null>(null);

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

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

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

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

  return (
    <div
      ref={box}
      role={role}
      tabIndex={-1}
      aria-label={label}
      aria-multiselectable={role === 'listbox' && multi ? true : undefined}
      className={styles.popup}
      data-popup=""
      data-up={at?.up || undefined}
      data-part={role === 'menu' ? 'menu' : 'listbox'}
      style={{
        translate: at ? `${at.x}px ${at.y}px` : undefined,
        minWidth: at?.w || undefined,
        visibility: at ? undefined : 'hidden',
      }}
      onKeyDown={onKeyDown}
    >
      {children}
    </div>
  );
}

/** One choice in a listbox: a check shows on the chosen ones. */
export function Option({
  selected,
  onSelect,
  lead,
  demo,
  children,
}: {
  selected: boolean;
  onSelect: () => void;
  lead?: ReactNode;
  demo?: string;
  children: ReactNode;
}) {
  return (
    <div
      role="option"
      aria-selected={selected}
      tabIndex={-1}
      className={styles.option}
      data-demo={demo}
      onClick={onSelect}
      onKeyDown={(event) => {
        if (event.key === 'Enter' || event.key === ' ') {
          event.preventDefault();
          onSelect();
        }
      }}
    >
      {lead}
      <span className={styles.optionText}>{children}</span>
      <span className={styles.optionCheck} data-on={selected || undefined} aria-hidden="true">
        <Icon name="check" width={2.4} />
      </span>
    </div>
  );
}

export function MenuItem({
  onSelect,
  kind = 'action',
  checked,
  disabled,
  demo,
  children,
}: {
  onSelect: () => void;
  kind?: 'action' | 'radio' | 'checkbox';
  checked?: boolean;
  disabled?: boolean;
  demo?: string;
  children: ReactNode;
}) {
  const role =
    kind === 'radio' ? 'menuitemradio' : kind === 'checkbox' ? 'menuitemcheckbox' : 'menuitem';
  return (
    <button
      type="button"
      role={role}
      aria-checked={kind === 'action' ? undefined : !!checked}
      aria-disabled={disabled || undefined}
      tabIndex={-1}
      className={styles.option}
      data-demo={demo}
      onClick={() => {
        if (!disabled) onSelect();
      }}
    >
      <span className={styles.optionText}>{children}</span>
      {kind !== 'action' && (
        <span className={styles.optionCheck} data-on={checked || undefined} aria-hidden="true">
          <Icon name="check" width={2.4} />
        </span>
      )}
    </button>
  );
}

export function PopupLabel({ children }: { children: ReactNode }) {
  return (
    <div className={styles.popupLabel} role="presentation">
      {children}
    </div>
  );
}
```

### filter-builder/cells.tsx

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

import type { Company, HealthId, Person, StageId } from './data';
import { HEALTH, STAGES } from './data';
import styles from './filter-builder.module.css';

/*
 * The small pieces the table and the value pickers share: a person's initials on their tint, a
 * company's mark, a stage pill and a health chip.
 */

export function Avatar({ person, size = 20 }: { person: Person; size?: number }) {
  const initials = person.name
    .split(' ')
    .map((part) => part[0])
    .slice(0, 2)
    .join('');
  return (
    <span
      className={styles.avatar}
      style={{ width: size, height: size, background: person.tint, fontSize: size * 0.42 }}
      aria-hidden="true"
      data-part="avatar"
    >
      {initials}
    </span>
  );
}

/** A company's mark: a small abstract shape in its colour, drawn here. */
export function CompanyMark({ company }: { company: Company }) {
  const c = company.tint;
  const shape = {
    ring: (
      <>
        <circle cx="8" cy="8" r="5.2" fill="none" stroke={c} strokeWidth="2.6" />
        <circle cx="8" cy="8" r="1.4" fill={c} />
      </>
    ),
    tile: (
      <>
        <rect x="1.5" y="1.5" width="13" height="13" rx="3.4" fill={c} />
        <rect x="5" y="5" width="6" height="6" rx="1.4" fill="#fff" />
      </>
    ),
    chevron: (
      <path d="M2 3.2h4.6L11 8l-4.4 4.8H2L6.4 8zM8.6 3.2h3.6L14 8l-1.8 4.8H8.6L11 8z" fill={c} />
    ),
    bars: (
      <>
        <rect x="2" y="7.5" width="3" height="6.5" rx="1" fill={c} />
        <rect x="6.5" y="4.5" width="3" height="9.5" rx="1" fill={c} />
        <rect x="11" y="2" width="3" height="12" rx="1" fill={c} />
      </>
    ),
    diamond: (
      <>
        <path d="M8 1.5 14.5 8 8 14.5 1.5 8z" fill={c} />
        <path d="M8 5.2 10.8 8 8 10.8 5.2 8z" fill="#fff" opacity="0.85" />
      </>
    ),
    peak: <path d="M1.5 13.5 6.2 4.5l2.6 4.6 1.6-2.4 4.1 6.8z" fill={c} />,
  }[company.mark];
  return (
    <svg viewBox="0 0 16 16" className={styles.mark} aria-hidden="true" data-part="company-mark">
      {shape}
    </svg>
  );
}

export function StagePill({ stage }: { stage: StageId }) {
  return (
    <span className={styles.stagePill} data-stage={stage} data-part="stage-pill">
      {STAGES.find((s) => s.id === stage)?.label}
    </span>
  );
}

export function HealthSquare({ health }: { health: HealthId }) {
  return <span className={styles.square} data-health={health} aria-hidden="true" />;
}

export function HealthChip({ health }: { health: HealthId }) {
  return (
    <span className={styles.healthChip} data-part="health-chip">
      <HealthSquare health={health} />
      {HEALTH.find((h) => h.id === health)?.label}
    </span>
  );
}
```

### filter-builder/filter-builder.module.css

```css
/* Filter builder (filter-builder.tsx): a CRM's Opportunities table on a grey stage, white by day
   and near-black by night. The card holds the page head, the view tabs, the toolbar and the
   table; the Filters popover opens over the table, under its button, and the pickers open over
   both, on the stage.

   Under 560 px of popover a condition's value takes a second line; under 640 px of card the
   toolbar keeps only Filters' label and scrolls sideways, and the table scrolls inside its box.

   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: #eef0f3;
  --card: #ffffff;
  --card-edge: #e3e5e9;
  --line: #eceef1;
  --ink: #1c1d21;
  --ink-2: #61646d;
  --ink-3: #686b73;
  --hover: #f3f4f6;
  --hover-strong: #eef0f3;
  --field: #ffffff;
  --field-edge: #e2e4e8;
  --panel: #f7f8f9;
  --popover: #ffffff;
  --popover-edge: #e4e6ea;
  --chip: #f1f2f4;
  --stripe: #f8f9fa;
  --bracket: #dcdfe4;
  --shadow: rgb(20 22 30 / 0.14);
  --shadow-near: rgb(20 22 30 / 0.06);
  --accent: #6b3cf0;
  --accent-ink: #ffffff;
  --accent-soft: #f1ecfe;
  --danger: #d93a3a;
  /* Health. */
  --critical: #e5383b;
  --risk: #e79a1c;
  --healthy: #2ba36a;
  /* Stages: fill, edge, text. */
  --discovery-bg: #f1f3f6;
  --discovery-edge: #e1e5eb;
  --discovery-ink: #4d5562;
  --requirements-bg: #fdf0f4;
  --requirements-edge: #f8d3df;
  --requirements-ink: #c22f66;
  --technical-bg: #f0eefe;
  --technical-edge: #dcd6fb;
  --technical-ink: #5a3fd8;
  --proposal-bg: #ebf4fe;
  --proposal-edge: #cfe3fb;
  --proposal-ink: #1f6bc6;
  --negotiation-bg: #fdf4e4;
  --negotiation-edge: #f6dfb2;
  --negotiation-ink: #9a6200;
  /* The same on both schemes. */
  --focus: #7c5cff;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.3);
  --sans: var(--body, Inter, ui-sans-serif, system-ui, sans-serif);
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --stage: light-dark(#eef0f3, #0b0b0d);
    --card: light-dark(#ffffff, #151518);
    --card-edge: light-dark(#e3e5e9, #26272c);
    --line: light-dark(#eceef1, #222327);
    --ink: light-dark(#1c1d21, #ececef);
    --ink-2: light-dark(#61646d, #a2a4ad);
    --ink-3: light-dark(#686b73, #8e9099);
    --hover: light-dark(#f3f4f6, #1f2024);
    --hover-strong: light-dark(#eef0f3, #25262b);
    --field: light-dark(#ffffff, #1a1b1f);
    --field-edge: light-dark(#e2e4e8, #2d2e34);
    --panel: light-dark(#f7f8f9, #1c1d21);
    --popover: light-dark(#ffffff, #18191c);
    --popover-edge: light-dark(#e4e6ea, #2c2d33);
    --chip: light-dark(#f1f2f4, #26272c);
    --stripe: light-dark(#f8f9fa, #19191d);
    --bracket: light-dark(#dcdfe4, #34353c);
    --shadow: light-dark(rgb(20 22 30 / 0.14), rgb(0 0 0 / 0.62));
    --shadow-near: light-dark(rgb(20 22 30 / 0.06), rgb(0 0 0 / 0.4));
    --accent: light-dark(#6b3cf0, #9d80ff);
    --accent-ink: light-dark(#ffffff, #151518);
    --accent-soft: light-dark(#f1ecfe, #251f3d);
    --danger: light-dark(#d93a3a, #f06464);
    --critical: light-dark(#e5383b, #f04a4d);
    --risk: light-dark(#e79a1c, #f0a83a);
    --healthy: light-dark(#2ba36a, #3cc07f);
    --discovery-bg: light-dark(#f1f3f6, #202228);
    --discovery-edge: light-dark(#e1e5eb, #30333b);
    --discovery-ink: light-dark(#4d5562, #b0b6c2);
    --requirements-bg: light-dark(#fdf0f4, #2c1620);
    --requirements-edge: light-dark(#f8d3df, #4c2334);
    --requirements-ink: light-dark(#c22f66, #f37aa6);
    --technical-bg: light-dark(#f0eefe, #211d3a);
    --technical-edge: light-dark(#dcd6fb, #362f63);
    --technical-ink: light-dark(#5a3fd8, #ab98ff);
    --proposal-bg: light-dark(#ebf4fe, #142236);
    --proposal-edge: light-dark(#cfe3fb, #1f3a5c);
    --proposal-ink: light-dark(#1f6bc6, #79b4f6);
    --negotiation-bg: light-dark(#fdf4e4, #2a2010);
    --negotiation-edge: light-dark(#f6dfb2, #4a3714);
    --negotiation-ink: light-dark(#9a6200, #f0b54d);
  }
}
.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;
  width: 100%;
  padding: clamp(10px, 3%, 28px);
  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) {
  margin: 0;
  padding: 0;
  border: 0;
  background: none;
  font: inherit;
  color: inherit;
  cursor: pointer;
}
.root button:disabled,
.root button[aria-disabled='true'] {
  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;
}

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

.card {
  position: relative;
  container-type: inline-size;
  border: 1px solid var(--card-edge);
  border-radius: 14px;
  background: var(--card);
  box-shadow: 0 1px 2px var(--shadow-near);
}
.head {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 18px 22px 12px;
}
.tile {
  display: grid;
  place-items: center;
  width: 34px;
  height: 34px;
  border: 1px solid var(--card-edge);
  border-radius: 9px;
  background: var(--card);
  box-shadow: 0 1px 2px var(--shadow-near);
}
.tileMark {
  width: 20px;
  height: 20px;
}
.title {
  margin: 0;
  font-size: 19px;
  font-weight: 500;
  letter-spacing: -0.01em;
}

.tabsRow {
  display: flex;
  align-items: flex-end;
  gap: 6px;
  padding: 0 22px;
  border-bottom: 1px solid var(--line);
  overflow-x: auto;
  scrollbar-width: none;
}
.tabs {
  display: flex;
  flex: none;
}
.tab {
  height: 40px;
  margin-bottom: -1px;
  padding: 0 16px !important;
  border: 1px solid transparent !important;
  border-bottom: 0 !important;
  border-radius: 9px 9px 0 0;
  color: var(--ink-2) !important;
  font-size: 14.5px !important;
  white-space: nowrap;
  transition: color 0.15s ease;
}
.tab:hover {
  color: var(--ink) !important;
}
.tab[aria-selected='true'] {
  border-color: var(--line) !important;
  background: var(--card);
  color: var(--ink) !important;
  font-weight: 500;
  box-shadow: 0 1px 0 var(--card);
}
.tab:focus-visible {
  outline-offset: -2px;
}
.tabsRule {
  flex: none;
  align-self: center;
  width: 1px;
  height: 20px;
  margin: 0 4px 0 6px;
  background: var(--line);
}
.addTab {
  display: inline-flex;
  flex: none;
  align-items: center;
  gap: 7px;
  height: 34px;
  margin-bottom: 3px;
  padding: 0 10px !important;
  border-radius: 8px;
  color: var(--ink-2) !important;
  font-size: 14.5px !important;
  white-space: nowrap;
}
.addTab svg {
  width: 17px;
  height: 17px;
}
.addTab:hover:not(:disabled) {
  background: var(--hover);
  color: var(--ink) !important;
}
.addTab:disabled {
  opacity: 0.45;
}

/* ---- Toolbar ---------------------------------------------------------------------------------- */

.toolbar {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 14px;
  overflow-x: auto;
  scrollbar-width: none;
}
.toolRule {
  flex: none;
  width: 1px;
  height: 20px;
  margin: 0 6px;
  background: var(--line);
}
.tool {
  display: inline-flex;
  flex: none;
  align-items: center;
  gap: 8px;
  height: 34px;
  padding: 0 11px !important;
  border-radius: 8px;
  font-size: 14.5px !important;
  white-space: nowrap;
  transition: background-color 0.15s ease;
}
.tool:hover,
.tool[data-over],
.tool[aria-expanded='true'] {
  background: var(--hover);
}
.tool[data-tool='filters'][data-on] {
  background: var(--hover-strong);
}
.toolIcon {
  width: 18px;
  height: 18px;
  color: var(--ink-2);
}
.badge {
  display: inline-grid;
  min-width: 21px;
  height: 21px;
  padding: 0 5px;
  overflow: hidden;
  border: 1px solid var(--field-edge);
  border-radius: 6px;
  background: var(--card);
  font-size: 12.5px;
  font-weight: 500;
  font-variant-numeric: tabular-nums;
  line-height: 19px;
  text-align: center;
}
.badgeNum {
  animation: roll 0.32s cubic-bezier(0.2, 0.9, 0.3, 1.25);
}
@keyframes roll {
  from {
    translate: 0 70%;
    opacity: 0;
  }
}

/* ---- Table ------------------------------------------------------------------------------------ */

.tabPanel {
  border-top: 0;
}
.tableBox {
  position: relative;
  height: 480px;
  overflow: auto;
  border-top: 1px solid var(--line);
  border-radius: 0 0 13px 13px;
  overscroll-behavior: contain;
  scrollbar-width: thin;
}
.table {
  width: 100%;
  min-width: 760px;
  border-collapse: separate;
  border-spacing: 0;
  font-size: 14.5px;
}
.table th,
.table td {
  height: 50px;
  padding: 0 18px;
  border-bottom: 1px solid var(--line);
  text-align: left;
  white-space: nowrap;
}
.tableBox[data-height='compact'] :is(tbody, tfoot) :is(th, td) {
  height: 38px;
}
.tableBox[data-height='tall'] :is(tbody, tfoot) :is(th, td) {
  height: 62px;
}
.table thead th {
  position: sticky;
  top: 0;
  z-index: 2;
  height: 42px;
  background: var(--card);
  font-weight: 500;
}
.table [data-col='name'] {
  position: sticky;
  left: 0;
  z-index: 1;
  min-width: 230px;
  background: var(--card);
  font-weight: 400;
}
.table thead [data-col='name'] {
  z-index: 3;
}
.table [data-col='amount'] {
  text-align: right;
  font-variant-numeric: tabular-nums;
}
.tableBox[data-lines='grid'] :is(th, td):not(:last-child) {
  border-right: 1px solid var(--line);
}
.tableBox[data-lines='stripes'] :is(th, td) {
  border-bottom-color: transparent;
}
.tableBox[data-lines='stripes'] thead th {
  border-bottom-color: var(--line);
}
.tableBox[data-lines='stripes'] .row:nth-child(even) :is(th, td) {
  background: var(--stripe);
}
.row :is(th, td) {
  transition: background-color 0.15s ease;
}
.row:hover :is(th, td) {
  background: var(--hover) !important;
}
.row {
  animation: rowIn 0.34s ease both;
}
@keyframes rowIn {
  from {
    opacity: 0;
  }
}
.table tfoot :is(th, td) {
  position: sticky;
  bottom: 0;
  height: 40px;
  border-top: 1px solid var(--line);
  border-bottom: 0;
  background: var(--card);
  color: var(--ink-2);
  font-size: 13.5px;
}
.table tfoot [data-col='name'] {
  z-index: 3;
}
.sumLabel {
  margin-right: 4px;
  color: var(--ink-3);
}
.sectionRow th {
  height: 44px !important;
  padding: 0 12px !important;
  background: var(--panel) !important;
}
.sectionButton {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  height: 32px;
  padding: 0 8px 0 4px !important;
  border-radius: 7px;
}
.sectionButton:hover {
  background: var(--hover-strong);
}
.sectionChevron {
  width: 16px;
  height: 16px;
  color: var(--ink-2);
  rotate: 0deg;
  transition: rotate 0.25s cubic-bezier(0.2, 0.9, 0.3, 1.2);
}
.sectionButton[aria-expanded='true'] .sectionChevron {
  rotate: 90deg;
}
.sectionCount {
  color: var(--ink-3);
  font-size: 13px;
  font-weight: 400;
  font-variant-numeric: tabular-nums;
}

/* Cells. */
.companyCell,
.ownerCell {
  display: inline-flex;
  align-items: center;
  gap: 10px;
}
.mark {
  width: 17px;
  height: 17px;
  color: var(--ink);
}
.avatar {
  display: inline-grid;
  flex: none;
  place-items: center;
  border-radius: 50%;
  color: #fff;
  font-weight: 600;
  letter-spacing: 0.02em;
  line-height: 1;
}
.stagePill {
  display: inline-block;
  max-width: 100%;
  padding: 3px 9px;
  overflow: hidden;
  border: 1px solid var(--discovery-edge);
  border-radius: 6px;
  background: var(--discovery-bg);
  color: var(--discovery-ink);
  font-size: 13.5px;
  line-height: 1.3;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
.stagePill[data-stage='requirements'] {
  border-color: var(--requirements-edge);
  background: var(--requirements-bg);
  color: var(--requirements-ink);
}
.stagePill[data-stage='technical'] {
  border-color: var(--technical-edge);
  background: var(--technical-bg);
  color: var(--technical-ink);
}
.stagePill[data-stage='proposal'] {
  border-color: var(--proposal-edge);
  background: var(--proposal-bg);
  color: var(--proposal-ink);
}
.stagePill[data-stage='negotiation'] {
  border-color: var(--negotiation-edge);
  background: var(--negotiation-bg);
  color: var(--negotiation-ink);
}
.healthChip {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 3px 10px 3px 9px;
  border: 1px solid var(--field-edge);
  border-radius: 6px;
  background: var(--card);
  font-size: 13.5px;
  line-height: 1.3;
}
.square {
  flex: none;
  width: 10px;
  height: 10px;
  border-radius: 2.5px;
  background: var(--critical);
}
.square[data-health='risk'] {
  background: var(--risk);
}
.square[data-health='healthy'] {
  background: var(--healthy);
}

/* No rows. */
.empty {
  position: absolute;
  inset: 43px 0 0;
  display: grid;
  place-content: center;
  justify-items: center;
  padding: 24px;
  text-align: center;
  animation: rowIn 0.3s ease both;
}
.emptyIcon {
  display: grid;
  place-items: center;
  width: 44px;
  height: 44px;
  margin-bottom: 12px;
  border: 1px solid var(--card-edge);
  border-radius: 12px;
  color: var(--ink-2);
}
.emptyIcon svg {
  width: 22px;
  height: 22px;
}
.emptyTitle {
  margin: 0;
  font-size: 15px;
  font-weight: 500;
}
.emptyText {
  margin: 4px 0 14px;
  color: var(--ink-2);
  font-size: 13.5px;
}
.emptyActions {
  display: flex;
  gap: 8px;
}
.emptyButton {
  height: 34px;
  padding: 0 13px !important;
  border: 1px solid var(--field-edge) !important;
  border-radius: 8px;
  background: var(--field) !important;
  font-size: 13.5px !important;
}
.emptyButton:hover {
  background: var(--hover) !important;
}
.emptyButton[data-tone='accent'] {
  border-color: var(--accent) !important;
  background: var(--accent) !important;
  color: var(--accent-ink) !important;
}

/* ---- The Filters popover ---------------------------------------------------------------------- */

.popover {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 5;
  container-type: inline-size;
  max-height: var(--pop-max, none);
  padding: 18px 18px 12px 16px;
  overflow-y: auto;
  border: 1px solid var(--popover-edge);
  border-radius: 13px;
  background: var(--popover);
  box-shadow:
    0 18px 44px -14px var(--shadow),
    0 2px 6px var(--shadow-near);
  transform-origin: 40px 0;
  animation: pop 0.24s cubic-bezier(0.2, 0.9, 0.3, 1.15);
  scrollbar-width: thin;
}
@keyframes pop {
  from {
    opacity: 0;
    scale: 0.96;
  }
}
.panelBody {
  position: relative;
  --label: 68px;
  --pill-x: 34px;
}

.groupGrid {
  position: relative;
  display: grid;
  grid-template-columns: var(--label) minmax(0, 1fr);
  row-gap: 10px;
}
.where {
  grid-row: 1;
  grid-column: 1;
  align-self: start;
  padding-top: 9px;
  color: var(--ink-2);
  font-size: 14.5px;
}
.emptyGroup {
  grid-column: 1 / -1;
  margin: 0;
  padding: 8px 0 2px;
  color: var(--ink-3);
  font-size: 13.5px;
}

.condition {
  position: relative;
  grid-column: 2;
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 0;
}
.rowBox {
  display: grid;
  grid-template-columns: 30px minmax(0, 1.36fr) minmax(0, 0.94fr) minmax(0, 1.42fr);
  flex: 0 1 438px;
  min-width: 0;
  height: 38px;
  border: 1px solid var(--field-edge);
  border-radius: 9px;
  background: var(--field);
  transition:
    box-shadow 0.2s ease,
    scale 0.2s ease;
}
.condition[data-dragging] {
  z-index: 4;
}
.condition[data-dragging] .rowBox {
  scale: 1.015;
  box-shadow: 0 12px 26px -10px var(--shadow);
}
.grip {
  display: grid;
  place-items: center;
  border-radius: 8px 0 0 8px;
  color: var(--ink-3) !important;
  cursor: grab !important;
  touch-action: none;
}
.grip:hover,
.grip[data-over] {
  background: var(--hover);
  color: var(--ink-2) !important;
}
.panelBody[data-dragging] * {
  cursor: grabbing !important;
}
.grip:focus-visible,
.select:focus-visible {
  outline-offset: -2px;
}
.gripIcon {
  width: 9px;
  height: 14px;
}
.select {
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 0;
  padding: 0 8px 0 12px !important;
  border-left: 1px solid var(--field-edge) !important;
  font-size: 14.5px !important;
  text-align: left;
  transition: background-color 0.15s ease;
}
.select:last-child {
  border-radius: 0 8px 8px 0;
}
.select:hover,
.select[data-over],
.select[aria-expanded='true'] {
  background: var(--hover);
}
.selectBody {
  display: flex;
  flex: 1;
  align-items: center;
  gap: 7px;
  min-width: 0;
}
.valueText {
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.placeholder {
  color: var(--ink-3);
  white-space: nowrap;
}
.preset {
  min-width: 0;
  padding: 2px 7px;
  overflow: hidden;
  border-radius: 6px;
  background: var(--chip);
  font-size: 13.5px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.valuePill {
  display: flex;
  min-width: 0;
}
.more {
  flex: none;
  padding: 1px 6px;
  border: 1px solid var(--field-edge);
  border-radius: 6px;
  color: var(--ink-2);
  font-size: 12.5px;
  font-variant-numeric: tabular-nums;
}
.chevron {
  width: 16px;
  height: 16px;
  margin-left: auto;
  color: var(--ink-2);
  transition: rotate 0.2s ease;
}
.select[aria-expanded='true'] .chevron {
  rotate: 180deg;
}
.trash,
.subRemove {
  display: grid;
  flex: none;
  place-items: center;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  color: var(--ink-2) !important;
  transition:
    background-color 0.15s ease,
    color 0.15s ease;
}
.trash svg,
.subRemove svg {
  width: 18px;
  height: 18px;
}
.trash:hover,
.subRemove:hover {
  background: var(--hover);
  color: var(--danger) !important;
}

/* The bracket that joins a group's rows, and its pill. */
.bracket {
  position: relative;
  grid-column: 1;
  min-height: 34px;
}
.bracketLine {
  position: absolute;
  top: 2px;
  bottom: 2px;
  left: var(--pill-x);
  right: 4px;
  border: 1.5px solid var(--bracket);
  border-right: 0;
  border-radius: 11px 0 0 11px;
}
.conj {
  position: absolute;
  top: 50%;
  left: var(--pill-x);
  display: inline-flex;
  align-items: center;
  gap: 5px;
  height: 32px;
  padding: 0 8px 0 10px !important;
  border: 1px solid var(--field-edge) !important;
  border-radius: 8px;
  background: var(--popover) !important;
  font-size: 14.5px !important;
  translate: -50% -50%;
  transition:
    background-color 0.15s ease,
    scale 0.2s cubic-bezier(0.2, 0.9, 0.3, 1.3);
}
.subgroup .conj {
  background: var(--panel) !important;
}
.conj:hover,
.conj[data-over] {
  background: var(--hover) !important;
}
.conj:active,
.conj[data-over] {
  scale: 0.95;
}
.conjText {
  display: inline-block;
  min-width: 26px;
  animation: flip 0.32s cubic-bezier(0.2, 0.9, 0.3, 1.25);
}
@keyframes flip {
  from {
    translate: 0 55%;
    opacity: 0;
  }
}
.conjIcon {
  width: 16px;
  height: 16px;
  color: var(--ink-2);
  rotate: 0deg;
  transition: rotate 0.5s cubic-bezier(0.25, 1.3, 0.4, 1);
}
.conj[data-conj='or'] .conjIcon {
  rotate: 180deg;
}

/* A subgroup: a tinted panel with its own rows and foot. */
.subgroup {
  position: relative;
  grid-column: 2;
  min-width: 0;
  padding: 10px 12px 8px 14px;
  border-radius: 12px;
  background: var(--panel);
}
.subgroup .groupGrid {
  --label: 70px;
}
.subgroup .subgroup {
  background: var(--card);
  box-shadow: inset 0 0 0 1px var(--line);
}
.subgroup .subgroup .conj {
  background: var(--card) !important;
}
.subHead {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 30px;
  margin-bottom: 6px;
}
.caption {
  color: var(--ink-2);
  font-size: 14px;
}
.subRemove {
  width: 28px;
  height: 28px;
  opacity: 0.6;
}
.subRemove:hover,
.subRemove:focus-visible {
  opacity: 1;
}
.foot,
.rootFoot {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px 10px;
  margin-top: 10px;
}
.rootFoot {
  margin-top: 14px;
}
.addAccent,
.addPlain,
.clear {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  height: 32px;
  padding: 0 8px !important;
  border-radius: 8px;
  font-size: 14.5px !important;
  white-space: nowrap;
  transition: background-color 0.15s ease;
}
.addAccent {
  color: var(--accent) !important;
  font-weight: 500;
}
.addAccent:hover,
.addAccent[data-over] {
  background: var(--accent-soft);
}
.addPlain,
.clear {
  color: var(--ink-2) !important;
}
.addPlain:hover,
.clear:hover:not(:disabled) {
  background: var(--hover);
  color: var(--ink) !important;
}
.clear {
  margin-left: auto;
}
.clear:disabled {
  opacity: 0.45;
}
.addAccent svg,
.addPlain svg {
  width: 17px;
  height: 17px;
}

/* Where a dragged row will land. */
.dropLine {
  position: absolute;
  top: -1px;
  left: 0;
  z-index: 5;
  height: 2px;
  border-radius: 2px;
  background: var(--accent);
  pointer-events: none;
  transition:
    translate 0.16s cubic-bezier(0.2, 0.9, 0.3, 1.1),
    width 0.16s ease;
}
.dropLine::before {
  content: '';
  position: absolute;
  top: -3px;
  left: -4px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--popover);
  box-shadow: inset 0 0 0 2px var(--accent);
}

/* The pill between rows, for narrow popovers. */
.joiner {
  display: none;
}

/* A narrow popover: the value takes the row's second line. */
@container (max-width: 560px) {
  .panelBody {
    --label: 50px;
    --pill-x: 24px;
  }
  .subgroup .groupGrid {
    --label: 46px;
  }
  .subgroup {
    padding: 8px 8px 6px 10px;
  }
  .where {
    font-size: 13px;
  }
  .rowBox {
    grid-template-columns: 26px minmax(0, 1.2fr) minmax(0, 1fr);
    grid-template-rows: 36px 36px;
    flex-basis: auto;
    height: auto;
  }
  .grip {
    grid-row: 1 / 3;
    border-radius: 8px 0 0 8px;
  }
  .select {
    padding: 0 6px 0 9px !important;
    font-size: 13.5px !important;
  }
  .select[data-slot='value'] {
    grid-column: 2 / 4;
    grid-row: 2;
    border-top: 1px solid var(--field-edge) !important;
    border-radius: 0 0 8px 0;
  }
  .select[data-slot='op'] {
    border-radius: 0 8px 0 0;
  }
  .trash {
    width: 28px;
  }
  .conj {
    padding: 0 6px 0 7px !important;
    font-size: 13px !important;
  }
  .conjText {
    min-width: 0;
  }
  .conjIcon {
    width: 14px;
    height: 14px;
  }
  .addAccent,
  .addPlain,
  .clear {
    font-size: 13.5px !important;
  }
}

/* A phone's popover: one column, the pill between the rows, the field over operator and value. */
@container (max-width: 440px) {
  .popover {
    padding: 12px 12px 8px;
  }
  .groupGrid,
  .subgroup .groupGrid {
    grid-template-columns: minmax(0, 1fr);
    row-gap: 6px;
  }
  .where,
  .bracket {
    display: none;
  }
  .condition,
  .subgroup {
    grid-column: 1;
    grid-row: auto !important;
  }
  .joiner {
    display: flex;
    align-items: center;
    gap: 8px;
    padding-left: 10px;
  }
  .joiner::before {
    content: '';
    width: 1.5px;
    height: 14px;
    margin-right: 2px;
    background: var(--bracket);
  }
  .joiner .conj {
    position: static;
    height: 28px;
    translate: none;
  }
  .joinerText {
    color: var(--ink-3);
    font-size: 13px;
  }
  .rowBox {
    flex: 1 1 0;
    grid-template-columns: 24px auto minmax(0, 1fr);
  }
  .select {
    gap: 4px;
    padding: 0 5px 0 8px !important;
    font-size: 13px !important;
  }
  .chevron {
    width: 14px;
    height: 14px;
  }
  .preset {
    padding: 2px 5px;
  }
  .select[data-slot='field'] {
    grid-column: 2 / 4;
    border-radius: 0 8px 0 0;
  }
  .select[data-slot='op'] {
    grid-column: 2;
    grid-row: 2;
    border-top: 1px solid var(--field-edge) !important;
    border-radius: 0;
  }
  .select[data-slot='value'] {
    grid-column: 3;
    grid-row: 2;
  }
  .subgroup {
    padding: 8px 8px 4px 10px;
  }
  .caption {
    font-size: 13px;
  }
  .subHead {
    margin-bottom: 4px;
  }
  .trash {
    width: 26px;
  }
  .rootFoot {
    gap: 2px 4px;
  }
}

/* ---- Pickers and menus ------------------------------------------------------------------------ */

.popup {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
  display: grid;
  align-content: start;
  min-width: 190px;
  max-height: 300px;
  padding: 5px;
  overflow-y: auto;
  border: 1px solid var(--popover-edge);
  border-radius: 11px;
  outline: none;
  background: var(--popover);
  box-shadow:
    0 16px 36px -12px var(--shadow),
    0 2px 5px var(--shadow-near);
  transform-origin: 30px 0;
  animation: pop 0.18s cubic-bezier(0.2, 0.9, 0.3, 1.15);
  scrollbar-width: thin;
}
.popup[data-up] {
  transform-origin: 30px 100%;
}
.option {
  display: flex;
  align-items: center;
  gap: 9px;
  min-height: 34px;
  padding: 0 9px !important;
  border-radius: 7px;
  outline: none;
  font-size: 14px !important;
  text-align: left;
  cursor: pointer;
  white-space: nowrap;
}
.option:hover:not([aria-disabled]),
.option:focus-visible,
.option[data-over] {
  background: var(--hover);
}
.option[aria-disabled='true'] {
  color: var(--ink-3) !important;
}
.optionText {
  flex: 1;
  min-width: 0;
}
.optionCheck {
  display: grid;
  place-items: center;
  width: 16px;
  height: 16px;
  margin-left: 12px;
  color: var(--accent);
  visibility: hidden;
}
.optionCheck svg {
  width: 16px;
  height: 16px;
}
.optionCheck[data-on] {
  visibility: visible;
}
.popupLabel {
  padding: 6px 9px 4px;
  color: var(--ink-3);
  font-size: 12.5px;
}

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

@container (max-width: 640px) {
  .head {
    padding: 14px 14px 10px;
  }
  .title {
    font-size: 17px;
  }
  .tabsRow {
    padding: 0 10px;
  }
  .tab {
    padding: 0 11px !important;
    font-size: 14px !important;
  }
  .toolbar {
    padding: 6px 8px;
  }
  .toolLabel:not([data-keep]) {
    position: absolute;
    width: 1px;
    height: 1px;
    overflow: hidden;
    clip-path: inset(50%);
  }
  .tool {
    padding: 0 9px !important;
  }
  .tableBox {
    height: 440px;
  }
  .table {
    min-width: 640px;
    font-size: 14px;
  }
  .table th,
  .table td {
    padding: 0 12px;
  }
  .table [data-col='name'] {
    min-width: 170px;
    max-width: 190px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

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

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

@media (prefers-reduced-motion: reduce) {
  .popover,
  .popup,
  .row,
  .empty,
  .badgeNum,
  .conjText {
    animation: none;
  }
  .conjIcon,
  .chevron,
  .sectionChevron,
  .dropLine,
  .rowBox,
  .conj {
    transition: none;
  }
}
```

### filter-builder/data.ts

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

import type { Group } from './filter';

/*
 * The sample a sales team's Opportunities table holds: people who own deals, the companies they
 * sell to, the stages a deal moves through and the deals themselves. Dates are days from today,
 * so the table reads the same whenever it opens.
 */

export type Person = { id: string; name: string; tint: string };
export type CompanyMarkShape = 'ring' | 'tile' | 'chevron' | 'bars' | 'diamond' | 'peak';
export type Company = { id: string; name: string; mark: CompanyMarkShape; tint: string };
export type StageId = 'discovery' | 'requirements' | 'technical' | 'proposal' | 'negotiation';
export type HealthId = 'critical' | 'risk' | 'healthy';

export type Opportunity = {
  id: string;
  name: string;
  amount: number;
  company: string;
  stage: StageId;
  health: HealthId;
  owner: string;
  /** Days until the next meeting; null when none is booked. */
  nextMeeting: number | null;
  /** Days since the last call, email or meeting; null when there has been none. */
  lastInteraction: number | null;
};

export const PEOPLE: Person[] = [
  { id: 'imani', name: 'Imani Okafor', tint: '#c27b52' },
  { id: 'theo', name: 'Theo Lindqvist', tint: '#5b7fd6' },
  { id: 'priya', name: 'Priya Raman', tint: '#b45aa8' },
  { id: 'mateo', name: 'Mateo Ruiz', tint: '#3f9a74' },
  { id: 'hana', name: 'Hana Mori', tint: '#d0a033' },
];

export const COMPANIES: Company[] = [
  { id: 'ostra', name: 'Ostra', mark: 'ring', tint: '#3d5bd9' },
  { id: 'brightmoor', name: 'Brightmoor', mark: 'tile', tint: '#e0912c' },
  { id: 'corvid', name: 'Corvid Labs', mark: 'chevron', tint: 'currentColor' },
  { id: 'halden', name: 'Halden & Co', mark: 'bars', tint: '#2f9e6b' },
  { id: 'vellum', name: 'Vellum', mark: 'diamond', tint: '#7b55e6' },
  { id: 'pinecrest', name: 'Pinecrest', mark: 'peak', tint: '#1e8fa3' },
];

export const STAGES: { id: StageId; label: string }[] = [
  { id: 'discovery', label: 'Discovery' },
  { id: 'requirements', label: 'Requirements' },
  { id: 'technical', label: 'Technical win' },
  { id: 'proposal', label: 'Proposal' },
  { id: 'negotiation', label: 'Negotiation' },
];

export const HEALTH: { id: HealthId; label: string }[] = [
  { id: 'critical', label: 'Critical' },
  { id: 'risk', label: 'At risk' },
  { id: 'healthy', label: 'Healthy' },
];

const deal = (
  id: string,
  name: string,
  amount: number,
  company: string,
  stage: StageId,
  health: HealthId,
  owner: string,
  nextMeeting: number | null,
  lastInteraction: number | null,
): Opportunity => ({
  id,
  name,
  amount,
  company,
  stage,
  health,
  owner,
  nextMeeting,
  lastInteraction,
});

export const OPPORTUNITIES: Opportunity[] = [
  deal('harbor', 'Harbor Expansion', 180000, 'ostra', 'technical', 'critical', 'imani', null, 3),
  deal('atlas', 'Atlas Rollout', 180000, 'brightmoor', 'technical', 'critical', 'imani', 4, 2),
  deal(
    'beacon',
    'Beacon Platform Upgrade',
    137500,
    'brightmoor',
    'requirements',
    'critical',
    'imani',
    null,
    null,
  ),
  deal(
    'cedar',
    'Cedar Line Renewal',
    220000,
    'brightmoor',
    'requirements',
    'risk',
    'imani',
    null,
    12,
  ),
  deal('driftwood', 'Driftwood Pilot', 124000, 'corvid', 'requirements', 'critical', 'imani', 9, 5),
  deal(
    'ember',
    'Ember Analytics Suite',
    137500,
    'corvid',
    'requirements',
    'healthy',
    'imani',
    2,
    null,
  ),
  deal(
    'fjord',
    'Fjord Data Migration',
    180000,
    'halden',
    'requirements',
    'critical',
    'imani',
    null,
    20,
  ),
  deal(
    'granite',
    'Granite Seat Expansion',
    60000,
    'halden',
    'technical',
    'critical',
    'imani',
    6,
    1,
  ),
  deal(
    'halcyon',
    'Halcyon Security Bundle',
    240000,
    'vellum',
    'technical',
    'healthy',
    'imani',
    3,
    1,
  ),
  deal(
    'iris',
    'Iris Onboarding Program',
    165000,
    'pinecrest',
    'requirements',
    'risk',
    'imani',
    5,
    4,
  ),
  deal(
    'juniper',
    'Juniper Multi-year Deal',
    310000,
    'vellum',
    'negotiation',
    'healthy',
    'theo',
    1,
    0,
  ),
  deal('kestrel', 'Kestrel Support Tier', 45000, 'ostra', 'proposal', 'risk', 'priya', null, 33),
  deal('lumen', 'Lumen API Add-on', 72000, 'corvid', 'discovery', 'healthy', 'mateo', 8, 2),
  deal(
    'meridian',
    'Meridian Regional Launch',
    195000,
    'pinecrest',
    'proposal',
    'critical',
    'theo',
    12,
    9,
  ),
  deal('nimbus', 'Nimbus Cloud Move', 150000, 'halden', 'negotiation', 'risk', 'hana', 20, 6),
  deal(
    'orchard',
    'Orchard Partner Deal',
    98000,
    'brightmoor',
    'discovery',
    'healthy',
    'priya',
    null,
    null,
  ),
  deal('pebble', 'Pebble Renewal', 54000, 'ostra', 'proposal', 'risk', 'imani', null, 1),
  deal('quarry', 'Quarry Analytics Pilot', 88000, 'halden', 'discovery', 'critical', 'imani', 7, 3),
];

/** A saved view: a tab with its own conditions. */
export type SavedView = { id: string; label: string; filter: Group };

export const VIEWS: SavedView[] = [
  {
    id: 'all',
    label: 'All opportunities',
    filter: {
      type: 'group',
      id: 'root',
      conj: 'and',
      items: [
        { type: 'condition', id: 'c-owner', field: 'owner', op: 'is', value: ['imani'] },
        {
          type: 'group',
          id: 'g-any',
          conj: 'or',
          items: [
            { type: 'condition', id: 'c-health', field: 'health', op: 'is', value: ['critical'] },
            {
              type: 'condition',
              id: 'c-meeting',
              field: 'nextMeeting',
              op: 'when',
              value: ['none'],
            },
            {
              type: 'condition',
              id: 'c-touch',
              field: 'lastInteraction',
              op: 'when',
              value: ['none'],
            },
          ],
        },
        {
          type: 'condition',
          id: 'c-stage',
          field: 'stage',
          op: 'anyOf',
          value: ['requirements', 'technical'],
        },
      ],
    },
  },
  {
    id: 'best',
    label: 'Best case',
    filter: {
      type: 'group',
      id: 'root',
      conj: 'and',
      items: [
        { type: 'condition', id: 'b-amount', field: 'amount', op: 'over', value: ['150000'] },
        { type: 'condition', id: 'b-health', field: 'health', op: 'isNot', value: ['critical'] },
      ],
    },
  },
  {
    id: 'quarter',
    label: 'This quarter',
    filter: {
      type: 'group',
      id: 'root',
      conj: 'and',
      items: [
        {
          type: 'condition',
          id: 'q-meeting',
          field: 'nextMeeting',
          op: 'when',
          value: ['thisMonth'],
        },
        {
          type: 'condition',
          id: 'q-stage',
          field: 'stage',
          op: 'anyOf',
          value: ['proposal', 'negotiation'],
        },
      ],
    },
  },
];

export const money = (n: number) => `$ ${n.toLocaleString('en-US')}`;
```

### filter-builder/glyphs.tsx

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

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

const PATHS = {
  plus: 'M12 5v14M5 12h14',
  chevronDown: 'M7.5 10l4.5 4.5 4.5-4.5',
  trash:
    'M4.5 6.5h15M9.5 6.5V4.8c0-.7.5-1.2 1.2-1.2h2.6c.7 0 1.2.5 1.2 1.2v1.7M6.5 6.5l.8 12.2c.1.9.8 1.6 1.7 1.6h6c.9 0 1.6-.7 1.7-1.6l.8-12.2M10.2 10.5v6M13.8 10.5v6',
  swap: 'M18.5 9.5A7 7 0 0 0 6 7.6M5.5 4v4h4M5.5 14.5A7 7 0 0 0 18 16.4M18.5 20v-4h-4',
  groups: 'M4 7h9M4 12h6M4 17h9M15 9.5l3.5 2.5-3.5 2.5',
  filter: 'M4.5 7h15M7.5 12h9M10.5 17h3',
  groupBy: 'M4.5 5h15v14h-15zM8 9.5h8M8 14.5h5',
  fields: 'M3.8 9.3 9 4.5h10.7v10.7l-5.2 5.2H3.8zM14.2 9.8h.01',
  rowHeight: 'M9.5 6h10M9.5 12h10M9.5 18h10M4.5 4.5v3M4.5 10.5v3M4.5 16.5v3',
  layout: 'M4 5.5h16v13H4zM4 10.5h16',
  check: 'M5 12.5l4.5 4.5L19 7.5',
  close: 'M7 7l10 10M17 7 7 17',
  funnelOff: 'M4.5 5.5h15l-5.8 7.2v5.6l-3.4 1.8v-7.4z',
  chevronRight: 'M10 7.5l4.5 4.5-4.5 4.5',
} as const;

export type IconName = keyof typeof PATHS;

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

/** Six dots in two columns: the handle a row is dragged by. */
export function Grip({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 12 18" className={className} aria-hidden="true" focusable="false">
      {[3, 9].map((x) =>
        [4, 9, 14].map((y) => (
          <circle key={`${x}-${y}`} cx={x} cy={y} r="1.35" fill="currentColor" />
        )),
      )}
    </svg>
  );
}

/** The page's own mark: a vault of three columns under a roof, on a warm tile. */
export function VaultMark({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" className={className} aria-hidden="true" focusable="false">
      <path d="M3.5 9 12 4l8.5 5z" fill="#c9a04a" />
      <path d="M3.5 9h17v1.6h-17z" fill="#a37b2c" />
      <path d="M6 11.5h2.2v6H6zM10.9 11.5h2.2v6h-2.2zM15.8 11.5H18v6h-2.2z" fill="#8a8f99" />
      <path d="M4 18h16v2H4z" fill="#a37b2c" />
      <circle cx="12" cy="7.4" r="1.1" fill="#fff4d6" />
    </svg>
  );
}
```

### filter-builder/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 (filter-builder.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 filters and the table. 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>
  );
}
```

### filter-builder/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 };
}
```