# `ixfx-detail-list`

A list that scales horizontally, not vertically. Items are laid out in equal-width columns; they flow top→bottom down a column, then wrap to the top of the next column to the right. The component has a fixed vertical extent and scrolls horizontally.

Selection semantics match `ixfx-vertical-list` — same modes, same `list-*` events, same keyboard gestures — but navigation is a 2-D grid (Up/Down move within a column, Left/Right jump columns).

---

## Contents

- [`ixfx-detail-list`](#ixfx-detail-list)
  - [Contents](#contents)
  - [Quick start](#quick-start)
    - [Declarative HTML items](#declarative-html-items)
    - [Programmatic items](#programmatic-items)
  - [Item types](#item-types)
    - [Plain `<li>` elements](#plain-li-elements)
    - [Object items](#object-items)
  - [Properties](#properties)
  - [Selection](#selection)
    - [Getters](#getters)
    - [Methods](#methods)
    - [Drag-selection from item space](#drag-selection-from-item-space)
  - [Interaction modes](#interaction-modes)
  - [Custom checkbox](#custom-checkbox)
  - [Events](#events)
  - [Native drag-out](#native-drag-out)
  - [Drops and reorder](#drops-and-reorder)
  - [Keyboard navigation](#keyboard-navigation)
    - [Wrapping](#wrapping)
  - [Incremental search](#incremental-search)
    - [Highlight styling](#highlight-styling)
  - [Grouping](#grouping)
  - [Filter predicate](#filter-predicate)
  - [Sorting](#sorting)
    - [Simple sort](#simple-sort)
    - [Sort by property](#sort-by-property)
    - [Custom comparator](#custom-comparator)
  - [Asynchronous data](#asynchronous-data)
    - [Promise provider](#promise-provider)
    - [Streaming provider](#streaming-provider)
  - [View state](#view-state)
  - [CSS variables](#css-variables)
  - [CSS parts](#css-parts)
  - [Performance](#performance)

---

## Quick start

### Declarative HTML items

```html
<ixfx-detail-list id="my-list" selection-mode="single">
  <li>Alpha</li>
  <li>Bravo</li>
  <li>Charlie</li>
</ixfx-detail-list>

<script type="module">
  import '@ixfx/components';

  const list = document.querySelector('#my-list');
  list.addEventListener('list-select', ({ detail }) => {
    const [item] = detail.selected;
    console.log('selected:', item?.textContent);
  });
</script>
```

Items flow down columns (vertically) then wrap to the next column:

```
Alpha    Golf     November  Uniform
Bravo    Hotel    Oscar    Victor
Charlie  India    Papa     Whiskey
Delta    Juliett  Quebec   X-ray
Echo     Kilo     Romeo    Yankee
Foxtrot  Lima     Sierra   Zulu
```

### Programmatic items

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

const list = document.querySelector<DetailListElement>('ixfx-detail-list')!;

list.addItem('Document A');
list.addItem('Image 01.png');

// Or pass an element directly
const li = document.createElement('li');
li.textContent = 'Custom item';
list.addItem(li);

// removeItem / removeItems return a Promise that resolves once the row is gone
list.removeItems(list.selectedItems);
```

Rows added mid-list collapse + fade in; `removeItem` / `removeItems` collapse +
fade them out before detaching, so the rows around them slide to make or close
the gap. A bulk populate isn't animated, and it's all skipped under
`prefers-reduced-motion: reduce` (`--ixfx-list-item-move-duration`, default
`200ms`).

---

## Item types

### Plain `<li>` elements

The simplest item type. Items are positioned by CSS flexbox into columns.

```html
<ixfx-detail-list>
  <li>Item one</li>
  <li>Item two</li>
</ixfx-detail-list>
```

**Attributes supported on `<li>`:**

| Attribute | Description |
|---|---|
| `data-search-label` | Override searchable text (defaults to `textContent`) |
| `data-key` | Stable identity for selection persistence across sort/rebuild |
| `data-value` | Alternative to `data-key` |
| `data-icon` | Icon name to display (injects `<ixfx-icon>`) |
| `not-checked` | In `checked` mode, renders without a checkbox and cannot be checked |
| `hidden` | Hides the item from view and navigation |

Descendants of an item may use `data-drag-select-content` to make their whole
box count as content, or `data-drag-select-blank` to make their box a marquee
starting area. These are useful for custom item layouts; normally the list
detects visible text and leaf elements (such as images and icons) automatically.

### Object items

Pass an array of objects and configure how to display them:

```typescript
const files = [
  { name: 'Report Q1.pdf', size: 220, kind: 'doc' },
  { name: 'Photo 01.png', size: 1400, kind: 'img' },
  { name: 'Notes.txt', size: 3, kind: 'doc' },
];

list.items = files;
list.displayProperty = 'name';
list.keyProperty = 'name'; // Preserves selection across rebuilds
```

**Object-related properties:**

| Property | Type | Description |
|---|---|---|
| `items` | `readonly unknown[]` | Array of objects to render |
| `displayProperty` | `string` | Property name to use as label |
| `keyProperty` | `string` | Property name for stable identity |
| `iconProperty` | `string` | Property name for icon name |
| `iconColorProperty` | `string` | Property name for the icon's CSS colour |
| `textColorProperty` | `string` | Property name for the caption's CSS colour |
| `badgeProperty` | `string` | Property name for a Finder-style badge |
| `formatter` | `(item: unknown, index: number) => string \| Node` | Custom renderer |
| `searchText` | `(item: unknown, index: number) => string` | Text incremental search matches (default: the caption if a string, else the row's whole text) |

```typescript
list.formatter = (item, index) => {
  const file = item as { name: string; size: number };
  return `${file.name} (${file.size} KB)`;
};
```

Reassigning `items` keeps the row of every object that is still in the new
array (matched by identity), so `list.items = [...list.items, next]` creates
one `<li>` rather than rebuilding the list — selection, cursor and scroll stay
put, and the new row animates in like `addItem()`. Pass new objects (or change
`displayProperty`, `formatter`, …) to rebuild rows. With a `formatter`, a row
is only kept at the same index, since the formatter receives the index.

Because reused rows aren't re-run through the `formatter`, state it reads from
outside the item (sizes, fit mode, …) doesn't reach existing rows when the same
objects are reassigned. Call `list.reformat()` to rebuild every row, or assign a
new `formatter` function (a new identity counts as a shape change).

When `formatter` returns a `Node`, search falls back to the row's whole text
(sublines, sizes, dates). Set `searchText` to match on just the name:

```typescript
list.searchText = item => (item as { name: string }).name;
```

Retrieve the original data for an element:

```typescript
const data = list.getItemData(liElement);
```

### Per-item icon colour, text colour and badges

Three more property-name lookups, in the same idiom as `iconProperty`: each
names the property on the item object that carries the value.

| Property | Applies to | Value |
|---|---|---|
| `icon-color-property` | the injected `<ixfx-icon>` | a CSS colour string |
| `text-color-property` | the caption | a CSS colour string |
| `badge-property` | a right-justified slot after the caption | anything Lit can render, or a DOM `Node` |

```typescript
list.displayProperty = `name`;
list.iconProperty = `icon`;
list.iconColorProperty = `iconColor`;
list.textColorProperty = `textColor`;
list.badgeProperty = `badge`;
list.items = [
  { name: `Report.pdf`, icon: `file`, badge: tagChip(`orange`) },
  { name: `Overdue.txt`, textColor: `crimson` },
];
```

Icons paint from `currentColor`, so `iconColor` recolours the glyph. Both
colours are applied inline, which means they also win over the selected /
tickled text colours — pick something legible against both, or leave them off
and let the component's theming handle selection contrast.

`undefined`, `null`, `''` and `false` all count as "not supplied", so a badge
can be made conditional without rebuilding the collection:

```typescript
list.badgeProperty = `badge`;   // rows without a tag simply have no badge
```

Changing any of these properties (or `items`, `formatter`, `displayProperty`,
`iconProperty`, `keyProperty`) rebuilds the rows.

The badge lands as a `<span class="item-badge">` in the row's light DOM, with
its layout applied as inline styles — a `::slotted()` rule can't reach inside a
slotted `<li>`. Drive it from `--detail-list-badge-gap` (or override with
`!important`). The icon's own gap is `--detail-list-icon-gap`.

---

## Properties

| Property | Attribute | Type | Default | Description |
|---|---|---|---|---|
| `selectionMode` | `selection-mode` | `'single' \| 'multiple' \| 'none'` | `'single'` | How selection works |
| `interactionMode` | `interaction-mode` | `'implicit' \| 'standard' \| 'manual' \| 'checked' \| 'sticky' \| 'vscode'` | `'standard'` | Click/keyboard behavior |
| `sort` | `sort` | `'none' \| 'ascending' \| 'descending'` | `'none'` | Sort direction |
| `sortBy` | `sort-by` | `string` | — | Object property to sort by |
| `sortComparator` | — | `(a, b) => number` | — | Custom sort function |
| `filterPredicate` | — | `(el: Element) => boolean` | — | Filter visible items |
| `itemWrap` | `item-wrap` | `'stop' \| 'wrap'` | `'stop'` | Keyboard wrap behavior |
| `provider` | — | `IDataProvider` | — | Async data source |
| `checkboxRenderer` | — | `function \| object` | — | Custom checkbox |

---

## Selection

### Getters

```typescript
const selected = list.selectedItem;       // First selected element or undefined
const allSelected = list.selectedItems;   // Array of all selected elements
```

### Methods

```typescript
list.select(item);          // Select an item
list.deselect(item);       // Deselect an item
list.selectMany([item1, item2]); // Select multiple
list.clearSelection();     // Clear all selections
list.selectAll();          // Select all visible items (if permitted)
```

### Drag-selection from item space

Mouse or pen press-and-drag draws a rectangle selecting every intersected row
(automatic with `selection-mode="multiple"` or a multi `interaction-mode`;
`disable-drag-select` opts out). When `items-draggable` is also enabled, a
drag starting on text, an image, or other item content starts native drag-out;
start on the empty part of a row to draw the selection rectangle. Without
`items-draggable`, dragging from content still starts the rectangle. A plain
click on blank row space still clicks/selects the item; touch still scrolls.

The blank/content decision uses the actual text and leaf-element bounds, so
items can contain any combination of images, labels, icons, and wrappers. For
an unusual layout, mark a descendant `data-drag-select-content` to reserve its
whole box for native dragging, or `data-drag-select-blank` to designate a
filler/spacer as a marquee starting area:

```html
<li data-key="photo-1">
  <span data-drag-select-content><img src="photo.jpg" alt="" /></span>
  <span>Photo 1</span>
  <span data-drag-select-blank style="flex: 1"></span>
</li>
```

Interactive controls and checkbox cells do not start marquee selection.

### Key-based selection

`Element` references die when the item set is rebuilt (re-fetch, re-sort,
filter). Drive selection by a stable **`data-key`** (or `data-value`) instead —
the Element API is unchanged, the key API is additive. Object items built from
`items` / a provider get their key stamped automatically from `keyProperty`.

```typescript
list.selectKeys(['row-3', 'row-7']);   // replace selection; keys with no row yet apply when the row appears
list.addSelectedKeys(['row-9']);       // multi-select modes only
list.removeSelectedKeys(['row-3']);
list.selectedKeys;                     // ReadonlySet<string>

list.focusKey('row-7');                // move cursor to an item + scroll into view
list.tickledKey;                       // key under the cursor, or undefined

list.addEventListener('list-select', ({ detail }) => {
  console.log([...detail.selectedKeys]);   // carried alongside detail.selected
});
```

Restore a selection across a data reload:

```typescript
const keep = [...list.selectedKeys];
list.items = await fetchRows();         // Element refs are stale...
list.selectKeys(keep);                  // ...keys still resolve
```

### Viewport

```typescript
list.visibleKeys();   // string[] — keys of items currently in the scroll viewport
```

Items lay out as a fixed-height, horizontally-scrolling column grid, so this
is a horizontal intersection test against the scroll container — every row
of an intersecting column counts as visible. Hidden (filtered-out) and
keyless items are omitted. Use it to prioritise viewport-first work (e.g.
metadata or thumbnail fetches for what's on screen right now). Mirrors
`ixfx-grid-list.visibleKeys()` and `ixfx-data-grid.getVisibleRange()`.

As a push counterpart, the list dispatches `detail-list-viewport-change` with
`{ renderedKeys, visibleKeys }` whenever either key set changes — scroll,
resize, or content change. At most once per animation frame, and only when
the sets actually differ from the last dispatch. `renderedKeys` is every
keyed, non-hidden item (the list has no virtual window); `visibleKeys`
matches `visibleKeys()`.

---

## Interaction modes

| Mode | Description |
|---|---|
| `standard` | Click replaces selection. Ctrl+click toggles. Shift+click creates range. Cmd+A selects all. Moving the cursor with the keyboard selects the item under it; Shift+move grows the selection from the anchor. |
| `implicit` | Click always replaces selection (no modifier support). |
| `checked` | Checkbox column toggles selection; rows marked `not-checked` have no checkbox. |
| `sticky` | Every click toggles. Cmd+A selects all. |
| `vscode` | Like `standard`, but moving the cursor does not change the selection; Shift+move extends it from the anchor. |
| `manual` | No auto-selection; drive state via `select()` / `deselect()` programmatically. |

---

## Custom checkbox

In `checked` mode, provide a custom checkbox renderer:

```typescript
list.checkboxRenderer = (checked) => checked
  ? html`<span>✓</span>`
  : html``;
```

Or use the shorthand object form:

```typescript
list.checkboxRenderer = { checked: '✓', unchecked: '' };
```

---

## Events

| Event | Detail | Description |
|---|---|---|
| `list-select` | `{ selected: Element[] }` | Selection changed |
| `list-tickle` | `{ item: Element }` | Hover/focus cursor moved |
| `list-activate` | `{ item: Element }` | Item activated (Enter/double-click) |
| `list-item-click` | `{ item: Element }` | Item clicked |
| `detail-list-viewport-change` | `{ renderedKeys, visibleKeys }` | Rendered/visible key sets changed (scroll, resize, content) |
| `list-native-drag-start` | `{ key, index, item, selectedKeys, selected, preview }` | Cancelable; native item drag begins |
| `list-drop` | `{ target, dataTransfer }` | A drop landed (`items-droppable`): see [Drops and reorder](#drops-and-reorder) |
| `list-reorder` | `{ keys, target }` | Cancelable; a drag that started here ended between two of its own items (`items-reorderable`) |

```typescript
list.addEventListener('list-select', (e) => {
  console.log('Selected:', [...e.detail.selected].map(el => el.textContent));
});
```

---

## Native drag-out

Set `items-draggable` to make selectable rows draggable out of the list. On
`dragstart` the list fires the cancelable, `composed`, bubbling
`list-native-drag-start` event with
`{ key, index, item, selectedKeys, selected, preview }`:

- `selected` is the full selection as display-ordered `ListDragEntry[]`
  (`{ key, index, item, element }`); `selectedKeys` mirrors the keys. The
  origin rule applies: dragging an unselected row replaces the selection with
  it first.
- `preview` is the shared built-in drag preview: `preview.element` for
  `DataTransfer.setDragImage()` (a row of cards for ≤5 items, a compact
  `N items` list with `+N more` for 6+), plus a pre-painted `preview.canvas`
  for native hosts.
- Assign `dragPreviewRenderer` for a custom synchronous preview returning
  `{ element, hotspot?, canvas?, dispose? }`.
- `preventDefault()` on the event cancels the browser drag, but the sync
  listener still sees `preview` (incl. `canvas`) — what lets an Electron host
  rasterize it during the synchronous turn.

The built-in preview is theme-aware (`--surface-4`, `--surface-4-text`,
`--border-subtle`, `--radius-m`, `--accent`, `font`) and exposes
`part="drag-preview"`.

---

## Drops and reorder

Set `items-droppable` to accept native drops, `drop-positions` (`on`, `between` or `both`) to say whether a drop lands on an item or in the gap between two, and `items-reorderable` to let the user drag an items to a new position. Items flow down a column and wrap right, so the gap is the top or bottom half of an item (a line within the column); the gap after a column's last item is the gap before the next column's first. `between` is refused while `sort` or `groupBy` is set (`reorderBlocked` is `'sorted'` / `'grouped'`); `on` drops still work. Edge auto-scroll is horizontal.

```typescript
list.itemsReorderable = true;
list.addEventListener('list-reorder', (e) => {
  items = applyListReorder(items, item => item.id, e.detail);
  list.items = items; // the detail-list never reorders its own items
});
```

`list-reorder` `{ keys, target }` (cancelable) fires for a drag that started here and ended between its own an items; `list-drop` `{ target, dataTransfer }` for anything else. `target` is `{ kind: 'on', key }`, `{ kind: 'between', beforeKey, afterKey, index }` or `{ kind: 'empty' }`, with neighbours and `index` in the **full, unfiltered order**. Gate with `canDrop(target, dataTransfer)` and `canReorder(keys, target)`; `resolveInternalDrag` recognises a drag your host substituted with an OS drag. The indicator is `part="drop-indicator"` (`--list-drop-indicator-color`, `--list-drop-indicator-size`).

Everything about targets, events, `applyListReorder`, virtualisation and auto-scroll is shared by all the lists: see [Drops and drag-to-reorder](./user-list-drop.md).

---

## Keyboard navigation

The list must have focus for keyboard navigation. Click an item to focus, or set `tabindex="0"` on the element.

| Key | Action |
|---|---|
| ↑ / ↓ | Move up/down within the current column |
| ← / → | Jump to previous/next column (same row) |
| Home | Jump to first item |
| End | Jump to last item |
| Enter | Activate item (fires `list-activate`) |
| Space | Toggle selection (in modes that support it) |
| Escape | Clear selection / close search |
| Ctrl+F | Open incremental search |
| Ctrl+A | Select all (in modes that support it) |

### Wrapping

Set `item-wrap="wrap"` to enable wraparound navigation:

```html
<ixfx-detail-list item-wrap="wrap">...</ixfx-detail-list>
```

With wrapping:
- Down from last row → first row of next column (or first column if at end)
- Up from first row → last row of previous column (or last column if at start)
- Right from last column → first column
- Left from first column → last column

---

## Incremental search

A built-in type-ahead popover with **navigate** / **select** / **filter** modes — see [`docs/infra-incremental.md`](./infra-incremental.md). No default shortcut; open it with `list.registry.invoke('list.search.filter')` (or `.navigate` / `.select`). A filter change re-runs the column geometry automatically.

Search matches against `data-search-label` (or `textContent` as fallback). Use `data-search-label` to match against a different string than what's displayed:

```html
<li data-search-label="document a alpha">Document A</li>
```

For object items, `searchText` sets `data-search-label` per row (see [Object items](#object-items)).

### Highlight styling

Matched characters are highlighted with the `detail-list-search` highlight key. Style matches with:

```css
::highlight(detail-list-search) {
  background: yellow;
  color: black;
}
```

---

## Grouping

Group rows under collapsible headers, following `ixfx-data-grid` (see its [Grouping](./data-grid.md#grouping) section).

```ts
list.groupBy = 'kind';                                  // object items: property · declarative <li>: data-kind
list.groupBy = (data, li) => li.textContent![0];        // or a function of (data, element)
list.groupLabel = (key, items) => `${key} (${items.length})`;
list.collapseAllGroups();
```

| Member | Notes |
|---|---|
| `groupBy` / `group-by` | Property name (object items), else `data-<name>` attribute, or a function `(data, li) => string`. `null` ungroups and restores the original order. |
| `groupLabel` | `(groupKey, items) => string`. Default: the key, or `(none)`. |
| `cross-group-selection` | Default `false`: selecting in one group clears the others, and Shift-range, Ctrl+A and marquee stay in one group. Programmatic key APIs are never clamped. |
| `groups` | Read-only `{ key, label, count, collapsed }[]`. |
| `toggleGroup(key)`, `setGroupCollapsed(key, bool)`, `collapseAllGroups()`, `expandAllGroups()` | Collapse state. |

- **Layout:** headers are ordinary rows in the column flow — a header, then its items, then the next group's header, wrapping into the next column like any row. Groups do not start new columns, so a header can land at the bottom of a column.
- Order: original order → `sort` → partition. Groups appear in first-encounter order of the sorted, filtered list. Rows added later join their group; a row added out of order counts as last in the original order.
- Filtering (`filterPredicate`, filter-mode search) runs first; an emptied group loses its header.
- **Collapsed groups** hide their rows (`data-group-collapsed`); they leave navigation, select-all, range, marquee and drag-out but keep their selection.
- **Keyboard:** Up/Down skip headers, even mid-column. Left/Right pick the row in the neighbouring column nearest the current one vertically, since headers shift rows. Headers are never focused; collapse is by click or the API.
- Headers are `<ixfx-list-group-header data-ixfx-group-header>` children managed by the list — do not add or remove them yourself. Style through `--detail-list-group-header-height`, `--list-group-header-text` and `--list-group-header-border`.
- Events: `list-group-toggle` `{ groupKey, collapsed }`, `list-group-change` `{ groupBy }`.

## Filter predicate

Use `filterPredicate` to programmatically hide items:

```typescript
// Show only .doc files
list.filterPredicate = (el) => el.getAttribute('data-kind') === 'doc';

// Clear filter
list.filterPredicate = undefined;
```

Filtered items are hidden from view, keyboard navigation, and selection.

---

## Sorting

### Simple sort

```typescript
list.sort = 'ascending';  // or 'descending'
```

### Sort by property

```typescript
list.sortBy = 'size';  // Sort by 'size' property
list.sort = 'ascending';
```

### Custom comparator

```typescript
list.sortComparator = (a, b) => {
  // Sort by kind first, then by label
  const kindCompare = a.data.kind.localeCompare(b.data.kind);
  if (kindCompare !== 0) return kindCompare;
  return a.label.localeCompare(b.label);
};
```

The comparator receives `{ element, data, label }` where:
- `element` — the `<li>` DOM element
- `data` — the original object from `items` array
- `label` — the display string

---

## Asynchronous data

Use a `provider` for async data loading:

### Promise provider

```typescript
list.provider = async () => {
  const response = await fetch('/api/items');
  return response.json();
};
```

### Streaming provider

```typescript
list.provider = async function*() {
  for (let i = 0; i < 100; i++) {
    yield [{ id: i, name: `Item ${i}` }];
    await delay(100);
  }
}();
```

The provider function can return:
- A promise that resolves to an array
- An async iterable that yields arrays (streaming)

Streaming providers extend columns to the right as batches arrive.

**Performance.** When each batch is a pure append (identical items followed
only by new ones), the list appends DOM for just the new items rather than
rebuilding from scratch — streaming thousands of items over many small
batches stays cheap. If `sort` is set, re-sorting is coalesced: many batches
arriving within the same animation frame trigger a single re-sort, not one
per batch. A batch that isn't a pure append (items reordered, removed, or
replaced) falls back to a full rebuild.

---

## View state

Snapshot and restore *how* the list is showing its data, separately from the
data, as plain JSON keyed by item / group key. See
[`docs/infra-view-state.md`](./infra-view-state.md) for the shared
contract.

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

bindViewState(list, {
  load: () => JSON.parse(localStorage.getItem(`files`) ?? `null`),
  save: s => localStorage.setItem(`files`, JSON.stringify(s)),
});
list.provider = fetchFiles; // pending state applies as batches arrive
```

`kind: 'detail-list'`. Fields (`DetailListViewState`):

| Field | Shape | Notes |
|---|---|---|
| `selected` | `string[]` | Selected item keys (`data-key` / `data-value`, or `keyProperty`). In `checked` mode this is the checked set — `data-checked` is derived from the selection, so there is no separate field. |
| `expanded` | `Record<string, boolean>` | `{ [groupKey]: false }` per collapsed group. Groups default open, so only collapses are recorded; `true` re-opens. |
| `focus` | `string` | Keyboard-cursor key, recorded only when the cursor was moved by keyboard. Restoring it puts the list in keyboard mode. |
| `scroll` | `{ top, left?, anchor? }` | Horizontal: `left`, plus `anchor` = the top item of the first visible column and the px offset into it. |

`sort` is not view state: the list has no UI to change it, so it stays host
configuration.

- **Pending.** Keys not in the data stay pending and apply when a matching
  item appears — via `items`, a provider batch (only the new slice is
  searched), `addItem` / `setItems`, or a light-DOM append. Selected items that
  leave the data (rebuild, `clearItems`, removed `<li>`) are deselected
  silently and their keys go pending.
- Restored selection fires `list-select`; restored collapses fire
  `list-group-toggle` for groups that are present. Any explicit selection
  change drops pending selection.
- Changing `groupBy` drops collapses of the current groups but keeps pending
  (never-matched) collapsed keys, so a state restored before `groupBy` is set
  still applies.
- A pending scroll waits until its anchor item is laid out and the columns are
  wide enough; a wheel, pointer or navigation key cancels it.

```ts
list.getViewState();                          // pending included
list.getViewState({ includePending: false });
list.setViewState({ selected: [`row-3`] });   // partial: only fields present apply
list.clearPendingViewState();
list.addEventListener(`view-state-change`, e => e.detail /* { state, reason } */);
```

---

## CSS variables

| Variable | Default | Description |
|---|---|---|
| `--detail-list-bg` | `surface-3` | Background color |
| `--detail-list-text` | `surface-3-text` | Text color |
| `--detail-list-border` | `border` | Border color |
| `--detail-list-radius` | `radius-s` | Border radius |
| `--detail-list-column-width` | `220px` | Width of each column |
| `--detail-list-column-gap` | `8px` | Gap between columns |
| `--detail-list-item-height` | `28px` | Height of each item |
| `--detail-list-item-padding` | `0 var(--space-xs)` | Item padding |
| `--detail-list-scrollbar-width` | `auto` | Scrollbar width |
| `--detail-list-scrollbar-gutter` | `auto` | Scrollbar gutter |
| `--detail-list-scrollbar-color` | `auto` | Scrollbar color |

Plus all `--item-bg-*`, `--item-text-*` variables from the theme for selection/tickle states.

To explicitly size columns to the widest visible item, call `fitColumnWidth()`. It
returns the applied width in pixels and does not run automatically:

```ts
const width = await list.fitColumnWidth();
console.log(`Column width: ${width}px`);
```

The resulting pixel value is set on the element itself and overrides an inherited
`--detail-list-column-width` value. Lists otherwise continue to use the configured
CSS variable or the default `220px` width.

---

## CSS parts

| Part | Description |
|---|---|
| `list` | The `<ul>` container |
| `search-overlay` | The Ctrl+F search overlay |
| `checkbox` | The checkbox element (in `checked` mode) |
| `loading` | The loading indicator |

```css
ixfx-detail-list::part(search-overlay) {
  background: rgba(0, 0, 0, 0.8);
}
```

---

## Performance

Every item is a real `<li>` in the light DOM — there is no virtual window —
so the per-frame and per-hover paths must never scale with the item count.
They don't: scrolling binary-searches the column flow (`visibleKeys()` reads
O(log n) rects), the column grid used for keyboard navigation is measured
lazily and re-validated with a few probe reads, hover and selection update
only the rows that changed, and each row has `contain: paint` so restyling
one row doesn't repaint the list.

`contain: paint` means row content that overflows the row box is clipped to
it (and each row is its own stacking context). Rows are fixed-size, so this
only matters if a badge or custom node is wider than the column. It costs
~0.6 ms more compositor work per scroll frame at 10k rows and saves ~30 ms of
paint per hover / selection change.

**Any change to `detail-list.ts` that touches item caching, geometry,
`_syncItemStates`, scrolling or the add / remove paths should be checked with
both tools below.** At 10k items these paths used to cost ~30 ms of script per
scroll frame and 180 ms per arrow-key press.

| | `detail-list.perf.test.ts` (+ `detail-list-geometry.test.ts`) | `pnpm bench:detail-list` |
|---|---|---|
| Runs | with `pnpm test` (happy-dom, stubbed layout) | against the dev server, in headless Chrome |
| Measures | work counters: layout reads per scroll / keypress, rows created per append, attribute writes per hover; 1k → 10k scaling | real main-thread ms: script + style / layout / paint |
| Catches | O(n) creeping into scroll, hover, navigation, add / remove; stale caches | real-browser slowdowns, including paint |
| Use it | always (part of CI) | before / after any perf-sensitive change |

**Real-browser benchmark** — `scripts/bench/detail-list.ts` drives
`#list-objects` in `demo/detail-list.html` with 1k / 10k generated items,
plain and grouped by `kind`, and reports:

- `scroll` / `jump` `script` + `render` — main-thread ms per frame scrolling
  the columns at 40 px / 1200 px per frame, from a timeline trace.
- `hover`, `keyNav`, `select`, `addItem`, `removeItem`, `itemsAppend`
  (`items = [...items, x]`) — main-thread ms per operation (script + render),
  run with `prefers-reduced-motion: reduce` so row animations don't count.

Record a baseline on the unchanged code, make the change, compare:

```sh
pnpm start                                           # dev server, separate terminal
pnpm bench:detail-list --out /tmp/list-base.json     # before
pnpm bench:detail-list --compare /tmp/list-base.json # after
```

`--compare` lists metrics over `--threshold` (default 50%, ignoring changes
under 1 ms); add `--fail-on-regression` to exit non-zero. Other options:
`--items 1000,10000`, `--group-by kind` (empty to skip grouped runs), `--url`.
Baselines are machine-specific and the dev server runs Lit in dev mode, so
compare runs against each other rather than against fixed budgets. The data
grid has the same tooling (`pnpm bench:data-grid`); shared harness code is in
`scripts/bench/`.


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

