# `ixfx-vertical-list`

A scrollable vertical list of items with selection, keyboard navigation, and incremental search. Items can be plain `<li>` elements declared in HTML or rich custom elements added programmatically. Large lists can be [virtualized](#virtualisation) so only the visible rows exist in the DOM.

---

## Contents

1. [Quick start](#quick-start)
2. [Item types](#item-types)
3. [Properties](#properties)
4. [Sticky mode](#sticky-mode)
5. [Custom checkbox](#custom-checkbox)
6. [Selection](#selection)
7. [Events](#events)
8. [Native drag-out](#native-drag-out)
9. [Keyboard navigation](#keyboard-navigation)
10. [Incremental search](#incremental-search)
11. [Drop targets](#drop-targets)
12. [Context menu](#context-menu)
13. [In-place rename](#in-place-rename)
14. [Virtualisation](#virtualisation)
15. [View state](#view-state)
16. [CSS variables](#css-variables)
17. [CSS parts](#css-parts)

---

## Quick start

### Declarative HTML items

```html
<ixfx-vertical-list id="my-list" selection-mode="single">
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
</ixfx-vertical-list>

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

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

### Programmatic items

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

const list = document.querySelector<VerticalListElement>('ixfx-vertical-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);
```

---

## Item types

### Plain `<li>` elements

The simplest item type. Styled directly via `::slotted(li)` CSS from the component's shadow DOM.

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

Searchable text is the element's `textContent`. Override with `data-search-label` for custom search terms:

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

### Custom shadow-DOM components

Any element with a `data-list-item` attribute is recognised as a list item. This enables rich card-style rows built with Lit or any other framework:

```html
<ixfx-vertical-list>
  <my-track-card data-list-item track-title="Bohemian Rhapsody" artist="Queen"></my-track-card>
</ixfx-vertical-list>
```

Because the component cannot reach inside a custom element's shadow root, you must expose searchable text via a `data-search-label` attribute on the host element. The recommended pattern is to set this in the custom element's `willUpdate` lifecycle:

```typescript
override willUpdate(changed: PropertyValues) {
  super.willUpdate(changed);
  if (changed.has('trackTitle') || changed.has('artist')) {
    this.setAttribute('data-search-label', `${this.trackTitle} ${this.artist}`);
  }
}
```

To reflect selection state inside the custom element's shadow DOM, target the `:host([data-selected])` CSS selector:

```css
:host([data-selected]) .title {
  color: var(--item-text-selected, #fff);
}
```

---

## Properties

| Property / Attribute | Type | Default | Description |
|---|---|---|---|
| `selectionMode` / `selection-mode` | `'none' \| 'single' \| 'multiple'` | `'single'` | Which items can be selected simultaneously |
| `interactionMode` / `interaction-mode` | `ListInteractionMode` | `'standard'` | How gestures map to selection changes (see table below) |
| `itemEffect` / `item-effect` | `'none' \| 'sweep'` | `'none'` | Entry / exit effect for `items` rows. See [Item effects](#item-effects) |
| `virtualize` / `virtualize` | `boolean` | `false` | Only render the viewport window (+ overscan) into the DOM; pool and recycle the rest. See [Virtualisation](#virtualisation) |
| `itemHeight` / `item-height` | `number` | `0` | Fixed row height in px. Required for `virtualize` — every row must be exactly this tall |
| `itemsDroppable` / `items-droppable` | `boolean` | `false` | Rows and empty space accept native drops. See [Drop targets](#drop-targets) |
| `dropPositions` / `drop-positions` | `'on' \| 'between' \| 'both'` | `'on'` | Which targets a drag can resolve to |
| `itemsReorderable` / `items-reorderable` | `boolean` | `false` | A drag that starts here and ends between its own rows is a `list-reorder`. Implies `items-draggable` |
| `editValidator` | `((value, key) => boolean) \| undefined` | `undefined` | Opts in to [in-place rename](#in-place-rename) and validates the typed text. Unset ⇒ rows are plain text |
| `canDrop` | `((item, dataTransfer) => boolean) \| undefined` | `undefined` | Refuse a drag before any event or highlight |
| `filterPredicate` | `((el: Element) => boolean) \| undefined` | `undefined` | External filter; only items returning `true` are shown |
| `checkboxRenderer` | `((checked: boolean) => unknown) \| CustomCheckboxOptions \| undefined` | `undefined` | Custom content for the checkbox in `checked` mode. See [Custom checkbox](#custom-checkbox) |
| `formatter` | `((item: unknown, index: number) => unknown) \| undefined` | `undefined` | Renders one `items` entry into its row. See [Adapter items](#adapter-items) |
| `keyProperty` / `key-property` | `string` | `''` | Property on each `items` entry used for stable identity |
| `icon` | `((item, index) => unknown) \| undefined` | `undefined` | Per-item icon, prepended to the row |
| `iconColor` | `((item, index) => string \| undefined) \| undefined` | `undefined` | CSS colour for that icon |
| `textColor` | `((item, index) => string \| undefined) \| undefined` | `undefined` | CSS colour for the row's text |
| `badge` | `((item, index) => unknown) \| undefined` | `undefined` | Finder-style badge, right-justified on the row |

Switching `interactionMode` always clears the current selection.

### Adapter items

Set `items` and the list builds one `<li>` per entry, resolving each row
through the function-valued properties above. This is the only mode the
per-item appearance hooks apply to — declarative and programmatic elements
already own their own markup.

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

list.keyProperty = 'name';
list.formatter = item => (item as File).name;
list.icon = item => fileIcon((item as File).ext);
list.iconColor = item => (item as File).tint;
list.textColor = item => (item as File).overdue ? 'crimson' : undefined;
list.badge = item => {
  const { tags } = item as File;
  return tags.length > 1 ? stackedTagChips(tags) : tagChip(tags[0]);
};
list.items = files;
```

- `icon` is prepended to the row in a fixed-size slot; `iconColor` sets that
  slot's `color`, so glyphs painting from `currentColor` are recoloured.
- `textColor` is applied to the row itself.
- `badge` is appended after the text; the row is already a flex row, so the
  badge self-justifies to the trailing edge.

Both colours are applied inline, so 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 hook can be made conditional
without touching `items`. Changing any of these rebuilds the rows.

All four hooks are skipped when `formatter` returns a full row element (an
`<li>`, a `[data-list-item]`, or a custom element) — that element owns its own
markup. See [Item types](#item-types).

The icon and badge land as `<span class="item-icon">` / `<span class="item-badge">`
in the row's light DOM. Their layout is applied as inline styles — a
`::slotted()` rule can't reach inside a slotted `<li>` — so override it with
`!important`, or (better) drive it from the CSS variables above:

```css
#list-look {
  --list-item-icon-size: 18px;
  --list-item-badge-gap: 12px;
}
```

Parts: none for these two; they are light-DOM elements you can style with your
own selectors.

### Item effects

`item-effect="sweep"` animates the rows of an adapter list (`items`) as a whole, with CSS animation:

- **Exit:** when `items` changes, the old rows continue off to the left, one after another.
- **Entrance:** once they have gone, the new rows come in from the right, one after another. The first population plays the entrance too.
- **Direction:** `item-effect-direction="backward"` mirrors it (enter from the left, leave to the right), for going back up a level. Set it before changing `items`. `ixfx-flat-list` does this itself: going deeper sweeps forward, going up sweeps backward.

```html
<ixfx-vertical-list item-effect="sweep"></ixfx-vertical-list>
```

Tune it with CSS variables on the list: `--ixfx-item-effect-duration` (default `260ms`), `--ixfx-item-effect-stagger` (delay added per row, default `30ms`; the step is capped at 16 rows) `--ixfx-item-effect-easing` (entrance, default `ease-out`) and `--ixfx-item-effect-exit-easing` (exit, default `ease-in`).

Notes:
- Leaving rows are still in the list until their exit finishes, so the new rows (and `selectKeys()` for them) appear after it. `await list.updateComplete` waits for the swap, not for the entrance.
- Only `items` rows are animated; declarative children and `addItem()` keep the existing collapse animation. It is ignored while `virtualize` is on.
- Nothing animates under `prefers-reduced-motion: reduce`.
- The rows carry `data-item-phase="in" | "out"` while animating.

### `interactionMode`

| Value | Behaviour |
|---|---|
| `'implicit'` | Click always replaces selection. No modifier support. |
| `'standard'` | Plain click replaces selection; Ctrl/Cmd+click toggles; Shift+click range-selects (multiple mode only); Cmd+A selects all |
| `'vscode'` | Like `standard` for clicks; Shift+Arrow extends the range from the keyboard anchor |
| `'checked'` | Checkbox column on the left of every row; only that column is clickable and it spans the full row height so a tall card can still be toggled with a single click on the left; Space toggles the focused row. Rows marked `not-checked` get no checkbox and can't be checked (see [Non-checkable rows](#non-checkable-rows)). See [Custom checkbox](#custom-checkbox) for styling |
| `'sticky'` | Every tap/click on a row toggles its selection, with no checkbox column — the whole row is the tap target. Implies multiple selection, so touchscreen users can build a multi-selection without modifier keys. Space toggles the focused row; Cmd/Ctrl+A selects all |
| `'manual'` | No automatic selection; drive state entirely via `select()` / `deselect()` / `clearSelection()` |

---

## Sticky mode

`sticky` is the touchscreen-friendly way to build a multi-selection: **every tap or click on a row toggles its selection state**, and — unlike `checked` — there is no checkbox column, so the whole row is the tap target.

On a touchscreen there is no keyboard, so `standard` mode's Ctrl/Cmd+click toggle is unavailable. Before `sticky`, multi-selecting on touch was only possible in `checked` mode (via the checkbox column). `sticky` provides the same toggle behaviour with a much larger hit area and no injected checkbox UI.

Like `checked`, `sticky` **implies multiple selection regardless of `selectionMode`**, so each tap accumulates into the selection rather than replacing it. Tapping a selected row deselects it.

```html
<ixfx-vertical-list interaction-mode="sticky">
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
</ixfx-vertical-list>
```

```typescript
const list = document.querySelector<VerticalListElement>('#my-list')!;
list.interactionMode = 'sticky';
```

### Behaviour

| Input | Result |
|---|---|
| Tap / click a row | Toggles the row in/out of the selection |
| Space (focused row) | Toggles the focused row |
| Enter (focused row) | Activates the row and replaces the selection (same as `checked`) |
| Cmd/Ctrl+A | Selects all visible items |

Toggled rows get the standard selection highlight via the `data-selected` attribute (the same `--item-bg-selected` / `--item-text-selected` variables used in every other mode). Rows marked `not-checked` are only skipped in `checked` mode — in `sticky` mode every row toggles.

---

## Custom checkbox

In `checked` mode every row gets a checkbox column on the left — except rows marked [`not-checked`](#non-checkable-rows), which get no checkbox and can't be checked. The column is always a **full-height click target** (the wrapper uses `align-self: stretch`), so a single click anywhere on the left side of a tall card toggles it — you never have to precisely hit a small checkbox. Clicks on the row body (the text or custom card content) do **not** toggle, and the cursor is `default` there so the affordance is clear.

By default the column contains a native `<input type="checkbox">`. The visible square is small, but the entire column (~20–24px wide, full row height) is clickable.

### Subtle style — `checkboxRenderer`

Set `checkboxRenderer` to a function that returns a Lit template, or pass an options object for additional control. The function receives the row's current `checked` state. This is what enables the *subtle* style: render an empty template when unchecked and a translucent mark when checked.

```typescript
import { html } from 'lit';
import type { VerticalListElement } from '@ixfx/components';

const list = document.querySelector<VerticalListElement>('#my-list')!;
list.interactionMode = 'checked';

// Nothing when unchecked; a translucent tick when checked
list.checkboxRenderer = (checked) => checked
  ? html`<svg viewBox="0 0 16 16" width="14" height="14"
        fill="none" stroke="currentColor" stroke-width="2"
        stroke-linecap="round" stroke-linejoin="round"
        style="opacity:0.5">
      <polyline points="3,8 7,12 13,4" />
    </svg>`
  : html``;
```

#### Using `CustomCheckboxOptions`

Pass an options object to also control the checkbox column's `margin` and `width`:

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

list.checkboxRenderer = {
  renderer: (checked) => checked
    ? html`<svg viewBox="0 0 16 16" width="14" height="14"
          fill="none" stroke="currentColor" stroke-width="2"
          stroke-linecap="round" stroke-linejoin="round"
          style="opacity:0.5">
        <polyline points="3,8 7,12 13,4" />
      </svg>`
    : html``,
  margin: `0 6px 0 0`,  // left margin for the checkbox column (default: `0`)
  width: `24px`,         // width of the checkbox column (default: `24px`)
} satisfies CustomCheckboxOptions;
```

| Option | Type | Default | Description |
|---|---|---|---|
| `renderer` | `(checked: boolean) => unknown` | — | Required. Returns the Lit template to render inside the checkbox cell |
| `margin` | `string` | `0` | CSS margin for the checkbox column (e.g. `"0 6px 0 0"`) |
| `width` | `string` | `24px` | Width of the checkbox column |

Because the wrapper still spans the full row height and owns the click handler, the empty unchecked area is just as clickable as the visible tick — even though there is no border, background, or other visual indicator of where the column is.

### Non-checkable rows (`not-checked`)

Sometimes a list needs rows that are informational rather than selectable — headers, separators, "new document" placeholders. Mark an item with the `not-checked` attribute to opt it out in `checked` mode:

```html
<ixfx-vertical-list interaction-mode="checked">
  <li not-checked>Recent files</li>
  <li>Document A</li>
  <li>Image 01.png</li>
</ixfx-vertical-list>
```

A `not-checked` row:

- shows **no checkbox column** (nothing is rendered on its left),
- can **not be selected, toggled, or range-selected** — click, Space, `select()`, `selectMany()`, and `Cmd/Ctrl+A` all skip it,
- is still **visible and navigable** — the cursor moves onto it, and it still fires `list-item-click` and `list-activate` (e.g. Enter).

Outside `checked` mode the attribute has no effect, so the same item remains fully selectable in other interaction modes.

The attribute works on both plain `<li>` items and `data-list-item` custom elements (on the custom element itself, before it is wrapped).

When adding items programmatically, pass `notChecked: true` to `addItem()` instead of setting the attribute yourself:

```typescript
list.addItem('Header', { notChecked: true });
list.addItem('Document A');

// Or set the attribute directly on an element
const header = document.createElement('li');
header.textContent = 'Header';
header.setAttribute('not-checked', '');
list.addItem(header);
```

### How it works under the hood

In `checked` mode each checkable row has a `<span class="ixfx-list-checkbox" role="checkbox" part="checkbox">` prepended as the first child:

- When `checkboxRenderer` is set, your template is rendered into the span (via lit's `render()`) and re-rendered on every state change.
- When `checkboxRenderer` is **not** set, the span contains a real `<input type="checkbox">` with `pointer-events: none` — the span owns the click so there is exactly one toggle per click.
- `aria-checked` and `data-checked` on the span reflect the current state.
- `align-self: stretch` makes the span fill the row's cross-axis, giving you the full-height click target.

The element is also exposed as the `checkbox` CSS part, so you can tune the wrapper from outside:

```css
ixfx-vertical-list::part(checkbox) {
  width: 32px;          /* a wider column */
  color: var(--accent); /* recolour your rendered content */
}
```

You can change `checkboxRenderer` at any time (e.g., swap the subtle SVG for an animated check); the wrapper element swaps in place and the renderer is re-applied.

---

## Selection

### Programmatic API

```typescript
// Replace selection with a single item
list.select(element);

// Replace selection with multiple items — requires selectionMode="multiple", throws otherwise
list.selectMany([elementA, elementB, elementC]);

// Remove one item from the selection
list.deselect(element);

// Clear entire selection
list.clearSelection();

// Select all visible items (only works when multiple selection is effective)
list.selectAll();
```

Press-and-drag selects every row the band intersects (automatic with
`selection-mode="multiple"` or a multi `interaction-mode`;
`disable-drag-select` opts out). See `docs-user/vertical-list.md`.

### Adding and removing items

```typescript
// Append a string (wrapped in <li>) or an Element
list.addItem('New item');
list.addItem(myElement);

// In checked mode, add a row that shows no checkbox and can't be checked
list.addItem('Header', { notChecked: true });

// Remove a specific element (returns a Promise that resolves once it's gone).
// A selected item is deselected silently; its key stays pending (see View state).
list.removeItem(element);
list.removeItems(list.selectedItems);

// Remove all items and clear selection
list.clearItems();
```

Items added mid-list — via `addItem`, a direct `appendChild`, or a framework
binding — collapse + fade in, and the rows below slide down to make room.
`removeItem` / `removeItems` play the reverse (collapse + fade out) and then
detach, so the gap closes smoothly. A bulk populate isn't animated, and
everything is skipped under `prefers-reduced-motion: reduce`. Tune the timing
with the `--ixfx-list-item-move-duration` custom property (default `200ms`).

### Reading the selection

```typescript
// Most recently selected item (primary selection)
const item = list.selectedItem;
if (item) console.log(item.textContent?.trim());

// Full selection set
for (const el of list.selectedItems) {
  console.log(el.textContent?.trim());
}

// Via event
list.addEventListener('list-select', ({ detail }) => {
  const { selected, previous } = detail;
  for (const el of selected) {
    console.log(el.textContent?.trim());
  }
});
```

### Key-based selection

`Element` references die the moment you rebuild the item set (re-fetch, external
re-sort, filter). Give each item a **`data-key`** (or `data-value`) and drive
selection by that stable string instead. The Element API keeps working
unchanged — the key API is additive.

```html
<ixfx-vertical-list selection-mode="multiple">
  <li data-key="a">Apple</li>
  <li data-key="b">Banana</li>
  <li data-key="c">Cherry</li>
</ixfx-vertical-list>
```

```typescript
list.selectKeys(['a', 'c']);          // replace selection; keys with no row yet apply when the row appears
list.addSelectedKeys(['b']);          // multi-select modes only
list.removeSelectedKeys(['a']);
list.selectedKeys;                    // ReadonlySet<string>, e.g. Set { 'b', 'c' }

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

// list-select carries keys too
list.addEventListener('list-select', ({ detail }) => {
  console.log([...detail.selectedKeys]);
});
```

Selection survives a data reload by itself: keys of selected items that
leave the list (`clearItems`, `removeItem`, a DOM removal, an adapter rebuild)
go pending and are re-selected when items with the same keys come back.

```typescript
list.clearItems();
list.setItems(await fetchRows());     // previously-selected keys re-select
```

The `data-key` requirement is documented, not enforced: items without a key
simply never appear in `selectedKeys` and can't be targeted by `selectKeys` /
`focusKey`.

### Filtering by state

Use `selectedFilter()` to iterate over items based on their selection or checked state. Pass `'selected'`, `'checked'`, or `'either'` to filter accordingly:

```typescript
// Iterate over all selected items (data-selected="true")
for (const el of list.selectedFilter('selected')) {
  console.log('selected:', el.textContent?.trim());
}

// Iterate over all checked items (data-checked="true", only meaningful in checked mode)
for (const el of list.selectedFilter('checked')) {
  console.log('checked:', el.textContent?.trim());
}

// Iterate over all selected OR checked items
for (const el of list.selectedFilter('either')) {
  console.log('selected or checked:', el.textContent?.trim());
}
```

This is a generator function, so it can be converted to an array with `[...list.selectedFilter('selected')]` if needed.

### Attribute hooks on items

The component reflects state onto list items as data attributes. Use these in CSS or to read state from JavaScript:

| Attribute | Set when |
|---|---|
| `data-tickled` | The keyboard/pointer cursor is on this item |
| `data-selected` | The item is in the current selection |
| `data-checked` | Set in `checked` mode; mirrors `data-selected` |

The `not-checked` attribute is user-set, not reflected: it opts a row out of `checked` mode (see [Non-checkable rows](#non-checkable-rows)).

---

## Events

All events **bubble** and are **composed** (they cross shadow-DOM boundaries).

| Event | Detail type | When fired |
|---|---|---|
| `list-select` | `ListSelectDetail` | Selection changes by any means |
| `list-select-intent` | `ListSelectIntentDetail` | Cancelable; a gesture is about to change the selection (see below) |
| `list-tickle` | `ListTickleDetail` | An item enters cursor focus (hover or keyboard navigation) |
| `list-activate` | `ListActivateDetail` | User explicitly activates an item: Enter key or double-click |
| `list-item-click` | `ListItemClickDetail` | Raw click or Enter on any item |
| `vertical-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 |

### Detail types

```typescript
type ListSelectDetail = {
  readonly selected: ReadonlySet<Element>;  // Current full selection
  readonly previous: ReadonlySet<Element>;  // Selection before this change
  readonly selectedKeys: ReadonlySet<string>;
  readonly previousKeys: ReadonlySet<string>;
};

type ListTickleDetail   = { readonly item: Element };
type ListActivateDetail = { readonly item: Element };
type ListItemClickDetail = { readonly item: Element };
```

### Caller-owned selection: `list-select-intent` and `partialKeys`

`list-select-intent` is fired before any gesture changes the selection (in every `interactionMode`, including `manual`); `preventDefault()` means "I'll apply it". `partialKeys` marks rows as partially selected (`data-partial`, indeterminate checkbox in `checked` mode). Both are shared across the list-like components.
See [Selection intents, partial rows, unloaded keys](./user-selection-intents.md): `list-select-intent`, `partialKeys`, and keys that arrive later.

### Usage example

```typescript
list.addEventListener('list-select', ({ detail }) => {
  const labels = [...detail.selected]
    .map(el => el.getAttribute('data-search-label') ?? el.textContent?.trim())
    .join(', ');
  console.log('selection:', labels);
});

list.addEventListener('list-tickle', ({ detail }) => {
  previewPane.show(detail.item);
});

list.addEventListener('list-activate', ({ detail }) => {
  router.navigate(detail.item.dataset.key);
});

list.addEventListener('list-item-click', ({ detail }) => {
  analytics.track('list-click', detail.item.dataset.key);
});
```

---

## 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"`.

---

## Keyboard navigation

The element must be focused (click it or tab to it) before keyboard navigation works. A visible focus ring appears on focus.

| Key | Action |
|---|---|
| `Arrow Down` | Move cursor to next visible item. In `standard` mode the item under the cursor becomes the selection (and the anchor), as it does for every cursor move below; `implicit` does the same; `vscode` leaves the selection alone |
| `Arrow Up` | Move cursor to previous visible item |
| `Home` / `End` | Move cursor to the first / last item (across the whole list, including pooled rows when virtualized) |
| `Page Down` / `Page Up` | Move cursor by one viewport of rows |
| `Enter` | Activate the cursor item — fires `list-item-click` then `list-activate`; selects the item (except in `manual` mode) |
| `Space` | Toggle selection on the cursor item |
| `Shift+Arrow` / `Shift+Home` / `Shift+End` / `Shift+Page` | Extend the range from the anchor (`standard`, `vscode`, `manual`; in `standard` only with `selectionMode="multiple"`) |
| `Ctrl/Cmd+A` | Select all visible items (when effective multiple selection is on) |
| `Ctrl/Cmd+F` | Open the incremental search overlay |
| `Escape` | Clear the current selection (or close the search overlay if open) |

### While the search overlay is open

| Key | Action |
|---|---|
| `Arrow Down / Up` | Move cursor through the filtered list |
| `Enter` | Activate the cursor item (or first visible item) and close search |
| `Escape` | Close search overlay |

---

## Incremental search

A built-in type-ahead popover with three modes — **navigate** (cursor jumps to the best match, ↑/↓ cycle), **select** (matches become the selection), **filter** (non-matches hidden). See [`docs/infra-incremental.md`](./infra-incremental.md) for the full model, conversions between modes, and the `search-modes` attribute.

There is **no default shortcut**. Open it by invoking one of the commands on `list.registry`:

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

### Adding the page-level highlight rule

The CSS Highlight API requires a `::highlight()` rule in the page stylesheet to make matches visible. Add this to your page:

```css
::highlight(vertical-list-search) {
  background: var(--accent);
  color: var(--accent-text, #fff);
}
```

Without this rule the filtering still works (non-matching items are hidden) but matched text inside `<li>` items will not be highlighted.

### Searchable text

| Item type | Default search text | Override |
|---|---|---|
| `<li>` | `textContent` | `data-search-label` attribute |
| `[data-list-item]` custom element | `data-search-label` attribute | — |

Custom elements must always set `data-search-label` since the component cannot read their shadow DOM content.

### External `filterPredicate`

Supply a custom filter function to hide items independently of the search overlay:

```typescript
// Show only items tagged as 'document'
list.filterPredicate = (el) => el.dataset.type === 'document';

// Remove the filter
list.filterPredicate = undefined;
```

---

## Drop targets

Set `items-droppable` to make rows — and the empty space around them — accept native drags, including OS drags carrying files (`dataTransfer.files`, `text/uri-list`, custom MIME types). By default (`drop-positions="on"`) a drag resolves to the row under it, or to empty space. `drop-positions="between"` / `"both"` also resolve to the gap between two rows, and `items-reorderable` lets the user drag rows to a new position: see [Drops and drag-to-reorder](./user-list-drop.md), which covers targets, `list-reorder`, `applyListReorder`, filters, virtualisation and auto-scroll.

| Event | Detail | Notes |
|---|---|---|
| `list-drag-over` | `{ key, item, dataTransfer, target }` | Cancelable. **`preventDefault()` accepts the drop**; without it the drag is refused. Fires repeatedly while the drag moves. Not fired for an internal move between rows (`items-reorderable`), which needs no say-so |
| `list-drop` | `{ target, dataTransfer, key, item }` | The drop landed. `key` / `item` describe an `on` target and are `undefined` otherwise |
| `list-reorder` | `{ keys, target }` | Cancelable. A drag that started here ended between two of its own rows. The list never reorders itself |
| `list-drag-leave` | `{ key }` | The drag left its last target (also when it is cancelled) |

`target` is `{ kind: 'on', key }`, `{ kind: 'between', beforeKey, afterKey, index }` or `{ kind: 'empty' }`. The list sets `dropEffect` to `copy` when you accept an outside drag without choosing one — set `dataTransfer.dropEffect` in the `list-drag-over` handler to override.

The row under the drag gets `data-drop-target` (the host does, over empty space). Style it with `--list-drop-target-bg` and `--list-drop-target-outline`; the insertion line for a `between` target is `part="drop-indicator"` (`--list-drop-indicator-color`, `--list-drop-indicator-size`).

`canDrop = (target, dataTransfer) => boolean` refuses a drag up front — no events, no highlight — e.g. to let a leaf row refuse what a folder row accepts. (It used to receive the row element; it now receives the resolved target.) `canReorder = (keys, target) => boolean` gates internal moves.

```typescript
list.itemsDroppable = true;
list.canDrop = target => target.kind === 'on' && isFolder(target.key);
list.addEventListener('list-drag-over', e => e.preventDefault());
list.addEventListener('list-drop', ({ detail }) => {
  if (detail.target.kind === 'on')
    addFiles(detail.target.key, detail.dataTransfer.files);
});
```

---

## Context menu

`list-context-menu` `{ key, item, x, y, selectedKeys }` fires on right-click, and for the menu key (or Shift+F10) on the cursor row. A row that is not selected is selected first, as dragging does, so `selectedKeys` is what the menu acts on. Open your own `ixfx-menu-container` at `x, y` (viewport coordinates).

The event is cancelable: call `preventDefault()` to suppress the browser's native menu. The menu key never shows the native menu; it only fires this event. Right-clicking empty space fires nothing.

---

## In-place rename

Rename is **opt-in**: set `editValidator = (value, key) => boolean` first. Without it `beginEdit` returns `false` and rows stay plain text. The validator runs on commit; returning `false` rejects the text and the edit ends as a cancel.

`list.beginEdit(key)` swaps an [`ixfx-editable-label`](./editable-label.md) into the row, selects its text and focuses it. It returns `false` if there is no `editValidator`, or the row is unknown or not rendered.

The editor replaces the row's `[data-edit-label]` element, or the whole row if there is none. Mark the text element in rows that carry icons or badges, and set `data-edit-value` there if the editable text differs from its content.

| Event | Detail | When |
|---|---|---|
| `list-edit-commit` | `{ key, value }` | Enter or blur with a changed value |
| `list-edit-cancel` | `{ key }` | Escape, an unchanged value, or one the label rejects |

The list never rewrites the label itself; the original row content returns when editing ends. Update your data in response to `list-edit-commit`. `editingKey` reports the row being edited. Keys typed in the editor do not reach the list.

---

## Virtualisation

Set `virtualize` to window the list: only the rows near the viewport (plus an overscan of 3 rows) ever exist in the DOM. Everything else is pooled off-DOM and recycled **by identity** as you scroll, so a list of tens of thousands of rows keeps a tiny, fast DOM. Works for hand-supplied `<li>` / `data-list-item` elements **and** adapter (`items`) rows.

Offscreen space is held by two `data-virtual-spacer` rows bracketing the rendered window. If you query items yourself, exclude them (`li:not([data-virtual-spacer])`) — `querySelectorAll` with the plain `li` selector won't resolve pooled rows because they have no DOM node at all.

### Enabling it

```html
<ixfx-vertical-list virtualize item-height="30" selection-mode="multiple"
    style="height: 300px; --list-item-height: 30px">
</ixfx-vertical-list>
```

- **`item-height` is required.** The window math is pure fixed-stride arithmetic (no DOM measurement), mirroring `ixfx-grid-list`'s `itemSize`. Every row must be exactly that tall — set `--list-item-height` to the same value and keep row content single-line.
- With `item-height` at `0` the component warns and runs non-virtualized.
- It can be toggled at runtime: entering snapshots the current DOM order as the row registry; leaving reattaches every row in order and drops the spacers and pool. Selection and cursor survive both directions.

```typescript
list.virtualize = true;
list.itemHeight = 30;
```

### What works while virtualized

- **Selection and cursor survive scrolling.** Rows are detached/reattached, never recreated, and pooled rows hold live element refs — `selectAll()`, `Cmd/Ctrl+A`, and range operations span them too.
- **`data-key`s** are required for the key APIs (`selectKeys`, `focusKey`, `getItemByKey`, `renderedKeys`); selection by reference (click, `select()`) works regardless.
- **Mutations reconcile.** `addItem` / `setItems` / direct `appendChild` / `removeItem` / `clearItems` all keep working; appends beyond the window land in the pool.
- **Adapter mode** (`items` + `formatter`) virtualizes the same way, and `updateItem` writes through to pooled rows.

### Reading the window

```typescript
// Keys of the rendered window (viewport + overscan) — the priority set for
// prefetching, mirroring ixfx-grid-list.renderedKeys()
list.renderedKeys();

// Keys strictly intersecting the viewport (rect test) — for
// viewport-first work like thumbnail fetches
list.visibleKeys();

// Resolves pooled (off-DOM) rows too
list.getItemByKey('r4321');
```

Rather than polling, the list dispatches `vertical-list-viewport-change` with
`{ renderedKeys, visibleKeys }` whenever either key set changes — scroll,
resize, or content change (virtualized and plain modes alike). At most once
per animation frame, and only when the sets actually differ from the last
dispatch. Mirrors `ixfx-grid-list`'s `grid-list-viewport-change`.

### Limitations while active

- **Drag-select is disabled** — the window shifts under a drag, so the marquee band can't be tracked reliably.
- **Incremental-search `filter` mode is excluded** — it collapses rows via `hidden`, corrupting the fixed-stride geometry. `navigate` and `select` modes still work.

### Search, keyboard and accessibility while virtualized

- **Incremental search covers every row**, rendered or pooled. Matches in `navigate` / `select` mode don't change as you scroll, and highlights repaint as the window moves.
- **Keyboard navigation spans the whole list** (arrows, Home/End, Page Up/Down, `item-wrap="wrap"`). The cursor is scrolled to the nearest edge only when it would otherwise leave the viewport.
- **Native multi-row drag** includes selected rows that are currently pooled; `ListDragEntry.index` is the row's position in the full list.
- **Accessibility:** attached rows get `aria-setsize` / `aria-posinset` for the whole list. Rows without a `role` get `role="option"` and `aria-selected`; a role you set yourself is preserved. The inner list is `role="listbox"` unless the host has its own `role`.

---

## View state

The list implements the shared view-state API (see `docs/infra-view-state.md`):
snapshot *how* it shows its items as plain JSON and restore it later, before or
after the items exist. Kind: `vertical-list`. All state is keyed by each row's
`data-key` / `data-value`, so rows without a key don't take part.

| Field | Type | Meaning |
|---|---|---|
| `selected` | `string[]` | Selected keys. In `checked` mode this is the checked set. |
| `focus` | `string` | Keyboard cursor key. Only recorded while the cursor was last moved by keyboard. |
| `scroll` | `{ top, left?, anchor?: { key, offset } }` | First visible row's key plus px offset into it. Works with `virtualize` too. |

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

bindViewState(list, {
  load: () => JSON.parse(localStorage.getItem('files') ?? 'null'),
  save: s => localStorage.setItem('files', JSON.stringify(s)),
});

list.getViewState();                       // { v: 1, kind: 'vertical-list', selected, focus, scroll }
list.setViewState({ selected: ['a'] });    // partial: only fields present apply
list.clearPendingViewState();
list.addEventListener('view-state-change', e => e.detail /* { state, reason } */);
```

- **Pending state.** Keys that aren't in the list yet stay pending and apply as
  matching rows arrive through `addItem`, `setItems`, a plain `appendChild`, an
  `items` rebuild, or a virtual registry change. `getViewState()` includes pending
  state by default (`includePending: false` leaves it out).
- **Selection.** A restored selection fires the normal `list-select`. Any explicit
  selection change (click, key, `select*()`, `clearSelection()`) drops pending
  selection. A selected row that leaves the list is deselected **silently** (no
  `list-select`) and its key goes pending.
- **Scroll** is applied once the anchor row exists and the list is laid out
  (it is retried on data changes and resizes). The user's own wheel, touch,
  pointer or navigation key cancels a pending scroll.
- **Focus.** A keyboard cursor whose row leaves the list goes pending and comes
  back when the key reappears. Moving the cursor by keyboard, or `focusKey()`,
  drops a pending one.
- `view-state-change` is debounced (150 ms), bubbles and is composed.

---

## CSS variables

| Variable | Default | Description |
|---|---|---|
| `--list-bg` | `var(--surface-3)` | List background |
| `--list-text` | `var(--surface-3-text)` | Default text colour |
| `--list-border` | `var(--border)` | Border colour |
| `--list-radius` | `var(--radius-s)` | Border radius |
| `--list-item-height` | `28px` | Minimum row height for `<li>` items; set it to match `item-height` when virtualizing |
| `--list-item-padding` | `4px var(--space-m, 8px)` | Padding for `<li>` items |
| `--list-item-icon-size` | `1em` | Size of the adapter-mode per-item icon |
| `--list-item-icon-gap` | `6px` | Space between the adapter-mode icon and the row text |
| `--list-item-badge-gap` | `8px` | Space between the row text and a right-justified adapter-mode badge |
| `--item-bg-tickled` | `rgba(0,0,0,0.06)` | Row background when cursor is on it |
| `--item-bg-selected` | `rgba(25,118,210,1)` | Selected row background |
| `--item-text-selected` | `#fff` | Selected row text colour |
| `--item-bg-selected-tickled` | `rgba(21,101,192,1)` | Selected + cursor row background |
| `--accent` | — | Accent colour (focus ring, search highlight, checkbox) |
| `--transition` | `0.1s ease-out` | Transition timing for hover/selection changes |
| `--list-scrollbar-width` | `auto` | Maps to the `scrollbar-width` CSS property on the scroll container (`auto`, `thin`, `none`) |
| `--list-scrollbar-gutter` | `auto` | Maps to the `scrollbar-gutter` CSS property on the scroll container (`auto`, `stable`, `stable both-edges`) |
| `--list-scrollbar-color` | `auto` | Maps to the `scrollbar-color` CSS property on the scroll container (`auto` or a two-colour `thumb track` pair) |
| `--scroll-fade-width` | `30px` | How far the scroll edge fade extends in from each edge (see `docs/infra-theming.md` → *Scroll Fade*) |
| `--scroll-fade-strength` | `1` | How completely content fades at the edge, `0`–`1` (`1` = to transparent, `0` = no fade) |

The three `--list-scrollbar-*` variables are consumed by the shadow-DOM `<ul>` scroll container, so they can be set on any ancestor:

```css
ixfx-vertical-list {
  --list-scrollbar-width: thin;
  --list-scrollbar-gutter: stable;
  --list-scrollbar-color: var(--accent) var(--surface-2);
}
```

---

## CSS parts

| Part | Element |
|---|---|
| `list` | The `<ul>` scroll container |
| `search-overlay` | The floating search input overlay |
| `checkbox` | The per-row checkbox column wrapper in `checked` mode (present on checkable rows; hosts the native `<input>` or the user-rendered content) |

Use `::part()` to style these from outside the component's shadow DOM:

```css
ixfx-vertical-list::part(list) {
  padding: 4px 0;
}

ixfx-vertical-list::part(search-overlay) {
  border-radius: 8px;
}
```
