# blockeditor

> The block editor plugin: one article[data-blockeditor] as a live, collaborating page.

Source: https://clayjs.com/docs/plugins/blockeditor/

Before ClayJS 1.24.0 this plugin was named `page`; `?plugins=page` no longer loads it.

The blockeditor plugin turns a single `article[data-blockeditor]` into a collaborating page inside the block editor. It loads by name, and in edit mode brings `live`, `sync`, `upload`, `wire` and `ai-edit` with it. In view mode it brings its reader half only.

## What it does

The blockeditor plugin opens one `article[data-blockeditor]` with one `merge="blockeditor" clay="live"` Yjs store in the block editor. It loads in edit mode and requires a host that advertises the `blockeditor` extension. Without that extension, the saved article stays readable. `clay.blockeditor.flush()` waits for its edits to reach a checkpoint. Image and file blocks store their files through `clay.upload`, and on a host that stores no files the editor offers to embed them instead. In view mode the loader adds its reader half, `blockeditor-view`, by itself, so a reader's article follows each saved file without a reload; no URL names it.

## Writing in the page editor

The page editor is built for everyday writing: one document title, Markdown shortcuts you can take back with one Backspace, a toolbar that fits a phone, and a keyboard route in and out of it. Desktop toolbars, the saved formats and the collaboration model are unchanged.

### One title, derived or custom

A page's title comes from its content. The rule is the first top-level H1 in the page: its text with whitespace runs collapsed and trimmed. A page with no top-level H1 is `Untitled`. An H2, a heading inside a toggle or a list item's heading is not the title.

The same rule writes `<title>`, so the tab, the search result and the file all say the same thing, and the save projection and a server checkpoint derive it from the same captured model. A title derived at save time cannot describe content other than the bytes saved beside it.

A custom title opts out. `<meta name="clay-seo-title-mode" content="custom">` in `<head>` keeps the authored `<title>` exactly as written, and the SEO panel's title field is what writes that marker. Remove the marker and the next save derives the title again. Two ownership rules follow:

- **Derived is the default.** An H1 you rename renames the document.
- **Custom is explicit.** Nothing derived ever overwrites a custom title, and a custom title is never invented from a heading.

The file's name is not part of this. ClayJS never renames a document from its title: the host's route, the downloaded file name and the path in a local folder stay what they were. A title is content, not identity.

### Markdown shortcuts, one Backspace away

Typed at the start of a block:

| Typed | Becomes |
|---|---|
| `# `, `## `, `### ` | heading 1, 2 or 3 |
| `- `, `* `, `+ ` | bulleted list item |
| `1. ` or `1) ` | numbered list item |
| `[] `, `[ ] `, `[x] ` | checklist item, unchecked or checked |
| `> ` | toggle |
| ` ``` ` | code block (the whole paragraph) |
| `---` | divider |

The block keeps its id, its position and its parent: the shortcut retypes the block, it does not delete one and insert another, so a peer's edit to the same block is not thrown away and the change is one undo step.

Typed around text:

| Typed | Becomes |
|---|---|
| `**bold**` or `__bold__` | bold |
| `*italic*` or `_italic_` | italic |
| `` `code` `` | inline code |
| `~~strike~~` | strikethrough |
| `[label](address)` | a link, when the address is a safe one |

The delimiters are removed and the mark goes over the body where it already is, so marks on the text inside survive. A `| a | b |` row followed by Enter becomes a table with those column names.

**Backspace immediately after a shortcut puts the typed text back**, delimiters included, through the editor's own input-rule undo. It is the same history as everything else, so peer edits stay, and a later undo of that Backspace (redo) applies the shortcut again. A shortcut does not fire inside inline code or when the delimiter is escaped with a backslash, and text typed during an IME composition converts when the composition ends.

Typing joins one undo item the way it does in other editors: Cmd+Z removes the last word typed, not the last letter. A group continues while the keystroke lands in the same block, arrives within 500 ms of the one before it, inserts rather than replaces, and carries the same marks, and a space followed by the next word starts a new item. Deletions group the same way, one direction at a time. A command, and any change a script dispatches, is one item of its own.

### Empty placeholders are drawn, never written

The help an empty page shows is a decoration over the editor: it is drawn while a node is empty and it is never in the saved article, so an empty state can never become saved content. The title's placeholder and the block's `Type / for blocks` are the same mechanism:

```js
if (!node.content.size) decoration = Decoration.node(offset, offset + node.nodeSize, { class: "blockeditor-title-placeholder", "data-placeholder": TITLE_PLACEHOLDER });
```

The block placeholder is drawn the same way for an empty paragraph at the caret. The words live in the decoration and in the page's stylesheet, not in the document, so printing, exporting and a reader never see them.

### The block menu names every command before its code loads

The block menu is plain data: a label, an icon, a description and either a block type or the name of the action. A row whose feature is not in the boot names it instead of importing it, so discovery works before anything optional is downloaded and only the picked row loads code. The toolbar's current block type is read from the same list:

```js
const MENU_ITEMS = [...BLOCK_TYPES, ...INSERT_ITEMS];

function blockTypeOf(node) {
  const t = node.type.name;
  return BLOCK_TYPES.find((b) => b.type === t && (!b.attrs
    || (t === "heading" || t === "toggle" ? (b.attrs.level ?? null) === (node.attrs.level ?? null)
      : t === "list_item" ? b.attrs.kind === node.attrs.kind : true))) ?? BLOCK_TYPES[0];
}
```

A row such as `Mention` carries `command: "mentions"`, and its picker arrives on the pick. `insertItemsFor` adds a row only when the document can use it, so the chart row appears with the first table.

### On a phone

At widths up to 560 px the toolbar keeps four controls: **Bold**, **Italic**, **Link** and **More**, each at least 44 by 44 CSS px, in a bar 204 px wide and 8 px from the edge. The selection bubble stands down so there are never two bars.

**More** holds everything the desktop bar and menu carry: Strikethrough, Code, bulleted, numbered and checklist lists, **Turn into**, **Insert**, **Move up**, **Move down**, **Indent** and **Outdent**. Turn into and Insert open the same pickers as on a desktop, and a block action from the phone menu acts on the caret's block when nothing more is selected.

The bar is positioned from the visual viewport, not from the layout viewport: its top and horizontal bounds come from the visible area, so the on-screen keyboard cannot cover it, and it stays put when the visual viewport pans. The safe-area inset is read once per layout frame. Menus are constrained to the same viewport, open above the bar when there is room, and scroll inside themselves.

### The keyboard route

- **Escape** closes an open menu or link popover first, and puts focus back on the control that opened it, or the editor.
- With blocks selected, **Escape** leaves the writing surface for the first toolbar control and keeps the block selection, so a keyboard user is never stuck in contenteditable.
- Inside the toolbar, **Left** and **Right** walk the controls and **Escape** returns to the editor. The toolbar is one tab stop: **Tab** leaves it forward, **Shift-Tab** backward.
- **Tab** inside a table moves across its cells, **Shift-Tab** back; the editor leaves Tab to the browser everywhere else.

**Mod-A widens one scope at a time.** With the caret in a table cell it selects that cell's text, then the table, then every block in the page. Outside a table it selects the block's text, then every block. No press changes the document, so one Mod-A followed by Delete takes the cell's text or the table and never the whole page.

A table's column resize handle is a focusable vertical separator named for its column, with `aria-valuemin` 48, `aria-valuemax` 1200 and the current width as `aria-valuenow`. **Left** and **Right** preview a 10 px change, **Shift** makes the step 50 px, **Home** and **End** preview the minimum and the maximum, **Enter** commits and **Escape** cancels. A held arrow key and the keyup that ends it commit one command, not one undo item per repeat, and Tab or blur commits what is previewed before leaving. A table with no widths fills the page, and the first width set pins the other columns at their drawn widths in the same undo step. Double-clicking a handle resets the table to the page width, and pointer dragging is unchanged. A phone keeps the column's Width menu (Wider, Narrower, Fit to content, and Reset widths once the table has widths) instead of a drag target, and a rerender puts focus back on the same column's handle.

## Formatting

Four formats sit under **More** in the toolbar, beside Strikethrough, Code and the lists. On a phone they are behind More with everything else, so the primary row stays Bold, Italic, Link and More ([On a phone](https://clayjs.com/docs/plugins/blockeditor/#on-a-phone)).

| Format | Saved as | Set it with |
|---|---|---|
| Underline | the mark `underline`, saved as `<u>` | **Underline**, or Mod-u |
| Text color | the mark `text_color` with `{ color }`, saved as `<span data-color>` | **Text color**, then a color |
| Highlight | the mark `highlight` with `{ color }`, saved as `<mark data-color>` | **Highlight**, then a color |
| Quote | the block `quote`, saved as `<blockquote>` | **Quote** in the block menu or in Turn into, or `" ` at the start of a paragraph |

**Underline** toggles the mark and is saved as `<u>`. Mod-u toggles it too, and that shortcut belongs to an editable page selection only, so the browser keeps its own meaning for the key everywhere else.

**Text color** and **Highlight** share one fixed palette: gray, brown, orange, yellow, green, blue, purple, pink and red. Text color offers the nine keys and **Automatic**, which removes the mark. Highlight offers the same nine and **No highlight**, which removes only the highlight. There is no other color and no picker: a descriptor naming a color outside the palette stays in the file as content but is not one of these formats, and no command accepts arbitrary CSS, a URL or a style string.

**Quote** is the block type `quote`, with the same identity, hierarchy and inline content as a paragraph, and it is saved as `<blockquote>`. Enter it from Quote in the block menu (the plus or `/` on a line) or from Turn into, or type `" ` at the start of a paragraph. Backspace at the start of a quote puts the literal `" ` back, and the conversion is one undo step. `> ` still makes a toggle.

Each of the four asks the document's format gate before it writes anything, so a document whose floor is below the format is left exactly as it was and the refusal is a notice ([The page format floor](https://clayjs.com/docs/guide/live-sync/#the-page-format-floor)).

## Mentions and dates

Type `@` at the start of a word, or pick **Mention** from the block menu, and a list of people opens at the caret. It offers the people the document already names, with the host's own list laid over them by id, and what you type filters it by name. Choosing a person replaces the query with that person's name and puts the `mention` mark over it, in one transaction, followed by one unmarked space so typing at the edge of a mention stays plain text:

```html
<span data-blockeditor-mention="the-person-id">Ada Lovelace</span>
```

A mention is a labelled mark, not a link and not a record of anything on the network. It notifies nobody, looks up no account and sends nothing, and a reader shows it with none of this loaded. The label is the name at the moment of the pick, so a later rename never rewrites the sentence, and the id is a reference the people registry (`clay.people`) made. A person the host no longer lists is still named if the document holds them.

Pick **Date** from the block menu and the same list offers **Today** and **Tomorrow**, both resolved from the local calendar once when the command opens, so a list left open across midnight still writes the day you asked for. Choosing one writes that day as ISO text with the `date` mark over it:

```html
<time datetime="YYYY-MM-DD" data-blockeditor-date>YYYY-MM-DD</time>
```

A date stores the calendar day and nothing else: no time, no zone, no relative word and no reminder. The text a person reads is the day they picked.

Both commands ask the document's format gate before they write, so a document below the format keeps what it had and no mention or date lands in it ([The page format floor](https://clayjs.com/docs/guide/live-sync/#the-page-format-floor)). The list also stands down, writing nothing, when the `@` is deleted, the caret leaves the line, or a peer replaces the text under it.

## Checklist assignees and due dates

Every item in a checklist ends with two small tags, **Unassigned** and **No date**. They are always there in edit mode, so an item can be given a person or a day without opening a menu first. A reader sees neither tag.

Click **Unassigned**, or press **⌘⇧O** (**Ctrl+Shift+O** on Windows and Linux) inside the item, and a small **Assignee** panel opens under the tag:

- Type in **Find or type a name** to filter **People in this document**, the names the checklist already uses, each with how many items it holds (**1 item**, **3 items**). The current one has a tick.
- A name nobody has yet appears as **Assign to** followed by what you typed. **Enter** picks the first row.
- **Remove assignee** takes the name off the item.

Click **No date**, or press **⌘⇧D** (**Ctrl+Shift+D**), and a **Due date** panel opens:

- **Today**, **Tomorrow** and **Next week** (seven days from today) set the day in one click.
- Below them is a month, with **Previous month** and **Next month**. The arrow keys move a day or a week through the grid, and **Enter** or **Space** picks the focused day.
- **Clear date** takes the date off.

The tag then shows the person, or the day as **Today**, **Tomorrow** or a short date such as "Nov 4". A date that has passed on an unchecked item is drawn as overdue. **Escape** closes either panel and puts the cursor back in the item. Each choice is one step of undo, and the name and day are saved on the item itself, so they travel with the file.

An empty item shows a faint **To do**, and a click anywhere on its line puts the cursor in it. On a phone the panels fit the screen and every row is a full-size tap target.

## Document settings

The gear just left of the toolbar's **…** opens **Document settings**, the choices that belong to this one document. On a phone the gear is a **Document settings** row inside **…**.

There are two switches:

- **Checklist assignees** shows or hides the **Unassigned** tags and the names in them.
- **Checklist due dates** shows or hides the **No date** tags and the days in them.

Most documents are written by one person who never needs either, so both can be turned off. Turning a switch off only hides the tags: the names and dates already set stay saved in the document, and they come back when the switch is turned on again (the panel says so: **Hidden values stay saved and come back when turned on.**). While assignees are hidden, **⌘⇧O** does nothing, and the same for dates and **⌘⇧D**.

The settings are saved in the document, so they apply to everyone who opens it, and a change reaches the other people editing at once. If the host refuses the save, the switch flips back and says **That setting could not be saved.**

## Emoji

**Emoji** in the block menu opens a picker of 140 glyphs in seven groups, and choosing one replaces the selection with that glyph as ordinary text: no mark, no node and no attribute, so any reader shows it with none of this loaded. The glyph goes in whole. A joined family, a skin tone, a flag's regional pair and a keycap each count as one grapheme and are never cut in half. The list arrives the first time the picker opens (`page/emoji-data.js`), a failed fetch is not kept so the next opening asks again, and nothing in it is a font, a sprite, an image or an address.

## Toggle headings and the table of contents

**Toggle heading 1**, **Toggle heading 2** and **Toggle heading 3**, in Turn into or the block menu, make a line a toggle whose summary holds a heading of that level. The block stores `level` from 1 to 3 beside `open`, and is saved as a `<details>` with the heading in its `<summary>`:

```html
<details data-id="..." open><summary><h2>A section</h2></summary>...</details>
```

A level is a field only a newer page format reads, so a toggle heading asks the format gate on its first write, and a refusal leaves the line as it was.

**Table of contents** in the block menu inserts the `toc` block, which stores its own id and a `maxLevel` of 3 (saved as `data-max-level`). The block holds no copy of the headings: its entries are derived from the document each time it is drawn, from headings 1 to 6 and toggle headings 1 to 3 up to that level, with the page title left out. A rename, a move and a deletion therefore need no repair here. The entries are saved as one `nav` of links, and each link's anchor comes from that block's own stable id:

```html
<nav aria-label="Table of contents" data-type="toc" data-id="...">
  <ul><li><a href="#blockeditor-block-...">A section</a></li></ul>
</nav>
```

Following one of those links in the editor takes the caret to the block and opens the closed toggles above it for that reader alone: it writes nothing, makes no undo step and tells no peer. A target the document no longer holds is answered with **That link's block is gone**.

## Page icon and cover

**Page icon** in the More menu opens the same glyph list for the page's title, and choosing one writes it as the `pageIcon` field of the title heading. Only one whole grapheme can be stored: at most 32 code points and 128 bytes, and a browser with no grapheme segmenter refuses rather than cutting one in half. The saved article draws the glyph as `<span data-blockeditor-icon>`, and the title's own words stay the title.

**Add cover** in the More menu opens a file chooser. The image travels the same upload transport as an image block, with a progress bar and **Cancel**, and nothing reaches the page until the host answers with an address. The title heading then carries four fields, `pageCoverSrc`, `pageCoverAlt`, `pageCoverX` and `pageCoverY`, and is saved as one `header` holding the cover and the `h1`:

```html
<header data-blockeditor-heading="1"><img data-blockeditor-cover src="..." alt="" style="object-position:50% 50%"><h1>...</h1></header>
```

The two positions are percentages of the picture that stayed in view, and they start at 50. The cover command's position mode moves the picture under the hand or with the arrow keys, 5 percent a step, previews it without writing, and commits once on **Apply**, on **Enter** or on a release; **Escape** puts the picture back where it was. This release has no menu row for that mode. Nor is there a remove action: one undo of the cover's own commit takes the cover off, and the title's words and its icon stay.

On a host that stores no files, an image of png, jpeg, gif or webp at 1.5 MB or less is offered instead as **Keep this image inside the document**, which makes the document larger, and any other answer, a larger image or another type is refused and nothing is embedded.

A page with no title grows one: the icon and the cover commands make a heading with the decoration in the same step, and neither inserts anything on open.

## Moving blocks by touch

Only the grip takes a touch, so the page scrolls as usual everywhere else, and on a phone it is a 44 by 44 target whose `touch-action` is `none`. A touch that stays within 8 px for 250 ms starts a drag, and a release before that is a tap that opens the block menu. Moving more than 8 px before the hold, a second finger, `pointercancel`, a lost capture, a blur or leaving edit cancels.

An active touch drag goes through the same guarded move as the mouse and the keyboard: the same span named by block ids, the same neighbour and parent resolved again on release, the same admission, and the same one undo step. A drop that changes nothing says **Move cancelled**, a completed one says **Moved N blocks**, and a drag whose span or whose target is gone by the release ends without announcing anything. Keyboard Move is unchanged.

## Tables

A table is native semantics, in the editor and in the saved article alike: one `<table aria-label="Table">` with a `thead` and a `tbody`, each header cell a `<th scope="col">` whose `id` is the table's id and the column's id joined by a hyphen, and each body cell naming that header in `headers`. A sorted column's header carries `aria-sort`.

Above each table sits **Table actions**, opened by a click or by **Enter** or **Space**. It lists **Insert row above**, **Insert row below**, **Move row up**, **Move row down**, **Delete row**, **Insert column left**, **Insert column right**, **Move column left**, **Move column right**, **Delete column**, **Sort ascending**, **Sort descending**, **Rename column** and **Column width**. Every action names its table, its row and its column by id when the menu opens and finds them again by id when it runs, so a peer's reorder or deletion never hands an action another row or column: it refuses, leaves no undo entry and says **That part of the table is no longer available.** Focus stays on the same column, row or control, and moves to the control that took the removed one's place.

## Charts

A chart draws the numbers in one of the document's tables, and it follows that table: change a cell and the chart changes with it. Make one with **Chart** in the block menu, which appears once the document has a table (with several tables it asks which one), or with **Chart this table** in a table's gear menu. A new chart opens its **Edit chart** panel at once, so you choose what it shows right there, and **Remove** takes it away again.

Each chart has a header with its title (**Untitled chart** until you give it one), a chip naming its table, and **Edit chart**. The chip (**Go to source table**) moves the cursor into that table, which helps in a long document.

**Edit chart** opens one panel with everything the chart can change:

- **Chart type**: **Bar**, **Line** or **Pie**.
- **Source table**: any table in the document, named by the heading above it and its number of rows.
- **Labels column**: the column whose words label each point or slice.
- **Value columns**: the number columns to plot, each with its colour. A pie plots one value column across the rows (the panel says **Pie charts plot the first value column across rows.**), and the other columns you had chosen stay chosen for when you switch back to line or bar.
- **Highlight row**: one row to pick out, or **None**.
- **Chart title**: saved when you press **Enter** or leave the field.

**Done** or **Escape** closes the panel. **Remove** deletes the chart; undo brings it back. A pie leaves out rows that are zero or below, and its legend shows each value with its share, such as "42 (18%)".

If the table a chart was drawn from is deleted, the chart says **This chart's table was deleted**. Pick another table in the list and press **Use this table**, or press **Delete chart**. Undoing the table's deletion brings the chart back as it was. A table with no number column yet cannot be charted: you see **This table has no number column to chart yet.**

## Markdown import and export

**Import Markdown…** in the block menu takes a `.md`, `.markdown`, `text/markdown` or `text/plain` file. The file is measured before anything parses it: 2 MiB, and a file nested deeper than 32 levels or one that would become more than 10,000 blocks is refused with a reason and no change. The first import, and only the first, fetches `marked` from the release that served `clay.js` (`clay.assets.load("marked")`); its tokens are walked into page blocks, and no HTML that marked rendered ever reaches the page. A raw HTML block is kept as an inert block, cleaned of scripts, event handlers and script addresses, and inline markup stays literal text. A preview then lists the file's name, how many blocks arrived, the constructs the page cannot express (kept as written), each HTML block it cleaned, and the addresses it refused (left out), with **Insert at the selection** and **Cancel**. The insert writes one slice with fresh block, row and column ids at the line the command was asked for, found again by block id after the read: a line a peer deleted keeps the preview and writes nothing, and one a peer moved keeps the blocks at its new place. The whole insert is one undo step, and a newer page format is asked for only when the content needs it.

**Export as Markdown** in the More menu takes one snapshot, so a peer's edit while the report is open cannot change the file, and it lists what Markdown cannot carry before anything downloads: how many blocks were written, how many are kept as HTML and how many are lost, then the two lists, **Kept as HTML** and **Not kept in Markdown**, named per block. The extensions it writes are the page icon and the page cover of the title, a toggle, a table of contents, a chart, a board, a tool, raw HTML and a callout. A loss includes a heading icon, a toggle's collapse, an owner, a due date, an image's width, alignment or missing address, a file's size, type or missing address, a column's kind or width, a table's sort, and an inline object. When nothing is lost the panel says **Everything here is written as Markdown.** **Download** writes the file under the name the page carries, with a `.md` extension, and **Cancel**, a click outside or **Escape** stops it. No parser is fetched to export: the record is read once and the text is built from it. Nothing here writes to the page, enters the undo history or marks the page saved.

## A self-contained reading copy

**Export reading copy** in the More menu renders one static HTML file from a snapshot, through the same projection the saved page uses, and then reads every image and attachment the snapshot names once and writes each one into the file as a data URL. The panel names the captured title, the time it was taken and how many resources are inside the file, and it offers **Download** only when every resource resolved. A resource that could not be read, a type a reading copy does not carry, a live frame, and any reference that still points off the file are each listed with the block they sit in, and the panel offers **Try again** and **Close** instead. **Escape** closes it.

What travels inside the file is images of the drawn types (png, jpeg, gif, webp, avif, bmp, x-icon and vnd.microsoft.icon), fonts, audio and video. An attachment of an active type is refused by name rather than embedded: HTML, JavaScript, CSS, XML, XSL, XHTML, ECMAScript, wasm and SVG, and anything whose type ends in `+xml`, because a browser would run it or render it as a document. One resource is read within 20 MiB, the whole export within 50 MiB, each one waits 10 seconds, and three are read at a time.

The file makes no automatic external load. It carries no script, stylesheet, `link`, `meta` or `base`, every resource it shows is a data URL inside it, and a reference that would still make a browser request (a source, a source set, a poster, an object's data, a stylesheet's or a script's address, a `url()` or `@import` in a style) keeps the download shut. Toggles arrive open and the table of contents is a plain list rather than links, so the copy reads the same with nothing fetched.

## Content from a newer ClayJS

ClayJS 1.16.0 and later keep what a newer version writes, even where they have no way to edit it. That holds for the four formats above and for anything a later release adds.

- **Kept, not refused.** A mark name, a block type or a block field this version has no schema for is kept in the live document, in the saved article, through adoption, through copy and paste and through a server checkpoint. A neighbouring edit and save leaves every unknown item byte for byte as it was, and the revision hash covers it.
- **Shown inert.** A block whose type this version does not know draws as its own text under a **Newer format** label that names the type it was saved as, and it takes no keystrokes: nothing can be typed into it, and no command retypes it. Copying it copies the whole record. Text carrying an unfamiliar mark shows that text, and the mark's description stays beside it in the saved file.
- **Commands that would drop it refuse.** Turn into, the list buttons and the Code button refuse over a block that holds content from a newer version, change nothing, send no update, and show the notice **This block holds content from a newer version, so it can't be converted here.** A command that would erase an unfamiliar mark refuses the same way instead of rewriting the text without it.
- **Malformed data is still refused.** A malformed mark key, an envelope past the version this runtime reads, an update that does not decode and a record above the envelope budget refuse the source as before. Tolerance keeps valid content this version cannot read; it never turns corrupt content into accepted content.

Opening a file that holds newer content does not raise anything by itself: the format floor rises only when a writer asks for it on a write ([The page format floor](https://clayjs.com/docs/guide/live-sync/#the-page-format-floor)).

## Rewriting blocks with AI

In edit mode, `blockeditor` brings `wire` and [`ai-edit`](https://clayjs.com/docs/plugins/ai-edit/) unless `exclude=wire` or `exclude=ai-edit` is set. When the host lists an `ai-edit` helper in `/_/meta` `document.helpers`, pressing **⌘J** (**Ctrl+J** on Windows and Linux) opens the Ask AI composer on the blocks touched by the current selection, and **Ask AI to improve this page** in the [menu](https://clayjs.com/docs/plugins/menu/) opens the area picker (`clay.aiEdit.pick()`) to choose blocks by clicking or dragging.

The chosen blocks go through the `ai-edit` wire helper. When the reply arrives, the editor draws it as a preview decoration (`div.blockeditor-ai-preview`) that is not in the document or its Yjs store yet. While the preview is up, the editor is read-only and undo and redo are disabled. **Keep** applies the proposal as one undoable step and flushes the save; **Discard** drops the preview. Blocks the editor cannot rewrite as prose (`image`, `file`, `chart`, `board`, `toc`, `tool` and `preserved`) are held aside as placeholders in the request and restored verbatim by id when the reply is adopted. If any chosen block changes while the request is running or while the preview is up, the rewrite is refused and nothing is written. See [Block-based documents in `ai-edit`](https://clayjs.com/docs/plugins/ai-edit/#block-based-documents).

## Making and revising tools with AI

Type `/ai` (or `/tool` or `/generate`) in the block menu and pick **Make a tool with AI…**, or open a tool block's **Tool options** menu and pick **Revise…** (or select a single tool block and press **⌘J**, or click it in the area picker). Both open the shared Ask AI composer: `/ai` opens on `New tool` with the placeholder `"Describe the tool"`, and **Revise…** opens on `This tool` with `"What should change?"`. For what to make, how to ask, and worked examples, see [Tools](https://clayjs.com/docs/plugins/tools/).

### Host capability

A host enables tool generation by listing `{ "name": "blockeditor-tool", "state": "ready" }` (or `"unavailable"` when AI editing is turned off in the host) in `/_/meta` `document.helpers`. Without `blockeditor-tool` in `document.helpers`, `/ai` does not appear in the block menu and **Revise…** does not appear in **Tool options**. Listed as `unavailable`, the composer opens with the host's setup explanation and Send disabled.

### What goes on the wire

Sending calls `clay.wire.send(payload, { helper: "blockeditor-tool", document: "none" })` with a `blockeditor-tool/1` payload (`src/page/rich/page-tool.js`, `src/page/tool-transport.js`):

- `prompt`: the description typed in the composer (up to 8,192 UTF-8 bytes).
- `context`: `{ title, outline, tables }` built from the current document (`title` from the page title, `outline` from headings as `{ level, text }`, and `tables` as `{ id, name, cols, rows }`). Before sending, `trimmedContext` trims `context` to fit 16,384 UTF-8 bytes by dropping rows from the last table first and then outline entries.
- `target` and `current`: `null` for `/ai`. For **Revise…**, `target` is `{ toolId, rev }` and `current` is `{ artifact, state }`, where `artifact` holds the tool block's six string fields (`title`, `html`, `css`, `javascript`, `fallbackHtml`, `summary`) and `state` holds the tool's live data at `clay.live("blockeditor.tools").data[toolId][rev]` (or `{}`).

When `/ai` is chosen, the editor records a bookmark on the block where `/ai` was typed (`hostId`, `slashText`, `slashOffset`) so the preview and insert find that block again even if the slash text stays on the line while assets load.

### Preview, Keep and Discard

When the `wire/done` result `{ requestId, artifact, state, model }` arrives, the editor validates `artifact` (an object with those exact six string fields, encoded JSON at most 24,576 bytes) and `state` (cloneable JSON data, encoded at most 8,192 bytes). It then mounts the candidate in a view-mode tool host (`createToolHost` with `mode: "view"`, `seed: state`, and the document's tables) inside `div.blockeditor-ai-preview`. For a revision, or when `/ai` was run in an empty or slash-only text block, the preview hides that block in place; when `/ai` was run in a block that already has other text, the preview renders right after that block. Nothing is written to the document or the `blockeditor.tools` live store while the preview is up.

**Discard** disposes the preview host, clears the decoration, and writes nothing.

**Keep** runs a two-stage commit so a save failure never leaves a broken tool block in the page:

1. For a revision, it checks that the tool's live data at `clay.live("blockeditor.tools").data[toolId][rev]` still matches the JSON snapshot taken when the request started. If the tool's data changed while the new version was being made, **Keep** refuses with `This tool's data changed while AI was working, so it was not replaced. Ask again to include the latest data.`
2. It allocates a fresh `rev` (and a fresh block `id` for a new tool), writes `state` to `blockeditor.tools` at `[id, rev]`, and awaits `clay.save.flush()`. If writing or flushing fails, the preview clears, no block is inserted or updated, and the bar reports `The tool could not be saved, so it was not added. Try again.`
3. It checks again that the target tool block is still in the document at the same `rev` (or, for `/ai`, that the bookmarked block is still in the document) and that the live data has not moved. If the block moved or changed, **Keep** refuses (`This tool changed while you were revising, so nothing was replaced. Ask again.` or `The place for this tool moved. Close this and run /ai where you want the tool.`).
4. It clears the preview and dispatches one undoable step (`asStep`): for a revision, updating the tool block's `artifact` and `rev`; for `/ai`, removing any remaining `/ai` text at the bookmark and replacing the empty block or inserting the new `tool` block after it. It then flushes the save again.

### Prompt files and hosts

The prompt files the hosts feed the model ship in `@panphora/clayjs` at `tool-generation/system.md` and `tool-generation/context.md` (exported as `@panphora/clayjs/tool-generation/*` and listed in `dist/offline-manifest.json`). Hosts read the system prompt from their bundled release and never accept one from the client.

On **hyperclay.com**, `blockeditor-tool` is listed beside `ai-edit` for the document's owner and team editors. It runs DeepSeek V4.1 Flash, bills 2 AI credits per tool, and charges only when a valid tool reply is delivered to the client; a request that is cancelled, times out, is declined by the model or fails validation charges nothing. On **Hyperclay Local** and **HTML Clay**, `blockeditor-tool` runs the person's own `claude` or `codex` CLI under the same AI Editing setting and per-document one-request-at-a-time slot as `ai-edit`.

## History and the menu

`clay.blockeditor.history` exposes the page editor's own Yjs UndoManager (`{ undo(), redo(), canUndo, canRedo }`), the same stack that **⌘Z** and **⌘⇧Z** use. Peer edits from other tabs do not enter this tab's stack. While an AI preview is on screen, `canUndo` and `canRedo` both report `false`.

Whenever a step is added or popped, the stack clears, or an AI preview opens or closes, the blockeditor plugin fires `clay:undo-change` on `document` with `{ detail: { canUndo, canRedo } }`. When the [menu](https://clayjs.com/docs/plugins/menu/) plugin is loaded on a `blockeditor` document, its **Undo** and **Redo** items call `clay.blockeditor.history` and follow that event. The [`undo`](https://clayjs.com/docs/plugins/undo/) plugin cannot run beside `blockeditor`: if a script tag names both, the loader leaves `undo` out and logs `clayjs: plugin "undo" cannot run with "page" and was left out`.

## Remote carets

Remote carets need the block editor, one `<article data-blockeditor>`, `?plugins=sync`, and a host that announces `blockeditor-awareness-v1`. Anything less draws nothing, and sends nothing.

A selection is published as a page target. Its ends are the block id plus a Yjs relative position, `toBase64(Y.encodeRelativePosition(Y.createRelativePositionFromTypeIndex(flow, index, assoc)))`. Peers resolve them against their own current document, so a caret follows edits, splits, joins, and moves.

```js
store.setTarget({
  kind: "blockeditor",
  v: PRESENCE_VERSION,
  epoch,
  generation: binding.awareness.generation(),
  selection, // { kind: "text", anchor: { block, rel }, head: { block, rel } }
});
```

A position that cannot be resolved is not drawn: a deleted or hidden block, another generation, another shared type, or bytes that do not decode. It is never placed at a neighbouring block.

Each peer is a highlighted range plus a caret with their name as text only. The colour comes from a fixed palette, chosen by the person's id, and a peer can never supply a colour or markup.

A table cell is published as `{ kind: "cell", block, row, col }`. It is drawn as an outlined cell with one name tag, never a character caret inside the cell. A selection across two cells publishes nothing. A block selection outlines the blocks, and over 128 blocks only the focused block is published.

Publication clears during IME composition, and peers' decorations stay still until it ends. It also clears on blur, on `pagehide`, when the host stops announcing page awareness, and on disposal.

Carets are ProseMirror decorations. They never enter the document, its undo history, its Yjs value, or a save.

## The reader

A Document that boots in view and never enters edit loads the reader, `blockeditor-view`, not the editor. The loader adds it by itself; no URL names it. The plugin's implications stay in edit mode: the reader implies no live data service, no generic `sync` and no `upload`, so `plugins=blockeditor` in view mode resolves to `blockeditor-view` alone.

- **Saved, not live.** The reader follows the file the host serves, through a receive-only transport (`src/sync/saved-stream.js`): a startup GET once the stream opens, then frames, then a refetch and repair for whatever it missed. It never POSTs, never relays a live preview and needs no write credentials.
- **One receipt.** A reader holds exactly one: the exact bytes on screen, their ETag and the sequence they cover (`{ bytes, etag, seq }`). A duplicate or older frame is ignored without moving it, and a refused or failed read leaves both the article and the receipt as they were.
- **Keyed replacement.** Each accepted file replaces only the blocks whose saved form changed (`src/page/reader-patch.js`). An unchanged block keeps its node, so an open toggle, a mounted tool and find-in-page survive an update.
- **Explicit `sync`.** A page that also names `sync` keeps one stream: the reader opens none of its own and takes the saved files that lane applied. A peer's unsaved keystrokes never become a reader's saved content.
- **Who is here.** In view mode the reader also draws the roster of who is present, from the stream it already follows ([Presence](https://clayjs.com/docs/guide/live-sync/#presence)).
- **What it reports.** `clay:reader-status` fires on `document` for each file it handles: `{ state: "applied", etag, seq }` once one is on screen, `{ state: "blocked" }` when a read or an apply was refused.
- **When it is ready.** The reader's `ready` settles without waiting for a file: without `sync` it settles `null` once its saved transport has started, and with `sync` it settles to the started reader, because that lane starts the reader before it returns. Either way `clay:ready` never waits on the network and fires even if the stream never opens, and a page that is not one `article[data-blockeditor]`, or whose reader cannot start, settles `null`.
- **When the file is here.** The reader module's `acquired` (`src/plugins/page-view.js`, beside `ready`) settles to the started reader on the first accepted saved file, or to `null` on a read or an apply that was refused or failed, and that first answer is the one it keeps. The stream keeps running either way, so a later accepted file still starts a reader. Await `acquired`, not `ready`, for the file.

## Across a mode change

The blockeditor plugin is a participant of the mode lifecycle, with the id `clay:blockeditor` and order 400. [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.

On a live entry the editor is imported while the tab still shows view, and it takes the article over from the reader: the reader gives the article up (`yieldArticle`), and takes it back (`reclaimArticle`) if the entry is refused or the preparation fails. The session's saves and autosave are held until the commit, so nothing is written before it.

Entering adopts the file already on screen as its baseline, so a clean enter and exit leaves the file byte for byte as the host served it. Anything typed after the commit is saved from there.

## When it is ready

`clay.blockeditor.ready` is the boot itself, not the loader's. It resolves once the saved article has been adopted and the editor accepts typing, with the boot result `{ phase, reason, installId, at }`. `clay.blockeditor.status` is that same result for the newest installation, or `null` before one has started.

`clay.ready` does not wait for it. `plugins/page.js` exports no `ready`, so `await clay.ready` can resolve while the saved article is still the thing on screen. Await `clay.blockeditor.ready`, or read `clay.blockeditor.status.phase`, before touching `clay.blockeditor.view`. Late plugins do wait: the loader holds them until `clay.blockeditor.ready` settles.

| `phase` | What it means |
|---|---|
| `loading` | the saved article is being read and validated |
| `joining` | the editor's code downloads beside the room join, and capability, the first save and the page handle are settled |
| `adopting` | the editor is mounted and the saved article is being adopted into the room |
| `ready` | adoption succeeded and input is enabled on this installation's view |
| `blocked` | the boot settled without an editable page; `reason` says what stopped it |
| `error` | the boot threw; ClayJS reports `reason` `boot-failed` |

Every installation has its own id, and `clay.blockeditor.install()` starts a new one, disposing the last. A plain page load starts one too, which is what `clay.blockeditor.ready` is.

### The boot marks

Each boundary is a `performance.mark` with `{ detail: { installId } }`:

| Mark | Exact boundary |
|---|---|
| `document:boot` | an installation starts, before the source is validated |
| `document:assets-ready` | the editor's code is in hand; a failure here is `editor-assets-failed` |
| `document:authority-ready` | the capability and first-save gates passed, the page handle is admitted and the binding is created |
| `document:input-ready` | adoption succeeded and editable was enabled on the current mounted view |

A failed or cancelled installation never emits `document:input-ready`, and neither mark after `document:boot` is emitted by a branch that failed. `document:authority-ready` says the room admitted this tab and the binding exists; it does not say the writer election is over or that the feature views the article demands have installed. Those settle under the adopting phase, before input is enabled.

### A blocked page is a settled page

Blocked readiness is an answer, not a rejection. `clay.blockeditor.ready` resolves, `clay.blockeditor.status.phase` is `blocked`, and `reason` names the boundary that stopped it: `no-blockeditor` or `ambiguous-blockeditor` (not exactly one `article[data-blockeditor]` and one `merge="blockeditor"` tag), `invalid-blockeditor-source`, `invalid-blockeditor-json`, `unsupported-blockeditor-format`, `missing-capability` (no `blockeditor` extension), `first-save-refused`, `first-save-conflict`, `missing-blockeditor-store`, `admission-failed`, `editor-assets-failed`, `mount-failed`, `adoption-refused`, `adoption-timeout`, `adoption-error`, `blockeditor-replaced`, `view-detached`, or `boot-incomplete`. There is no editable page in that case: the saved article stays as the host served it, or an already mounted editor is left read-only because the page was replaced, and nothing takes a keystroke. The plugin draws its own notice, with Download a copy and Copy text where the host refused to keep the article. A page that must offer another route reads the phase rather than catching anything:

```js
const result = await clay.blockeditor.ready;
if (result?.phase !== "ready") console.warn("this page cannot be edited here:", result?.reason);
```

## Offline

The editor, the theme sheets and the fonts are part of the release the local hosts bundle, so editing a page works offline in both Hyperclay Local and HTML Clay. Pictures from other sites do not. See [Offline in a local host](https://clayjs.com/docs/guide/hosts/#offline-in-a-local-host).

## Pages

- [clayjs.com](https://clayjs.com) — the tutorial
- [clayjs.com/get-started](https://clayjs.com/docs/guide/quick-start/) — zero to a saving file in four steps
- [clayjs.com/docs](https://clayjs.com/docs/) — the reference
- [clayjs.com/advanced](https://clayjs.com/docs/regions/) — regions, save hooks, satellites
- [clayjs.com/plugins](https://clayjs.com/docs/plugins/) — the heavyweight plugins
- [htmlclay.com](https://htmlclay.com) — the desktop app; [htmlclay.com/features](https://htmlclay.com/docs/features/) — everything it does
- [github.com/hyperspacesystems/clayjs](https://github.com/hyperspacesystems/clayjs) — source
