# `ixfx-flat-list`

Navigate a tree inside one flat list. Each level shows its branches and leaves together; entering a branch replaces the list with that branch's children. An [`ixfx-crumb-navigation`](./crumbs.md) above the scroll area shows the path and jumps to any ancestor.

It wraps [`ixfx-vertical-list`](./vertical-list.md), so selection modes, interaction modes, keyboard shortcuts, incremental search, drag-out and drag-select behave as they do there. The data model is the same `TreeNode` / `TreeDataModel` that `ixfx-crumb-navigation` and `ixfx-tree-list` use.

```html
<ixfx-flat-list style="height: 280px"></ixfx-flat-list>
```

```typescript
const list = document.querySelector('ixfx-flat-list')!;
list.root = { item: { key: 'root', label: 'Home' }, children: [/* … */] };
list.addEventListener('flat-list-activate', ({ detail }) => open(detail.node));
```

## Properties

| Property / attribute | Type | Default | Description |
|---|---|---|---|
| `root` | `TreeNode` | | Root of the tree |
| `model` | `TreeDataModel` | | Alternative to `root` (and `loadChildren`); stays in sync with model changes |
| `path` | `readonly string[]` | `[]` | Keys from the root (excluded) to the level shown |
| `loadChildren` | `LoadChildrenCallback` | | Loads a branch whose `children` is `undefined`. Results are written back to `node.children`, as in crumb-navigation |
| `filterPredicate` | `(node, depth) => boolean` | | Hides non-matching nodes |
| `sort` | `(a, b) => number` | | Orders nodes within a level |
| `branchOrder` / `branch-order` | `'first' \| 'mixed'` | `'first'` | `first`: branches then leaves. `mixed`: one list in `sort` / source order |
| `selectionMode` / `selection-mode` | | `'single'` | As `ixfx-vertical-list` |
| `interactionMode` / `interaction-mode` | | `'standard'` | As `ixfx-vertical-list` |
| `itemWrap`, `searchModes`, `itemsDraggable` | | | Passed to the inner list |
| `itemsDroppable` / `items-droppable` | `boolean` | `false` | Rows and empty space accept native drops. See [Drops](#drops) |
| `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` (bubbles out of the list). Implies `items-draggable` |
| `canDrop` | `(node, dataTransfer) => boolean` | | Refuse a drag up front. `node` is the row, or the current level's node over empty space |
| `validateEdit` | `(value, node) => boolean` | | Opts in to [rename](#rename) and validates the typed text |
| `markedKey` / `marked-key` | `string` | | Keep this node's row visibly marked across level changes. Not a selection |
| `virtualize`, `itemHeight` / `item-height` | `boolean`, `number` | `false`, `0` | Render only visible rows; needs a fixed row height. See [virtualisation](./vertical-list.md#virtualisation) |
| `withUp` / `with-up` | `boolean` | `false` | Up button in the crumb bar. Off by default, since clicking the last crumb also goes up |
| `hideRoot` / `hide-root` | `boolean` | `false` | Hide the root crumb |
| `itemEffect` / `item-effect` | `'none' \| 'sweep'` | `'none'` | Animate the rows when the level changes: the old level sweeps out to the left, then the new one in from the right, staggered; going back up mirrors it. See [item effects](./vertical-list.md#item-effects) |
| `hideNav` / `hide-nav` | `boolean` | `false` | Hide the whole crumb navigation, Up button included. Keyboard, double-click and `navigate*()` still work. A slotted toolbar stays; with none, the bar disappears |
| `emptyText` / `empty-text` | `string` | `'Empty'` | Shown for a level with no children |

A node counts as a branch unless `item.isLeaf` is `true` or its `children` is `[]`. Set `item.isLeaf: false` to force a branch even when `children` is `[]`: an empty folder that can still be entered, showing `emptyText`. `item.icon`, `iconColor`, `textColor` and `badge` are honoured.

## Performance

**Set `virtualize` and `item-height` for big levels.** Without them every row of the level is a DOM element: at 100k rows that is
a 2.6 s first render and ~400 ms per arrow key. With them, only the window exists in the DOM.

What the component itself does at scale:

- Row lookups by key are indexed (a selection maps every selected key; select-all over 100k rows used to be 100k scans of 100k).
- The path to the level shown is cached and re-validated against the tree on each use, so a render, a select or a key press doesn't
  re-search a wide level, and in-place edits to `children` are still picked up. Finding a key path (crumb select) is iterative.
- Row ordering is one pass (no copies for the sort / branches-first split) and an unfiltered level isn't copied.

The inner `ixfx-vertical-list` now moves its virtual window in O(window) instead of O(rows): a scroll frame or an arrow key no longer
re-parks, re-indexes and re-filters every row.

Reference, 100k rows, virtualised, Chrome (`pnpm bench:flat-list`, needs `pnpm start`):

| | before | after |
|---|---|---|
| scroll frame (script) | 33–35 ms | ~1.1–1.4 ms |
| arrow key (script) | 45 ms | ~3 ms |
| select all | 20.5 s | ~60 ms |
| go into a branch among 100k siblings | 2.7 s | ~0.6 s |
| first render | 2.2 s | ~0.5 s |
| retained heap | 264 MB | ~107 MB |

Still O(rows): a rebuild of the level (first render, going up into a 100k level, a new `sort` / `filterPredicate`) takes ~0.5 s, because the
inner list creates a row element for every item, even offscreen ones (kept in an off-DOM pool). Creating them lazily is the next step.

## Methods

| Method | Description |
|---|---|
| `navigateTo(keys)` | Show the level at this key path. `false` if it does not resolve |
| `navigateInto(key)` | Enter a child branch |
| `navigateUp()` | Go to the parent. `false` at the root |
| `currentNode` | Node whose children are listed |
| `selectedNodes` | Selected `TreeNode`s in the current level |
| `beginEdit(key)` | Rename a row in place. Needs `validateEdit` and `item.editable`; `false` otherwise |
| `registry` / `dispatch(id, args)` | The inner list's command registry, e.g. `dispatch('list.search.filter')` |
| `list` | The inner `ixfx-vertical-list` |
| `getViewState(options?)` / `setViewState(state)` / `clearPendingViewState()` | See [View state](#view-state) |

## Events

| Event | Detail | When |
|---|---|---|
| `flat-list-navigate` | `{ path, previousPath, node, direction }` | The level changed. `direction` is `into`, `up` or `jump` |
| `flat-list-select` | `{ selected, selectedKeys, previous }` | Selection changed (nodes, not elements) |
| `flat-list-activate` | `{ node }` | A **leaf** was double-clicked or Enter was pressed |
| `flat-list-drop` | `{ node, dataTransfer }` | Something was dropped. See [Drops](#drops) |
| `flat-list-context-menu` | `{ node, nodes, x, y }` | Cancelable. See [Context menu](#context-menu) |
| `flat-list-edit-commit` | `{ node, value }` | A rename was committed |
| `flat-list-edit-cancel` | `{ node }` | A rename ended without a change |

The inner list's `list-*` events also cross the shadow boundary, with row elements as their `item`.

## Navigation

| Gesture | Action |
|---|---|
| Click the chevron, double-click, `Enter`, `Arrow Right` on a branch | Enter it |
| `Arrow Left`, `Backspace` | Go up. The cursor lands on the branch you came from |
| Crumb, caret menu, Up button | Jump to that node. Clicking the last crumb (the level being shown) goes up to its parent. Choosing a leaf from a caret menu shows its level and selects it |
| Everything else | See [vertical-list keyboard navigation](./vertical-list.md#keyboard-navigation) |

Selection is cleared on every level change. Arrow Left and Backspace are ignored while the search field is focused.

## View state

The level shown and its selection, cursor and scroll, as plain JSON for the
host to persist (see [docs/infra-view-state.md](./infra-view-state.md)):

```ts
{ v: 1, kind: 'flat-list', path: ['docs', 'work'], selected: ['a.txt'], focus: 'a.txt', scroll: { top: 0 } }
```

`selected`, `focus` and `scroll` belong to the level at `path`. They are held
until that level is shown, then handed to the inner list, which applies them
as its rows arrive (see the vertical-list README).

- Keys not loaded yet stay pending: the list shows the deepest level it can
  reach and continues as data arrives. Showing a level loads it (via
  `loadChildren` / `model`), so a saved path through lazy levels loads one
  level at a time.
- If new data drops the level shown, the list steps up to the closest
  ancestor and the level (with its selection) goes pending; it is returned to
  when its keys reappear. This also applies to a `path` assigned before the
  data has loaded.
- An explicit navigation (gesture, `navigate*()`, or assigning `path`) drops
  a pending level; an explicit selection drops a pending selection.
- The inner crumb's and list's own `view-state-change` events are stopped at
  this element; it fires its own.

## Drops

With `items-droppable`, a drag over a row, or over empty space, is accepted unless `canDrop` refuses it. A drop fires `flat-list-drop` with that row's node, or the **current level's node** for empty space or a gap between rows, and the resolved `target` (`{ kind: 'on', key }`, `{ kind: 'between', beforeKey, afterKey, index }` or `{ kind: 'empty' }`). Dropping on a branch row reports it and does **not** enter it. Native OS drags work: `dataTransfer` carries `files`, `text/uri-list` and any custom MIME type the source wrote. The row under the drag gets the vertical-list [drop highlight](./vertical-list.md#drop-targets).

`canDrop` is `(target, dataTransfer) => boolean` (it used to receive the node). With `drop-positions="between"` / `"both"` the gap between two rows of the current level is a target, and with `items-reorderable` a drag that starts here and ends between two of its rows fires the inner list's `list-reorder` `{ keys, target }` — keys are node keys — which bubbles out of the flat list. Apply it to the current level's children with `applyListReorder`; the list never reorders anything itself. See [Drops and drag-to-reorder](./user-list-drop.md).

## Context menu

`flat-list-context-menu` fires on right-click or the menu key. The row is selected first, so `nodes` is the selection to act on and `node` is the row clicked. Open your own `ixfx-menu-container` at `x, y`. Call `preventDefault()` to suppress the native menu.

## Rename

Rename is **opt-in**: set `validateEdit = (value, node) => boolean`, and mark the rows that may be renamed with `item.editable: true`. Without both, rows are plain text and `beginEdit` returns `false`. Returning `false` from the validator rejects the text and the edit ends as a cancel.

```typescript
list.validateEdit = (value, node) => value.trim() !== '' && !names.has(value);
list.addEventListener('flat-list-edit-commit', ({ detail }) => rename(detail.node.item.key, detail.value));
list.beginEdit('set:2');   // e.g. from your own context menu
```

`beginEdit(key)` starts the edit. Commit and cancel arrive as `flat-list-edit-commit` / `flat-list-edit-cancel`. The label is not rewritten for you: change `item.label` in your tree in response, and the level refreshes.

## Incremental search

Navigate / select / filter search works over the current level, as in [`ixfx-vertical-list`](./vertical-list.md#incremental-search) — see [`docs/infra-incremental.md`](./infra-incremental.md). `search-modes` limits the modes. There is no default shortcut: bind a key or button to `dispatch('list.search.filter')` (or `.navigate` / `.select`). The highlight rule is built in, so no page-level `::highlight()` rule is needed. The search is closed when the level changes.

## CSS variables

`--flat-list-bg`, `--flat-list-text`, `--flat-list-border`, `--flat-list-radius`, `--flat-list-crumb-padding`, `--flat-list-crumb-font-size` (default `--text-s`), `--flat-list-toolbar-gap`, `--flat-list-chevron-gap`, `--flat-list-marked-bg`, `--flat-list-marked-bar`, `--flat-list-empty-text`. Each falls back to the matching `--list-*` variable. Other `--list-*` variables (e.g. `--list-item-height`) reach the inner list.

## Toolbar slot

Anything you put inside the element goes in a toolbar to the right of the crumb bar, which shrinks to make room. With nothing slotted, the crumbs use the full width.

```html
<ixfx-flat-list>
  <ixfx-button>New Set</ixfx-button>
</ixfx-flat-list>
```

Space between items is `--flat-list-toolbar-gap`.

## CSS parts

`crumbs` (the bar above the list), `toolbar` (the slot's wrapper), `empty`.
