# Miller Columns

A Miller column component displays hierarchical data as multiple vertical columns, like macOS Finder or email clients. Each column shows the children of the selected item in the previous column.

---

## MillerBaseElement / MillerListElement

### Attributes

| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| `headers` | boolean | `false` | Show column headers labeling each column with its parent item |

### Properties

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `root` | `MillerNode \| undefined` | — | The root node of the tree. Assigning a new root re-applies the open path, selection and cursor by key (see [View state](#view-state)); a rebased view is reset. |
| `restoreLoads` | `boolean` | `true` | Whether restoring view state may call `loadChildren` / `model` to open a saved path through unloaded branches. |
| `selectionMode` | `MillerSelectionMode` | `'implicit'` | Controls how items are selected. See [Selection Modes](#selection-modes) below. |
| `selectedKeys` | `ReadonlySet<string>` (getter) / `Iterable<string>` (setter) | — | The set of currently selected item keys. Assigning replaces the entire selection and triggers a re-render. |
| `loadChildren` | `MillerLoadChildrenCallback \| undefined` | — | Callback to load children for lazy nodes. If undefined, clicking a lazy node opens an empty column. |

### CSS Variables

These can be overridden in your CSS:

| Variable | Default | Description |
|----------|---------|-------------|
| `--column-bg` | `var(--surface-l)` | Background color of columns |
| `--column-header-bg` | `var(--surface)` | Background color of column headers |
| `--column-header-text` | `var(--surface-muted-text)` | Text color of column headers |
| `--column-separator` | `var(--surface-h)` | Color of column borders/dividers |
| `--column-resize-handle` | `var(--surface-h)` | Color of resize handles |
| `--column-resize-handle-hover` | `var(--accent)` | Color of resize handle on hover |
| `--column-resize-width` | `4px` | Width of resize handles |
| `--item-hover-bg` | `var(--item-bg-tickled)` | Background on item hover |
| `--item-selected-bg` | `var(--item-bg-selected)` | Background of selected item |
| `--item-selected-text` | `var(--item-text-selected)` | Text color of selected item |
| `--miller-list-badge-gap` | `0.5em` | Space between a per-item label and its right-justified badge |
| `--icon-size` / `--icon-spacing` | `1em` / `0.3em` | Per-item icon size and gap |

Inherited from theme:
- `--font-family` - Font family
- `--font-weight-bold` - Bold font weight
- `--text-s`, `--text-m`, `--text-l` - Font sizes
- `--space-xs`, `--space-s`, `--space-m` - Spacing
- `--radius-s` - Border radius
- `--transition` - Transition timing

### Methods

```typescript
// Navigate to a node by key path (root-to-target keys, excluding root itself).
// Only works with already-loaded children — returns false if any node along
// the path has unloaded children or if a key is not found.
navigateTo(keys: readonly string[], options?: { reveal?: 'edge' | 'center-if-hidden'; silent?: boolean }): boolean

// Re-sync after children arrays were patched in place (used by MillerTreeController.sync()):
// the open path and selection re-resolve by key; removed nodes close their
// columns / are deselected, and come back if their key reappears.
invalidateStructure(): void

// Navigate to the first loaded node (breadth-first) matching a predicate.
// Returns false if no match is found in the currently loaded tree.
navigateToNode(predicate: (node: MillerNode) => boolean): boolean

// View state — see "View state" below
getViewState(options?): MillerListViewState
setViewState(state: Partial<MillerListViewState>): void
clearPendingViewState(): void
```

### Events

All events bubble and are composed.

| Event | Detail | Description |
|-------|--------|-------------|
| `expand` | `{ node: MillerNode, depth: number }` | FYI - fired after a column opens. |
| `collapse` | `{ node: MillerNode, depth: number }` | FYI - fired when a column closes. |
| `item-click` | `{ node: MillerNode, depth: number }` | Fired when any item is clicked. |
| `select` | `{ node: MillerNode, depth: number }` | Fired when Enter is pressed on an item. |
| `header-click` | `{ depth: number, label: string, path: MillerNode[] }` | Fired when a column header is clicked (requires `headers` attribute). `path` is the ancestry chain from root down to the node whose label is shown in the header. |
| `change` | — | Fired when selection changes in `checked` mode (checkbox toggled). |

---

## Selection Modes

Set via the `selectionMode` property (not an HTML attribute). Default: `'implicit'`.

```typescript
type MillerSelectionMode = 'implicit' | 'standard' | 'manual' | 'checked' | 'vscode';
```

### `implicit` (default)

Selection follows the cursor path — whatever is open in the column pane is considered selected. This is the classic Miller column behaviour and is unchanged from prior versions.

### `standard`

Explicit multi-select similar to a file manager:

| Input | Action |
|-------|--------|
| Click | Single-select item and expand (sets anchor, clears others) |
| Shift+Click | Contiguous range from anchor to item (within same depth) |
| Cmd/Ctrl+Click | Toggle item without expanding (no anchor change) |
| Arrow Up/Down | Move focus, select the item under the cursor and re-seat the anchor |
| Home / End | Move focus to the first / last item in the column (selects it, as Arrow Up/Down) |
| Page Up / Page Down | Move focus up / down by one visible page (clamped to the column) |
| Shift+Arrow / Home / End / Page keys | Extend range from anchor (bootstraps anchor from current position if unset) |
| Enter | Select focused item (sets anchor) |
| Shift+Enter | Extend range to focused item |

### `vscode`

Extends `standard` with persistent multi-selection across cursor movement:

| Input | Action |
|-------|--------|
| Click | Single-select item and expand (clears others) — same as `standard` |
| Shift+Click | Contiguous range from anchor — same as `standard` |
| Cmd/Ctrl+Click | Toggle item without expanding — same as `standard` |
| Arrow Up/Down | Move cursor **only** — selection is preserved, anchor is not re-seated |
| Home / End / Page Up / Page Down | Move cursor only, as Arrow Up/Down |
| Shift+Arrow / Home / End / Page keys | Extend range from anchor — same as `standard` |
| Arrow Right | Expand/navigate into branch — selection is preserved (does not clear) |
| Enter | Add focused item to selection (sets anchor) |
| Shift+Enter | Extend range to focused item |

The key difference from `standard`: in `vscode` mode the cursor is free to move without disturbing the accumulated multi-selection. Only a plain unmodified click clears the selection.

### `manual`

The component never modifies `selectedKeys`. All clicks and keyboard actions fire events as normal but selection state is entirely driven by the caller via the public API. Use this when you want to implement custom selection logic.

### `checked`

A checkbox appears beside each item. Clicking the row navigates/expands as usual; clicking the checkbox toggles selection. Selecting a branch recursively selects all loaded descendants. Checkbox state follows a three-state cycle: **indeterminate → checked → unchecked**.

- **Checked**: item key is in `selectedKeys`
- **Unchecked**: item key is not in `selectedKeys` and no loaded descendants are selected
- **Indeterminate**: some (but not all) loaded descendants are selected

The `change` event is fired on the component after every checkbox toggle.

---

## Selection intents and partial rows

`ixfx-miller-list` fires a cancelable `list-select-intent` before a click (all interaction modes, including `manual`), a checkbox toggle or a Shift+Arrow range changes the selection; `preventDefault()` means "I'll apply it". Navigation (opening the node's column) still happens. It also fires `list-select` `{ selectedKeys, previousKeys, previous }` next to `select`, and supports `partialKeys` (indeterminate checkbox in `checked` mode, `.partial` otherwise; selected wins; in `checked` mode a node is indeterminate if either the loaded descendants or `partialKeys` say so, as in the tree). Ticking a branch in `checked` mode is one `toggle` intent with `descendants: true` and `checked` (the state it is being set to), exactly as in `ixfx-tree-list`: `keys` lists the node and every loaded descendant, and the caller can express it as a rule ("this folder and everything under it"). See [Selection intents, partial rows, unloaded keys](./user-selection-intents.md).

## Selection API

```typescript
// Read current selection
const keys: ReadonlySet<string> = el.selectedKeys;

// Replace entire selection (triggers re-render)
el.selectedKeys = ['key-a', 'key-b'];

// Select or deselect a single node
// In 'checked' mode, selecting a branch recursively selects all loaded descendants
el.setSelected(node: MillerNode, selected: boolean): void

// Return all currently-selected MillerNodes (searches loaded tree only)
el.getSelected(): MillerNode[]

// Clear all selection state
el.clearSelection(): void
```

---

## Types

```typescript
type MillerItem = {
  key: string;           // Unique identifier
  label: string;         // Display text
  isLeaf?: boolean;      // If true, clicking never fires 'expand'
  data?: unknown;        // Arbitrary user data
  icon?: string;         // Optional icon name
  iconColor?: string;    // Optional CSS colour for the icon
  textColor?: string;    // Optional CSS colour for the label
  badge?: unknown;       // Optional Finder-style badge (anything Lit can render)
  tooltip?: string;      // Optional tooltip text
  value?: string;        // Optional string value
};

type MillerNode = {
  item: MillerItem;
  children?: MillerNode[];  // undefined = unloaded, [] = confirmed empty
};
```

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

`iconColor` and `textColor` are plain CSS colour strings; the icon paints from
`currentColor`, so `iconColor` recolours the glyph. `badge` is anything Lit
can render — a `TemplateResult`, a DOM `Node`, or a string — and shows up
right-justified on the row, after the name and before the expand caret, the
way Finder's list view shows colour tags.

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

el.root = {
  item: { key: 'root', label: 'Documents' },
  children: [
    { item: { key: 'a', label: 'Archive.zip', icon: 'file', badge: tagChip('orange') } },
    {
      item: {
        key: 'b',
        label: 'Overdue.txt',
        icon: 'file',
        iconColor: 'var(--accent)',
        textColor: 'crimson',
        badge: stackedTagChips(['red', 'yellow']),
      },
    },
  ],
};
```

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 badge can be made conditional.

The badge renders as `<span class="item-badge" part="badge">`, so
`::part(badge)` works from outside the component.

CSS: `--miller-list-badge-gap`.

---

## Basic Usage

### Static Columns

```html
<ixfx-miller-list id="miller" headers></ixfx-miller-list>

<script type="module">
  const el = document.getElementById('miller');
  
  el.root = {
    item: { key: 'root', label: 'My Computer' },
    children: [
      {
        item: { key: 'c', label: 'C:' },
        children: [
          { 
            item: { key: 'users', label: 'Users' },
            children: [
              { item: { key: 'jane', label: 'Jane', isLeaf: true } },
              { item: { key: 'barry', label: 'Barry', isLeaf: true } }
            ]
          },
          { item: { key: 'windows', label: 'Windows', isLeaf: true } }
        ]
      },
      {
        item: { key: 'd', label: 'D:' },
        children: [
          { item: { key: 'games', label: 'Games', isLeaf: true } }
        ]
      }
    ]
  };

  // Respond to clicks
  el.addEventListener('item-click', ({ detail }) => {
    console.log('Clicked:', detail.node.item.label, 'at column', detail.depth);
  });

  // Respond to header clicks (if headers enabled)
  el.addEventListener('header-click', ({ detail }) => {
    console.log('Header clicked:', detail.label, 'at depth', detail.depth);
    console.log('Path:', detail.path.map(n => n.item.label));
  });
</script>
```

### Lazy Loading

Set the `loadChildren` callback to handle loading children on demand. The callback
receives the node, depth, and an AbortSignal. It should return the children array
(or a Promise that resolves to it). The callback is debounced by 150ms.

```html
<ixfx-miller-list id="miller"></ixfx-miller-list>

<script type="module">
  const el = document.getElementById('miller');
  
  // Children at root level are pre-loaded; deeper nodes will be loaded on demand
  el.root = {
    item: { key: 'root', label: 'Root' },
    children: [
      { item: { key: 'a', label: 'Alpha' } },  // children: undefined → lazy
      { item: { key: 'b', label: 'Beta' } },
    ]
  };

  el.loadChildren = async (node, depth, signal) => {
    // Return children array (sync or async)
    return fetchChildren(node.item.key, signal);
  };

  async function fetchChildren(key, signal) {
    const response = await fetch(`/api/children/${key}`, { signal });
    return response.json();
  }
</script>
```

If no `loadChildren` callback is set, clicking a lazy node opens an empty column.

**FYI Events:**
- `expand`: fired after a column opens. Detail: `{ node, depth }`
- `collapse`: fired when a column closes (user navigates away or load is aborted). Detail: `{ node, depth }`

### Programmatic Navigation

```javascript
// Navigate by key path — keys are item.key values from root's children downwards.
// Returns false (silently) if any node along the path has not yet been loaded.
el.navigateTo(['c', 'users', 'jane']);

// Or find by predicate across already-loaded nodes
el.navigateToNode(node => node.item.label === 'System32');
```

### Column Resizing

Columns can be resized by dragging the handle on the right edge of each
column. Widths are part of the view state (`columnWidths`, keyed by depth):

```javascript
el.setViewState({ columnWidths: { 0: 150, 1: 200, 2: 180 } });
```

### View state

`getViewState()` / `setViewState()` snapshot and restore how the columns are
showing the data, as plain JSON keyed by `item.key`. The component never
stores it; `bindViewState()` wires it to storage. See
[docs/infra-view-state.md](./infra-view-state.md).

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

bindViewState(el, {
  load: () => JSON.parse(localStorage.getItem('miller') ?? 'null'),
  save: s => localStorage.setItem('miller', JSON.stringify(s)),
});
el.root = await fetchRoot(); // saved state applies as nodes arrive
```

`kind: 'miller-list'`. Fields:

| Field | Type | Meaning |
|---|---|---|
| `path` | `string[]` | Key of the open branch at each depth, column 0 first, relative to the view root. |
| `selected` | `string[]` | `selectedKeys` (the checked set in `checked` mode). |
| `focus` | `string` | Keyboard cursor key, only when last moved by keyboard. |
| `columnWidths` | `Record<string, number>` | User-resized widths in px, keyed by depth. |
| `columnScroll` | `Record<string, ScrollState>` | Scroll of each scrolled column, keyed by the key of the node whose children it lists (the view root's key for column 0). |

`path` is an ordered array rather than the shared `expanded` record because a
Miller view has exactly one open branch per column.

- State for keys not loaded yet stays **pending** and applies as nodes appear:
  a new `root`, `invalidateStructure()` after children were patched in place,
  or a lazy load. A saved path `a > b > c` opens as each node arrives.
- With `restoreLoads` (default `true`) a saved path through unloaded branches
  is opened via `loadChildren` / `model`, one load at a time, so it cascades.
- New `root` data keeps the open path, selection and cursor for keys that
  still exist; keys that left go pending (deselected silently) and come back
  if they reappear. Restored selection fires `select` with
  `origin: 'programmatic'`.
- Any explicit selection change drops pending selection; any explicit
  navigation (click, arrow keys, `navigateTo`, rebasing) drops the pending
  path. The view root itself is not part of the state.
- `view-state-change` fires (debounced) on selection, navigation, keyboard
  cursor moves, column resize and column scroll.

---

## MillerTreeController

Bridge an ixfx `TraversableTree` to a Miller component. Children are populated
lazily — the controller handles `expand` events by synchronously reading from
the underlying tree.

```typescript
import { Trees } from '@ixfx/collections';
import { MillerTreeController } from './miller-tree-controller.js';

const root = Trees.Mutable.createNode({ key: 'root', label: 'Root' });
Trees.Mutable.addValue({ key: 'a', label: 'Alpha' }, root);

const ctrl = new MillerTreeController(
  Trees.Mutable.asDynamicTraversable(root),
  document.querySelector('ixfx-miller-list'),
  { 
    // Both the value and the raw tree node are provided so you can inspect
    // child count, identity, etc. when building the MillerItem.
    valueToItem: (value, treeNode) => ({ 
      key: value.key, 
      label: value.label,
      isLeaf: value.isLeaf 
    }) 
  }
);

ctrl.connect();

// Navigate to a value — ancestors with unloaded children are populated first
ctrl.navigateToValue(v => v.label === 'Target');

// Clean up event listeners when done
ctrl.disconnect();
```

### MillerTreeControllerOptions

```typescript
type MillerTreeControllerOptions<T> = {
  // Convert a tree node's value to a MillerItem.
  // key and label are required. If isLeaf is omitted, it is inferred
  // from whether the TraversableTree node has any children.
  valueToItem: (value: T, node: TraversableTree<T>) => MillerItem;
  // Installed as element.loadChildren by connect(). Defaults to a synchronous
  // read from the source tree. sync() never touches it.
  loadChildren?: LoadChildrenCallback;
};
```

### Methods

```typescript
// Re-derive children of already-loaded nodes from the source tree and patch them
// in place (arrays mutated, MillerNodes reused by key). viewRoot is reset only if
// its node was removed. Refreshes the element once.
sync(): void

// Lookups that avoid searching the source tree. Key paths are RELATIVE TO THE
// VIEW ROOT; identities outside a rebased view return false.
lookupByKey(key: string): TraversableTree<T> | undefined
navigateToKeyPath(keys: readonly string[], options?: TreeNavigateOptions): boolean
navigateToIdentity(identity: unknown, options?: TreeNavigateOptions): boolean
```

```typescript
// Wire up the controller — sets element.root and provides loadChildren callback.
// Safe to call again after disconnect().
connect(): void

// Remove all event listeners and release internal state.
disconnect(): void

// Navigate the component to the first node (depth-first) whose value matches predicate.
// Any ancestor MillerNodes with unloaded children are populated synchronously first.
// Returns false if no matching node is found.
navigateToValue(predicate: (value: T) => boolean): boolean
```

---

## Keyboard Navigation

Miller columns support full keyboard navigation when the component has focus:

| Key | Action |
|-----|--------|
| `Arrow Up` | Move focus to previous item in column |
| `Arrow Down` | Move focus to next item in column |
| `Arrow Right` | Select focused item and open its children (if any) |
| `Arrow Left` | Go back to previous column |
| `Home` / `End` | Move focus to the first / last item in the column |
| `Page Up` / `Page Down` | Move focus up / down by one visible page |
| `Enter` | Fire `select` event on focused item; in `standard` mode also selects and sets anchor |
| `Shift+Arrow` / `Home` / `End` / `Page` keys | In `standard` mode: extend selection range from anchor |
| `Shift+Enter` | In `standard` mode: extend selection range to focused item |
| `Escape` | Cancel pending lazy load / go back one column |

---

## Performance

**Any change to `miller-base.ts` or `miller-list.ts` that touches `render`,
the per-item template, selection handling, cursor movement, column opening or
lazy loading should be checked with `pnpm bench:miller`.** Every update
re-renders every item in every open column, so an accidental O(items) (or
O(descendants), in `checked` mode) per-keystroke cost is easy to introduce and
shows up directly as key-repeat lag.

`scripts/bench/miller.ts` drives `demo/miller.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
list and runs two scenarios per item count (default 500 and 2000 rows per
column): `standard`, and `checked` with a loaded 20 × 10 subtree under most
rows (which the checkbox state scan must walk). It reports:

- `arrow` / `page` / `hover` — main-thread `script` and `render` ms per
  Arrow Down, Page Up/Down, or hover (from a timeline trace).
- `resize` — the same, per frame of a column-resize drag.
- `openMs` — median ms to click a branch whose children are already loaded and
  render the new column.
- `lazyOpenMs` — the same for an unloaded branch resolved by an instant
  `loadChildren`. This exposes any artificial delay in the lazy-load path
  (clicks must start loading immediately; only keyboard navigation is
  debounced).
- `checkToggleMs` — median ms to toggle a branch checkbox (`checked` only).

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

```sh
pnpm bench:miller --out /tmp/miller-base.json      # before
pnpm bench:miller --compare /tmp/miller-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. `--items 500,5000`
changes the column 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, 2000 rows per column, `standard`):
an Arrow / Page / hover update is ~4 ms script + ~1 ms render; a resize frame
~9.5 ms render; opening a loaded column ~20 ms, a lazy one ~7 ms. In `checked`
mode with the 20 × 10 subtrees, key and hover updates are ~11-12 ms and a
checkbox toggle ~27 ms, because each render scans every visible row's loaded
subtree.

---

## Subclassing MillerBaseElement

Create custom column renderers by subclassing `MillerBaseElement`. Override
`renderColumnContent` to control how items are rendered. The following protected
members are available for subclasses to use:

```typescript
// True if node is currently selected at the given depth
_isSelected(node: MillerNode, depth: number): boolean

// True if node has keyboard focus at the given depth
_isFocused(node: MillerNode, depth: number): boolean

// Returns the index of the focused item at the given depth
_getFocusedIndex(depth: number): number

// Call this to handle an item click (selection, expand, events)
_handleItemClick(node: MillerNode, depth: number): void

// Handle a checkbox click for the given node (used in 'checked' mode).
// Returns the new checked state (true = selected) after the toggle.
// Also fires the 'change' event on the element.
_handleCheckboxClick(event: MouseEvent, node: MillerNode, depth: number): boolean

// The current selection set — read/write in subclasses
_selectedKeys: Set<string>
```

Example:

```typescript
import { MillerBaseElement } from './miller-base.js';
import { html, css } from 'lit';
import { customElement } from 'lit/decorators.js';
import type { MillerNode } from './types.js';

@customElement('ixfx-miller-custom')
export class MillerCustomElement extends MillerBaseElement {
  protected override renderColumnContent(nodes: MillerNode[], depth: number) {
    return html`
      <div class="custom-column">
        ${nodes.map(node => html`
          <div
            class="custom-item ${this._isSelected(node, depth) ? 'selected' : ''} 
                               ${this._isFocused(node, depth) ? 'focused' : ''}"
            @click=${() => this._handleItemClick(node, depth)}
          >
            ${node.item.label}
          </div>
        `)}
      </div>
    `;
  }

  static override styles = [
    ...MillerBaseElement.styles,
    css`
      .custom-item.selected { background: var(--item-selected-bg); }
      .custom-item.focused  { outline: 2px solid var(--accent); }
    `,
  ];
}
```
