# `ixfx-data-grid`

A virtualised data grid with sortable/resizable/reorderable columns, single/multi selection, grouping, and inline cell editing. Handles 200+ rows with windowed rendering and keyboard navigation.

---

## Quick start

```html
<ixfx-data-grid id="grid" style="height:400px"></ixfx-data-grid>

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

  const grid = document.querySelector('#grid');
  grid.columns = [
    { key: 'name', label: 'Name', width: 160 },
    { key: 'age', label: 'Age', width: 70, align: 'right' },
    { key: 'score', label: 'Score', width: 90, align: 'right' },
  ];
  grid.rows = [
    { key: 'r0', name: 'Ada', age: 30, score: 9.123 },
    { key: 'r1', name: 'Bob', age: 25, score: 4 },
  ];
</script>
```

Import via bundle: `import '@ixfx/components';` or per-component `import '@ixfx/components/data-grid';`.

---

## Columns

```ts
type DataGridColumn = {
  key: string;
  label: string;
  width?: number; minWidth?: number; maxWidth?: number;
  visible?: boolean;
  sortable?: boolean; sortFn?: (a,b)=>number;
  resizable?: boolean; reorderable?: boolean;
  align?: 'left'|'center'|'right'; // default left, applied as justify-content + tabular-nums for numbers
  renderer?: (row, col, rowIndex) => unknown; // Lit template or string
  selectable?: boolean;
  groupable?: boolean;
  editable?: boolean;
  dataType?: 'text'|'number'|'boolean'|'custom'; // default 'text'. Controls sorting and auto-editor.
  editor?: 'auto'|'select' | DataGridEditorFactory; // 'auto' infers from dataType
  editorPopup?: boolean;                // render the editor in an anchored popup (see "Rich editor popup")
  editTrigger?: 'default'|'click';      // 'click' = single click opens (user mode)
  editorOptions?: readonly (string|{value,label})[];
  formatter?: (value, row, col) => unknown;
  button?: false | true | { icon?: string }; // default false. true or {icon} shows a button in the header on hover.
};
```

* `width` defaults to `150`. Drag the handle between headers to resize; double-click handle to auto-size to content. Drag the grip handle (shared `dimpled` spot handle — see [docs/infra-handle.md](./infra-handle.md)) to reorder.
* `align` controls cell content justification. Numeric columns should use `right` (or `center` for Age) – cells use `font-variant-numeric: tabular-nums` so decimal points align when paired with a fixed formatter.
* `renderer` overrides default `String(value)` display. Use `html` from `lit`.

### Per-row icon, text colour and badges (nominated columns)

A grid has no per-item schema, so each appearance feature is opted into by
nominating the **column** that carries it. The value itself is read off the
**row**, not off the nominated column's own value — so one row can tint just
one of its cells.

| Property | Attribute | Effect |
|---|---|---|
| `textColorColumn` | `text-color-column` | The cell for this column takes the row's `textColor`. |
| `iconColumn` | `icon-column` | The cell for this column renders the row's `icon` first, tinted by `iconColor`. |
| `badgeColumn` | `badge-column` | The cell for this column renders the row's `badge`, right-justified after the value. |

```ts
import { html } from 'lit';
import { tagChip, stackedTagChips } from './my-tags.js';   // your own SVGs

grid.textColorColumn = 'status';
grid.iconColumn = 'avatar';
grid.badgeColumn = 'status';

grid.rows = [
  { status: 'Healthy',  avatar: avatarUrl, textColor: 'seagreen', icon: ring(), iconColor: 'seagreen' },
  { status: 'Degraded', avatar: avatarUrl, textColor: 'goldenrod', badge: tagChip('yellow') },
  { status: 'Failed',   avatar: avatarUrl, textColor: 'crimson',
    badge: stackedTagChips(['red', 'orange']) },
];
```

All three are additive — `col.renderer` / `col.formatter` still own the
cell's value; this only decorates it, and cells being edited render their
editor untouched. `undefined`, `null`, `''` and `false` all count as "not
supplied", so a row can simply omit the field.

`textColor` is applied inline, so it also wins over the selected row's text
colour — pick something legible against both, or leave it off and let
`zebraStripes` / selection do their thing.

Note that a right-justified badge takes space from the cell's own value, which
is clipped rather than ellipsised while the badge is present. Nominate a
column with room to spare, or a dedicated tag column.

CSS: `--data-grid-cell-icon-size`, `--data-grid-cell-icon-gap`,
`--data-grid-badge-gap`. Parts: `part="icon"`, `part="badge"`.

---

## Rows & keys

```ts
grid.rows = [{ key: 'r0', ... }, ...];
grid.getRowKey = (row, i) => row.key ?? row.id ?? String(i);
```

Reassign `rows` to update. Sorting is derived from `sortState`.

The sorted / filtered / grouped row model is only re-derived when one of its
inputs is **reassigned** — `rows`, `sortState`, `columns`, `filterPredicate`,
`groupBy`, `groupLabel`, `getRowKey` (or a group is collapsed). Scroll, hover,
selection and edit updates skip it, so they cost O(visible rows), not O(rows).
Mutating a row object in place and calling `requestUpdate()` re-renders the
cell but does not re-filter, re-group or re-sort — reassign `rows` for that.

When the row set changes without a wholesale replace — rows spliced in, rows
filtered out — the new rows fade in and, for ~0.3s afterwards, every row slides
to its new position instead of snapping (so an inserted row's neighbours make
room and a removed row's gap closes). Skipped under `prefers-reduced-motion:
reduce`; timing is `--data-grid-row-move-duration` (default `200ms`).

### Streaming appends — `appendRows()`

Reassigning `rows` re-runs `_applySort([...rows])` + `_rebuildFlat()` every
time — O(n log n) per batch, quadratic over a full load. When feeding the grid
from a stream (paged fetch, incremental scan), use `appendRows()` instead:

```ts
for await (const batch of stream) {
  grid.appendRows(batch);
}
```

It still sets `rows` to a new array reference (reactivity preserved) but
**bypasses the `rows` setter's full rebuild** — the derived arrays are extended
over the appended slice only. When a sort is active the new rows show unsorted
for one frame, then a single coalesced re-sort runs. Scroll position, selection
and cursor are preserved across the append.

### Updating rows — `updateRows()` / `refreshRow()`

To change a few rows without reassigning `rows` (which re-sorts and rebuilds
everything), replace them by key:

```ts
grid.updateRows([{ key: 'a1', row: { ...row, badge: 'new' } }]); // or a Map<key, row>
grid.refreshRow('a1'); // row object mutated in place — just re-render it
```

`updateRows` patches the derived row model in place when each replacement keeps
the same key, sort position (the active comparator ties old and new), group and
`filterPredicate` result — the usual case for metadata arriving for a row.
Anything else (a re-keyed row, a changed sort value, ...) makes the whole batch
fall back to a normal `rows` reset, so the result is always correct. Unknown
keys and identical objects are ignored; selection, cursor and scroll are kept.
Batch many records into one call. `refreshRow` re-renders only if the row is in
the rendered window and does not re-sort or re-group.

### Scrolling: overscan, row recycling and the edge fade

- `overscan` (default `2`) is the number of rows rendered beyond the viewport
  on each side. `overscan-max` (default `0`, off) lets the window also run ahead
  in the direction of travel, up to that many rows, in proportion to scroll
  velocity; the lead is dropped ~150ms after scrolling stops. It only pays off
  when the main thread drops frames (the lead costs ~1.4ms render + ~0.7ms script
  per frame at 1500px/frame in headless Chrome), so enable it where flings
  outrun the window.
- Row elements are **recycled**: a row entering the window re-binds the element
  of one that left (slot-keyed `repeat`, see `data-grid-slots.ts`) instead of
  creating a new element and removing the old one. A row that stays in the
  window keeps its element. The host carries `[scrolling]` while scrolling, which
  switches row transitions off so a re-bound row doesn't animate from the
  previous row's look.
- `no-scroll-fade` (`noScrollFade`) removes the vertical edge-fade mask from
  `.viewport` — a masked scroller is re-rasterised as it scrolls.

### Performance

**Any change to `data-grid.ts` that touches `willUpdate`, `render`, the row
model (`_rebuildFlat`, sorting, grouping, filtering), scrolling or
`appendRows` should be checked with both tools below.** The per-frame paths are
easy to make O(rows) by accident: before these guards existed, one stray
rebuild-per-update made scrolling 50k grouped rows cost ~146 ms a frame.

There are two layers:

| | `data-grid.perf.test.ts` | `pnpm bench:data-grid` |
|---|---|---|
| Runs | with `pnpm test` (happy-dom) | against the dev server, in headless Chrome |
| Measures | grid JS work: call counts and 2k → 20k scaling | real main-thread ms per frame: script + style/layout/paint |
| Catches | O(n) / O(n²) creeping into scroll, hover, add/remove | real-browser slowdowns, including rendering cost |
| Use it | always (it's part of CI) | before / after any perf-sensitive change |

**Unit-level guards** — `data-grid.perf.test.ts` asserts that a scroll frame /
hover does work proportional to the visible window (flat from 2k to 20k rows,
including sorted / grouped / filtered), that a sub-row scroll doesn't
re-render, and that adding / removing rows scales at most linearly. They use
call counts and size ratios rather than absolute times, so they don't flake on
slow machines. `pnpm test:perf` prints the per-scenario timings.

**100k-row reference (happy-dom, JS only)** — scroll frame ≈ 0.4 ms, select ≈ 0.25 ms,
hover ≈ 0.25 ms (also right after an `appendRows`), `appendRows(500)` ≈ 1 ms ungrouped
(≈ 17 ms grouped: the grouped flat list is rebuilt), `rows` reassign ≈ 7–20 ms,
sort toggle ≈ 30 ms, ≈ 16–18 MB retained on top of the rows (flat entries ≈ 6 MB,
key index ≈ 3.5 MB). Hover must stay O(1): the tickled controller's `isEnabled`
hook exists so hovering never builds a per-row item array.

**Real-browser benchmark** — `scripts/bench/data-grid.ts` drives
`demo/data-grid.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`). For 1k / 50k rows, plain and grouped by `status`, it
reports:

- `scroll script` / `scroll render` — main-thread ms per frame at 40 px/frame
  (wheel / trackpad), from a timeline trace.
- `jump script` / `jump render` — the same at 1200 px/frame (scrollbar drag /
  fling: every row in the window is replaced each frame).
- `insert3Ms`, `removeOneMs`, `appendRows500Ms`, `selectMs` — median time from
  the call until Lit has rendered and style + layout are flushed.

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

```sh
pnpm bench:data-grid --out /tmp/grid-base.json      # before
pnpm bench:data-grid --compare /tmp/grid-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
~±25%). Add `--fail-on-regression` to exit non-zero. Other options: `--rows
1000,50000`, `--group-by status` (empty to skip grouped runs), `--url`.
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, 50k rows): a smooth-scroll frame is
~1.5 ms script + ~2 ms render; a jump frame ~6 ms + ~4.5 ms; add / remove one
row ~7 ms; select ~1 ms. All flat across row count and grouping, except
add / remove, which is linear in rows.

---

## Selection & interaction

| Property | Type | Default | Description |
|---|---|---|---|
| `selectionMode` / `selection-mode` | `'none'|'single'|'multiple'` | `'single'` | How many rows can be selected |
| `interactionMode` / `interaction-mode` | `'standard'|'implicit'|'checked'|'sticky'|'vscode'|'manual'` | `'standard'` | Gesture mapping (same as `ixfx-vertical-list`) |

See `ixfx-vertical-list` README for mode table. Data-grid adds checkbox column in `checked` mode.

### Programmatic selection & cursor

```ts
grid.selectedKeys;                 // ReadonlySet<string> of selected row keys
grid.selectedKeys = ['r3', 'r7'];  // replace (clamped to known rows, single-mode keeps the last)
grid.selectKeys(['r3', 'r7']);     // alias of the setter

grid.tickleRow('r7');              // move the row cursor + scroll it into view
grid.tickledKey;                   // row key under the cursor, or undefined
```

The setter fires `datagrid-select` `{ selectedKeys, previous }` (and `list-select`
`{ selectedKeys, previousKeys, previous }`, the name the other list components use)
only when the selection actually changes. A cancelable `list-select-intent` fires
before every selection gesture, and `partialKeys` marks partially selected rows
(`data-partial`, indeterminate checkbox in `checked` mode).
See [Selection intents, partial rows, unloaded keys](./user-selection-intents.md): `list-select-intent`, `partialKeys`, and keys that arrive later.

Selected rows that leave `rows` are deselected silently, and reselected if they
return. See [View state](#view-state). In `checked` mode the row checkbox toggles
the row.

---

## Native drag-out

Set `items-draggable` to make selectable rows draggable out of the grid. A
dragged row is one logical item and its preview renders identically to the
other list components. 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 }`, where `item` is the row value and
  `element` the `.row` div); `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 rows, a compact
  `N items` list with `+N more` for 6+; the row caption is the first visible
  column's formatted value), 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. Column-header reorder (pointer
  drag) is a different mechanism and is unaffected.

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 row or in the gap between two, and `items-reorderable` to let the user drag a rows to a new position. The gap is the top or bottom half of a row (a line between rows). `between` is refused while a sort column is active or rows are grouped (`reorderBlocked` is `'sorted'` / `'grouped'`); `on` drops still work. Column reordering (`DataGridColumn.reorderable`) is separate.

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

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

---

## Text overflow

```html
<ixfx-data-grid cell-overflow="pan-text"></ixfx-data-grid>
```

| `cellOverflow` / `cell-overflow` | Behaviour |
|---|---|
| `ellipsis` (default) | Cell text is CSS-truncated with an ellipsis. |
| `pan-text` | A cell's text swaps to an `ixfx-pan-text` (looping pan, revealing the full value) while its row is selected or under the tickle cursor (hover / keyboard cursor); otherwise it's ellipsised like normal. Only applies to plain (non-`renderer`) columns. |

---

## Zebra striping

```html
<ixfx-data-grid zebra-stripes></ixfx-data-grid>
```

`zebraStripes` / `zebra-stripes` (boolean, default `false`) tints every other
row towards the theme's text colour, which reads as lighter in dark themes
and darker in light themes. Selected / tickled rows keep their own
background regardless of striping.

`--data-grid-zebra-intensity` (default `6%`) is the `color-mix()` percentage
used for the tint — raise it for stronger contrast, lower it for a subtler
stripe:

```css
ixfx-data-grid { --data-grid-zebra-intensity: 12%; }
```

---

## Auto-sizing a column

Double-clicking a column's resize handle fits it to its contents instantly.
To do the same programmatically, with an animated width change:

```ts
grid.autoSizeColumn('name'); // -> boolean
```

Width is measured from the header label plus every row's *formatted* value
(via canvas `measureText`, clamped to `minWidth`/`maxWidth`), so it's accurate
for plain text columns. It returns `false` and does nothing for:

- an unknown column key,
- a column with `resizable: false`,
- a column with a `renderer` that gives no hint of its size — its rendered
  output (icons, badges, custom markup, etc.) can't be reliably measured from
  the raw value. Opt in with either:
  - `fixedExtraWidth: n` — pixels added to the measured text width (e.g. a
    thumbnail beside the text), or
  - `measure: (row, col) => px` — your own content-width measure per row.

`--data-grid-column-resize-duration` (default `180ms`) controls the
transition speed.

---

## Sorting

Click header to cycle `asc → desc → none`. Or set:

```ts
grid.sortState = { key: 'age', direction: 'asc' };
```

Events: `datagrid-sort` `{ sort, previous }`. Custom `sortFn` per column.

Sorting uses `dataType` to determine comparison strategy:
- `'number'`: numeric comparison
- `'boolean'`: false < true
- `'text'` (default) or `'custom'`: `String.localeCompare`

Override with `sortFn` on the column.

### Column header button

A clickable button appears in the column header on hover (pointer devices). It fires `datagrid-header-button-click` with `{ key, column, icon, clientX, clientY, anchorElement }`:

```ts
grid.addEventListener('datagrid-header-button-click', e => {
  const { key, column, icon, clientX, clientY, anchorElement } = e.detail;
  showPopupMenu(clientX, clientY); // or use anchorElement for CSS anchor positioning
});
```

- `button: false` (default) — no button shown
- `button: true` — show button using grid's default icon
- `button: { icon: 'settings' }` — show button with custom icon (any Lucide icon name)

Grid-level default icon is `columnButtonIcon` (`ellipsis`). Set the grid's `column-button-icon` attribute to change it globally.

The `anchorElement` (the `<span class="col-button">`) can be used with the [CSS anchor positioning API](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_anchor_positioning) if the popup lives in the same shadow tree, or its bounding rect can be read for manual positioning.

Additionally, `datagrid-header-pointerup` fires on pointerup over the header label (the text, not the button), giving `{ key, column }` — call `preventDefault()` on it to suppress sorting.

---

## Grouping

```ts
grid.allowGrouping = true;
grid.groupBy = 'department'; // or (row)=>String(row.dept)
grid.groupLabel = (key, rows) => `${key} (${rows.length})`;
grid.groupableColumns = ['department','age']; // optional allowlist
```

Collapsible group headers (no background, just divider). Header bar `ixfx-menu-trigger` (gear) shows `Columns` check-items and `Group by` radio group – uses CSS anchor positioning with `position-try-fallbacks` so it never goes off-screen (flips `block`/`inline`, max-height `min(60vh,400px)` scrolls).

Cross-group selection:

```html
<ixfx-data-grid cross-group-selection></ixfx-data-grid>
```

* `cross-group-selection` (boolean, default `false` – matches `ixfx-grouped-item-lister`). When `false`, selecting in one group clears other groups; `Shift+click` range and `Ctrl+A` are clamped to the anchor's group. When `true`, selection spans groups. Logic lifted to `src/util/grouped-selection.ts`.

Events: `datagrid-group-change` `{ groupBy }`.

---

## Editing

### Editability modes

| `editability` | Behaviour |
|---|---|
| `disabled` | No editing |
| `manual` | Only via `startEdit` / `startRowEdit` |
| `user` (default) | Slow double-click (two clicks 150–700ms apart on same cell) opens editor; `Enter` on a tickled row opens `lastClickedCell` if editable else first editable |
| `immediate` | Editable cells render as editors by default |

```html
<ixfx-data-grid editability="user"></ixfx-data-grid>
```

```ts
grid.editable = (row, col) => col.key==='name' || col.key==='department';
// or per-column editable:true
```

### Editors

* `editor:'auto'` (default) → inferred from `dataType`:
  - `'text'` → `<input type="text">`
  - `'number'` → `<input type="number">`
  - `'boolean'` → `<input type="checkbox">`
* `editor:'select'` + `editorOptions: ['A','B']` → `<select>`
* `editor: (ctx)=>html`...` ` custom factory with `{ row, column, rowIndex, colIndex, value, commit, cancel }`

Editors are seeded with the cell's current value (`curVal`). For `select`, the matching `editorOptions` entry is preselected.

### Rich editor popup

Any `editor` factory can render in a popup instead of in the cell. Set `editorPopup: true` on the column and the
grid shows the factory's template in a native popover (top layer, so the cell's `overflow` can't clip it) anchored
under the cell. The cell keeps showing its value via `renderer`/`formatter`. The editor is created only while the popup
is open and removed when it closes.

```ts
{ key: 'colour', label: 'Colour', editable: true,
  editorPopup: true, editTrigger: 'click',
  renderer: r => html`<span class="swatch" style="background:${r.colour}"></span>`,
  editor: ctx => html`<ixfx-colour-picker value=${ctx.value}
    @input=${e => ctx.update(e.currentTarget.value)}></ixfx-colour-picker>` }
```

* `editTrigger: 'click'` opens on a single click in `user` mode (default is the slow double-click). In `immediate`
  mode popup columns open on a click rather than rendering an always-on editor.
* Context is `{ row, column, rowIndex, colIndex, value, commit, update, cancel }`. `update(v)` records a pending value
  without closing (live controls); `commit(v)` writes, fires `datagrid-cell-edit` and closes; `cancel()` discards.
* Click outside commits the last `update`d value; `Escape` cancels. Keys typed in the popup never drive grid navigation,
  and the popup is excluded from native row drag.
* `part="editor-popup"` is exposed for styling.
* `commit(v)` from any custom editor (inline or popup) now writes the value to the row, like the built-in editors.

### Programmatic

```ts
grid.startEdit('r4','name'); // single cell
grid.startRowEdit('r4'); // all editable cells in row
grid.stopEdit();
```

### Keyboard while editing

* `Tab` / `Shift+Tab` – commit and move to next/prev editable cell in same row, focus follows.
* `Up` / `Down` – commit and move to same column in adjacent row if editable, also moves tickled cursor.
* `Enter` – commit.
* `Escape` – cancel (revert) when grid has focus.
* Focus leaving the component reverts editors (unless `immediate`), committing only via explicit `Tab`/`Enter`/`Down`.

Implementation: `updated` focuses the editor (`data-col` attribute), `_suppressBlurCommit` prevents double-commit on Tab navigation, `_onFocusOut` reverts.

---

## Formatting & alignment

Global or per-column formatters transform display value (not stored value):

```ts
type GlobalFormatter = (value, columnName, row) => unknown;
grid.globalFormatter = (v, col) => col==='score' ? Number(v).toFixed(2) : v;
grid.setColumnFormatter('score', 'fixed', { digits: 3 }); // built-ins
grid.setColumnFormatter('score', v => String(v)); // custom
grid.setColumnFormatter('score', null); // clear
```

Built-ins:

| Name | Options | Example |
|---|---|---|
| `fixed` | `{digits:2}` | `9.1 → 9.10` |
| `percentage` | `{digits:0}` | `0.75 → 75%` |
| `integer` | – | `9.6 → 10` |

Column `formatter?: (value,row,col)=>unknown` also supported. Formatted value is shown when no `renderer`; if `renderer` exists it receives raw row.

Demo: `Score` is random float `0–100` with 0–3 decimals, `align:'right'`, `font-variant-numeric: tabular-nums`, `fixed` 3 digits for decimal alignment. `Age` is `align:'center'` to demo middle alignment.

---

## Column visibility & menu

Gear menu (`ixfx-menu-trigger` placement `bottom-end`, `inset-area: block-end span-inline-end`) lists `Columns` (check-items) and `Group by` (radio). Toggle visibility via `col.visible=false` or menu. Event: `datagrid-column-visibility` `{key, visible}`.

Set `col.group` to a heading (e.g. the facet a column came from) and the menu
lists columns sharing that group in one submenu; ungrouped columns stay at the
top level.

`column-menu` attribute: `none` (default) hides the gear menu; `auto` opts in to
rendering it. `col.visible` + `datagrid-column-visibility` give full external
control, so a host can own the column-visibility UI.

Other events: `datagrid-column-reorder` `{from,to,columns}`, `datagrid-column-resize` `{key,width}`, `datagrid-cell-click` `{rowKey,colKey,rowIndex,colIndex}`, `datagrid-cell-edit` `{rowKey,colKey,oldValue,newValue}`.

---

## Keyboard navigation

Grid is focusable (`tabindex=0`). When not editing:

| Key | Action |
|---|---|
| `ArrowDown/Up` | Move tickled cursor, scroll into view. `standard`: selects the row under the cursor; with `Shift` extends the range from the anchor (`vscode`/`manual`: only with `Shift`) |
| `Home/End` | First/last data row |
| `Enter` | If `editability=user` and row has editable cell, open editor (prefers `lastClickedCell`); else select row |
| `Space` | Toggle selection |
| `Escape` | Clear selection (or cancel edit) |
| `Ctrl/Cmd+A` | Select all (clamped to anchor group if `!crossGroupSelection`) |

The cursor skips group header rows. Moving it scrolls synchronously, so the target row is rendered in the same update, and moving up onto the first row of a group reveals its header.

**Accessibility:** the grid is `role="grid"` with `aria-rowcount` / `aria-colcount`; header cells are `columnheader` (with `aria-sort`), rows carry `aria-rowindex` (absolute, so it stays correct while windowed) and `aria-selected`, and group rows have a `rowheader` with `aria-expanded`.

**Editing while scrolling:** the row being edited is pinned in the DOM even if scrolled out of the window, so its input keeps focus and the edit isn't lost. It is not listed in `renderedKeys()`.

---

## Incremental search

A built-in type-ahead popover with **navigate** (cursor + scroll to best match),
**select** (matching rows become the selection), and **filter** (non-matching
rows dropped from the flat list) modes. No default shortcut:

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

A row is matched against the displayed (formatted) text of one column: the
`search-column` attribute (`searchColumn` property) names it, defaulting to the
first visible column. Searching every column makes dates and sizes match
queries like `12`, which is rarely what Find is for. Set the `rowSearchText`
property, `(row) => string`, to match against something else, e.g. several
columns joined. `select` mode needs `selection-mode="multiple"` to hold more
than one row.

Matched characters in the search column are highlighted under the
`data-grid-search` key, coloured by `--search-highlight-bg` /
`--search-highlight-color` (default `--accent` / `--accent-text`). Matches
against a custom `rowSearchText` aren't highlighted, since they can't be
mapped onto a cell, and neither are cells drawn by a column `renderer`. `filterPredicate`
(a `(row) => boolean` property) filters rows directly. `search-modes` limits the
offered modes. Full model: [`docs/infra-incremental.md`](./infra-incremental.md).

---

## CSS variables & parts

| Variable | Default | Description |
|---|---|---|
| `--data-grid-row-height` | `28px` | Row height |
| `--data-grid-row-move-duration` | `200ms` | Insertion / removal animation duration |
| `--data-grid-header-height` | `32px` | Header height |
| `--data-grid-bg` | `var(--surface-3)` | Grid background |
| `--data-grid-header-bg` | `var(--surface-2)` | Header background |
| `--data-grid-border` | `var(--border)` | Outer/between border |
| `--data-grid-header-text` | `var(--surface-3-text)` | Header text |
| `--data-grid-cell-icon-size` | `1em` | Size of a per-row cell icon (`icon-column`) |
| `--data-grid-cell-icon-gap` | `6px` | Space between that icon and the cell value |
| `--data-grid-badge-gap` | `6px` | Space between the cell value and a right-justified per-row badge |
| `--data-grid-scrollbar-width` | `auto` | `scrollbar-width` of the scroller |
| `--data-grid-scrollbar-gutter` | `auto` | `scrollbar-gutter` of the scroller (`stable` keeps the scrollbar from overlapping rows) |
| `--data-grid-scrollbar-color` | `auto` | `scrollbar-color` of the scroller |

Inherits global theme (`--surface-*`, `--accent`, `--item-*`, `--space-*`, `--radius-*`, `--shadow-m`). Cells use `font-variant-numeric: tabular-nums`. Group rows are transparent with divider.

`::part` exports: `viewport` (the scrolling element), `icon` and `badge` — the wrappers the per-row appearance hooks
render (`icon-column` / `badge-column`). A press in the scrollbar strip (right edge
/ bottom edge of the viewport, at least 16px when the scrollbar is an overlay) never
starts a native row drag. Everything else (header/row/cell) is
still shadow-internal.

---

## Methods

| Method | Signature | Description |
|---|---|---|
| `setColumnFormatter` | `(key, preset\|fn\|null, opts?)` | Set built-in or custom formatter |
| `startEdit` | `(rowKey, colKey)` | Open single-cell editor |
| `startRowEdit` | `(rowKey)` | Open row editors |
| `stopEdit` | `()` | Cancel editors |
| `getVisibleRange` | `()=>{startRow,endRow,startCol,endCol}` | Virtual window |
| `appendRows` | `(rows)` | Add rows without a full re-sort/rebuild — for streaming |
| `updateRows` | `(entries)` | Replace rows by key (`{key,row}[]` or `Map`); patches the row model in place when nothing positional changed — see [Updating rows](#updating-rows--updaterows--refreshrow) |
| `refreshRow` | `(key)` | Re-render one row after mutating its object in place |
| `selectKeys` / `set selectedKeys` | `(keys)` | Replace the selection by row key |
| `tickleRow` | `(key)` | Move the row cursor and scroll it into view |
| `getViewState` / `setViewState` / `clearPendingViewState` | see [View state](#view-state) | Snapshot / restore selection, cursor, scroll, groups, columns, sort |
| `autoSizeColumn` | `(key)=>boolean` | Resize a column to fit its contents, animating the width. Returns `false` (no-op) for an unknown column, `resizable: false`, or a `renderer` column without `measure`/`fixedExtraWidth` — see [Auto-sizing a column](#auto-sizing-a-column). |

| Getter | Type | |
|---|---|---|
| `selectedKeys` | `ReadonlySet<string>` | Selected row keys |
| `tickledKey` | `string \| undefined` | Row key under the cursor |

### Viewport events

The grid dispatches `datagrid-viewport-change` with
`{ renderedKeys, visibleKeys }` whenever the rendered/visible window changes —
scroll, resize, or a change to `rows` / `sortState` / `columns` / `groupBy` /
`filterPredicate` / `rowHeight`. At most once per animation frame, and only
when the key sets actually differ from the last dispatch. Mirrors
`ixfx-grid-list`'s `grid-list-viewport-change`.

---

## View state

The grid implements the shared view-state API (`docs/infra-view-state.md`):
`getViewState()`, `setViewState()`, `clearPendingViewState()` and a debounced
`view-state-change` event. `bindViewState()` persists it in two lines:

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

bindViewState(grid, {
  load: () => JSON.parse(localStorage.getItem(`orders-grid`) ?? `null`),
  save: s => localStorage.setItem(`orders-grid`, JSON.stringify(s)),
});
grid.columns = defs;
for await (const batch of stream)
  grid.appendRows(batch); // saved selection / cursor / scroll apply as rows arrive
```

`kind: 'data-grid'`. Fields (all optional on `setViewState`; present fields
replace, absent ones are untouched):

| Field | Shape | |
|---|---|---|
| `selected` | `string[]` | Selected row keys (the checked set in `checked` mode) |
| `focus` | `string` | Row cursor key — recorded only after keyboard navigation |
| `scroll` | `{ top, left?, anchor?: { key, offset } }` | `anchor` is the first visible row's key; `left` is raw px |
| `expanded` | `Record<groupKey, boolean>` | Groups default open, so only collapsed groups (`false`) are recorded |
| `columns` | `Record<columnKey, { width?, visible?, order? }>` | `order` is a rank: lower is further left |
| `sort` | `{ key, direction } \| null` | `null` = unsorted |
| `groupBy` | `string \| null` | Only recorded when `allowGrouping` is on (the user can change it); a function `groupBy` is never recorded |

**Pending state.** Keys that aren't in the data stay pending and are applied
when a matching row, group or column appears, which covers restoring before
data, `rows` resets and rebuilds, and `appendRows()` streams. When a selected
row leaves `rows` it is deselected silently and its key goes pending. When it
comes back it is reselected and `datagrid-select` fires. Any explicit
selection change (`selectKeys`, click, key, `Esc`) drops pending selection.
Resolving pending state on `appendRows()` looks only at the appended slice.

**Columns.** Saved width and visibility for a column apply once, when the
column is first defined. After that the column definition is the source of
truth, so a host that later redefines the column wins. A column that is
removed from `columns` keeps its last width and visibility pending until it
returns. A saved `order` reorders the columns it names within the positions
they occupy. Columns it doesn't name keep their place. It is kept until every
column it names has appeared, so late columns still land in their saved
position. Dragging a header to reorder drops it. Applied layout goes onto
copies of the column objects, and `columns` is reassigned.

**Rows keyed by index.** With the default `getRowKey`, a row with neither
`key` nor `id` is keyed by its sorted index. Index keys change on every sort,
insert or rebuild, so these rows are never recorded in `selected`, `focus` or
the scroll anchor (`scroll.top` / `left` are still recorded). Supply a
`getRowKey` (or `key` / `id` fields) to make their state restorable. A
custom `getRowKey` is trusted to be stable.

Change events: `user` for selection, cursor moves, scrolling, sort clicks,
column resize / auto-size / reorder / visibility, group collapse and group-by
menu choices; `restore` for state applied from `setViewState()` or pending
state.

---

## Demo

`demo/data-grid.html` + `demo/data-grid.ts`: 200 rows, `Department` random, `Score` float, `Name`/`Department` editable (`user` mode, slow double-click; `Tab`/`Up`/`Down` navigation; `Enter` from tickled row). Controls: Selection/Interaction/Group by/Editability/`column-menu` + `Edit first row` (manual), a `Stream +5,000 rows` button (`appendRows`), and `selectKeys` / `tickleRow` buttons.


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

