# Advanced window.clay

> Members on window.clay for plugin authors, custom editors, and code that runs inside the save and mode lifecycle.

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

For plugin authors, custom editors, and code that hooks into the save or mode lifecycle; for the everyday surface, see [window.clay](https://clayjs.com/docs/api/).

## Members

| Member | What it does |
| --- | --- |
| `clay.addDocumentTransform(fn, {required})` | Register a callback that receives the cloned document before serialization. The live page is never touched. Runs on every change check too, so keep it pure and repeatable (no timestamps, counters, or network). See below. |
| `clay.onSnapshot(fn, {required})` | Like `addDocumentTransform`, but runs for every snapshot, including live-sync broadcasts. See below. |
| `clay.markDirty()` | Tell live sync the person just edited something it cannot see: an editor whose own UI is `editor-ui` and which writes its data itself. Call it on each user edit. Without it, an edit made while an incoming update waits on a script or stylesheet load can be recorded as already saved. Present on every edit-mode page, and in view mode when `sync` is loaded. |
| `clay.modeLifecycle` | The edit-mode participants and the live mode facts: `register(participant)` returns an unregister function, `canWrite()` says whether a write is admitted now, and `state` is a frozen snapshot. See below. |
| `clay.derived` | The derived-paint policy: what a sapjs paint owns (`isDerivedAttr(el, name)`, `stripDerived(root)`) and the hook an engine registers to repaint after a merge. ClayJS uses it to leave painted values out of comparisons, undo and merges. Apps rarely call it. See [sap.js: records, views and totals in markup](https://clayjs.com/docs/guide/components/#sap-js-records-views-and-totals-in-markup). |
| `clay.Mutation` | The shared mutation hub (one MutationObserver for the whole page, region rules applied). `clay.Mutation.onAnyChange(opts, cb)` respects `clay="no-watch"` regions. See [Advanced](https://clayjs.com/docs/advanced/satellites/). |
| `clay.registerUnsavedState({id, isPending})` | For an editor whose work can be ahead of the page (its model not yet written into the DOM): `isPending()` is called fresh whenever the close warning checks, and the warning fires while it returns true. Returns `{changed(), dispose()}`; call `changed()` when the answer may have changed. |
| `clay.recovery` | The local recovery copy of unsaved writing: one store per document and mode, for the channels a page registers. Edit mode only, draft mode included. `register({channel, version, readSaved, describe})` returns a channel whose `stage`, `flush`, `list`, `dismiss`, `subscribe` and `dispose` work at once. See below and [recovery](https://clayjs.com/docs/recovery/). |
| `clay.region` | Region policy helpers and strip selectors (see clay.internals.region; the same object, also published as `STRIP_FROM_SAVE`-style constants). |
| `clay.editPlugins` | The frozen list of plugin names an edit session on this page would load, even while the page is in view. Chrome such as the menu reads it to offer an edit-only feature before the switch. |
| `clay.save.replace(html, {etag})` | One conditional write of a whole document this page did not build, the write an upgrade makes (upgrade plugin). See [conditional saves](https://clayjs.com/docs/conditional-saves/). |

### `clay.modeLifecycle`

`clay.mode`, `clay.isEditMode` and `clay.canEdit` are read-only getters over the live mode facts, so they follow a committed mode change. Assigning to one of them throws in strict code and is dropped in sloppy code.

`register(participant)` adds a participant and returns a function that unregisters it. A participant is `{id, order, prepare(context)}`: `id` is a required, unique string; `order` (default `0`) decides prepare order; and `prepare` returns a lease, or nothing to sit this transition out. `prepare` may fetch and build inert UI. The lease is `{ready, enable, quiesce, resume, dispose}`: an optional `ready` promise resolves once the participant can be enabled, `enable` is synchronous once every participant has prepared, `quiesce` stops new writes without losing buffers, `resume` brings the same lease back after a refused exit, and `dispose` runs only after a committed exit. `context` is `{generation, destination, signal, represented, reader, initial, isCurrent()}`: `represented` is the saved file the view session represents, with its `etag` and bytes, `reader` is that view session, and `initial` is true for the session this tab booted into. Check `isCurrent()` after each await and give up when it is false, because a stale preparation is thrown away. An `id` that starts with `clay:` belongs to ClayJS's own modules, and registering one throws a `TypeError`.

Registering throws `TypeError` for a missing `id` or `prepare`, for an `id` already registered, and whenever the page is not idle in view: a participant registers in view mode, before the mode it joins. Registering never loads the controller. A script that has to register before ClayJS boots pushes the participants onto `window.clay.modeParticipants` (creating that array), and the queue is drained when an explicit edit starts.

`canWrite()` is whether a write is admitted right now: no transition is running and this tab is in edit mode (draft mode included). `state` is frozen and holds `{mode, phase, destination, generation, reason}`: `phase` is `"idle"` between transitions, `"entering"` or `"leaving"` during one, and `"blocked"` when entering edit failed; `destination` is where edits land, `"draft"` in draft mode, `"demo"` when the demo plugin saves to `localStorage`, and `"host"` otherwise; `generation` counts committed transitions; and `reason` is the code of the last refusal, or `null`. `clay:modechange` fires on `document` after a committed change. A declared document, `<html clay-mode-switch="live">`, switches live, so `clay.setMode` commits with no reload there; an undeclared document saves, writes the receipt and reloads. See [switching modes](https://clayjs.com/docs/guide/edit-mode/#switching-modes-clay-setmode).

### `clay.addDocumentTransform(fn, {required})` and `clay.onSnapshot(fn, {required})`

If a registered callback throws before it changes the clone, ClayJS logs the error once and continues the save without that callback. If it changed the clone and then threw, the capture stops, so its half-done changes are never saved. Pass `{ required: true }` when a failure must stop the capture instead of saving incomplete HTML. Throwing an error with a string `code` property also stops the capture.

```js
clay.addDocumentTransform((root) => {
  for (const el of root.querySelectorAll("[data-private]")) el.remove();
}, { required: true });
```

### `clay.recovery`

A copy of writing the host has not accepted, kept in this browser, so a reload has something to offer. It is not a save: a completed write means this browser kept a copy, and ClayJS never renders a page from it. Absent in view mode, where a reader opens no database. A document is covered only for the channels its adapters register; there is no whole-body observer serializing the page after every edit.

```js
const entries = clay.recovery.register({
  channel: "journal.entries",
  version: 1,
  readSaved(html) {
    const doc = new DOMParser().parseFromString(html, "text/html");
    return new Map([...doc.querySelectorAll("#entries > article.entry")]
      .map((el) => [el.dataset.id, el.querySelector(".entry-body")?.textContent ?? ""]));
  },
  describe(record) {
    return { label: record.key, text: record.payload };
  }
});

const { id, revision } = entries.stage({ key: entryId, baseEtag, base: savedText, payload: textarea.value });
const receipt = await entries.flush();
```

| Call | Resolves |
|---|---|
| `clay.recovery.register(spec)` | a channel, synchronously; registering one channel twice throws |
| `stage({ key, kind, baseEtag, base, payload, lineage })` | `{ id, revision }`, synchronously, not a durable receipt |
| `flush()` | `{ ok: true, stored: [{ id, revision }] }` after the transaction completes, or `{ ok: false, code }` |
| `list()` | `{ ok, records, status }` |
| `dismiss(id, { revision })` | `{ ok: true, id, revision }`, or `code: "stale"` when a newer revision landed since |
| `subscribe(fn)` | an unsubscribe. Detail is `{ channel, status, count, revisions }`, never payloads |
| `dispose()` | a best-effort flush; listeners released, records kept |
| `clay.recovery.status()` | `{ ok, code, durable, usage, identityMismatch }` |
| `clay.recovery.subscribe(fn)` | an unsubscribe, for the same detail on every channel registered here |

`code` is `unavailable`, `blocked`, `quota`, `over-budget`, `unknown-schema`, `aborted`, `uncloneable`, `stale`, `missing`, `invalid` or `error`. `durable` is `false` until a transaction completes, and a page must never present memory as a durable copy. A save clears a revision only when its own capture's bytes cover it: a skipped save, a refusal, a conflict, an error and an unknown outcome clear nothing. [Recovery](https://clayjs.com/docs/recovery/) covers the store's scope, its 32 MiB per document and 64 MiB per database limits, privacy, and the difference between journaled, acknowledged and checkpointed.
