# Saving and restoring list state

The list, tree, grid and layout components can give you a snapshot of their
*view state*: what the user has done to them, as opposed to the data you gave
them. That covers:

- which items are selected (or checked)
- which tree branches and groups are open or collapsed
- where the list is scrolled to
- where the keyboard cursor is
- column widths, column order, column visibility and sort, in grids
- panel sizes and arrangement, in layouts

You give the component data. The component keeps track of the view state.
When you want that state to survive (a reload, a route change, a data
refresh), ask for a snapshot and hand it back later.

The components never store anything themselves. Where the snapshot goes
(localStorage, a URL, a server, nowhere) is up to you.

Internal design notes for component authors are in
[`infra-view-state.md`](./infra-view-state.md).

---

## Quick start

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

const tree = document.querySelector(`ixfx-tree-list`)!;

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

tree.root = await fetchTree(); // before or after, it doesn't matter
```

That's all. `bindViewState`:

1. calls `load()` once and applies the result,
2. calls `save()` after each change (debounced, about 150 ms after the user stops),
3. calls `save()` again when the page is hidden (`pagehide`), so the last change isn't lost.

It returns a function that stops saving:

```ts
const stop = bindViewState(el, { load, save });
// later
stop();
```

If `load()` throws (bad JSON, say), it logs a warning and carries on with no
saved state.

---

## Doing it by hand

Every view-stateful component has the same three methods and one event:

```ts
const state = el.getViewState();   // plain JSON object
el.setViewState(state);            // apply it, any time

el.addEventListener(`view-state-change`, (e) => {
  e.detail.state;   // the full current state
  e.detail.reason;  // 'user' | 'data' | 'restore'
});

el.clearPendingViewState();        // see "Pending state" below
```

### `getViewState(options?)`

Returns a plain object you can pass straight to `JSON.stringify`. It contains
only arrays, records, strings, numbers and booleans.

```ts
el.getViewState();                                  // everything
el.getViewState({ include: [`columns`, `sort`] });  // only some fields
el.getViewState({ includePending: false });         // only what's live now
```

`includePending` defaults to `true`, which is almost always what you want; see
[Pending state](#pending-state).

### `setViewState(state)`

- Can be called before the component has any data, before it's connected, or
  at any point afterwards.
- Accepts a **partial** state. Fields you include replace the current value,
  and fields you leave out are untouched:

  ```ts
  el.setViewState({ selected: [`invoice-42`] });   // only changes the selection
  ```

- Ignores state meant for a different component, or from a different schema
  version, and logs a warning. Feeding a data-grid's saved state into a tree
  does nothing.

### `view-state-change`

Fired after changes, debounced. It bubbles, but is **not** composed: it won't
escape the shadow root of a component that contains it. Listen on the
component itself.

`reason` tells you what caused the change:

| `reason` | Meaning |
|---|---|
| `user` | The user clicked, typed, dragged or scrolled. |
| `data` | You changed the data and the component adjusted. |
| `restore` | Saved state was applied, either by `setViewState()` or because a matching item just arrived. |

When several things happen inside one debounce window, the strongest reason
wins (`user` > `data` > `restore`). `bindViewState` skips `restore` events by
default, because they only echo what you just loaded. Pass
`saveOnRestore: true` if you want them saved too.

---

## Key ideas

### Everything is keyed

State refers to items by **key**, never by position: `item.key` for trees,
`data-key` (or `data-value`) for element lists, the row key in data-grid, the
column `key` or `id`, the group key, the panel id. That's what lets saved state
survive sorting, filtering, inserting, and rebuilding the data from scratch.

**Your items need stable keys.** An item without a key can't be restored. In
data-grid, rows without a `key` or `id` fall back to their row index, and those
index keys are deliberately never saved. Give rows real keys, or a stable
`getRowKey`.

### Pending state

When saved state names a key that isn't in the current data, the component
**keeps it pending** and applies it as soon as an item with that key appears.

This means you don't have to wait until all your data has loaded before
restoring:

```ts
tree.setViewState({ expanded: { A: true, B: true, C: true } });

tree.root = rootWith(A);                     // A opens
// … later
addChild(A, B); tree.invalidateStructure();  // B opens
// … later
addChild(B, C); tree.invalidateStructure();  // C opens
```

It also works the other way. When your data changes and an item disappears,
its state isn't thrown away; it goes pending. If the item comes back, so does
its state:

```ts
list.setItems(page1);     // user selects 'x'
list.clearItems();        // 'x' is gone, so its selection is pending
list.setItems(page1);     // 'x' is selected again
```

`getViewState()` includes pending state by default. If you save mid-reload,
you get the full saved state, not just the part that has loaded so far.

Pending state is dropped when:

| State | Pending entries are dropped when… |
|---|---|
| selection | the selection changes in any other way: a click, a key, `select…()`, `clearSelection()`. An old saved selection never merges into a new one. |
| expanded / collapsed | never on their own. Each key is tracked separately, so collapsing `A` doesn't forget that `C`, below it, was open. |
| scroll | the user scrolls (wheel, touch, drag, arrow or page keys), or the saved position has been reached. |
| keyboard cursor | the cursor moves. |
| anything | you call `setViewState()` with that field, or `clearPendingViewState()`. |

Each kind of pending state is capped at 2,000 keys, and the oldest are dropped
first.

### Selection events

When pending selection is applied because its item arrived, the component
fires its **normal selection event** (`select`, `list-select`,
`datagrid-select`, and so on), so your selection handlers run as usual. Where
the event has an `origin` field, it is `'programmatic'`.

When a selected item *leaves* the data, it is deselected **silently**, with no
event, and its key goes pending.

### Scroll

Scroll is saved as the **key of the first visible item plus a pixel offset**,
along with the raw pixel position as a fallback:

```json
{ "top": 4820, "anchor": { "key": "row-311", "offset": 12 } }
```

When restored, the component waits until that item exists and there's enough
content to scroll to, then scrolls there. If the user scrolls first, the saved
position is dropped, because the user's scroll wins.

### Keyboard cursor

`focus` is only recorded when the cursor was moved with the keyboard. Mouse
hover isn't saved. Restoring `focus` puts the component in keyboard mode, so
the cursor is visible.

### Lazy trees

`ixfx-tree-list` has a `restoreLoads` property, which defaults to `true`. If a
saved-open branch hasn't loaded its children, the tree loads them through
`loadChildren` / `model`, one branch at a time, so a saved deep path opens all
the way down. That can mean several requests in a row. Set
`tree.restoreLoads = false` if you'd rather only re-open branches as you load
them yourself.

---

## Component reference

| 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` |
| `ixfx-sunbursttree-list` | `sunbursttree-list` | `selected`, `focus`, `zoom` |
| `ixfx-icicletree-list` | `icicletree-list` | `selected`, `focus`, `zoom`, `scroll` |
| `ixfx-treemap-list` | `treemap-list` | `selected`, `focus`, `zoom` |
| `ixfx-hyperbolictree-list` | `hyperbolictree-list` | `selected`, `focus`, `center`, `zoom` |
| `ixfx-split-layout` | `split-layout` | `layout` |
| `ixfx-twosplit-layout` | `twosplit-layout` | `layout` |
| `ixfx-dock-host` | `dock-host` | `layout` |

Each component's README has a "View state" section with details.

### Shared fields

| Field | Type | Notes |
|---|---|---|
| `v` | `1` | Schema version. |
| `kind` | `string` | Which component the state is for. |
| `selected` | `string[]` | Selected keys. In `checked` interaction mode this is the checked set. |
| `expanded` | `Record<string, boolean>` | Only explicit choices are recorded, and a missing key means "default". Tree branches default to closed, so open ones are `true`. Groups default to open, so collapsed ones are `false`. |
| `focus` | `string` | Keyboard cursor key. |
| `scroll` | `{ top, left?, anchor?: { key, offset } }` | See [Scroll](#scroll). |

### `ixfx-data-grid` extras

```ts
{
  columns: { [columnKey]: { width?: number; visible?: boolean; order?: number } },
  sort: { key: string; direction: 'asc' | 'desc' } | null,
  groupBy: string | null,   // only when allowGrouping is on; a function groupBy is never saved
}
```

- A saved width or visibility is applied when the column first appears. If you
  redefine that column afterwards, your definition wins.
- A column you remove keeps its saved width and visibility pending, ready for
  when it comes back.
- A saved `order` places the columns it names; other columns stay where they are.

### `ixfx-multicol-list` extras

```ts
{
  columns: MulticolColumnState[],            // display order: { id, categoryKey, sort, grouped, menu?, width? }
  selectedByColumn: { [columnId]: string[] }, // missing or [] means 'All'
  scrollByColumn: { [columnId]: ScrollState },
}
```

A saved column whose category isn't in `categories` yet is inserted at its
saved position once that category appears.

### `ixfx-miller-list` extras

```ts
{
  path: string[],                              // key of the open branch at each depth, column 0 first
  columnWidths: { [depth: string]: number },   // px
  columnScroll: { [parentKey: string]: ScrollState },  // only scrolled columns; column 0 uses the view root's key
}
```

- `path` is relative to the current view root, which isn't saved. A saved path
  only matches when restored under the same view root.
- `restoreLoads` (default `true`) opens a saved path through unloaded branches
  one load at a time.
- Any explicit navigation (click, arrow keys, Escape, `navigateTo`,
  `revealKey`, rebasing) drops a pending path.

### `ixfx-crumb-navigation` extras

```ts
{
  path: string[],   // keys from the root down to the current location
}
```

- The location *is* the selection, so there's no separate `selected`.
- With a pending path, the crumb moves to the deepest loaded ancestor and keeps
  going as data arrives, firing `select` at each step. With `restoreLoads` it
  calls `loadChildren` itself.
- Setting `selectedNode` counts as an explicit move and drops a pending path.
  **Set the initial `selectedNode` before calling `setViewState` /
  `bindViewState`**, or it will override what you restore.

### `ixfx-flat-list` extras

```ts
{
  path: string[],   // the folder being shown
  // selected / focus / scroll apply to the level at `path`
}
```

A saved path through lazy levels loads one level at a time, because showing a
level loads it. If new data removes the level being shown, the list steps up
and that level, with its selection, goes pending.

### `ixfx-sunbursttree-list` and `ixfx-icicletree-list` extras

```ts
{
  zoom: string[],   // key path from the root's children to the zoomed-in node; [] = whole tree
}
```

- `zoom` is a path so a lazy tree can be loaded down to it. `restoreLoads`
  (default `true`) loads the path one level at a time.
- A restored zoom fires `zoom` and `expand`, just like a user's zoom.
- Any explicit zoom (click, `zoomTo`, `navigateTo`, Escape, crumbs) drops a
  pending one.
- The icicle also saves `scroll`, as plain `top` / `left` pixels with no anchor.
- The sunburst only needs keys to be unique among siblings, so a restored
  `selected` key that repeats in several folders matches the first one,
  depth-first.

### `ixfx-treemap-list` extras

```ts
{
  zoom: string[],   // key path from the root's children to the zoomed-in node; [] = whole tree
}
```

There's no `expanded`, because zooming takes its place, and no `scroll`,
because the treemap fills its box. Like the tree, it has `restoreLoads`
(default `true`): a deep saved zoom loads each ancestor in turn. A restored zoom
fires `zoom`, not `expand`, and doesn't animate.

### `ixfx-hyperbolictree-list` extras

```ts
{
  center: string[], // key path from the root's children to the centred node; [] = root
  zoom: number,     // magnification
}
```

- `center` is a **path**, not a single key, because keys may repeat across
  branches in this component. Saving the path keeps the right node.
- Free panning and disk rotation **aren't saved**. They're raw geometry that
  stops making sense when the data changes, so a restored view sits exactly on
  `center`.
- `restoreLoads` (default `true`) loads the path one level at a time.
- A restored centre fires `focus`, not `expand`, and snaps instead of animating.

### `ixfx-split-layout` extras

```ts
{
  layout: { [childId]: { weight: number; collapsed?: boolean } },
}
```

- `weight` is the child's share (0 to 1) of the resizable space. For a
  collapsed child it's the share it expands back to.
- **Only direct children with an `id` you set are saved.** Generated ids
  (`p-1`, `g-2`) depend on position, so they'd apply sizes to the wrong child.
  Give every child you want remembered an `id`.
- A nested `ixfx-split-layout` is saved as one entry. Its own children are in
  its own view state, so bind it separately.
- Sizes for a child that isn't slotted yet are applied when a child with that
  id appears. A child that's removed keeps its size pending, so re-adding it
  restores the size.
- Set the `forget-absent` attribute to turn pending off, so children that leave
  are forgotten.

### `ixfx-twosplit-layout` extras

```ts
{
  layout: { a?: { size: string; collapsed?: boolean }, b?: { size: string; collapsed?: boolean } },
}
```

This view-state `layout` field has nothing to do with the `layout`
(orientation) attribute.

### `ixfx-dock-host` extras

```ts
{
  layout: DockLayout,   // the whole tree: splits, stacks, sizes, active tabs, collapse
}
```

- A panel id that's saved in the layout but hasn't been added yet keeps its
  place. It shows as a placeholder tab until the panel arrives, and
  `addPanel()` without a target then puts it there.
- Closing or removing a panel takes it out of the layout. Its place isn't
  remembered.
- `clearPendingViewState()` does nothing on the dock, because placeholders are
  part of the layout. Use `removePanel(id)` to drop one.
- `setViewState()` before the dock is connected wins over a `layout` attribute.

---

## Porting from the old APIs

### Removed methods

| Component | Old | New |
|---|---|---|
| `ixfx-multicol-list` | `el.columns` (getter) | `el.getViewState().columns` |
| `ixfx-multicol-list` | `el.setColumns(states)` | `el.setViewState({ columns: states })` |
| `ixfx-miller-list` | `el.getConfig()` / `el.setConfig({ columnWidths })` | `el.getViewState().columnWidths` / `el.setViewState({ columnWidths })`. Same shape. The `MillerConfig` type is gone too. |
| `ixfx-split-layout` | `el.getLayout()` / `el.setLayout(snapshot)` | `el.getViewState().layout` / `el.setViewState({ layout })`. **The shape changed**; see below. |
| `ixfx-dock-host` | `el.saveLayout()` / `el.loadLayout(layout)` | `el.getViewState().layout` / `el.setViewState({ layout })`. Same `DockLayout` shape as before. |

`ixfx-tree-list`'s `getConfig()` / `setConfig()` is **not** removed. It only
holds display configuration (`indent`), not view state.

**Saved data from the old APIs is not read by the new ones.** If you have
stored layouts or configs you need to keep, convert them once on load:

```ts
// multicol-list: an old saved `columns` array
const old = JSON.parse(localStorage.getItem(`multicol-columns`) ?? `null`);
if (Array.isArray(old))
  el.setViewState({ columns: old });   // same shape as before
```

```ts
// miller-list: an old saved MillerConfig
const oldMiller = JSON.parse(localStorage.getItem(`miller-config`) ?? `null`);
if (oldMiller?.columnWidths)
  miller.setViewState({ columnWidths: oldMiller.columnWidths });
```

```ts
// dock-host: an old saved DockLayout is already the right shape
const oldDock = JSON.parse(localStorage.getItem(`dock-layout`) ?? `null`);
if (oldDock)
  dock.setViewState({ layout: oldDock });
```

```ts
// split-layout: an old LayoutSnapshot ({ root: { kind, id, weight, collapsed, children } })
// becomes a record of the layout's direct children
const snap = JSON.parse(localStorage.getItem(`split-layout`) ?? `null`);
if (snap?.root?.children) {
  const kids = snap.root.children;
  const total = kids.reduce((sum, c) => sum + (c.weight ?? 1), 0) || 1;
  const layout = Object.fromEntries(kids.map(c =>
    [c.id, { weight: (c.weight ?? 1) / total, ...(c.collapsed ? { collapsed: true } : {}) }]));
  split.setViewState({ layout });
}
```

Check the result for split-layout: the new state keeps only children that have
an `id` you gave them (see below), and weights are shares of the resizable space.

### Replacing hand-rolled persistence

The common old pattern was to save on some event and restore with a setter:

```ts
// Before
const saved = localStorage.getItem(`miller-config`);
if (saved) el.setConfig(JSON.parse(saved));
el.addEventListener(`pointerup`, () =>
  localStorage.setItem(`miller-config`, JSON.stringify(el.getConfig())));
```

```ts
// After
bindViewState(el, {
  load: () => JSON.parse(localStorage.getItem(`miller-state`) ?? `null`),
  save: s => localStorage.setItem(`miller-state`, JSON.stringify(s)),
});
```

The new version also saves selection, expansion, cursor and scroll, and it
saves after keyboard changes and on `pagehide`, which `pointerup` missed.

### Re-selecting after a data refresh

You no longer need to remember the selection yourself across a data refresh:

```ts
// Before
const keep = [...list.selectedKeys];
list.setItems(fresh);
list.selectKeys(keep);
```

```ts
// After
list.setItems(fresh);   // selection for keys still present (or returning later) is kept
```

The same applies to replacing `tree.root`. Selection, expansion and cursor
carry over for every key the new root still has.

If you want the *old* behaviour, where a refresh clears everything, ask for it
explicitly:

```ts
list.setItems(fresh);
list.clearPendingViewState();
list.clearSelection();
```

### Behaviour changes to check

These used to work differently. If your code relied on the old behaviour,
adjust it.

| Component | Before | Now |
|---|---|---|
| `ixfx-tree-list` | Assigning a new `root` cleared the selection and keyboard cursor. | Selection and cursor are kept for every key the new root still contains. Others go pending. |
| `ixfx-tree-list` | Expansion for a key that disappeared and came back was forgotten. | It comes back open. |
| `ixfx-tree-list` | Selection held references to the old root's nodes after `root` was replaced. | Selection is re-matched by key onto the new root's nodes. |
| `ixfx-vertical-list` | `removeItem()` on a selected item fired `list-select`. | It deselects silently, and the key goes pending. |
| `ixfx-vertical-list`, `ixfx-detail-list` | A selected element removed straight from the DOM stayed in the selection as a stale reference. | It's dropped from the selection, and its key goes pending. |
| `ixfx-detail-list`, `ixfx-vertical-list` | `clearItems()` followed by `setItems()` lost the selection. | Matching keys are re-selected. |
| `ixfx-grid-list` | Items leaving `items` / `removeItems()` fired one `list-select`. | They're deselected silently, and their keys go pending. `clearItems()` still fires its empty `list-select`. |
| `ixfx-grid-list` | | A saved selection for an item that's filtered out or inside a collapsed group stays pending until the item is shown. |
| `ixfx-data-grid` | Keys of rows removed from `rows` stayed in `selectedKeys`. | They're deselected silently and go pending, and they're re-selected (with `datagrid-select`) if the rows return. |
| `ixfx-data-grid`, `ixfx-tree-list`, lists | A cursor on a removed item was left dangling. | The cursor is cleared. If it was a keyboard cursor, it comes back when the item does. |
| `ixfx-miller-list` | Assigning a new `root` cleared the selection and the open columns. | The open path, selection and cursor carry over by key; missing keys go pending. |
| `ixfx-miller-list` | `invalidateStructure()` left removed nodes selected or open. | Removed parts close or deselect, and come back if their keys reappear. |
| `ixfx-crumb-navigation` | A new `root` without the current location left it pointing at a missing node. | It steps back to the closest ancestor silently, and returns if the key reappears. |
| `ixfx-flat-list` | A `path` set before its data loaded was cut short for good. | It waits, and extends as the data arrives. |
| `ixfx-icicletree-list` | Assigning a new `root` reset selection, zoom and cursor. | They're kept by key; missing ones go pending. |
| `ixfx-sunbursttree-list`, `ixfx-icicletree-list` | A zoom node that disappeared fell back to the whole tree for good. | It still falls back, but the zoom comes back if the node does. |
| `ixfx-treemap-list` | Assigning a new `root` cleared selection, zoom and cursor. | They're kept by key; missing ones go pending. |
| `ixfx-hyperbolictree-list` | Assigning a new `root` / `model` reset selection, cursor and centre. | They're kept by key. If the centred node survives, so do pan and rotation; if not, the view returns to the root and the centre goes pending. |
| `ixfx-split-layout` | Adding, removing or collapsing a child re-read every size from the DOM attributes, which reset sizes the user had dragged. | Sizes the user dragged are kept. The DOM only wins when a `size` / `weight` / `sizes` / `fixed` / `collapsed` attribute actually changes. |
| `ixfx-split-layout` | (README described `storage-key` persistence.) | That was never implemented and has been removed from the README. Use `bindViewState`. |
| `ixfx-dock-host` | `addPanel(el)` with no target always added to the first stack. | If the panel's id has a saved place, it goes there. |
| `ixfx-multicol-list` | `setColumns()` dropped columns whose category didn't exist. | They stay pending and appear when the category does. |

"Deselected silently" means your selection handler won't run when an item
leaves the data. If you mirror the selection elsewhere, read `selectedKeys`
after changing the data, or listen for `view-state-change`.

---

## Recipes

### Several components, one storage entry

```ts
const KEY = `workspace`;
const saved = JSON.parse(localStorage.getItem(KEY) ?? `{}`);
const parts = { tree, grid, layout };

for (const [name, el] of Object.entries(parts)) {
  bindViewState(el, {
    load: () => saved[name],
    save: (s) => {
      saved[name] = s;
      localStorage.setItem(KEY, JSON.stringify(saved));
    },
  });
}
```

### State per dataset

Keys are only meaningful within one dataset, so include the dataset in your
storage key:

```ts
bindViewState(grid, {
  load: () => JSON.parse(localStorage.getItem(`grid:${projectId}`) ?? `null`),
  save: s => localStorage.setItem(`grid:${projectId}`, JSON.stringify(s)),
});
```

### Saving only some of it

```ts
bindViewState(grid, {
  load: () => JSON.parse(localStorage.getItem(`grid-columns`) ?? `null`),
  save: () => localStorage.setItem(`grid-columns`,
    JSON.stringify(grid.getViewState({ include: [`columns`, `sort`] }))),
});
```

### State in the URL

```ts
const fromUrl = new URLSearchParams(location.search).get(`sel`);
if (fromUrl)
  list.setViewState({ selected: fromUrl.split(`,`) });

list.addEventListener(`view-state-change`, (e) => {
  const url = new URL(location.href);
  url.searchParams.set(`sel`, (e.detail.state.selected ?? []).join(`,`));
  history.replaceState(null, ``, url);
});
```

### Reset to defaults

```ts
el.clearPendingViewState();
el.setViewState({ selected: [], expanded: {} });
localStorage.removeItem(`files-tree`);
```

---

## Caveats

- **Stable keys are required.** Items without a key (or with index-based keys)
  can't have their state restored.
- **No `origin` on some events.** The treemap's and hyperbolic tree's `select`
  events have no `origin` field, so a restored selection can't be told apart
  from a user's there. Use `view-state-change`'s `reason` instead.
- **Key collisions.** Tree keys must be unique across the whole tree. If a node
  moves to a different parent with the same key, its open/selected state moves
  with it.
- **Lazy restore makes requests.** With `restoreLoads`, restoring a deep tree
  makes one `loadChildren` call per saved-open branch, one after another.
- **Hidden items.** A cursor or scroll anchor on an item that's filtered out or
  inside a collapsed group stays pending until the item is visible again. Some
  components only retry when items are added, not when a filter is lifted.
- **Uniform row heights.** The tree's scroll anchor assumes rows are all the
  same height, as its virtualisation already does.
