# Rich Text Editor

> RichTextEditor from @salmonui/rich-text - an HTML editor on ProseMirror that server-renders its value, with toolbars, quick toolbars, tables, media uploads through callbacks, find and replace, source view, mentions and a streaming AI hook.

Canonical: https://salmonui.dev/docs/editors/rich-text-editor

`RichTextEditor` edits an HTML value. It lives in
`@salmonui/rich-text`, the one Salmon UI package that may use ProseMirror;
every other package except `@salmonui/pdf-viewer` has no runtime
dependencies.

```tsx
import { RichTextEditor } from '@salmonui/rich-text';
import '@salmonui/rich-text/styles.css';

<RichTextEditor
  aria-label="Body"
  defaultValue="<p>Hello</p>"
  onChange={(html) => save(html)}
  onUpload={async (file) => ({ src: await uploadToServer(file) })}
/>;
```

The stylesheet carries the button, menu and mention rules the toolbar and
the mention list render, so it is the only stylesheet besides
`@salmonui/core/styles.css` (the theme, once per app).

## Server rendering and loading

The server renders the toolbar shell and the sanitized HTML of `value`
inside the content element (`role="textbox"`, `aria-multiline`). After
hydration the editing engine loads with one dynamic `import()` and mounts
on that same element, so the markup matches and there is no hydration
warning. The root entry never loads ProseMirror on the server;
`loadRichTextEngine()` preloads it on the client if you want the first
keystroke to be instant. To show stored HTML read-only, use
[`RichTextContent`](https://salmonui.dev/docs/editors/rich-text-content).

## Value

`value` / `defaultValue` hold an HTML string; `onChange(html)` fires once
per batch of transactions, `changeDelay` (ms) widens the batch, and `onBlur(html)` gives a
change-on-blur timing. A controlled `value` goes into the engine, never through
React re-rendering the content. Every value in and every HTML out passes
the always-on sanitizer (see
[HTML sanitizer and paste cleanup](https://salmonui.dev/docs/editors/html-sanitizer-and-paste)).

Through `actionsRef`:

| Member | Does |
| --- | --- |
| `getHtml({ xhtml? })` | The HTML value; `xhtml: true` self-closes void elements |
| `getText()` | Plain text, blocks joined by new lines |
| `commands.bold()`, `commands.insertTable({ rows, cols })`, ... | Typed commands; each fires `onBeforeCommand` (cancellable) and `onCommand` |
| `run(id, ...args)` | A command or toolbar action by id |
| `getSelection()` / `setSelection(anchor, head)` / `focus()` | Selection API |
| `clearHistory()` | Empties undo and redo |
| `openDialog(id)` / `closeDialog()` | Built-in dialogs |
| `insertFiles(files)` | Inserts images or media through `onUpload` |

There is no `refreshUI`: toolbar state follows the editor state.

## Toolbar

`toolbar` lists built-in item ids, `'|'` separators and custom items
(`{ id, label, icon, onClick, pressed, disabled }`); a built-in id can be
written `{ id: 'bold', disabled: true }`. Defaults are in
`RICH_TEXT_DEFAULT_TOOLBAR`. Items are `Button`, `ToggleButton` and
`MenuButton` from `@salmonui/buttons`, inside an APG toolbar: one tab stop,
arrow keys move between items, Alt+F10 in the editor focuses the toolbar and
Escape returns.

- `toolbarOverflow`: `'menu'` (default) moves
  what does not fit into a "More" menu, `'scroll'` scrolls, `'wrap'` uses
  several rows.
- `toolbarPosition: 'top' | 'bottom'`, `stickyToolbar`.
- `toolbar="floating"` shows the toolbar only over a text selection;
`toolbar={false}` hides it.
- `quickToolbars`: item lists per context (`link`, `image`, `table`, `text`,
  `audio`, `video`; `false` hides one), shown in a popover next to the
  selected link, image, table or media. The defaults are
  `RICH_TEXT_DEFAULT_QUICK_TOOLBARS`. The `text` quick toolbar appears over
  a text selection only when you give it a list (or with
  `toolbar="floating"`). An audio or video node selected with the arrow
  keys shows the `audio` or `video` list.

```tsx
<RichTextEditor
  quickToolbars={{
    text: ['bold', 'italic'],            // a selection toolbar next to the fixed one
    video: ['alignments', 'removeNode'],
    link: false,                         // no link popover
  }}
/>
```

### Live demo: Inline rich text toolbar

Live demo: https://salmonui.dev/demos/editors/rich-text-editor-inline

RichTextEditor in inline mode - toolbar="floating" shows a toolbar over the selection with links, the format painter and the emoji picker; the link quick toolbar opens, edits and removes links.

`Demo.tsx`:

```tsx
'use client';

import { RichTextEditor, type RichTextEmoji } from '@salmonui/rich-text';
import '@salmonui/rich-text/styles.css';
import { EventLog, useEventLog } from '../../components/demo-kit';

const initial =
  '<h3>Team update</h3>' +
  '<p>This editor has no fixed toolbar: <strong><em>select any text</em></strong> and the toolbar appears over the selection.</p>' +
  '<p>Read the <a href="https://example.com/changelog" target="_blank" rel="noopener noreferrer">changelog</a> for details. Plain text here waits for the format painter.</p>' +
  '<p>Type a colon and a word, like :rocket or :tada, for emoji.</p>';

// A short emoji list replaces the built-in lazy one (emojiList).
const EMOJI: readonly RichTextEmoji[] = [
  { emoji: '🚀', name: 'rocket', keywords: ['launch', 'ship'] },
  { emoji: '🎉', name: 'tada', keywords: ['party', 'celebrate'] },
  { emoji: '✅', name: 'check', keywords: ['done', 'yes'] },
  { emoji: '⚠️', name: 'warning', keywords: ['risk', 'careful'] },
  { emoji: '👀', name: 'eyes', keywords: ['look', 'review'] },
  { emoji: '🐟', name: 'fish', keywords: ['salmon'] },
];

export default function RichTextEditorInlineDemo() {
  const [log, push] = useEventLog();
  return (
    <div style={{ display: 'grid', gap: 12, maxWidth: 720 }}>
      <RichTextEditor
        aria-label="Team update"
        defaultValue={initial}
        toolbar="floating"
        quickToolbars={{
          text: ['bold', 'italic', 'underline', 'fontColor', '|', 'link', 'formatPainter', 'emoji', 'clearFormat'],
          link: ['openLink', 'editLink', 'removeLink'],
        }}
        emojiList={EMOJI}
        placeholder="Write an update"
        onBeforePopupOpen={(event) => push(`onBeforePopupOpen: ${event.popup}`)}
        onCommand={(event) => push(`onCommand: ${event.command}${event.args.length ? ` ${JSON.stringify(event.args)}` : ''}`)}
        onDialogClose={(event) => push(`onDialogClose: ${event.dialog}`)}
        style={{ minBlockSize: 220 }}
      />
      <EventLog entries={log} />
    </div>
  );
}
```

## Formatting

Marks: bold, italic, underline, strikethrough, subscript, superscript,
inline code, font family, font size, text color and background color, plus
uppercase and lowercase commands (`fontFamilies`, `fontSizes`,
`colors` set the pickers). Blocks: paragraph and heading formats,
alignment, bulleted, numbered and checklists with list styles, indent and
outdent, line height, blockquote, horizontal rule and clear format.
The format painter copies marks and the block format: a click applies once,
a double click keeps applying, Escape ends. Markdown-style input
rules (`# `, `- `, `1. `, `> `, `[] `, ```` `) work as you type.

## Links, images, media, tables and code

- Links: insert and edit dialog (text, URL, open in a new window, which adds
  `rel="noopener noreferrer"`), and a quick toolbar to open, edit or remove.
Unsafe URLs are refused.
- Images: dialog (URL, alt, size, caption), resize handles, and
  `onUpload(file) => Promise<{ src, alt? }>`. A pasted or dropped image shows
  a pending placeholder until the promise settles; a rejection removes it
  and calls `onUploadError`. Without `onUpload`, `imageInsert` is `'blob'`
  (default) or `'base64'`.
- Audio and video from a URL or `onUpload`, rendered with native controls;
  embeds (`<iframe>`) only from hosts in `embedHosts`.
- Tables: insert dialog, row and column insert and delete, header row, merge
  and split cells, column resize by dragging, table styles.
- Code blocks with a `codeLanguages` picker; `highlight(code, language)`
  decorates them, no highlighter is bundled.
- `onBrowseFiles(kind)` opens your own file browser from the image and media
  dialogs.

## Paste, import and export

`pasteCleanup` normalizes Word and Google Docs HTML to the editor
vocabulary, keeps it, pastes plain text, or prompts. There is no
built-in Word or PDF service: `onImport(file) => Promise<string>`
receives the file from the import item and returns HTML that is sanitized
and inserted, and `getHtml()` gives the HTML to export. A server converts
Word files (for example with mammoth, LibreOffice or a document server) and
renders PDF from that HTML; built-in DOCX interop is not included.

### Live demo: Rich text media, code, import and AI

Live demo: https://salmonui.dev/demos/editors/rich-text-editor-insert

RichTextEditor inserts - audio and video from a URL or an upload, allow-listed embeds, a code block with an application highlight hook, an application file browser, file import, HTML export and a streaming, provider-agnostic AI assistant.

`Demo.tsx`:

```tsx
'use client';

import { useEffect, useRef, useState } from 'react';
import { RichTextEditor, type RichTextAiRequest, type RichTextEditorActions } from '@salmonui/rich-text';
import { Button } from '@salmonui/buttons/button';
import '@salmonui/rich-text/styles.css';
import { EventLog, useEventLog } from '../../components/demo-kit';

const initial =
  '<h3>Release kit</h3>' +
  '<p>Insert media from the Audio and Video items, browse the demo assets from the Image or Audio dialog, import a file, or ask the assistant.</p>' +
  '<pre><code class="language-ts">const answer = 42;\n// a comment\nexport function greet(name: string) {\n  return `Hello ${name}`;\n}</code></pre>';

/** A tiny tokenizer for the highlight hook (no highlighter is bundled): keywords, strings and comments. */
const highlight = (code: string) => {
  const ranges: { from: number; to: number; className: string }[] = [];
  for (const m of code.matchAll(/\/\/[^\n]*|`[^`]*`|'[^']*'|"[^"]*"|\b(?:const|let|function|return|export|import|from)\b/g)) {
    const text = m[0];
    const className = text.startsWith('//') ? 'demo-tok-comment' : /^[`'"]/.test(text) ? 'demo-tok-string' : 'demo-tok-keyword';
    ranges.push({ from: m.index, to: m.index + text.length, className });
  }
  return ranges;
};

/** One second of a 440 Hz tone as a WAV object URL, generated in the browser. */
function makeTone(): string {
  const rate = 8000;
  const samples = rate;
  const view = new DataView(new ArrayBuffer(44 + samples * 2));
  const text = (offset: number, value: string) => [...value].forEach((ch, i) => view.setUint8(offset + i, ch.charCodeAt(0)));
  text(0, 'RIFF');
  view.setUint32(4, 36 + samples * 2, true);
  text(8, 'WAVEfmt ');
  view.setUint32(16, 16, true);
  view.setUint16(20, 1, true);
  view.setUint16(22, 1, true);
  view.setUint32(24, rate, true);
  view.setUint32(28, rate * 2, true);
  view.setUint16(32, 2, true);
  view.setUint16(34, 16, true);
  text(36, 'data');
  view.setUint32(40, samples * 2, true);
  for (let i = 0; i < samples; i++) view.setInt16(44 + i * 2, Math.sin((2 * Math.PI * 440 * i) / rate) * 8000 * (1 - i / samples), true);
  return URL.createObjectURL(new Blob([view], { type: 'audio/wav' }));
}

function makeSwatch(color: string): string {
  const c = document.createElement('canvas');
  c.width = 160;
  c.height = 90;
  const ctx = c.getContext('2d')!;
  ctx.fillStyle = color;
  ctx.fillRect(0, 0, 160, 90);
  ctx.fillStyle = '#ffffff';
  ctx.font = 'bold 18px sans-serif';
  ctx.fillText(color, 12, 52);
  return c.toDataURL('image/png');
}

type Asset = { readonly kind: 'image' | 'audio'; readonly src: string; readonly alt: string };
type Browse = { readonly kind: 'image' | 'audio' | 'video'; readonly resolve: (asset: { src: string; alt?: string } | null) => void };

const wait = (ms: number, signal: AbortSignal) =>
  new Promise<void>((resolve, reject) => {
    const timer = setTimeout(resolve, ms);
    signal.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(new DOMException('Aborted', 'AbortError'));
    });
  });

/** A provider-agnostic assistant: an application would call its own model endpoint and stream the text back. */
async function* fakeAssistant({ prompt, selectionHtml, signal }: RichTextAiRequest): AsyncIterable<string> {
  const subject = selectionHtml ? 'the selected text' : 'this document';
  const answer = `Here is a short take on ${subject} for "${prompt}": the release kit bundles audio, video and code samples, and every insert stays editable.`;
  for (const word of answer.split(' ')) {
    await wait(60, signal);
    yield `${word} `;
  }
}

const readText = (file: File) => file.text();
const escapeHtml = (text: string) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

export default function RichTextEditorInsertDemo() {
  const [log, push] = useEventLog();
  const [assets, setAssets] = useState<readonly Asset[]>([]);
  const [browse, setBrowse] = useState<Browse | null>(null);
  const actions = useRef<RichTextEditorActions | null>(null);
  // Generated assets need the DOM: create them after hydration.
  useEffect(() => {
    setAssets([
      { kind: 'image', src: makeSwatch('#2f7d6d'), alt: 'Teal swatch' },
      { kind: 'image', src: makeSwatch('#c0563c'), alt: 'Salmon swatch' },
      { kind: 'audio', src: makeTone(), alt: 'A 440 Hz tone' },
    ]);
  }, []);
  const dialog = useRef<HTMLDialogElement | null>(null);
  useEffect(() => {
    if (browse && !dialog.current?.open) dialog.current?.showModal();
  }, [browse]);
  const pick = (asset: { src: string; alt?: string } | null) => {
    browse?.resolve(asset);
    setBrowse(null);
    dialog.current?.close();
  };
  const choices = browse ? assets.filter((asset) => asset.kind === browse.kind) : [];
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <style>{'.demo-tok-keyword{color:#a0427a;font-weight:600}.demo-tok-string{color:#2f7d4f}.demo-tok-comment{color:#6b7280;font-style:italic}'}</style>
      <RichTextEditor
        aria-label="Release kit"
        defaultValue={initial}
        actionsRef={actions}
        toolbar={['bold', 'italic', '|', 'image', 'audio', 'video', 'embed', 'codeBlock', '|', 'import', 'aiAssistant', '|', 'undo', 'redo']}
        embedHosts={['www.youtube-nocookie.com', 'player.vimeo.com']}
        codeLanguages={[
          { value: 'ts', label: 'TypeScript' },
          { value: 'css', label: 'CSS' },
        ]}
        highlight={highlight}
        onUpload={async (file) => ({ src: URL.createObjectURL(file), alt: file.name })}
        onBrowseFiles={(kind) => {
          push(`onBrowseFiles: ${kind}`);
          return new Promise((resolve) => setBrowse({ kind, resolve }));
        }}
        aiAssistant={{ onRequest: fakeAssistant }}
        importAccept=".html,.htm,.txt,.md"
        onImport={async (file) => {
          push(`onImport: ${file.name}`);
          const text = await readText(file);
          return /\.html?$/i.test(file.name) ? text : text.split(/\n{2,}/).map((block) => `<p>${escapeHtml(block)}</p>`).join('');
        }}
        onCommand={(event) => push(`onCommand: ${event.command}`)}
        style={{ minBlockSize: 320 }}
      />
      {/* The application's file browser: a native modal dialog above the editor's own dialog. */}
      <dialog
        ref={dialog}
        aria-label={`Demo ${browse?.kind ?? ''} files`}
        onCancel={() => pick(null)}
        style={{ padding: 16, border: '1px solid var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-lg)', background: 'var(--salmon-surface-overlay)', color: 'inherit' }}
      >
        <p style={{ marginBlockStart: 0 }}>
          <strong>Your file browser ({browse?.kind})</strong>
        </p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {choices.length === 0 ? <span>No {browse?.kind} files in this demo.</span> : null}
          {choices.map((asset) => (
            <Button key={asset.alt} variant="outline"onClick={() => pick({ src: asset.src, alt: asset.alt })}>
              {asset.alt}
            </Button>
          ))}
          <Button variant="outline" onClick={() => pick(null)}>
            Cancel
          </Button>
        </div>
      </dialog>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        <Button
          variant="outline"
          disabled={assets.length === 0}
          onClick={() => {
            const tone = assets.find((asset) => asset.kind === 'audio');
            if (tone) actions.current?.commands.insertAudio({ src: tone.src });
          }}
        >
          Insert the generated tone
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            const html = actions.current?.getHtml() ?? '';
            const url = URL.createObjectURL(new Blob([`<!doctype html><meta charset="utf-8"><title>Release kit</title>${html}`], { type: 'text/html' }));
            const link = document.createElement('a');
            link.href = url;
            link.download = 'release-kit.html';
            link.click();
            URL.revokeObjectURL(url);
          }}
        >
          Export HTML
        </Button>
      </div>
      <EventLog entries={log} />
    </div>
  );
}
```

## Find and replace, source view, count, fullscreen, print

- Find and replace: highlighted matches, next and previous, replace and
  replace all, from the `'findReplace'` toolbar item.
- `'sourceCode'` switches to an HTML textarea; switching back sanitizes it.
- `showCount` shows the character count in the status bar; `maxLength` is
  enforced by a transaction filter, so typing and pasting past it is
  refused while deletions still apply; the count is announced politely at
  thresholds only.
- `resizable`, controlled `fullscreen` / `onFullscreenChange`, and
  `'print'`, which prints the content only.

## Slash menu, emoji and mentions

- `/` at the start of a word opens the block menu (`slashMenu`: `true`, or
  your own items with `onSelect`).
- The `'emoji'` item and `:` open the emoji picker (search, arrows, Enter);
  the built-in list is a lazy chunk, `emojiList` replaces it.
- `mentions={{ trigger: '@', items | onSearch, renderItem }}` attaches
  [`Mention`](https://salmonui.dev/docs/dropdowns/mention) to the editor and inserts mention
  nodes.

## AI assistant

`aiAssistant={{ onRequest({ prompt, selectionHtml, signal }) }}` may return
a string or an `AsyncIterable<string>`. The answer streams into a pending
insert that the user accepts or discards. Model output is inserted as
escaped text, never rendered as HTML. There is no built-in model or
provider. WebMCP tool registration is not built in:
register `actionsRef` commands yourself.

## Keyboard, Enter and Tab

The default shortcuts are the common editor ones (Mod+B, Mod+I, Mod+U, Mod+Z,
Mod+Shift+Z, Mod+Y, Mod+K for a link, Mod+Shift+F for fullscreen, Mod+Shift+H for the source view, ...); `keyBindings` maps a key to a
command id, an action id, a function, or `false` to remove a default.
`enterKey` (`'p'`, `'div'`, `'br'`) and `shiftEnterKey` choose
what Enter and Shift+Enter insert; `tabKey: 'focus'` (default) leaves Tab to
the page, `'indent'` indents.

## Undo

Transaction history with `undoLimit` and `undoGroupDelay` (ms between
typing groups); toolbar items `'undo'`, `'redo'`.

## Forms, states and events

`name` renders a hidden input with the HTML value, form reset restores
`defaultValue`, `required` blocks an empty submit, and `invalid` sets
`aria-invalid`. `placeholder`, `readOnly` and `disabled`.

Inside a [`Field`](https://salmonui.dev/docs/inputs/field) the editor uses the Field error
display of the Inputs components: the field label names the editor
(`aria-labelledby`), the description and the visible error are in
`aria-describedby`, `aria-errormessage` points at the error, and the
Field's rules run on blur and when a submit reaches the empty `required`
editor. Pass the HTML to the Field as `value` (an empty editor reports
`''`):

```tsx
import { Field } from '@salmonui/inputs/form';
import '@salmonui/inputs/form/styles.css';

<Field label="Article body" description="Shown on the front page" name="body" validation={{ required: true }} value={html}>
  {() => <RichTextEditor name="body" required defaultValue="" onChange={setHtml} />}
</Field>
```

Events come in before/after pairs: `onBeforeCommand` / `onCommand`,
`onToolbarItemClick`, `onBeforeDialogOpen` / `onDialogClose`,
`onBeforePopupOpen`, `onToolbarStateChange`.

### Live demo: Rich text API, forms and events

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

RichTextEditor driven from code and forms - typed commands, selection and history through actionsRef, Enter and Tab configuration, a custom key binding, readOnly and disabled, a disabled toolbar item, required form submit and reset, every before/after event, right to left and localized labels.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { RichTextEditor, type RichTextEditorActions } from '@salmonui/rich-text';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import '@salmonui/rich-text/styles.css';
import { EventLog, useEventLog } from '../../components/demo-kit';

const initial = '<p>Edit this note, then try the buttons below the editor.</p>';

const FR_TEXT = { toolbar: 'Mise en forme', bold: 'Gras', italic: 'Italique', underline: 'Souligné', undo: 'Annuler', redo: 'Rétablir', link: 'Lien', table: 'Tableau' };

const ENTER_KEYS = ['p', 'div', 'br'];
const TAB_KEYS = ['focus', 'indent'];
const STATES = ['editable', 'readOnly', 'disabled'];

export default function RichTextEditorApiDemo() {
  const [log, push] = useEventLog();
  const [enterKey, setEnterKey] = useState<'p' | 'div' | 'br'>('p');
  const [tabKey, setTabKey] = useState<'focus' | 'indent'>('focus');
  const [state, setState] = useState<'editable' | 'readOnly' | 'disabled'>('editable');
  const [blockTables, setBlockTables] = useState(false);
  const [underlineOff, setUnderlineOff] = useState(false);
  const [rtl, setRtl] = useState(false);
  const [french, setFrench] = useState(false);
  const [html, setHtml] = useState('');
  const [submitted, setSubmitted] = useState<string | null>(null);
  const [history, setHistory] = useState('nothing to undo, nothing to redo');
  const actions = useRef<RichTextEditorActions | null>(null);
  const run = (label: string, fn: (a: RichTextEditorActions) => unknown) => () => {
    const a = actions.current;
    if (!a) return;
    const result = fn(a);
    if (result !== undefined) push(`${label}: ${typeof result === 'string' ? result : JSON.stringify(result)}`);
  };
  return (
    <form
      style={{ display: 'grid', gap: 12 }}
      onSubmit={(event) => {
        event.preventDefault();
        setSubmitted(String(new FormData(event.currentTarget).get('note') ?? ''));
      }}
      onReset={() => setSubmitted(null)}
    >
      <fieldset style={{ display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center', border: 0, margin: 0, padding: 0 }}>
        <legend style={{ fontWeight: 600, padding: 0 }}>Options</legend>
        <label>
          enterKey{' '}
          <Select aria-label="enterKey" data={ENTER_KEYS} value={enterKey} onValueChange={(value) => value != null && setEnterKey(value as typeof enterKey)} />
        </label>
        <label>
          tabKey{' '}
          <Select aria-label="tabKey" data={TAB_KEYS} value={tabKey} onValueChange={(value) => value != null && setTabKey(value as typeof tabKey)} />
        </label>
        <label>
          State{' '}
          <Select aria-label="State" data={STATES} value={state} onValueChange={(value) => value != null && setState(value as typeof state)} />
        </label>
        <Checkbox checked={blockTables} onCheckedChange={(checked) => setBlockTables(checked)}>
          Cancel table dialogs
        </Checkbox>
        <Checkbox checked={underlineOff} onCheckedChange={(checked) => setUnderlineOff(checked)}>
          Disable Underline
        </Checkbox>
        <Checkbox checked={rtl} onCheckedChange={(checked) => setRtl(checked)}>
          dir=&quot;rtl&quot;
        </Checkbox>
        <Checkbox checked={french} onCheckedChange={(checked) => setFrench(checked)}>
          French labels
        </Checkbox>
      </fieldset>
      <div dir={rtl ? 'rtl' : 'ltr'}>
        <RichTextEditor
          aria-label="Note"
          name="note"
          required
          defaultValue={initial}
          placeholder="Write a note (required)"
          readOnly={state === 'readOnly'}
          disabled={state === 'disabled'}
          actionsRef={actions}
          onChange={setHtml}
          toolbar={['undo', 'redo', '|', 'bold', 'italic', { id: 'underline', disabled: underlineOff }, '|', 'unorderedList', 'link', 'table']}
          enterKey={enterKey}
          shiftEnterKey="br"
          tabKey={tabKey}
          undoLimit={50}
          undoGroupDelay={800}
          keyBindings={{ 'Mod-Shift-x': 'strike' }}
          localeText={french ? FR_TEXT : {}}
          onBeforeCommand={(event) => push(`onBeforeCommand: ${event.command}`)}
          onCommand={(event) => push(`onCommand: ${event.command} (applied: ${event.applied})`)}
          onToolbarItemClick={(event) => push(`onToolbarItemClick: ${event.id}`)}
          onBeforeDialogOpen={(event) => {
            if (blockTables && event.dialog === 'table') {
              event.preventDefault();
              push('onBeforeDialogOpen: table cancelled');
            } else push(`onBeforeDialogOpen: ${event.dialog}`);
          }}
          onDialogClose={(event) => push(`onDialogClose: ${event.dialog}`)}
          onToolbarStateChange={(toolbarState) => {
            setHistory(`${toolbarState.canUndo ? 'can undo' : 'nothing to undo'}, ${toolbarState.canRedo ? 'can redo' : 'nothing to redo'}`);
          }}
          style={{ minBlockSize: 200, inlineSize: '100%' }}
        />
      </div>
      <div role="group" aria-label="Editor actions" style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        <Button variant="outline" onClick={run('commands.bold()', (a) => a.commands.bold())}>
          commands.bold()
        </Button>
        <Button variant="outline" onClick={run('commands.insertTable', (a) => a.commands.insertTable({ rows: 2, cols: 3, headerRow: true }))}>
          commands.insertTable(2 × 3)
        </Button>
        <Button variant="outline" onClick={run('getSelection()', (a) => a.getSelection())}>
          getSelection()
        </Button>
        <Button
          variant="outline"
          onClick={run('setSelection(1, 5)', (a) => {
            a.setSelection(1, 5);
            a.focus();
          })}
        >
          setSelection(1, 5) + focus()
        </Button>
        <Button variant="outline" onClick={run('undo()', (a) => a.commands.undo())}>
          undo()
        </Button>
        <Button variant="outline" onClick={run('redo()', (a) => a.commands.redo())}>
          redo()
        </Button>
        <Button variant="outline" onClick={run('clearHistory()', (a) => {
            a.clearHistory();
            return 'history cleared';
          })}>
          clearHistory()
        </Button>
        <Button variant="outline" onClick={run('openDialog', (a) => a.openDialog('link'))}>
          openDialog(&apos;link&apos;)
        </Button>
        <Button variant="outline" onClick={run('getHtml({ xhtml: true })', (a) => a.getHtml({ xhtml: true }))}>
          getHtml({'{'} xhtml: true {'}'})
        </Button>
      </div>
      <p style={{ margin: 0 }}>History (onToolbarStateChange): {history}</p>
      <div style={{ display: 'flex', gap: 8 }}>
        <Button type="submit">Submit</Button>
        <Button type="reset" variant="outline">Reset</Button>
      </div>
      <p aria-live="polite" style={{ margin: 0 }}>
        {submitted === null ? `Current value: ${html.length} characters of HTML.` : `Submitted note: ${submitted}`}
      </p>
      <EventLog entries={log} />
    </form>
  );
}
```

## Localization, RTL and styling

`localeText` (defaults in `RICH_TEXT_EDITOR_DEFAULT_LOCALE_TEXT`), inherited
`dir` (the toolbar mirrors, the content follows), `className` and `style`
on the root; set the size with CSS `width` and `height`. Colors
come from the theme seeds. There is no built-in persistence (see
[Design notes](https://salmonui.dev/docs/editors/rich-text-editor#design-notes)).

## Extensions

`extensions` adds nodes, marks, commands, key bindings, input rules,
toolbar items and ProseMirror plugins (an async plugin factory is awaited
before the editor mounts); collaboration from `@salmonui/rich-text/collab`
is one. See [Headless editor](https://salmonui.dev/docs/editors/headless-editor).

## Modern Rich Text Editor

A floating toolbar, slash menu, mentions, Markdown shortcuts and block
editing are configuration of `RichTextEditor`, see
[Modern Rich Text Editor](https://salmonui.dev/docs/editors/modern-rich-text-editor).

## Design notes

- No iframe mode: the content is a `contenteditable` element whose
  CSS is scoped under `.salmon-rich-text`, so the editor server-renders its
  value and shares the page theme. Scope custom content CSS under the
  editor's `className`.
- No built-in Word or PDF service: conversion needs a server, and
  the editor should not call a vendor endpoint. Use `onImport` for Word
  import and send `getHtml()` to your own converter for
  Word or PDF export.
- No built-in file browser: `onBrowseFiles(kind)` opens your own
  browser (see the
  [File Manager](https://salmonui.dev/docs/navigation/file-manager)).
- No built-in model: `aiAssistant.onRequest` calls your provider
  and handles each prompt request.
- No WebMCP tools: tool registration would tie the editor to one
  agent protocol that is still moving. Register `actionsRef.current.commands`
  as tools in application code, with your own confirmation step before a
  tool runs.
- 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` or
  `defaultValue`.
- `refreshUI` is not needed: toolbar state follows the editor state.

## API reference

[`@salmonui/rich-text`](https://salmonui.dev/docs/reference/rich-text) lists every prop,
command, callback and type of `RichTextEditor`, `RichTextContent`,
`BlockEditor` and the engine; [`@salmonui/rich-text/collab`](https://salmonui.dev/docs/reference/rich-text/collab)
the collaboration helpers.

### Live demo: Rich Text Editor

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

An HTML editor with the default toolbar, quick toolbars, tables, uploads through a callback, mentions, a character limit and the live HTML value.

`Demo.tsx`:

```tsx
'use client';

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

const people = [
  { value: 'ana', label: 'Ana Lima' },
  { value: 'ben', label: 'Ben Okafor' },
  { value: 'chen', label: 'Chen Wei' },
];

const initial =
  '<h2>Release notes</h2><p>Type <strong>/</strong> for blocks, <strong>@</strong> to mention someone and <strong>:</strong> for emoji.</p>' +
  '<ul><li><p>Select text for the quick toolbar</p></li><li><p>Paste from Word: the markup is cleaned</p></li></ul>' +
  '<table><tbody><tr><th><p>Area</p></th><th><p>Status</p></th></tr><tr><td><p>Editor</p></td><td><p>Ready</p></td></tr></tbody></table>';

// Uploads become object URLs here; an application sends the file to its server and returns the stored URL.
const upload = async (file: File) => ({ src: URL.createObjectURL(file), alt: file.name });

export default function RichTextEditorDemo() {
  const [log, push] = useEventLog();
  const [html, setHtml] = useState(initial);
  const actions = useRef<RichTextEditorActions | null>(null);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 12 }}>
      <RichTextEditor
        aria-label="Release notes"
        defaultValue={initial}
        actionsRef={actions}
        onChange={setHtml}
        changeDelay={150}
        onUpload={upload}
        mentions={{ items: people }}
        showCount
        maxLength={5000}
        resizable
        onCommand={(event) => push(`command: ${event.command}`)}
        style={{ minBlockSize: 320 }}
      />
      <details>
        <summary>HTML value ({html.length} characters)</summary>
        <pre style={{ whiteSpace: 'pre-wrap', fontSize: 12 }}>{html}</pre>
      </details>
      <EventLog entries={log} />
    </div>
  );
}
```
