# Multicol List

A faceted-filtering component: each column shows one property (facet) of the *same*
dataset, and selections narrow every other column (Lightroom-style cross-filtering).
Despite the miller-style appearance it is not a hierarchy — see `plans/multicol-list-impl.md`
for the design rationale.

The component does **not** own the data. For each column it hands a query (the column's
facet plus every *other* column's current choices) to a data provider you supply. The
provider returns that column's choices; items may carry a `count` for display.

---

## ixfx-multicol-list

### Properties

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `categories` | `readonly MulticolCategory[]` | `[]` | Facet definitions (tree, shown in the header picker menu). Only leaves are selectable as a column's category; a node with `children` is just a menu group. Keys are resolved across the whole tree. Each may carry `description` (shown as a tooltip on the column header label) and `defaults`: `grouped`, `groupBy`, `allLabel`, `sort`. |
| `dataProvider` | `IDataProvider<MulticolQuery, MulticolItem>` \| `undefined` | — | Called per column whenever that column's inputs change. Sync arrays, Promises and async-iterables are supported; the `AbortSignal` is honoured. |
| `selectionMode` | `ListSelectionMode` | `'multiple'` | `'none'`, `'single'` or `'multiple'` selection within a column. |
| `minColumns` | `number` | `1` | Floor for column removal. |
| `maxColumns` | `number` | `5` | Ceiling for column addition; `0` = unlimited. |
| `virtualizeThreshold` | `number` | `2000` | A column with more choices than this (and not grouped) renders only the rows near its viewport. `0` always renders every row. See [Performance](#performance). |

### Methods

```typescript
// View state: column layout, per-column selection and scroll (see below)
getViewState(options?: GetViewStateOptions<MulticolListViewState>): MulticolListViewState
setViewState(state: Partial<MulticolListViewState>): void
clearPendingViewState(): void

// Add a column for a category key, optionally at a position.
addColumn(categoryKey: string, position?: number): void

// Remove a column by id (respects minColumns).
removeColumn(columnId: string): void

// One MulticolColumnSelection per column, in display order.
// `values: []` means the column is at 'All' (contributes no filter).
getSelection(): readonly MulticolColumnSelection[]

// Every column back to 'All'. Fires multicol-select for each column that changed.
clearSelection(): void

// Auto-size columns to fit their content. Measures header labels and item text (including
// counts), then sets each column to the minimum width needed. Optional min/max overrides.
autoSizeColumns(options?: { minWidth?: number; maxWidth?: number }): Promise<void>
```

Unless a layout is restored with `setViewState({ columns })`, the element auto-seeds
one column (the first category) once `categories` is assigned.

### Events

| Event | Detail | Description |
|-------|--------|-------------|
| `multicol-select` | `{ columnId, columns }` | A column's selection changed. `columns` is a full snapshot (see `getSelection`). |
| `multicol-columns-change` | `{ columns, reason }` | Column layout changed. `columns` is the live layout (`MulticolColumnState[]`, as in view state). `reason` is one of `'add' \| 'remove' \| 'reorder' \| 'category' \| 'sort' \| 'grouping' \| 'resize'` (a view-state restore reports `'add'`). Resize fires **once on pointer-up** with the final width — never during the drag. |
| `view-state-change` | `{ state, reason }` | Debounced view-state snapshot; see [View state](#view-state). |

---

## Performance

A column with more than `virtualize-threshold` choices (default 2000) that is **not grouped** windows its rows: its list scrolls itself and
only the ~20 rows near the viewport are in the DOM (28px rows, `--list-item-height`). Selection, select-all, the "All" row, keyboard
navigation, sort, partial keys, tags and view-state scroll / selection restore work as for any column — selection is by key, so rows that
aren't rendered can still be selected. A column switches between windowed and plain when a re-query takes it across the threshold; grouped
columns are never windowed (one list per group). `autoSizeColumns()` measures only the rendered rows of a windowed column.

Sorting uses one shared `Intl.Collator` (`localeCompare` with options builds a collator per comparison: ~2.2 s for 100k labels, ~0.2 s now),
and `ixfx-vertical-list.visibleKeys()` binary-searches large lists instead of reading every row's rect.

Reference, one column of 100k choices plus two small ones, Chrome (`pnpm bench:multicol-list`, needs `pnpm start`; `--classes
filter,sort,scroll,selectall` picks what to run; also reports `domNodes` and `layoutObjects`):

| | before | after |
|---|---|---|
| first render | 1.45–1.57 s | ~0.19 s |
| rows in the DOM | 100,000 | 19 |
| layout objects | 500,331 | 428 |
| pick a value in a small column (the big column re-queries to 5k) | 152 ms | ~12 ms |
| back to "All" (100k rows again) | 1.42 s | ~0.15 s |
| click one row in the big column | 157 ms | ~2.5 ms |
| re-sort the big column | 1.51 s | ~0.15 s |
| select all in the big column | 1.60 s | 62 ms |
| jump-scroll frame (render) | 58–61 ms | ~2.4 ms |

What it does **not** fix: the inner list still builds a detached `<li>` (with its label and count spans) for every item, so a 100k column still
holds ~500k DOM nodes (about the same as before) and ~20 MB of JS heap; what goes away is the layout tree and the per-query / per-scroll work over
all of it. Building those rows lazily, on first render, is the next step (it would help `ixfx-flat-list` too).

## Selection intents and partial rows

Gestures in a column (click, Space, Enter, Shift+Arrow, Cmd/Ctrl+A, marquee, the column's incremental search, the "All" row) fire a cancelable `list-select-intent` on the multicol host with `columnId` set; `keys` are that column's item keys. Going back to "All" is a `clear` intent. `preventDefault()` leaves the column alone.

`partialKeys` marks items as partially selected in every column that has an item with that key; `setColumnPartialKeys(columnId, keys)` adds keys for one column only. Selected wins. See [Selection intents, partial rows, unloaded keys](./user-selection-intents.md).

## Data flow

1. A selection change in column *i* re-queries **every other** column; column *i*'s list
   is left untouched so the user keeps their place.
2. Adding, removing or changing a column's category re-queries all columns (a category
   swap resets that column to 'All' and applies the new category's `defaults`).
3. Sort, grouping toggle and reorder are client-side only — no re-query.
4. Each column keeps one in-flight request; a newer request aborts the older one and
   late results are dropped.
5. Selections that disappear from a column's data are pruned; an empty selection falls
   back to 'All' (a column is never left with nothing).

Every column injects an 'All' row (label from the category's `allLabel`, default `'All'`)
at the top, selected by default. Choosing values clears All; choosing All clears values.

---

## View state

Implements the shared view-state contract (`docs/infra-view-state.md`); `kind` is
`multicol-list`. Persist it with `bindViewState()`:

```typescript
import { bindViewState } from '@ixfx/components';

bindViewState(el, {
  load: () => JSON.parse(localStorage.getItem(`photos-facets`) ?? `null`),
  save: s => localStorage.setItem(`photos-facets`, JSON.stringify(s)),
});
```

| Field | Type | Meaning |
|---|---|---|
| `columns` | `MulticolColumnState[]` | Layout in display order: `{ id, categoryKey, sort, grouped, menu?, width? }`. |
| `selectedByColumn` | `Record<columnId, string[]>` | Selected item keys per column. A column that's absent (or `[]`) is at 'All'. |
| `scrollByColumn` | `Record<columnId, ScrollState>` | Each column list's scroll, anchored to the first visible item key. |

The shared `selected` / `scroll` / `focus` / `expanded` fields are not used.

- **`columns`** re-uses live columns by `id` (re-pointing the category if it differs,
  which resets that column to 'All' and applies the category defaults, then the
  saved `sort` / `grouped` / `width`), creates the others, reorders to match and
  removes columns not listed. A non-empty layout suppresses auto-seeding. A column
  whose category isn't in `categories` stays **pending** and is inserted at its
  saved position once `categories` includes it.
- **Selection** keys a column's data doesn't contain stay pending and are selected
  when items with those keys arrive (firing the normal `multicol-select` and
  cascade). Keys that leave a column's data are deselected and go pending. Any
  explicit selection change (click, the All row, `clearSelection()`) drops all
  pending selection. Selection saved for a column id that doesn't exist yet is
  handed over when that column is restored.
- **Scroll** waits until the anchor item has rendered; the user scrolling the
  column cancels it.
- `getViewState()` includes pending state by default (`{ includePending: false }`
  for live state only).

---

## Header interactions

- **Category label** — opens a menu of all categories; the current one is disabled.
- **Burger** (visible on column hover) — remove column, add column (left/right),
  sort ascending/descending, grouping toggle.
- **Header drag** — reorder columns; a caret marks the drop gap.
- **Right edge** — drag to resize (80–480 px, default 220).

---

## CSS variables

| Variable | Default | Description |
|----------|---------|-------------|
| `--multicol-list-bg` | `var(--surface-3)` | Column background |
| `--multicol-list-header-bg` | `var(--surface-2)` | Header background |
| `--multicol-list-header-text` | `var(--surface-3-text)` | Header text colour |
| `--multicol-list-border` | `var(--border)` | Column separator |
| `--multicol-list-min-column-width` | `80px` | Resize floor |
| `--multicol-list-max-column-width` | `480px` | Resize ceiling |
| `--multicol-list-header-font-size` | `unset` (inherits) | Header label font size |

Inherited from the theme: `--font-family`, `--text-s`/`--text-m`, `--space-*`,
`--radius-s`, `--accent`, `--transition`.

---

## Example

```typescript
import type { MulticolItem, MulticolQuery } from '@ixfx/components/multicol-list.js';

el.categories = [
  { key: `year`, label: `Year`, defaults: { allLabel: `Any year` } },
  { key: `camera`, label: `Camera`, defaults: {
    grouped: true,
    groupBy: (item: MulticolItem) => (item.data as { brand?: string }).brand ?? `?`,
  } },
];

el.dataProvider = (query: MulticolQuery, signal) => {
  // query.categoryKey — which facet to enumerate
  // query.otherSelections — Map<columnId, string[]> of every OTHER column's
  //                         choices ([] = that column is at 'All')
  return computeFacet(query.categoryKey, query.otherSelections);
};

el.addEventListener(`multicol-select`, (event) => {
  showResults(event.detail.columns);
});
```


**Item tags:** `tags` hook / `tagKeys` → `data-tags` and `part="… tag-<name>"`; `tagBehaviour` switches off `selectable` / `focusable` / `draggable` / `searchable` per tag. See [Item tags](./user-item-tags.md).

See `demo/multicol-list.html` for a full in-memory example with counts.
