# Block Editor

> BlockEditor - a block-based editor with a JSON value, slash menu, selection toolbar, drag handles and block menus, mentions and labels, paste cleanup, undo, server rendering and opt-in Yjs collaboration.

Canonical: https://salmonui.dev/docs/editors/block-editor

`BlockEditor` from `@salmonui/rich-text` edits a document of blocks:
paragraphs, headings, bulleted, numbered and checklist items, quotes,
callouts, code, images, tables, dividers, toggles, audio and video.
It runs on the same ProseMirror engine and schema as
`RichTextEditor`. The value is plain JSON with a stable `id` on every block:

```tsx
import { BlockEditor, type Block } from '@salmonui/rich-text';
import '@salmonui/rich-text/styles.css';

const [blocks, setBlocks] = useState<Block[]>([
  { id: 'title', type: 'heading', props: { level: 1 }, content: [{ type: 'text', text: 'Plan' }] },
  { id: 'todo', type: 'checklistItem', props: { checked: false }, content: [{ type: 'text', text: 'Write the spec' }] },
]);

<BlockEditor aria-label="Notes" value={blocks} onChange={setBlocks} />
```

`defaultValue` makes it uncontrolled. The server renders the blocks as
sanitized HTML inside the element the engine mounts on after hydration, so
the first paint is the real content and hydration never differs; ProseMirror
and the editor UI load afterwards with a dynamic `import()`.

### Live demo: Block Editor

Live demo: https://salmonui.dev/demos/editors/block-editor

A controlled BlockEditor with checklists, a callout, nested lists, code, mentions and labels; the block JSON and the block events update as you edit.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { BlockEditor, type Block } from '@salmonui/rich-text';
import '@salmonui/rich-text/styles.css';
import { EventLog, useEventLog } from '../../components/demo-kit';

const initial: Block[] = [
  { id: 'title', type: 'heading', props: { level: 2 }, content: [{ type: 'text', text: 'Launch plan' }] },
  {
    id: 'intro',
    type: 'paragraph',
    content: [
      { type: 'text', text: 'Type ' },
      { type: 'text', text: '/', marks: [{ type: 'code' }] },
      { type: 'text', text: ' for blocks, select text for the toolbar, or drag the handle to reorder.' },
    ],
  },
  { id: 'goals', type: 'heading', props: { level: 2 }, content: [{ type: 'text', text: 'Tasks' }] },
  { id: 't1', type: 'checklistItem', props: { checked: true }, content: [{ type: 'text', text: 'Write the announcement' }] },
  { id: 't2', type: 'checklistItem', props: { checked: false }, content: [{ type: 'text', text: 'Review with ' }, { type: 'mention', id: 'ana', label: 'Ana Lima', trigger: '@' }] },
  { id: 'note', type: 'callout', props: { tone: 'warning' }, content: [{ type: 'text', text: 'Ship after the docs are live.' }] },
  {
    id: 'steps',
    type: 'numberedListItem',
    content: [{ type: 'text', text: 'Freeze the release branch' }],
    children: [{ id: 'steps-a', type: 'bulletListItem', content: [{ type: 'text', text: 'Tag ' }, { type: 'label', id: 'release', label: 'release', trigger: '#', tone: 'info' }] }],
  },
  { id: 'steps2', type: 'numberedListItem', content: [{ type: 'text', text: 'Publish the packages' }] },
  { id: 'code', type: 'code', props: { language: 'ts' }, content: [{ type: 'text', text: "import { BlockEditor } from '@salmonui/rich-text';" }] },
];

const people = [
  { value: 'ana', label: 'Ana Lima' },
  { value: 'ben', label: 'Ben Okafor' },
  { value: 'chen', label: 'Chen Wei' },
];
const labels = [
  { value: 'release', label: 'release', tone: 'info' },
  { value: 'bug', label: 'bug', tone: 'danger' },
];

export default function BlockEditorDemo() {
  const [blocks, setBlocks] = useState<Block[]>(initial);
  const [log, push] = useEventLog();
  return (
    <div style={{ display: 'grid', gap: 12, maxWidth: 720 }}>
      <BlockEditor
        aria-label="Launch plan"
        value={blocks}
        onChange={setBlocks}
        onBlockChange={(event) => push(`${event.type}: ${event.block.id} (${event.block.type})`)}
        onBlockMove={(event) => push(`move (${event.source}): ${event.block.id}`)}
        mentions={{ items: people }}
        labels={{ items: labels }}
        codeLanguages={[
          { value: 'ts', label: 'TypeScript' },
          { value: 'css', label: 'CSS' },
        ]}
        placeholder="Type / for blocks"
      />
      <details>
        <summary>Value ({blocks.length} top-level blocks)</summary>
        <pre style={{ maxBlockSize: 240, overflow: 'auto', fontSize: 12 }}>{JSON.stringify(blocks, null, 2)}</pre>
      </details>
      <EventLog entries={log} />
    </div>
  );
}
```

## Block model

```ts
interface Block {
  id: string;
  type: BlockType;
  props?: Record<string, unknown>;
  content?: InlineContent[];   // the block's own text
  children?: Block[];          // sub-items, toggle body, quote and callout body
}
```

`props` by type: heading `level` and `textAlign`; paragraph `textAlign`;
numberedListItem `start` (begins a new numbered list); checklistItem
`checked`; callout `tone` (`info`, `success`, `warning`, `danger`,
`neutral`); code `language`; toggle `open`; image `src`, `alt`, `caption`,
`width`, `height`; audio `src`; video `src`, `width`, `height`; table
`headerRow` and `rows` (rows of cells of inline content) and `variant`.

Inline content is shared with `RichTextEditor`: text with marks
(`bold`, `italic`, `underline`, `strike`, `subscript`, `superscript`,
`code`, and `color`, `backgroundColor`, `fontFamily`, `fontSize` with a
value), links, mentions, labels and hard breaks.

Consecutive list items of one kind form one list. Ids round-trip through
`data-block-id`; the editor keeps them present and unique (a duplicated or
split block gets a new id).

## Serialization

`blocksToHtml(blocks)` and `htmlToBlocks(html)` are pure and server-safe:
render stored blocks in a mail or a static page, or import HTML.
Both go through the sanitizer; `htmlToBlocks` gives blocks without
`data-block-id` deterministic ids from their position (`b0`, `b2-1`), so the
server and the client agree. The editor itself converts through the same two
functions, so there is one conversion path.

```ts
import { blocksToHtml, htmlToBlocks } from '@salmonui/rich-text';

const html = blocksToHtml(blocks);    // '<h1 data-block-id="title">Plan</h1>...'
const again = htmlToBlocks(html);     // deep-equals blocks
```

Render blocks read-only with `<RichTextContent blocks={blocks} />`.

## Editing blocks from code

The controlled value is the block API: adding, removing, moving and
updating are array edits. Immutable helpers keep untouched subtrees
identical: `findBlock`, `findParentId`, `forEachBlock`, `insertBlocks(blocks,
inserted, { before | after | parent, index })`, `removeBlocks(blocks, ids)`,
`updateBlock(blocks, id, patch)` (props merge) and `moveBlock(blocks, id,
position)`.

For an uncontrolled editor, `actionsRef` offers the same edits plus the
selection and command API:

| Method | Does |
| --- | --- |
| `getBlocks()`, `getBlock(id)` | Read the document |
| `insertBlocks(blocks, position?)`, `removeBlocks(ids)`, `updateBlock(id, patch)` | Edit as one undo step |
| `moveBlock(id, position)` | Move; `false` when `onBeforeBlockMove` cancels |
| `turnInto(id, type)` | Change a block's type, keeping its text |
| `getSelection()`, `setSelection({ blockId, offset })` | The caret as a block and an offset |
| `focus()`, `runCommand(id, ...args)` | Focus; run a toolbar command (`bold`, `heading2`, `insertTable`, `undo`, ...) |
| `getHtml()`, `print()` | Sanitized HTML; print the content |

## Slash menu, selection toolbar and turning into

Typing `/` at the start of a block or after a space opens the slash menu:
the built-in entries `paragraph`, `heading1`..`heading3`,
`bulletList`, `numberedList`, `checklist`, `quote`, `callout`, `code`,
`toggle`, `image`, `table` and `divider`, grouped and filtered by the typed
text. Arrow keys move, Enter or Tab picks, Escape closes. `slashMenu` lists
the entries (custom ones are `{ id, label, keywords, group, onSelect({
block, actions }) }`); `false` turns the menu off.

Selecting text shows the selection toolbar with bold, italic,
underline, strikethrough, inline code, link and `turnInto`; `inlineToolbar`
lists its entries (custom ones as above) or hides it with `false`.
`transforms` restricts the types `turnInto` offers.

## Drag handles and block menus

Hovering a block (or moving the caret into it) shows a drag handle in the
inline-start gutter. Clicking it opens the block action
menu on the shared `Menu`: turn into, duplicate, delete, move up and move
down, image settings for images, row and column commands for tables, and
custom entries from `blockActions`. Dragging it moves the block: a line
shows the drop position, and dropping further to the inline end of a list
item, quote, callout or toggle nests the block inside it. The drag runs
outside React state. `draggable={false}` removes the handles;
`onBeforeBlockMove` (call `preventDefault()` to cancel) and `onBlockMove({
block, from, position, source })` report moves from the pointer, the
keyboard and `actionsRef`.

Right click opens the context menu: cut, copy, duplicate, delete,
move up, move down, turn into, and custom entries from `contextMenu`
(`false` keeps the browser menu; Shift and right click always does).

### Live demo: Block Editor API

Live demo: https://salmonui.dev/demos/editors/block-editor-api

BlockEditor from code - insert, update, move, turn into and remove blocks through actionsRef, selection and commands, a custom context menu, image upload, highlighted code, a table block, paste events, sanitized HTML import and export, rebound keys, read only, print, right to left and localized menus.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { BlockEditor, blocksToHtml, htmlToBlocks, type Block, type BlockEditorActions } from '@salmonui/rich-text';
import '@salmonui/rich-text/styles.css';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { EventLog, useEventLog } from '../../components/demo-kit';

const text = (value: string) => [{ type: 'text' as const, text: value }];

const initial: Block[] = [
  { id: 'title', type: 'heading', props: { level: 2 }, content: text('Sprint review') },
  { id: 'intro', type: 'paragraph', content: text('Right click a block for the context menu, or use the buttons below to edit blocks from code.') },
  {
    id: 'scores',
    type: 'table',
    props: {
      headerRow: true,
      rows: [
        [text('Team'), text('Points')],
        [text('Editors'), text('21')],
        [text('Grid'), text('34')],
      ],
    },
  },
  { id: 'snippet', type: 'code', props: { language: 'ts' }, content: text("const done = tasks.filter((task) => task.done); // filtered\nexport default done;") },
  { id: 'next', type: 'paragraph', content: text('Type / and pick Image to upload a picture.') },
];

const highlight = (code: string) =>
  [...code.matchAll(/\/\/[^\n]*|\b(?:const|export|default|return)\b/g)].map((m) => ({ from: m.index, to: m.index + m[0].length, className: m[0].startsWith('//') ? 'demo-tok-comment' : 'demo-tok-keyword' }));

const AR_TEXT = { slashMenu: 'إدراج كتلة', turnInto: 'تحويل إلى', duplicate: 'تكرار', delete: 'حذف', moveUp: 'نقل لأعلى', moveDown: 'نقل لأسفل', cut: 'قص', copy: 'نسخ' };

const UNSAFE = '<h3 onclick="alert(1)">Pasted heading</h3><p>Safe text <img src=x onerror="alert(1)"><a href="javascript:alert(1)">bad link</a></p><script>alert(1)</script>';

export default function BlockEditorApiDemo() {
  const [log, push] = useEventLog();
  const [readOnly, setReadOnly] = useState(false);
  const [rtl, setRtl] = useState(false);
  const [blockPaste, setBlockPaste] = useState(false);
  const [html, setHtml] = useState<string | null>(null);
  const actions = useRef<BlockEditorActions | null>(null);
  const count = useRef(0);
  const act = (fn: (a: BlockEditorActions) => void) => () => {
    if (actions.current) fn(actions.current);
  };
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <style>{'.demo-tok-keyword{color:#a0427a;font-weight:600}.demo-tok-comment{color:#6b7280;font-style:italic}'}</style>
      <div role="group" aria-label="Options" style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
        <Checkbox checked={readOnly} onCheckedChange={(checked) => setReadOnly(checked)}>
          readOnly
        </Checkbox>
        <Checkbox checked={blockPaste} onCheckedChange={(checked) => setBlockPaste(checked)}>
          Cancel pastes with images (onBeforePaste)
        </Checkbox>
        <Checkbox checked={rtl} onCheckedChange={(checked) => setRtl(checked)}>
          Right to left (Arabic menus)
        </Checkbox>
      </div>
      <div dir={rtl ? 'rtl' : 'ltr'}>
        <BlockEditor
          aria-label="Sprint review"
          defaultValue={initial}
          actionsRef={actions}
          readOnly={readOnly}
          undoLimit={100}
          codeLanguages={[
            { value: 'ts', label: 'TypeScript' },
            { value: 'css', label: 'CSS' },
          ]}
          highlight={highlight}
          onUpload={async (file) => {
            push(`onUpload: ${file.name} (1 s)`);
            await new Promise((resolve) => setTimeout(resolve, 1000));
            return { src: URL.createObjectURL(file), alt: file.name };
          }}
          contextMenu={[
            'cut',
            'copy',
            'duplicate',
            'delete',
            'turnInto',
            { id: 'copyId', label: 'Log block id', onSelect: ({ block }) => push(`context menu: block ${block?.id ?? 'none'}`) },
          ]}
          keyBindings={{ duplicateBlock: 'Mod-Shift-d', print: false }}
          onBeforePaste={(event) => {
            if (blockPaste && event.files.length > 0) {
              event.preventDefault();
              push(`onBeforePaste: ${event.files.length} file(s) refused`);
            } else push(`onBeforePaste: ${event.html ? 'html' : 'text'}${event.files.length ? ` + ${event.files.length} file(s)` : ''}`);
          }}
          onPaste={(event) => push(`onPaste: ${event.blocks.length} block(s): ${event.blocks.map((b) => b.type).join(', ')}`)}
          onSelectionChange={(selection) => {
            if (selection) push(`onSelectionChange: ${selection.blockId} @ ${selection.offset}`);
          }}
          localeText={rtl ? AR_TEXT : {}}
          style={{ minBlockSize: 280 }}
        />
      </div>
      <div role="group" aria-label="Block API" style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        <Button variant="outline"
          type="button"
          onClick={act((a) => {
            count.current += 1;
            a.insertBlocks([{ id: `todo-${count.current}`, type: 'checklistItem', props: { checked: false }, content: text(`Follow-up ${count.current}`) }], { after: 'intro' });
          })}
        >
          insertBlocks (after intro)
        </Button>
        <Button variant="outline" type="button" onClick={act((a) => a.updateBlock('title', { props: { level: 1 } }))}>
          updateBlock(title, level 1)
        </Button>
        <Button variant="outline" type="button" onClick={act((a) => push(`moveBlock(next, before title): ${a.moveBlock('next', { before: 'title' })}`))}>
          moveBlock(next, before title)
        </Button>
        <Button variant="outline" type="button" onClick={act((a) => a.turnInto('intro', 'callout'))}>
          turnInto(intro, callout)
        </Button>
        <Button variant="outline" type="button" onClick={act((a) => a.removeBlocks(['snippet']))}>
          removeBlocks([snippet])
        </Button>
        <Button variant="outline" type="button" onClick={act((a) => push(`getBlock(title): ${JSON.stringify(a.getBlock('title')?.content)}`))}>
          getBlock(title)
        </Button>
        <Button variant="outline" type="button" onClick={act((a) => push(`getSelection(): ${JSON.stringify(a.getSelection())}`))}>
          getSelection()
        </Button>
        <Button variant="outline"
          type="button"
          onClick={act((a) => {
            a.setSelection({ blockId: 'intro', offset: 0 });
            a.focus();
          })}
        >
          setSelection(intro, 0) + focus()
        </Button>
        <Button variant="outline" type="button" onClick={act((a) => push(`runCommand(bold): ${a.runCommand('bold')}`))}>
          runCommand(&apos;bold&apos;)
        </Button>
        <Button variant="outline" type="button" onClick={act((a) => push(`runCommand(undo): ${a.runCommand('undo')}`))}>
          runCommand(&apos;undo&apos;)
        </Button>
        <Button variant="outline" type="button" onClick={act((a) => a.print())}>
          print()
        </Button>
      </div>
      <div role="group" aria-label="Serialization" style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        <Button variant="outline" type="button" onClick={act((a) => setHtml(blocksToHtml(a.getBlocks())))}>
          blocksToHtml(getBlocks())
        </Button>
        <Button variant="outline"
          type="button"
          onClick={act((a) => {
            const blocks = htmlToBlocks(UNSAFE);
            a.insertBlocks(blocks, { after: 'title' });
            push(`htmlToBlocks(unsafe HTML): ${blocks.length} sanitized block(s) inserted`);
          })}
        >
          htmlToBlocks(unsafe HTML) and insert
        </Button>
      </div>
      {html === null ? null : (
        <details open>
          <summary>blocksToHtml output</summary>
          <pre style={{ whiteSpace: 'pre-wrap', fontSize: 12 }}>{html}</pre>
        </details>
      )}
      <EventLog entries={log} />
    </div>
  );
}
```

## Mentions and labels

`mentions={{ items }}` and `labels={{ items }}` attach the contenteditable
`Mention` to the editor: `@` inserts a mention atom, `#` a label
atom (the item's `tone` colors it). Both triggers can be changed; `items` is
an array or a `@salmonui/data` source.

## Images, code and tables

The image entry of the slash menu opens a file picker. With
`onUpload(file) => Promise<{ src, alt? }>` the block is pending until the
upload settles; without it the image is a blob URL. The caption is editable
text under the image. Hovering the image shows a resize handle (always
shown, and larger, on touch screens); dragging it scales the image with its
aspect ratio and writes `width` and `height` to the block on release, so the
drag itself never re-renders React. The block menu's image settings edit the
alternative text and the width from the keyboard. An image dropped or
pasted into text becomes its own block.

Code blocks take `codeLanguages` (the language picker, a labelled
"Code language" select with "Plain text" first) and the `highlight` hook of
`RichTextEditor`: `(code, language) => { from, to, className }[]`, applied
as decorations, so the classes style the editor but never reach the block
value. Choosing a language sets the block's `props.language`.

```tsx
<BlockEditor
  codeLanguages={[{ value: 'ts', label: 'TypeScript' }, { value: 'css', label: 'CSS' }]}
  highlight={(code) => [...code.matchAll(/\b(const|let)\b/g)].map((m) => ({ from: m.index, to: m.index + m[0].length, className: 'tok-keyword' }))}
/>
```

Table blocks use the table
commands: insert and delete rows and columns, merge and split cells, toggle
the header row, from the block menu or `runCommand`.

## Paste

Paste goes through the shared paste cleanup: `pasteCleanup={{ mode:
'clean' }}` by default, `'keep'`, `'plainText'` or `'prompt'`, plus tag and
attribute filters. Word and Google Docs content arrives as real headings,
lists and marks. `onBeforePaste({ html, text, files })` can cancel a paste
with `preventDefault()`; `onPaste({ html, text, blocks })` follows it. All
content is sanitized: only the schema's nodes and marks survive and
text is always escaped, so there is no encode switch. See
[HTML sanitizer and paste cleanup](https://salmonui.dev/docs/editors/html-sanitizer-and-paste).

## Undo, keys and Markdown

Every edit, including block moves and menu actions, is one undo step:
Ctrl+Z (Cmd+Z), Ctrl+Y or Ctrl+Shift+Z; `undoLimit` sets the depth.
Under collaboration, undo is per user.

Default keys, rebindable with `keyBindings={{ commandId:
'Mod-Shift-x' }}` (`false` removes a default):

| Keys | Command |
| --- | --- |
| Ctrl/Cmd+Shift+Arrow Up / Down | `moveBlockUp` / `moveBlockDown` |
| Ctrl/Cmd+D | `duplicateBlock` |
| Ctrl/Cmd+Shift+Backspace | `deleteBlock` |
| Alt+F10 | Focus the selection toolbar, or open the block menu |
| Shift+F10 | `contextMenu` |
| Ctrl/Cmd+P | `print` |
| Tab / Shift+Tab | Nest / unnest a list item |

The `RichTextEditor` formatting keys work as well. Markdown shortcuts turn a
block as you type: `# ` to `###### ` headings, `- ` or `* ` bullets, `1. `
numbers, `[] ` checklist items, `> ` quotes and three backticks code.

The editing surface is `role="textbox"` with `aria-multiline`, labelled by
`aria-label` or `aria-labelledby`; menus are `role="menu"`, the slash menu a
`listbox`, and the selection toolbar an APG toolbar.

## Read only, print and events

`readOnly` keeps the content selectable but not editable and removes the
handles and menus. `actionsRef.current.print()` prints the content
only, with the page's styles.

Events: `onChange(blocks)`, `onBlockChange({ type: 'add' | 'update'
| 'remove' | 'move', block })`, `onSelectionChange({ blockId, offset } |
null)`, `onFocus` and `onBlur`.

`localeText` replaces any string; the direction is inherited from the page,
so under `dir="rtl"` the handles sit on the right; `className` and `style`
go to the root.

## Collaboration

`@salmonui/rich-text/collab` adds Yjs collaboration to
`BlockEditor` and `RichTextEditor` through `extensions`. The application
owns the `Y.Doc`, the provider (y-websocket, WebRTC, ...) and the server:

```tsx
import { createCollaboration } from '@salmonui/rich-text/collab';

const extensions = useMemo(
  () => [createCollaboration({ doc, awareness: provider.awareness, user: { id: me.id, name: me.name, color: '#2563eb' } })],
  [doc, provider],
);

<BlockEditor aria-label="Notes" extensions={extensions} />
```

Edits sync through the `Y.Doc`; with `awareness`, remote cursors and
selections show each user's name and color; the engine's history is
replaced by the Yjs undo manager, so undo reverts only your own changes. The
`Y.Doc` is the source of truth: seed it once with `await
seedCollaborationDoc(doc, html)` and read it with `await
collaborationDocToHtml(doc)` (server rendering, persistence) instead of
driving the editor with a controlled `value`.

### Live demo: Block Editor collaboration

Live demo: https://salmonui.dev/demos/editors/block-editor-collab

Two BlockEditors on one shared Yjs document through @salmonui/rich-text/collab - live edits, remote cursors with names and colors, per-user undo, a seeded document and its HTML read back.

`Demo.tsx`:

```tsx
'use client';

import { useEffect, useState } from 'react';
import * as Y from 'yjs';
import { Awareness, applyAwarenessUpdate, encodeAwarenessUpdate } from 'y-protocols/awareness';
import { BlockEditor, RichTextContent, type RichTextExtension } from '@salmonui/rich-text';
import { collaborationDocToHtml, createCollaboration, seedCollaborationDoc } from '@salmonui/rich-text/collab';
import '@salmonui/rich-text/styles.css';
import { Button } from '@salmonui/buttons/button';

interface Peer {
  readonly name: string;
  readonly doc: Y.Doc;
  readonly awareness: Awareness;
  readonly extensions: readonly RichTextExtension[];
}

type AwarenessChange = { added: number[]; updated: number[]; removed: number[] };

const SEED =
  '<h2 data-block-id="title">Shared agenda</h2>' +
  '<p data-block-id="p1">Both editors edit one Yjs document. Type here and watch the other side.</p>' +
  '<ul data-type="checklist"><li data-checked="false" data-block-id="c1"><p>Pick a launch date</p></li></ul>';

/**
 * Two peers in one page, each with its own Y.Doc and Awareness, connected by update events.
 * A real application connects one Y.Doc to its server with a provider (y-websocket, WebRTC, ...).
 */
async function connect(): Promise<[Peer, Peer]> {
  const a = new Y.Doc();
  const b = new Y.Doc();
  await seedCollaborationDoc(a, SEED);
  Y.applyUpdate(b, Y.encodeStateAsUpdate(a));
  a.on('update', (update: Uint8Array, origin: unknown) => origin !== 'peer' && Y.applyUpdate(b, update, 'peer'));
  b.on('update', (update: Uint8Array, origin: unknown) => origin !== 'peer' && Y.applyUpdate(a, update, 'peer'));
  const wa = new Awareness(a);
  const wb = new Awareness(b);
  wa.on('update', ({ added, updated, removed }: AwarenessChange, origin: unknown) => {
    if (origin !== 'peer') applyAwarenessUpdate(wb, encodeAwarenessUpdate(wa, [...added, ...updated, ...removed]), 'peer');
  });
  wb.on('update', ({ added, updated, removed }: AwarenessChange, origin: unknown) => {
    if (origin !== 'peer') applyAwarenessUpdate(wa, encodeAwarenessUpdate(wb, [...added, ...updated, ...removed]), 'peer');
  });
  return [
    { name: 'Ana', doc: a, awareness: wa, extensions: [createCollaboration({ doc: a, awareness: wa, user: { id: 'ana', name: 'Ana', color: '#2563eb' } })] },
    { name: 'Ben', doc: b, awareness: wb, extensions: [createCollaboration({ doc: b, awareness: wb, user: { id: 'ben', name: 'Ben', color: '#db2777' } })] },
  ];
}

export default function BlockEditorCollabDemo() {
  // Yjs documents and awareness timers exist only in the browser: the server renders the loading state.
  const [peers, setPeers] = useState<[Peer, Peer] | null>(null);
  const [html, setHtml] = useState<string | null>(null);
  useEffect(() => {
    let live = true;
    let created: [Peer, Peer] | null = null;
    const destroy = (pair: [Peer, Peer]) => {
      for (const peer of pair) {
        peer.awareness.destroy();
        peer.doc.destroy();
      }
    };
    void connect().then((pair) => {
      created = pair;
      if (live) setPeers(pair);
      else destroy(pair);
    });
    return () => {
      live = false;
      if (created) destroy(created);
    };
  }, []);
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      {peers ? (
        <div style={{ display: 'grid', gap: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))' }}>
          {peers.map((peer) => (
            <section key={peer.name} aria-label={`${peer.name}'s editor`} style={{ display: 'grid', alignContent: 'start', gap: 8, padding: 12, border: '1px solid var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-lg)', background: 'var(--salmon-surface-base)' }}>
              <strong>{peer.name}</strong>
              <BlockEditor aria-label={`${peer.name}'s document`} extensions={peer.extensions} style={{ minBlockSize: 160 }} />
            </section>
          ))}
        </div>
      ) : (
        <div style={{ display: 'grid', gap: 6 }}>
          <p role="status" style={{ margin: 0 }}>
            Connecting the two editors…
          </p>
          <RichTextContent value={SEED} aria-label="Shared agenda (loading)" />
        </div>
      )}
      <div>
        <Button variant="outline" type="button" disabled={!peers} onClick={() => peers && void collaborationDocToHtml(peers[0].doc).then(setHtml)}>
          collaborationDocToHtml(doc)
        </Button>
      </div>
      {html === null ? null : <pre style={{ whiteSpace: 'pre-wrap', fontSize: 12 }}>{html}</pre>}
    </div>
  );
}
```

## Design notes

- Version history (`getVersionHistory`) is not included: it needs a
  snapshot store, diffing and a restore UI whose storage the application
  owns. Keep
  snapshots of the `onChange` value, or Yjs snapshots under `/collab`, and
  restore one by passing it back as `value`.
- There is no built-in persistence: components never write to
  `localStorage` on their own, because hidden persistence breaks server
  rendering consistency; store what `onChange` reports and pass it back as
  `value`.
- Block edits are array edits on the value plus `actionsRef`. The value is
  JSON already, so it is the saved format; convert to and from HTML with
  `blocksToHtml` / `htmlToBlocks`.

## API reference

[`@salmonui/rich-text`](https://salmonui.dev/docs/reference/rich-text) lists `BlockEditor`,
its `BlockEditorActions`, the block types and the serialization helpers;
[`@salmonui/rich-text/collab`](https://salmonui.dev/docs/reference/rich-text/collab) the
collaboration helpers.
