# `ixfx-grid-list`

A virtualised grid of items — thumbnails, cards, or arbitrary slotted markup —
with selection, keyboard navigation, and captions. Windowed rendering keeps the
DOM small regardless of item count; the same component does a wrapping grid, a
single vertical column, or a horizontally-scrolling strip.

---

## Contents

1. [Quick start](#quick-start)
2. [Items & keys](#items--keys)
3. [Sizing & layout](#sizing--layout)
4. [Captions](#captions)
5. [Orientation](#orientation)
6. [Selection](#selection)
7. [Cursor](#cursor)
8. [Events](#events)
9. [Native drag-out](#native-drag-out)
10. [Drops and reorder](#drops-and-reorder)
11. [Keyboard](#keyboard)
12. [Grouping](#grouping)
13. [View state](#view-state)
14. [Virtualisation](#virtualisation)
15. [Performance](#performance)
16. [CSS parts](#css-parts)
17. [Choosing a list component](#choosing-a-list-component)

---

## Quick start

```html
<ixfx-grid-list id="grid" selection-mode="single" item-size="120" gap="8">
  <div class="tile" data-key="a" data-label="Apple">🍎</div>
  <div class="tile" data-key="b" data-label="Banana">🍌</div>
  <div class="tile" data-key="c" data-label="Cherry">🍒</div>
</ixfx-grid-list>

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

  const grid = document.querySelector('#grid');
  grid.addEventListener('list-select', ({ detail }) => {
    console.log([...detail.selectedKeys]);
  });
</script>
```

Items are **light-DOM children**. Each is projected into its own virtualised
cell via a named `<slot>`: the list sets each rendered item's `slot` attribute
(and removes it from items outside the window), so don't set `slot` on items
yourself. Add or remove children at any time — a `MutationObserver` picks the
change up and re-renders.

```typescript
import type { GridListElement } from '@ixfx/components/grid-list';

const grid = document.querySelector<GridListElement>('#grid')!;
for (const item of data) {
  const el = document.createElement('div');
  el.className = 'tile';
  el.dataset.key = item.id;
  el.dataset.label = item.name;
  el.textContent = item.glyph;
  grid.appendChild(el);
}
```

---

## Items & keys

| Item attribute | Purpose |
|---|---|
| `data-key` (or `data-value`) | Stable identity — for key-based selection, `focusKey`, and `visibleKeys()`. Recommended on every item. |
| `data-label` | Caption text (see [Captions](#captions)). Alternatively put the text in a `[data-grid-list-caption]` descendant. |
| `not-checked` | Item can't be tickled / checked (skipped by the cursor). |
| `hidden` | Item is excluded from layout and navigation. |

---

## Sizing & layout

| Property / attribute | Default | Description |
|---|---|---|
| `itemSize` / `item-size` | `160` | Cell width in px. Also the square's height for `separate` / `under` / `overlaid` / `hidden`. |
| `gap` | `8` | Gap between cells, px. |
| `captionHeight` / `caption-height` | `24` | Height reserved for the caption band in `separate` / `under`. |

Values are clamped and rounded. Changing `item-size` / `gap` re-anchors the
scroll on the item nearest the viewport centre (zoom stays put rather than
jumping to the top-left corner).

---

## Captions

`caption-style` — how the caption relates to the content:

| value | layout |
|---|---|
| `hidden` | No caption. Cell height = `item-size`. |
| `separate` | Content in a square; caption a **detached** label below it. Square and caption highlight independently (macOS Finder icon view). |
| `under` (default) | One box: content on top, caption strip **inside** it below. One selection outline. |
| `overlaid` | Caption floats over the content. |

`caption-align` — `left` \| `middle` (default) \| `right`. Text alignment; also
positions the pill in `separate`.

`overlaid` only:

- `caption-position` — `top` \| `middle` \| `bottom` (default).
- `caption-backdrop` — `scrim` (default, flat translucent panel) \| `gradient`
  (fades away from the caption edge) \| `blur` (frosted) \| `none` (text +
  shadow, no panel).

```html
<ixfx-grid-list caption-style="separate" caption-align="left"></ixfx-grid-list>
<ixfx-grid-list caption-style="overlaid" caption-position="top" caption-backdrop="gradient"></ixfx-grid-list>
```

---

## Orientation

`orientation`:

| value | layout | scrolls |
|---|---|---|
| `grid` (default) | wraps across as many columns as fit | vertically |
| `row` | a single row of items | **horizontally** |
| `column` | a single column of items | vertically |

`row` is the virtualised horizontal strip; `column` is the recommended
large-list replacement for `ixfx-vertical-list`.

### Snap-to-item

`snap-to-item` (`false` by default) — opt in to settle the viewport on the
nearest item boundary (`row`) or row boundary (`column`) once scrolling stops.
No effect in `grid` orientation.

This isn't implemented with native CSS `scroll-snap-type`: cells are
virtualised (only the visible window + overscan exist in the DOM, absolutely
positioned via `transform`), so the browser has no boxes to snap to once you
scroll a screen away, and the snap target would pop in/out of existence as the
window shifts. Instead, a short debounce after the last `scroll` event fires a
`scrollTo({ behavior: 'smooth' })` to the nearest boundary, computed the same
way the virtual window is (stride arithmetic — no measurement needed).

---

## Selection

`selection-mode` (`none` \| `single` \| `multiple`) and `interaction-mode`
(`standard` \| `implicit` \| `manual` \| `checked` \| `sticky` \| `vscode`) match
the other list components — see the `ixfx-vertical-list` README for the mode
table.

### Element API

```typescript
grid.select(el);              // replace with one item
grid.selectMany([a, b]);      // selection-mode="multiple" only
grid.deselect(el);
grid.clearSelection();
grid.selectAll();
grid.selectedItems;           // ReadonlySet<Element>
```

Press-and-drag on empty space between items draws a marquee rectangle selecting
every covered cell — a press that starts on an item never starts a marquee, so
it never fights an item drag or click (automatic with `selection-mode="multiple"`
or a multi `interaction-mode`; `disable-drag-select` opts out). Clicking empty
space *without* dragging clears the selection (Finder-style); the trailing click
after a marquee or item drag is swallowed so it cannot undo that drag's result.
See `docs-user/grid-list.md`.

### Key-based selection

`Element` references die when the item set is rebuilt. With a `data-key` on each
item, drive selection by key instead — additive, the Element API is unchanged.

```typescript
grid.selectKeys(['a', 'c']);        // replace; keys with no cell yet apply when the cell appears
grid.addSelectedKeys(['b']);        // multi-select modes only
grid.removeSelectedKeys(['a']);
grid.selectedKeys;                  // ReadonlySet<string>

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

Caller-owned selection: a cancelable `list-select-intent` fires before every gesture, and `partialKeys` marks partially selected cells (`data-partial`, `part="item partial"`).
See [Selection intents, partial rows, unloaded keys](./user-selection-intents.md): `list-select-intent`, `partialKeys`, and keys that arrive later.

Restore across a reload:

```typescript
const keep = [...grid.selectedKeys];
grid.replaceChildren(...(await fetchTiles()));
grid.selectKeys(keep);
```

---

## Cursor

The "tickled" cursor follows hover (mouse) or arrow keys (keyboard).

```typescript
grid.focusKey('b');      // move the cursor to an item and scroll it into view
grid.tickledKey;         // key under the cursor, or undefined
```

| Property / attribute | Default | Description |
|---|---|---|
| `disableHoverTickle` / `disable-hover-tickle` | `false` | When set, pointer hover no longer moves the cursor, fires `list-tickle`, or changes where arrow-key navigation resumes from, and the hover highlight is dropped so nothing *looks* interactive. Keyboard navigation, selection, and `focusKey()` are unaffected. |
| `scrollHoverTickle` / `scroll-hover-tickle` | `false` | Let hover follow cells that scroll beneath a stationary pointer. Off by default: during a scroll gesture, virtualised `pointerenter` events are ignored so `list-tickle` and the highlight hold still. Hover resumes on the next real pointer movement, or after the pointer leaves and re-enters the list. Click selection, keyboard navigation, and `focusKey()` are unaffected. |

```html
<ixfx-grid-list disable-hover-tickle></ixfx-grid-list>
```

Reflected as an attribute, so it can be toggled from CSS-adjacent tooling and
read back off the element.

### Scrolling vs hover

Because cells are virtualised, wheel / trackpad scrolling inserts new cells
under a stationary pointer, and each fresh cell fires `pointerenter` — the
cursor and any cursor-driven rendering (e.g. a large preview panel) churn for
as long as the gesture lasts, even though the pointer never moved.
By default those synthetic enters are ignored while the gesture is active
(set `scroll-hover-tickle` to let hover follow the content instead). While suppressed, the host carries a `data-scroll-hover-suppress`
attribute (the CSS `:hover` highlight is gated on it), which is removed on the
next real pointer movement or when the pointer leaves the list.

For views where hover should never drive anything, prefer the broader
`disable-hover-tickle`.

---

## Events

All bubble and are `composed`.

| Event | Detail | When |
|---|---|---|
| `list-select` | `{ selectedKeys, previousKeys, selected, previous }` | Selection changes by any means |
| `list-activate` | `{ key, index, item, element }` | Double-click or `Enter` on an item |
| `list-item-click` | `{ key, index, item, element }` | Single click / `Enter` |
| `list-tickle` | `{ key, index, item, element }` | Cursor moves onto an item |
| `grid-list-viewport-change` | `{ renderedKeys, visibleKeys }` | Scroll, resize, filter, content change, or `refreshLayout()` — the rendered window moved. Coalesced to once per frame and only dispatched when either key set differs from the last dispatch |
| `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`) |

`key` / `index` are the stable contract in both modes. `item` is backward-compatible: the light-DOM `Element` in element mode, the data value in data mode. `element` is the DOM node when there is one (`undefined` in data mode). `selected` / `previous` (Element sets) are populated in element mode only; use `selectedKeys` / `previousKeys` everywhere.

---

## Native drag-out

Set `items-draggable` to make selectable cells draggable out of the grid. On
`dragstart` the grid 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 cell replaces the selection with
  it first. Works in data-backed mode too — `item` is the data value and
  `element` is `undefined` there.
- `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? }`.
- Assign `writeDataTransfer(dataTransfer, detail)` to put your own payload on
  the drag (e.g. a custom MIME type). It is a public property on every list
  (`ixfx-grid-list`, `ixfx-vertical-list`, `ixfx-detail-list`, `ixfx-data-grid`,
  and forwarded by `ixfx-flat-list`), run synchronously in `dragstart` after a
  non-cancelled `list-native-drag-start`.
- `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 a cell or in the gap between two, and `items-reorderable` to let the user drag a cells to a new position. Gaps follow the flow axis: left / right of a cell in `grid` and `row` (a caret between cells), above / below in `column`. `between` is refused while `groupBy` is set (`reorderBlocked` is `'grouped'`); `on` drops still work. 

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

`list-reorder` `{ keys, target }` (cancelable) fires for a drag that started here and ended between its own a cells; `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

| Key | `grid` | `row` / `column` |
|---|---|---|
| `ArrowLeft` / `ArrowRight` | ∓1 item | ∓1 item |
| `ArrowUp` / `ArrowDown` | ∓/± one row | ∓1 item |
| `Home` / `End` | first / last | first / last |
| `PageUp` / `PageDown` | ± one screen of rows | ± one screen of items |
| `Enter` | activate | activate |
| `Space` | toggle selection | toggle selection |
| `Escape` | clear selection | clear selection |
| `Ctrl` / `Cmd` + `A` | select all (multi modes) | select all (multi modes) |

---

## Incremental search

A built-in type-ahead popover with **navigate** / **select** / **filter** modes.
No default shortcut — open it via a command on `grid.registry`:

```typescript
grid.registry.invoke('list.search.filter');   // or .navigate / .select
```

Search matches `data-label` (or `[data-grid-list-caption]` text, then
`data-search-label`, then `textContent`). Filter mode genuinely removes items
from the virtualised layout. Matched characters are highlighted under the
`grid-list-search` key. In data mode (`itemAdapter`) the captions live in the
shadow root and the grid styles them itself (`--search-highlight-bg` /
`--search-highlight-color`, default `--accent` / `--accent-text`). In element
mode the items are light DOM, so add a page-level rule:

```css
::highlight(grid-list-search) { background: var(--accent); color: var(--accent-text); }
```

`filterPredicate` (an `(el: Element) => boolean` property) filters element-mode
items directly, independent of search; the data-mode equivalent is
`itemFilterPredicate` (`(item, index) => boolean`). Filtering removes items from
layout and navigation without materialising anything in data mode. Limit modes
with `search-modes="navigate filter"`. Full model:
[`docs/infra-incremental.md`](./infra-incremental.md).

---

## Data-backed mode

For very large collections (a directory of 100k files), give the grid an
**ordered array plus an adapter** instead of one light-DOM element per item.
Only the visible window plus overscan is ever rendered — item content DOM is
created and torn down as the window moves.

```typescript
import type { GridListElement, GridListDataAdapter } from '@ixfx/components/grid-list';

const grid = document.querySelector<GridListElement<FileRecord>>('#grid')!;

grid.itemAdapter = {
  key:  f => f.path,                         // stable identity (required)
  label: f => f.name,                        // caption text
  render: f => html`<img src=${f.thumb} loading="lazy" decoding="async">`,
  disabled: f => f.locked,                   // optional — not selectable / tickle-able
  searchableText: f => `${f.name} ${f.ext}`, // optional — search haystack
  icon: f => fileIcon(f.ext),                // optional — above the cell content
  iconColor: f => f.tint,                    // optional — CSS colour for that icon
  textColor: f => f.textTint,                // optional — CSS colour for the caption
  badge: f => f.tag && tagChip(f.tag),       // optional — inline, before the name
};
grid.items = files;                          // readonly FileRecord[]
```

`render` returns anything Lit can render — a `TemplateResult`, a DOM `Node`, or a
string. It runs only for items in the rendered window.

`GridListDataAdapter<T>` is exported from both `@ixfx/components/grid-list` and
`@ixfx/components`. Keep the adapter instance **stable** — hold it in a field,
don't rebuild it each host render. Assigning a new `itemAdapter` reference makes
the grid reconstruct its data source, which is wasteful for a streaming
collection.

#### Per-item icon, colours and badges

The four optional appearance functions are the Finder-style per-item hooks:

| Function | Renders |
|---|---|
| `icon(item, index)` | Inside a sized, centred slot **above** the cell's content. Anything Lit can render. |
| `iconColor(item, index)` | `color` on that slot. Glyphs painting from `currentColor` are recoloured. |
| `textColor(item, index)` | `color` on the cell's caption. |
| `badge(item, index)` | A Finder-style badge, **inline at the head of the caption**, before the filename. |

```typescript
import { html } from 'lit';
import { tagChip, stackedTagChips } from './my-tags.js';

grid.itemAdapter = {
  key: f => f.path,
  label: f => f.name,
  render: f => html`<img src=${f.thumb} loading="lazy">`,
  icon: f => html`<ixfx-icon name="file" style="width:100%;height:100%"></ixfx-icon>`,
  iconColor: f => f.tint,
  textColor: f => (f.overdue ? 'crimson' : undefined),
  badge: f => (f.tags.length > 1 ? stackedTagChips(f.tags) : tagChip(f.tags[0])),
};
```

`undefined`, `null`, `''` and `false` all count as "not supplied", so a hook
can be made conditional without touching the collection. Both colours are
applied inline, which means they also win over the selected / tickled caption
colours — pick something legible against both, or leave them off and let the
component's theming handle selection contrast.

Element mode needs none of this: you own the light-DOM markup, so set the
colours yourself and put the badge markup wherever you want it.

CSS: `--grid-list-icon-size`, `--grid-list-icon-gap`, `--grid-list-badge-gap`.

Parts: `part="icon"` and `part="badge"` on the wrappers this adds.

| Method | Effect |
|---|---|
| `setItems(items)` | Replace the collection. Selection / cursor keep any key still present; vanished keys are deselected silently and held pending (see [View state](#view-state)). |
| `appendItems(items)` | Add to the end. Scroll, selection and cursor untouched; no reflow animation. |
| `updateItem(key, item)` | Replace one item. A visible cell re-renders in place; an offscreen one updates when scrolled in. |
| `updateItems(entries)` | Replace many items at once — the batched form of `updateItem`. See [Batched updates](#batched-updates). |
| `refreshItem(key)` | Re-render one cell **without** changing `items`. See [Refreshing a cell](#refreshing-a-cell). |
| `removeItems(keys)` | Remove items. Removed keys drop out of selection / cursor silently and are held pending. |
| `clearItems()` | Drop everything. Resets selection / cursor and emits one empty `list-select`; the keys are held pending, so re-adding them restores the selection. |

Selection, cursor, keyboard nav, search, filtering, `count`, `renderedCount`,
`renderedKeys()` and `visibleKeys()` behave identically to element mode — all
key-based. Data-mode events carry the data value as `detail.item` and
`detail.element` is `undefined`; read `detail.selectedKeys` for selection.
`selectedItems` (an Element set) is element-mode only.

Duplicate keys are warned about once; the first occurrence wins for key-based
operations.

#### Batched updates

`updateItems(entries)` applies many replacements with **one** array copy and
**one** source rebuild:

```typescript
grid.updateItems([
  { key: 'a', item: { ...fileA, name: 'Renamed' } },
  { key: 'b', item: { ...fileB, thumb: newThumb } },
]);

// A Map works too:
grid.updateItems(new Map([['a', newA], ['b', newB]]));
```

It has the same semantics as the equivalent run of `updateItem` calls: unknown
keys are ignored, selection / cursor / scroll are untouched, and an entry whose
`item` is the identical object already at that key is skipped. If nothing
changes, `items` keeps its identity and nothing is emitted.

**Use `updateItems` rather than a loop of `updateItem`s** when you have more
than one row to change. A loop pays one array copy per call, so changing n rows
costs n copies; the batched form pays one. On a 20k-item collection, replacing
500 rows measured ~22 ms as a loop versus ~0.7 ms as one batch (happy-dom).

#### Refreshing a cell

`updateItem(key, item)` with the **same object** that is already at `key` is a
no-op — the array is not copied and nothing is emitted. That is the right
behaviour when you only want to push the *data* through.

If instead you want to redraw a cell whose data is unchanged — because the
adapter renders something that lives outside the item, such as a thumbnail that
just finished loading — use `refreshItem(key)`:

```typescript
grid.refreshItem('a');   // re-renders the cell for 'a'; `items` is untouched
```

The adapter's `render` is called again for that cell, so it picks up the new
state. The `items` array keeps its identity, so nothing is copied and the
collection is not rebuilt.

---

## Grouping

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

```ts
grid.groupBy = 'kind';                       // data mode: item property · element mode: data-kind attribute
grid.groupBy = item => item.locked ? 'Locked' : 'Open';   // or a function (Element in element mode)
grid.groupLabel = (key, items) => `${key} (${items.length})`;
grid.crossGroupSelection = false;            // default
grid.collapseAllGroups();
```

| Member | Notes |
|---|---|
| `groupBy` / `group-by` | `string` property (data mode) or `data-<name>` attribute (element mode), or a function. `null` ungroups. |
| `groupLabel` | `(groupKey, items) => string`. Default: the key, or `(none)` for the empty key. |
| `cross-group-selection` | Default `false`: selecting in one group clears the others, and Shift-range, Ctrl+A and marquee stay inside one group. Programmatic `selectKeys` / `addSelectedKeys` are never clamped. |
| `group-header-height` / `group-header-width` | Header size in px (`grid` / `column` height, `row` width). Defaults 28 / 120. |
| `groups` | Read-only `{ key, label, count, collapsed }[]` in display order. |
| `toggleGroup(key)`, `setGroupCollapsed(key, bool)`, `collapseAllGroups()`, `expandAllGroups()` | Collapse state. |

- Groups appear in first-encounter order. Filters (`filterPredicate`, `itemFilterPredicate`, incremental filter) run first, so an emptied group loses its header and counts follow the filter.
- **Collapsed groups** leave the effective order: not navigable, not rendered, not in select-all, range, marquee or drag-out. Their selection state is kept. A collapsed key is not auto-expanded by `focusKey()`.
- Changing `groupBy` (from any path) clears the collapse state. Saved collapse state from `setViewState()` that hasn't matched a group yet is kept.
- **Layout:** in `grid` / `column` a header spans the full width and its items restart at column 0 beneath it. In `row` orientation the header is an inline cell of `group-header-width`.
- **Keyboard:** Left/Right step through items, crossing groups. Up/Down keep the column, hop across headers and clamp on a short last row. Headers are never focused; collapsing is by click or the API.
- Events: `list-group-toggle` `{ groupKey, collapsed }`, `list-group-change` `{ groupBy }`.
- Headers are `ixfx-list-group-header` elements (`part="group-header"`), themeable through `--list-group-header-text` / `--list-group-header-border`.

Differences from data-grid: group state is reset on every `groupBy` change, the empty key is labelled `(none)`, headers are skipped by arrow keys, and the collapse API and events are exposed.

---

## View state

Snapshot and restore how the grid is showing its data, separately from the
data. The contract is shared with the other list components; see
[`docs/infra-view-state.md`](./infra-view-state.md).

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

bindViewState(grid, {
  load: () => JSON.parse(localStorage.getItem(`photos-grid`) ?? `null`),
  save: s => localStorage.setItem(`photos-grid`, JSON.stringify(s)),
});
grid.items = await fetchPhotos(); // pending state applies as items arrive
```

`kind`: `grid-list`. Type: `GridListViewState`.

| Field | Shape | Meaning |
|---|---|---|
| `selected` | `string[]` | Selected item keys. |
| `expanded` | `Record<string, boolean>` | Group key → open. Groups default open, so only collapsed groups (`false`) are recorded. |
| `focus` | `string` | Keyboard-cursor key. Recorded only while the cursor was last moved by keyboard. |
| `scroll` | `{ top, left?, anchor? }` | `anchor` is the first item of the first visible line plus the px offset into that line, along the main axis (`left` in `row` orientation, `top` otherwise). |

Members: `getViewState(options?)`, `setViewState(state)`,
`clearPendingViewState()`, and the debounced `view-state-change` event.

Grid-specific behaviour:

- Works the same in element mode (light-DOM children with `data-key`) and data
  mode (`items` + `itemAdapter`). Keyless children have auto-assigned
  positional keys, which never appear in view state.
- A key counts as present when its item is in the effective order: an item
  that is filtered out, or inside a collapsed group, keeps its saved selection
  pending until it shows. Restoring `expanded` and `selected` together re-opens
  groups first, so a saved selection inside a saved-open group resolves.
- A collapsed group whose items all leave (data reset, filter) keeps its
  collapsed state pending and is collapsed again when it comes back.
  Restoring collapse state does not fire `list-group-toggle`.
- Items that leave the data are deselected **without** a `list-select`; their
  keys go pending and are re-selected (with a `list-select`) if they return.
- A restored cursor puts the list in keyboard input mode, so it is shown and
  recorded like a keyboard-moved cursor.
- Scroll restore waits until the anchor item is present and the viewport is
  measured, then until the content is long enough. It is cancelled by the
  user's own wheel, touch, pointer or navigation key. The anchor is re-laid out
  with the current geometry, so a different column count still lands on the
  same item's line.

## Virtualisation

Only the cells in (or near) the viewport are in the DOM — in both element and
data mode.

```typescript
grid.count;             // total items (after filtering)
grid.renderedCount;     // cells currently in the shadow DOM
grid.renderedKeys();    // keys of the rendered window — viewport + overscan (prefetch set)
grid.visibleKeys();     // keys strictly intersecting the viewport (no overscan)
```

`grid-list` handles hundreds of thousands of items in every orientation. Keys of
keyless light-DOM items (auto-assigned internally) are omitted from
`renderedKeys()` / `visibleKeys()` / `selectedKeys`.

### Accessibility

Cells are `role="option"` with `aria-setsize` (the filtered, non-collapsed count)
and `aria-posinset`, so assistive technology sees the true list size even though
only a window of cells is in the DOM. Group headers are `role="presentation"`.
A container resize that changes the column count keeps the centre item in view.

### Hidden containers

`refreshLayout()` re-reads the viewport after an ancestor's visibility or size
changed — e.g. a dock tab being re-activated. It is safe to call while hidden
(a zero-sized measurement never replaces the last usable geometry) and forces a
repaint of the virtual window even when the size is unchanged. Scroll position,
zoom anchoring and selection survive a hide/show cycle. `remeasure()` is an
alias.

---

## Scroll fade & insertion animation

The scrollable edge is fade-masked whenever there's more content that way — a
zero-JS `scroll-timeline` mask (`scroll-fade-y` for `grid` / `column`,
`scroll-fade-x` for `row`). See `docs/infra-theming.md` → *Scroll Fade*; tune the
reach with `--scroll-fade-width` (default `30px`).

When the child list changes **mid-list** (not a first populate or a wholesale
`replaceChildren`), the cells slide to their new position rather than snapping —
so an inserted item's neighbours make room and a removed item's gap closes — and
a freshly inserted cell also fades in. The transition is confined to a short
window after the mutation, so it never fires during scroll virtualisation, and
it's suppressed under `prefers-reduced-motion: reduce`. Duration:
`--grid-list-item-move-duration` (default `200ms`).

---

## Performance

**Any change to `grid-list.ts`, `grid-list-source.ts` or `grid-list-layout.ts`
that touches `render`, the per-cell template, the item source, scrolling,
cursor movement or item insertion should be checked with `pnpm bench:grid-list`.**
A per-frame path that quietly becomes O(items) is easy to introduce — see the
list at the end of this section for the ones that have bitten before.

`scripts/bench/grid-list.ts` drives `demo/grid-list.html` in an isolated
headless Chrome (its own temp profile; set `CHROME_PATH` if Chrome isn't in a
standard location). It needs the dev server running (`pnpm start`). It mounts
its own full-window list in **data mode** (adapter + `items`, default 5k and 50k
items) and **element mode** (light-DOM children, default 2k and 10k), and
reports main-thread ms from a timeline trace:

- `scroll` — script + render per frame at 40 px/frame (wheel / trackpad).
- `jump` — the same at 1200 px/frame (scrollbar drag / fling: the whole window
  is replaced every frame).
- `key arrow` / `key page` / `key jump` — script + render per key press for
  Arrow keys, PageUp/PageDown, and End/Home (cursor crosses the whole list).
- `append1`, `append100`, `insertMid`, `removeMid` — script + render per dynamic
  change (data mode: `appendItems` / `items` / `removeItems`; element mode:
  light-DOM `append` / `insertBefore` / `remove`). Run with
  `prefers-reduced-motion` so the 200 ms slide animation isn't measured.

Workflow — record a baseline on the unchanged code, make the change, compare:

```sh
pnpm bench:grid-list --out /tmp/grid-list-base.json      # before
pnpm bench:grid-list --compare /tmp/grid-list-base.json  # after
```

`--compare` prints each metric's % change and lists anything over
`--threshold` (default 50%, and never changes under 1 ms — run-to-run noise is
a few %). Add `--fail-on-regression` to exit non-zero. `--data-items 5000,100000`
and `--element-items 2000,20000` change the sizes. Baselines are
machine-specific, so keep them local rather than committing them. The dev
server runs Lit in dev mode, so absolute numbers are higher than a production
build — compare runs against each other, not against a budget.

Reference numbers (M-series Mac, dev mode; all flat in item count except
inserts): a smooth-scroll frame ~2–3 ms script + ~2.5 ms render; a jump-scroll
frame ~5 ms script (data) / ~9–16 ms (element) + ~7 ms render; an Arrow / Page
key ~2–3 ms + ~3 ms; End / Home ~6 ms (data) / ~9–13 ms (element) + ~7 ms.
Inserting is O(items): one `appendItems` costs ~5 ms at 5k items and ~21 ms at
50k (the source and search index are rebuilt, and `items` is copied); the
element-mode equivalents are ~8 ms at 2k and ~16 ms at 10k.

### 100k items

Reference at 100k items, Chrome (`pnpm bench:grid-list --data-items 100000 --element-items 100000`; now also reports `firstRenderMs`,
`heapMB`, and `selectAllMs` / `clickMs` / `updateItemMs` / `updateItems100Ms` / `replaceMs`; `--classes scroll,keys,inserts,level` picks
what to run):

| | data mode before → after | element mode before → after |
|---|---|---|
| first render | 74 → 21–41 ms | 331 → 208 ms |
| retained heap | 26 → 11 MB | 22.5 → 7.3 MB |
| `selectAll()` | 30 → 32 ms | ~90 s → 52 ms |
| `updateItem` / `updateItems(100)` / replace `items` | 29 / 29 / 35 → 15 / 14 / 16 ms | n/a |
| insert / append / remove one | 24–26 → 7.5–12 ms | ~100 → ~45 ms |
| scroll / jump / arrow frame | unchanged (~2.5 / ~5.8 / ~5 ms) | unchanged |

What changed:

- **The search index is built when search opens**, not on every item change. It was a `{ key, label }` and a fuzzy-index entry per
  item, rebuilt (and kept) on every mutation even if nobody ever searched; it is now marked stale while search is idle, rebuilt on open,
  and released on close. (This is in the shared `ListSearchController`, so the other lists get it too.)
- **Element mode resolves keys through the raw-index map** instead of scanning every element's `data-key`: `selectedItems`, and so every
  selection change, was O(selected × items).
- **`willUpdate` only reconciles removed keys when something is keyed by them** (a selection, the cursor, a refreshed cell), instead of
  building two key arrays and a 100k-entry `Set` on every items change.
- **Element mode only writes `draggable` where it differs**, and clears stale `data-tickled` / `data-selected` markers by selector
  instead of visiting every item.

Still O(items): replacing or mutating `items` rebuilds the source (key map, effective order) at ~7–16 ms per 100k; element mode re-reads
the whole light DOM (~45 ms at 100k) on a child change; and element-mode scroll / jump / End-Home frames cost more than data mode (8 / 14 / 45 ms
vs 2.5 / 5.8 / 7 ms) because the browser re-resolves slots across 100k light-DOM children — prefer data mode past a few tens of thousands of items.

### Mutation API

`src/grid-list/grid-list.perf.test.ts` guards the data-mode mutation API with
**work counters** — how many times the adapter's `key` is called per mutation.
That number must not scale with the item count. Run it with:

```sh
pnpm test:perf            # all perf suites, verbose
PERF_REPORT=1 pnpm vitest run src/grid-list/grid-list.perf.test.ts
```

The mutation paths keep a key → raw index map, so a lookup is O(1) rather than
an O(n) scan of the array:

- `updateItem(key, item)` — one lookup and one array copy. Passing the
  identical object is a no-op (no copy, no emit).
- `updateItems(entries)` — many replacements, one copy, one rebuild.
- `appendItems(items)` — the appended items are added to the map; the existing
  ones are not re-scanned.

Things that keep the per-frame paths flat, and that the benchmark guards:

- **Cell recycling.** Cells are keyed by a stable cell id, not the item key, so
  a cell scrolled out of the window is handed to an item scrolling in rather
  than destroyed and recreated. (Item-keyed `repeat` gets steadily slower in
  Chrome when every key in the window is new — a scrollbar drag or fling.) A
  recycled cell carries the `recycled` class for one render, which disables its
  transitions so it never animates from the previous item's state or position.
- **Per-cell slots (element mode).** Each cell has a fixed
  `<slot name="gl-cell-<id>">`; the item it shows gets a matching `slot`
  attribute, and items outside the window have none. Renaming slots instead
  makes the browser re-match every light-DOM child.
- **The light DOM is only re-read when it changes** (child list, or an item's
  `hidden` / `data-key` / `data-value`), not on every scroll / hover / cursor
  update; `data-tickled` / `data-selected` are updated only on the items whose
  state changed.

---

## CSS parts

| Part | Element |
|---|---|
| `viewport` | The scroll container |
| `item` | A cell. Also carries the state tokens `selected` / `tickled`, e.g. `::part(item selected)` |
| `content` | The rendered content wrapper (data mode) |
| `thumb` | The square holding the slotted content (element mode) |
| `caption` | The caption element (absent for `caption-style="hidden"`) |
| `icon` | The per-item icon wrapper (data mode, when the adapter's `icon` returns something) |
| `badge` | The per-item badge wrapper (data mode, when the adapter's `badge` returns something) |

Host CSS custom properties: `--grid-list-item-bg`, `--grid-list-radius`,
`--grid-list-gap`, `--grid-list-item-move-duration` (insertion animation,
default `200ms`), `--scroll-fade-width` (edge fade reach, default `30px`),
`--grid-list-icon-size` / `--grid-list-icon-gap` / `--grid-list-badge-gap`
(per-item appearance, data mode), plus the shared `--item-bg-*` / `--accent`
theme tokens.

### Thumbnail well (Finder-style selection)

The `thumb` region — the square behind the slotted content — has its own set of
background variables, so you can give a selected item a *tinted well* with the
**caption** still taking the accent colouring (the way Finder's icon view
highlights). All are unset by default, so nothing changes until you opt in.

| Variable | Applies when | Default fallback |
|---|---|---|
| `--grid-list-thumb-bg` | always | `transparent` (box modes) / `--grid-list-item-bg` (`separate`) |
| `--grid-list-thumb-bg-tickled` | under the cursor | `--item-bg-tickled` |
| `--grid-list-thumb-bg-selected` | cell selected | `--grid-list-thumb-bg` |
| `--grid-list-thumb-bg-selected-tickled` | selected + under the cursor | `--item-bg-selected-tickled` |
| `--grid-list-thumb-selection-wash` | box-mode selection overlay colour | `--accent` |
| `--grid-list-thumb-selection-wash-opacity` | box-mode selection overlay strength | `0.18` (set `0` to drop it) |

```css
/* Finder-style: caption goes accent, well goes a step lighter than the surface */
ixfx-grid-list[caption-style="separate"] {
  --grid-list-thumb-bg-selected: color-mix(in oklab, var(--surface-3), white 12%);
}
/* box modes (under / overlaid / hidden): swap the accent wash for the tint */
ixfx-grid-list {
  --grid-list-thumb-selection-wash-opacity: 0;
  --grid-list-thumb-bg-selected: color-mix(in oklab, var(--surface-3), white 12%);
}
```

### Scrollbar

The scroll container maps three variables straight onto the standard scrollbar
properties (both orientations):

| Variable | Default | Maps to |
|---|---|---|
| `--grid-list-scrollbar-width` | `auto` | `scrollbar-width` — `auto` \| `thin` \| `none` (hide it) |
| `--grid-list-scrollbar-gutter` | `auto` | `scrollbar-gutter` — `auto` \| `stable` \| `stable both-edges` |
| `--grid-list-scrollbar-color` | `auto` | `scrollbar-color` — `auto` or a `thumb track` colour pair |

```css
ixfx-grid-list {
  --grid-list-scrollbar-width: none;               /* suppress entirely */
  /* or: --grid-list-scrollbar-width: thin;
         --grid-list-scrollbar-color: var(--accent) transparent; */
}
```

For finer control, style `::part(viewport)` directly (including
`::part(viewport)::-webkit-scrollbar` in Blink/WebKit).

---

## Choosing a list component


**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).

- **Large lists** — prefer `ixfx-grid-list` with `orientation="column"` over
  `ixfx-vertical-list`. `vertical-list` renders every child; `grid-list` is
  windowed.
- **Small, declarative, richly-slotted lists** — `ixfx-vertical-list` stays the
  simpler choice.
- **Horizontal virtualised strip** — `ixfx-grid-list` with `orientation="row"`.
- **Tabular data with columns / sort / grouping / inline edit** —
  `ixfx-data-grid`.
