# View state

A common API for snapshotting and restoring *how* a component is showing its
data — selection, expansion, scroll, column sizes, panel layout — separately
from the data itself.

- The component **never persists** anything. It hands out plain JSON and takes
  it back; where it is stored is the host's business (`bindViewState()` makes
  that a two-liner).
- State is **keyed**, never positional: item keys, column ids, group keys,
  panel ids. That is what lets it be re-applied to data that was rebuilt,
  re-sorted or streamed in.
- State for keys the data doesn't contain yet is kept **pending** and applied
  when a matching item appears. Set a saved tree state, then build the tree up
  over time: as `A > B > C` arrives, each branch opens.

Core lives in `src/common/view-state/` and is exported from the package index.

---

## Using it

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

const stop = bindViewState(tree, {
  load: () => JSON.parse(localStorage.getItem(`files-tree`) ?? `null`),
  save: s => localStorage.setItem(`files-tree`, JSON.stringify(s)),
});

tree.root = await fetchRoot(); // pending state applies as items arrive
```

`bindViewState` loads once (immediately), saves on every debounced
`view-state-change` (skipping `restore` echoes) and on `pagehide`. Returns a
function that stops saving.

Without the helper:

```ts
const saved = el.getViewState();          // plain JSON
el.setViewState(saved);                   // any time — before or after data
el.setViewState({ selected: [`a`] });     // partial: only fields present apply
el.getViewState({ include: [`columns`] }) // only some fields
el.clearPendingViewState();               // forget not-yet-matched state
el.addEventListener(`view-state-change`, e => e.detail /* { state, reason } */);
```

---

## API (every view-stateful component)

| Member | Description |
|---|---|
| `getViewState(options?)` | Snapshot as plain JSON. `include` limits fields; `includePending` (default **true**) adds state for keys not currently present. |
| `setViewState(state)` | Apply a partial state. Fields present **replace** the current value; absent fields are untouched. Keys not in the data go pending. A state whose `kind` or `v` doesn't match is ignored with a warning. |
| `clearPendingViewState()` | Drop pending (unmatched) state. |
| `view-state-change` event | Debounced (150 ms trailing), `bubbles`, **not** `composed` — events from view-stateful children inside a component's shadow root stay inside it. `detail: { state, reason }`. Flushed immediately on disconnect. |

`reason` is the strongest cause since the last event: `user` (interaction) >
`data` (component adjusted to a data change) > `restore` (pending state applied,
or `setViewState()`).

### Shared fields (`ViewStateBase`)

| Field | Type | Meaning |
|---|---|---|
| `v` | `1` | Schema version. |
| `kind` | `string` | Component kind, e.g. `tree-list`. |
| `selected` | `string[]` | Selected item keys. In `checked` interaction modes this is the checked set. |
| `focus` | `string` | Keyboard cursor key (only recorded when the cursor was moved by keyboard). |
| `scroll` | `{ top, left?, anchor?: { key, offset } }` | `anchor` = first visible item's key + px offset into it. Preferred over `top` because it survives inserts above. |
| `expanded` | `Record<string, boolean>` | Explicit open / closed choices for branches or groups. A missing key means "component default", so it works for things that default open (groups) and closed (tree branches). |

Components add their own fields (see the table at the end).

---

## Semantics

**Pending state.** Every keyed piece of state is either *live* (its key exists
in the data) or *pending*. On every data change a component:

1. moves live state whose key has gone to pending (so a data reset does not lose it), and
2. applies pending state whose key now exists.

Pending sets are capped at 2000 keys per facet (oldest dropped).

**What supersedes pending state:**

| Facet | Pending is dropped when… |
|---|---|
| selection | any explicit selection change (click, key, `select*()`, `clearSelection()`). Selection is all-or-nothing, so an old saved selection must never merge into a new one. |
| expansion | never implicitly — tracked per key. Collapsing `A` doesn't forget that `C` (below it) was open. |
| scroll | the user scrolls / navigates (wheel, touch, pointer, nav key), or the position is reached. |
| focus | the cursor is moved. |
| anything | `setViewState()` with that field, or `clearPendingViewState()`. |

**Restored selection fires the normal selection event** (with
`origin: 'programmatic'` where the event has one). A key that *leaves* the data
is deselected silently.

**Lazy trees.** With `restoreLoads` (default `true`), a saved-open branch whose
children aren't loaded is opened via `loadChildren` / `model`, one load at a
time, so a saved deep path cascades open. Set `restoreLoads = false` to only
re-open branches as the host loads them.

**Save while restoring.** `getViewState()` includes pending state by default,
and the pending scroll (not the current one) while a scroll restore is in
flight. Without this, a save during a streamed rebuild would overwrite the
stored state with a partial one.

---

## Adding view state to a component

1. **Types.** Declare `XxxViewState = ViewStateBase & { …own fields }` in the
   component's `types.ts` (or a `*-view-state.ts`), JSON-only (arrays /
   records, no Sets / Maps / class instances). Export it.

2. **Controller.** One field:

   ```ts
   #viewState = new VS.ViewStateController<XxxViewState>(this, {
     kind: `xxx`,
     capture: () => this.getViewState(),
   });
   ```

   `import * as VS from '../common/view-state/index.js';`

3. **Pending facets.** Hold pending state next to live state, using the pure
   helpers in `pending.ts` (`partitionKeys`, `partitionFlags`, `capKeys`,
   `flagsToRecord`, `keysToArray`…). Put reconcile logic in a pure function in
   its own module (`tree/tree-view-state.ts` is the reference) — the big
   components are already over the 1000-line budget.
   - Element lists: `ListSelectionController` already has pending keys —
     `restoreKeys()`, `resolvePending()`, `demote()`, `pendingKeys`,
     `clearPending()`. `reset()` demotes rather than forgets. Call
     `resolvePending()` after items are added / rebuilt, and `demote()` where
     removed items are pruned from the selection.

4. **Reconcile on data change.** Wherever the component learns its data
   changed (new `items` / `root`, added children, provider batch, lazy load),
   run reconcile inside `#viewState.restoring(() => …)`.

5. **Notify.** Call `#viewState.notify()` wherever user-visible state changes
   (selection dispatch, expand/collapse, column resize end, sort, scroll). It
   is cheap and debounced; inside `restoring()` it reports `restore`.

6. **Scroll.** After render: `observeScrollTarget(viewport)` once per viewport,
   call `notifyScroll()` from the viewport's `scroll` listener (it ignores
   scrolls while a restore is pending and labels the restore's own scroll),
   then `applyPendingScroll(s => …)` — return `true` only when the position was
   fully reached (anchor key rendered *and* content tall enough), so it is
   retried after the next batch. Use `captureElementScroll` /
   `restoreElementScroll` for DOM lists, `anchorFromRow` + `scrollToOffset`
   for virtualised lists with arithmetic geometry.

7. **Public API.** `getViewState(options)` builds the fields and passes them
   through `#viewState.shape(fields, options)`. `setViewState(state)` starts
   with `if (!this.#viewState.accepts(state)) return;`, then replaces each
   present field's pending state inside `restoring()` and reconciles.
   `clearPendingViewState()` empties pending facets and `pendingScroll`.

8. **Tests.** At minimum: restore before data; restore as data streams in;
   data reset keeps state; explicit selection drops pending selection;
   `getViewState()` includes pending; round-trip through `JSON.stringify`;
   wrong `kind` ignored.

---

## Component fields

| Component | `kind` | Fields |
|---|---|---|
| `ixfx-tree-list` | `tree-list` | `selected`, `expanded`, `focus`, `scroll` |
| `ixfx-vertical-list` | `vertical-list` | `selected`, `focus`, `scroll` |
| `ixfx-detail-list` | `detail-list` | `selected`, `expanded` (groups), `focus`, `scroll` |
| `ixfx-grid-list` | `grid-list` | `selected`, `expanded` (groups), `focus`, `scroll` |
| `ixfx-data-grid` | `data-grid` | `selected`, `expanded` (groups), `focus`, `scroll`, `columns`, `sort`, `groupBy` |
| `ixfx-multicol-list` | `multicol-list` | `columns`, `selectedByColumn`, `scrollByColumn` |
| `ixfx-miller-list` | `miller-list` | `selected`, `focus`, `path`, `columnWidths`, `columnScroll` |
| `ixfx-crumb-navigation` | `crumb-navigation` | `path` |
| `ixfx-flat-list` | `flat-list` | `path`, `selected`, `focus`, `scroll` (delegated to the inner list) |
| `ixfx-sunbursttree-list` | `sunbursttree-list` | `selected`, `focus`, `zoom` (key path) |
| `ixfx-icicletree-list` | `icicletree-list` | `selected`, `focus`, `zoom` (key path), `scroll` |
| `ixfx-treemap-list` | `treemap-list` | `selected`, `focus`, `zoom` (key path) |
| `ixfx-hyperbolictree-list` | `hyperbolictree-list` | `selected`, `focus`, `center` (key path), `zoom` (number) |
| `ixfx-split-layout` | `split-layout` | `layout` (by child `id`) |
| `ixfx-twosplit-layout` | `twosplit-layout` | `layout` (`a` / `b`) |
| `ixfx-dock-host` | `dock-host` | `layout` (`DockLayout`) |

User-facing guide and migration notes: [`list-state.md`](./list-state.md).

### Shared helpers

- `src/common/view-state/pending.ts` — pending key / flag sets.
- `src/common/view-state/tree.ts` — `reconcileSelection`, `reconcileExpansion`,
  `reconcileCursor`, `resolveKeyPath`, `pathFromJson` for tree-like components.
  Not exported from the package index.
- `ListSelectionController` (`src/interaction/`) — pending selection for element lists.

### Known gaps

- Components that hold a pending cursor / scroll anchor on a hidden item
  (filtered, collapsed group) mostly retry only when items are added.
- vertical-list, detail-list and data-grid report the scroll caused by their own
  restore as `user`; move them to `notifyScroll()`.
- `ixfx-panel-group` has no view state (its panels have no stable key).
