# Advanced undo

> Undo recording modes, mode-lifecycle sessions, kept recovery copies, and protected subtrees for custom editors and plugins.

Source: https://clayjs.com/docs/advanced/undo/

For custom editors, plugins, and apps managing command-only recording or recovery review actions; for everyday undo and redo, see [undo](https://clayjs.com/docs/plugins/undo/).

## Recording modes

`clay.undo.setRecording("automatic")` records every mutation the page makes. It is the default. Writes made within 500 ms of each other are coalesced into one step labelled `"Edit"`, so typing a sentence is a single undo.

`clay.undo.setRecording("commands")` records nothing on its own. Only a write bracketed by `clay.undo.command(label, fn)` earns a step. Everything else still changes the document, and a later replay sees those changes, but none of it appears in history:

- A live sync merge
- A derived paint, such as the attributes sapjs keeps up to date
- A sortable gesture's bookkeeping on the item it holds
- A late answer whose callback writes after its `await`

Switching modes is a boundary, not a merge: a change to or from edit ends the history, and the recording mode is carried across it, so a page set to `"commands"` is still `"commands"` after the next entry ([Across a mode change](#across-a-mode-change)). `setRecording` accepts only `"automatic"` or `"commands"`, and throws for anything else.

`clay.undo.ignoreAttribute(name)` keeps one of the page's own attributes outside history: it is saved like any attribute, but a change to it is never an edit, and a replay never compares it. Use it for maintenance values the page rewrites itself, such as a card number a repair reassigns, so that repair never makes an undo or redo refuse. It returns a function that removes the registration.

## Across a mode change

`undo` is a participant of the mode lifecycle, with the id `clay:undo` and order 350. [Switching without a reload](https://clayjs.com/docs/guide/edit-mode/#switching-without-a-reload-clay-mode-switch-live) describes how a participant is prepared, and [Leaving edit](https://clayjs.com/docs/guide/edit-mode/#leaving-edit) how an exit refuses.

History belongs to one edit session. A session starts its own over the page as it stands, so nothing an earlier session recorded is this one's to undo, and the commit that ends a session stops its recording. A mode change therefore ends the history, and `clay:undo-change` reports `canUndo: false` with it.

The recording mode is the page's choice and is not part of the session, so it survives: a page that asked for `"commands"` records commands after the next entry without asking again. The kept copies a page recorded are also outside the sessions, and outlive every one of them.

## Recovery

History belongs to this tab and this editing session, so a reload starts with nothing to undo. What a reload can still show is the losing side as plain data, kept on one internal channel of the [recovery store](https://clayjs.com/docs/recovery/) and never rendered back into the page. Nothing kept here is a save.

**A refused step is kept for you.** When an undo or redo refuses, ClayJS writes the step's description into the store: the entry id, its label, the direction, the code, every target, and each step's before and after. The receipt and `clay:undo-refused` go out first and the copy is made behind them, so a store that is slow, full or unavailable can never hold up the refusal; the step is still on top of this tab's stack either way. `clay:undo-kept` fires on `document` once the copy is settled:

```js
document.addEventListener("clay:undo-kept", (event) => {
  // { ok: true, entryId, direction }
  // { ok: false, code, entryId, direction } - the store wrote nothing
});
```

One record is kept per step and direction, under `refused:<entryId>:<direction>`: refusing the same step again replaces its copy, and the older one leaves only once the newer copy is durable, at the revision this tab can see. A refused record is never the kind a save covers, so a normal save dismisses nothing here.

**The page's own material.** A step nobody can replay is one kind of loss. Another is writing with nowhere left to go, such as a card another tab deleted while this one was typing in it. `clay.undo.keep` writes the page's own copy into the same store, and nothing else decides what that copy holds:

```js
const written = await clay.undo.keep({
  key: `card:${id}`,
  label: saved.title,
  context: { kind: "card", id, label: saved.title },
  payload: {
    text: [saved.title, ...drafts.map((d) => `${d.name}: ${d.text}`)].join("\n"),
    card: { title, desc, comment, listId },
  },
});
if (!written.ok) return;   // the drafts stay exactly where they are
for (const draft of drafts) clay.unsent.drop(draft.record, draft.name);
```

- `key` names the material, not the record it came from: one key holds one copy, so keeping the same key again replaces the earlier one. It is stored under `app:<key>`.
- `payload.text` is what the review panel quotes under Yours, and it is the difference between the two kinds a record can be: a copy holding one is staged as a text copy, one without it as a conflict copy. This channel reads no saved bytes, so no save clears either kind: a copy leaves when a person dismisses it, or when the page removes it once something durable covers it.
- `context` is `{ kind, id, label, field }` and is what names the material in the panel. A resolver registered with `clay.conflicts.registerContext` names it again in a later session.
- `written` is `{ ok: true, stored }`, where `stored` holds the `{ id, revision }` the copy was written at, or `{ ok: false, code }` when the store refused the write. The copy stays in memory either way, so this tab can still show it, but a reload would lose it: say so and keep offering the text some other way.
- `clay.undo.kept()` is what a later session reviews: `{ ok, records }`, with one `{ id, key, kind, revision, payload, supported }` per copy from every writer of this document, not only this tab. The label and the context a copy was kept with are inside its `payload`.
- `clay.undo.dismissKept(id, { revision })` removes one copy at the revision the reviewer was looking at. A copy another tab replaced since then is left exactly as it is, with `{ ok: false, code: "stale" }`.

**A review action the page offers.** `clay.undo.reviewActions(fn)` registers a provider that is asked about every record the review panel draws, and each action it returns becomes a button on that row. The panel never learns what a card is, and a provider that throws costs its own buttons only. The call returns a function that unregisters it:

```js
const unregister = clay.undo.reviewActions((record) => {
  const card = record?.payload?.card;
  if (!card || !String(record.key ?? "").startsWith("app:card:")) return [];
  return [{ label: "Keep as new card", run: () => keepAsNewCard(record) }];
});
```

An action's `run` may be async and answers `{ ok, dismiss }`. The panel dismisses a row only for `{ ok: true, dismiss: true }`, and only at the revision the row was drawn at. An action that removes its own record returns `{ ok: true, dismiss: false }`: that says the record is already gone, so the panel must not dismiss it a second time at a revision that no longer exists. Any other answer dismisses nothing and leaves the copy where it is. Either way the panel re-reads the store afterwards, so a row whose record your action removed goes by itself, and a failed one stays where it was.

```js
async function keepAsNewCard(record) {
  const kept = record.payload.card;
  const made = clay.undo.command("Keep as new card", () => {
    const card = makeCard(kept.title, freshId(), kept.desc);
    list.querySelector(":scope > ol.cards").prepend(card);
    return card;
  });
  if (!made) return { ok: false };
  const saved = await clay.save.flush();
  if (saved.state !== "saved" && saved.state !== "clean") return { ok: false };
  const cleared = await clay.undo.dismissKept(record.id, { revision: record.revision });
  return { ok: !!cleared.ok, dismiss: false };
}
```

The copy is made by one command, so it is one labelled step, and it leaves only after `clay.save.flush()` has had the host accept the new card's bytes: until then it is the only place that writing exists, and a save that failed or did not cover it leaves it reviewable.
