Olddevs UI4.14.0
ReferenceRichTextEditor

Field and screen

Status bar and Field notice

Under the field inside the frame there are two independent areas. The Status bar is what the screen puts there itself: "Saved", a word count, a co-author. The Field notice is what the kit and Tools report: an upload result, a paste rejection. The first is a React node in the status prop, the second is data and an engine command.

Status bar: status

<RichTextEditor
  value={html}
  onChange={setHtml}
  maxLength={2000}
  status={
    <span className="flex gap-3">
      <span role="status">{saved ? "Saved" : ""}</span>
      <span>{countWords(html)} words</span>
    </span>
  }
/>
  • The line sits inside the field's frame, in the maxLength counter row: its own content at the start, the kit's counter at the end. Without maxLength, or while there is no counter (it appears at 80 % of the limit), the line is sized by its own content alone. An empty status (null, undefined, false, "") renders no line.
  • The container has no role and no aria-live: the kit does not announce the line. A word count changes on every edit, and reading it aloud would mean talking over typing. If you need "Saved" to be announced, wrap only that in role="status" (the example above; with autosave on onBlur, see the recipe on the extension API page). Do not wrap the whole line in role="status".
  • It is visible in readOnly and in disabled alike: it is part of the field's frame, not of editing. With disabled the frame is muted as a whole, like other fields, together with the line.
  • The counter keeps its id and stays in the field's aria-describedby while visible; the screen's content is not part of the field's description.
  • Take the data from your own state: the word count from value/onChange, "Saved" from the server's response. Tools have no access to the Status bar: it has no owning Tool.
  • The default color is the second text step; the size is 11 px, with monospace digits. Set your own color on your own node: the third text step does not reach a 4.5:1 contrast ratio on the field's background.
  • RichTextView has no Status bar: it shows sanitized HTML without an engine.

Field notice: showNotice

One area under the field and only the latest message: a new one replaces the previous one, and showNotice(null) clears it. A notice is data, not a React node: a tone and the finished text.

type FieldNotice = { tone: "status" | "error"; text: string };

// From the screen, through `ref.editor`:
ref.current?.editor?.commands.showNotice({ tone: "error", text: "Couldn't insert the card." });
ref.current?.editor?.commands.showNotice(null);
  • status is invisible and only announced: the text goes to a role="status" live region outside the Document. Visually, the upload progress is shown by a placeholder in the Document, and live regions inside contenteditable are not read everywhere. It stays until it is replaced or cleared; a User edit does not touch it.
  • error is visible as a role="alert" line under the field, above the Status bar, until the next User edit, a new notice or showNotice(null). An edit is any change to the Document; a programmatic value replacement and clear() do not count as an edit; setMarkdown() and setJSON() clear the error. Show an error when the Document did not change as a result: without the line it would look like "nothing happened".
  • The notice has no durations, close buttons or spinners of its own: it goes away on its own only after an edit; otherwise it is cleared by a command.
  • The command does not change the Document: no transaction, no history step, no onChange. editor.can().showNotice(…) does not show a notice.
  • A notice without text (text: "") is the same as null. The kit does not translate the text: it is shown as is, without markup. The kit's own messages (files) go through the editor.* message catalog, and the strings of custom Tools come from their own message catalog.
  • Who calls it. The screen — ref.current.editor.commands.showNotice(…). A custom Tool — from its Extensions: this.editor.commands.showNotice(…) in a Tiptap extension. Every Editor has the command regardless of tools, including without image. The FieldNotice type is exported from @olddevs/ui/editor; it also provides the types for editor.commands.showNotice.
  • Image messages go through the same channel: "Uploading photo.png…" and "photo.png uploaded" are status; an upload failure, "not an image" and "files can't be uploaded" are error. An error from a Tool and a file message share one area: a new one replaces the previous one.

Field height: maxHeight and resizable

By default the Editor grows with the Document, and a long text stretches the page. maxHeight limits the Document area: up to the limit the field grows as usual, beyond it the Document scrolls inside the frame. resizable adds a height handle at the area's bottom edge. The decision is ADR-0059.

<RichTextEditor aria-label="Description" maxHeight={320} value={html} onChange={setHtml} />
<RichTextEditor aria-label="Note" maxHeight="24rem" resizable defaultValue={draft} />
  • Units. A number is pixels, a string is any CSS length ("24rem", "60vh"). There is no row-count option like maxRows in TextControl: Blocks have different heights.
  • What scrolls. Only the Document area: the Document, its Skeleton, the Source mode field and the Block handle. The fixed Toolbar above it and the Status bar with the Field notice under it stay in place, the frame does not move. The scrollbar sits at the frame.
  • resizable with maxHeight — maxHeight becomes the starting height, not a limit: the field stretches both taller and shorter. Two systems that control height at the same time produce a field that jumps on every edit. The same reasoning applies to autosize in TextControl. Without maxHeight the start is the Document's height. The area does not shrink below 128 px (a few lines).
  • The height handle is the kit's own, not the browser's corner. The browser renders the native resize: vertical as its own corner, which ignores the theme: in a dark one it is a white square on the frame. The kit's handle is a strip at the area's bottom edge with a grip in the middle, styled like the SplitPanel strip: the grip is --line, on hover --fg-2, while dragging and on focus the accent. The visible strip is 10 px, the hit zone 26 px (WCAG 2.5.8). For keyboard users there is a slider "Resize the editor" (editor.resizeField, the value is editor.fieldHeight): the Up and Down arrow keys move it by 16 px, with Shift by a pixel; dragging with the mouse moves focus to it, so you can fine-tune the height with the arrow keys. A double click on the strip returns the starting height. A height set by dragging persists until the field unmounts: saving it between visits is the screen's job.
  • The Block handle and overlays travel with the text. The "⋮" handle sits inside the area and scrolls together with the Block; beyond the area's edge it is clipped and does not overlap the Toolbar. The floating Toolbar, the Bubble menu and the image panel listen to the area's scroll, not the page's; at the area's edge they flip below the selection. The Text card and the "/" Slash menu follow the range and the caret the same way: their anchor is tied to the Document (contextElement).
  • Without the props nothing changes: the area is a plain element without styles, the field grows with the Document, and the Toolbar sticks to the top of the browser window.
  • In fullscreen mode neither prop applies. The area takes the height of the window and scrolls itself, there is no height handle, and both come back when the field is collapsed (see "Fullscreen mode").

Paper: surface

surface="theme" (the default) renders the Document in the app's theme, as in Notion, Confluence and Slack. surface="paper" renders a light Paper in any theme (dark, dim, brand), like "Switch Modes" in Word: the text, links, text color and highlight, tables, image captions, the task list, the code block (GitHub Light) and the author's color look as in the light theme.

<RichTextEditor surface="paper" aria-label="Email body" value={html} onChange={setHtml} />

When to use the Paper. A Document that will leave the app with a light look: a print or PDF preparation screen, an email editor, a document template. The author sees the text as it will be read, and the author's color does not lose contrast when the theme changes. For notes, comments and task descriptions the Paper is not needed: the Document lives in the app and follows its theme.

What stays in the app theme. The Paper is only the editable area. The Toolbar (fixed and floating), the Slash menu, the link, image and color popovers, the table menu, dialogs, the labels and counter under the field, the field's frame and the focus ring around it are in the app theme: this is the interface, not the Document. The Paper's edge is the app theme's --line frame and --shadow-1 shadow, so the Paper stands apart on both a dark and a light background.

How it is built. The Paper carries a nested data-theme="light" — through it the highlights (--marker-*) and the syntax highlighting theme take light values. The kit tokens (--fg-0, surfaces, --accent-strong) are declared only on :root[data-theme] and do not understand a nested theme, so the Document reads not them but the --rte-* roles (src/editor/styles/tokens.ts): in a theme they map to kit tokens, on the Paper to the same --od-* primitives that the light theme assigns. A test checks the match with the light theme by parsing styles.css.

  • The accent on the Paper is the app theme's fill (--accent), not the light accent-strong: for a brand and the violet accent the light step exists only in a light app. The fill is designed for white text on top of it, so used as text on the white Paper it meets 4.5:1 with any brand. In a light app the link, the accent color and focus on the Paper use exactly the light accent-strong.
  • Focus inside the Paper (the code block language button, task list checkboxes) is an outline of the same accent: the dark theme's light accent-strong does not reach 3:1 contrast on white.
  • The code block header on the Paper is light: the background and text come from the syntax highlighting theme selected by the nested data-theme, and the border and line are the Paper's roles. The language button, the language label and "Copy" use the --rte-secondary role, hover is --rte-control-hover, not the tokens of a ghost button: those would have stayed with dark theme values, and a light icon would end up on a white header.
  • The Callout tone on the Paper has its own --rte-tone-* roles with light theme values (see the "Wrapper" section, "Tone"): the app theme's status *-soft and *-strong would be dark on a white Paper.
  • Contrast is checked by npm run contrast: every Paper pair against the Paper itself, in each theme × accent × brand.
  • RichTextView with the same surface shows the Document on the same Paper.

Fullscreen mode

The fullscreen Tool (present in full, not in basic) expands the field to the whole window for long work with text (ADR-0082). It is a layer of the kit, not the browser's Fullscreen API: the API has no support for elements on iPhone, the Editor's popovers live in a portal and would not show inside a fullscreen element, and the browser keeps Esc for itself. So the layer works the same everywhere, including inside a Dialog or a Drawer. The Tool has no Block and no markup: the Schema, the sanitizer, Markdown, JSON and RichTextView do not change.

<RichTextEditor /> // the "Fullscreen" item in "…" is there
<RichTextEditor preset="basic" /> // no fullscreen mode
  • The way in. The "Fullscreen" checkbox item (an expand icon) in the "view" section of the "…" menu, on the fixed Toolbar and in the Bubble menu; from screen code the open(), close() and toggle() commands; Ctrl/⌘+Shift+F with focus in the Document turns the mode on and off. F11 stays the browser's: it fills the screen with the whole page, not the field.
  • The look. The layer is the app's background across the window. The Toolbar is across the top, the Status bar at the bottom, and the Document scrolls itself as a 60rem column (about 960px) in the middle; the width is in rem, not in characters, because the column holds tables, pictures and Column layouts too. On a window narrower than that the column takes the whole width less the margins. The Table of contents, if enabled, stays at the left, and the column is centered in the space to its right. The Paper stays a sheet on the app's background, as wide as the column.
  • Full width. As in Notion, the "Full width" checkbox item right after "Fullscreen" spreads the Document across the whole window, with side margins that grow with it: 24px on a narrow window, 48px from md, 96px from xl, and no maximum width. The Toolbar and the Status bar do not change; the Paper sheet stretches with the Document. The item is in the "…" menu only while the field is in fullscreen: on the page the field's width is the page's, and the item would do nothing. It has no shortcut. The width switches instantly. The choice outlives collapsing; between page loads the screen keeps it, see below. maxHeight and resizable do not apply while the layer is open (the area takes the height of the window, and the height handle is gone) and come back after it. On a phone the layer is 100dvh, the Toolbar sticks to the top, and the on-screen keyboard is not handled separately, as everywhere in the kit.
  • The way out. "Collapse" is a visible button at the right edge of the Toolbar (and in the corner of the layer when there is no fixed Toolbar: toolbar="floating", "bubble" or "none", readOnly), because a touch screen has no Esc. Esc collapses the field one level at a time (ADR-0041, ADR-0077): with the blockSelection Tool the first Esc in the text selects the Block, the second ends the selection and collapses the field; in a Dialog or a Drawer the next Esc closes the window. An open menu, popover or the Slash menu of the Editor keeps its own Esc. Without blockSelection the first Esc collapses the field.
  • Nothing is lost. It is the same engine, the same edit history, caret and selection: the field's DOM moves into the layer and back, and the caret scrolls into view. On the way out the page returns to where it was scrolled, and focus goes to the Document. onFocus and onBlur do not fire: the layer is a part of the field. value, onChange, getHTML() and the other exports do not see the mode.
  • Layers. The layer joins the stack of ADR-0041 at the step above a Dialog (alert) and below popovers (popover), so the Editor's menus, popovers and tooltips lie on top of it, and the Insert table dialog opened from it too. It locks the page scroll (useScrollLock) while it is open. It enters and leaves with the kit's existing fadein and fadeout; with prefers-reduced-motion the movement goes and the fade stays (ADR-0043).
  • Focus stays in the layer. Tab from the last control goes to the first, and Shift+Tab from the first to the last, so the keyboard never walks into the page behind. The page, and the Dialog or Drawer around the field, are aria-hidden and inert while the layer is open and come back as they were. Live regions (a toast, a status line) are left alone.
  • Announcement. The change of the mode is announced through the Field notice (status): "Fullscreen mode on" and "Fullscreen mode off".
  • Where it does not open. In the Source mode (the Document is not on screen) and in a disabled field open() returns false. A readOnly field opens: reading a long text is the point.
  • Weight. The layer uses the non-modal Radix dialog the kit already depends on (the focus scope that pauses the focus trap of a Dialog around the field, and the layer order of Esc); it adds no package.

The message catalog strings are editor.fullscreen (the item and the layer's name), fullWidth (the "Full width" item), fullscreenExit ("Collapse"), fullscreenOpened and fullscreenClosed; the icons are ExpandIcon, FullWidthIcon and CollapseIcon.

Fullscreen mode state and commands

useRichTextToolState(ref, "fullscreen") reads the state and ref.current?.tool("fullscreen") calls the commands. The general rules for both are in the "Handle (ref) and a custom toolbar outside the field" section.

OptionDefaultMeaning
fullWidthfalseThe layer opens with the Document across the window. Only the starting value: the item and toggleFullWidth() take over after it
State fieldMeaning
openThe field fills the window. It turns false when collapsing starts, not when the fade ends
fullWidthThe layer's Document spreads across the window. It holds outside the layer too, for the next time it opens
CommandWhat it does
open()Expand the field, the same as the item. false when it is already open, in a disabled field and in the Source mode
close()Collapse it, the same as "Collapse". false when it is not open
toggle()Open it if collapsed, collapse it if open. false where open() is refused
toggleFullWidth()Switch between the column and the whole window, the same as the item. Always true: it is a view preference, so it works outside the layer (the choice applies the next time it opens), in readOnly, in a disabled field and in the Source mode

The kit does not keep "Full width" between page loads: there is no localStorage in it (ADR-0018). A screen that wants the choice remembered keeps the state in its own storage and passes it back as the option:

const ref = useRef<RichTextEditorHandle>(null);
const fullWidth = useRichTextToolState(ref, "fullscreen", (state) => state.fullWidth);
useEffect(() => {
  if (fullWidth !== null) settings.save("editor.fullWidth", fullWidth);
}, [fullWidth]);

<RichTextEditor
  ref={ref}
  tools={[
    ...RICH_TEXT_PRESETS.full,
    tool("fullscreen", { fullWidth: settings.load("editor.fullWidth") ?? false }),
  ]}
/>;

Focus mode

The focus Tool (present in full, not in basic) shows everything outside the Block with the caret faint, at 40% opacity, as in iA Writer and Ulysses (ADR-0082). The Tool is two things: decorations over the Document, and a checkbox item. It has no Block, and the Schema, the sanitizer and Markdown do not change. It is a separate Tool from fullscreen because the mode is useful in an ordinary field too.

<RichTextEditor /> // the item in "…" is there, the mode is off
<RichTextEditor tools={[...RICH_TEXT_PRESETS.full, tool("focus", { enabled: true })]} /> // on from the start
  • Display only. The dimming is decorations: value, onChange, getHTML(), getMarkdown(), getJSON(), the edit history and RichTextView do not see it. Turning the mode on and off is not an edit.
  • What is current. The Block unit of Block selection (ADR-0077): the Block of its container. In a list it is the item (a nested item dims the text of the item around it), a table is one Block as a whole, a Block of a column is one Block, not the whole Column layout. A text selection across Blocks keeps all of them as they are. The footnote list is never a Block unit, but the focus mode follows its notes: with the caret in one footnote that note is as it is, and the text Blocks and the other notes are dimmed; with the caret in the text the whole list is dimmed like any other Block.
  • What dims. Everything outside the Block goes to 40% opacity: text with its inline code and highlight fills, list markers and task checkboxes, footnote numbers, invisible characters, images, videos, code Blocks, block formulas and horizontal rules, and a quote, a toned Wrapper, a Details Block, a column, a table or the footnote list as a whole, fill, frame and line included. Opacity, not a color, so a link, an author color, a marker fill and a code Block's highlight keep their own colors, only fainter, on the theme, on the Paper and on the Wrapper tones alike. Nothing goes faint twice: inside a Wrapper or a table that is already faint the text stays as it is. A container with the caret inside keeps its frame, and its other Blocks dim as text. The contrast of the dimmed text is below 4.5:1 on purpose (about 3:1 on the dark themes, 2.4:1 on the light theme and the Paper): it is the background around the Block being written, not the text being read, and it comes back in full as soon as the caret reaches it or the focus leaves the Document.
  • When it is off. There is no dimming without focus in the Document (the Toolbar or the page has it), over a Block selection, and in a readOnly field. It comes back with the focus.
  • Off at the start. The Tool is in full, and a kit update must not change how every Editor on that Preset looks, so the mode is off until the author turns it on with the "Focus mode" item of the "…" menu (the fixed Toolbar and the Bubble menu), or the enabled option does. Ctrl/⌘+Shift+J with focus in the Document does the same as the item.
  • Scrolling is ordinary. There is no typewriter mode that keeps the caret line in the middle: it scrolls on every character and looks bad with reduced motion.

The message catalog string is editor.focusMode; the icon is FocusModeIcon.

Focus mode options

A tool("focus", options) entry sets only the start: after that the item and the command control the mode.

OptionMeaningDefault
enabledThe mode is on from the startfalse

Focus mode state and command

useRichTextToolState(ref, "focus") reads the state and ref.current?.tool("focus") calls the command.

State fieldMeaning
enabledThe mode is on. Follows the item, the command and the enabled option at start
CommandWhat it does
toggle()Turn the mode on if off and off if on, the same as the item. false in the Source mode

Table of contents

The toc Tool puts the Table of contents of the Document in the Editor's left gutter: the same strip of strokes and the same list as RichTextToc, but the Editor holds the place itself (ADR-0068). It is in neither Preset, full or basic: the Table of contents moves the text, and a kit update does not change the layout of screens that did not ask for it. Switch it on by name:

<RichTextEditor tools={[...RICH_TEXT_PRESETS.full, "toc"]} defaultValue={html} />

A tool("toc", options) entry also switches the Tool on and configures it at the same time (see "Table of contents options" below).

  • Place. A column to the left of the Document, inside the field frame. It exists only while there is a strip, from two h1–h4 headings at the top level and in Wrappers: with the second heading the text moves right; without it the text stays at the edge, as without the Tool. The first stroke is level with the first line of the first heading.
  • Sticky positioning. The strip sticks under the fixed Toolbar (and under the app header: --topbar-h, ADR-0016); without a Toolbar, to the edge of the window. In a field with maxHeight or resizable it sticks to the top of the scrolling area, and the highlight and the jump count from there; the page does not scroll.
  • The list works as in RichTextToc: hover opens it to the right of the strip, Enter and Space open it from the keyboard, arrows move between items, Escape closes it; the current section is highlighted in the strip and in the list; the width is 240px, and a long heading is cut with an ellipsis. A click on an item does not close the list: moving the pointer away does.
  • A jump while editing puts the caret at the end of the heading, so you can type right away, as in the document outline of Google Docs; the Table of contents does the scrolling, and the heading flashes a fading background. In readOnly there is no caret, so focus goes to the heading itself.
  • A live Document. The list is rebuilt shortly after each edit: a new, renamed or removed heading shows in the strip. In Source mode there is no Table of contents, because the Document is hidden.
  • No Toolbar button. To show or hide the Table of contents, the screen changes tools (and remounts the field with a key, as for any set of Tools).

Message catalog string: editor.toc ("Table of contents"), the name of the strip and the label of the list.

Table of contents options

A tool("toc", options) entry switches the Tool on and configures it. The standalone RichTextToc takes the same offsetVar, levels and listWidth: the two share one core.

OptionMeaningDefault
offsetVarThe name of the CSS variable that holds the height of the screen's sticky header (ADR-0016), written in full with the two leading dashes: --header-h. A jump puts the heading under the header, and the highlight treats a section as current from the header's bottom edge. It does not move the Editor's own sticky Toolbar, which still sits under --topbar-h.--topbar-h
levelsThe heading levels in the Table of contents: a subset of 1–4. A heading of any other level is in neither the strip nor the list, and item indentation is counted from the largest remaining level. An empty array and invalid values are replaced by the default. With fewer than two headings left, there is no gutter.[1, 2, 3, 4]
listWidthThe list width: pixels or a CSS length. Fixed rather than sized to the longest heading.240
// The screen's header publishes its height in `--header-h`; the Table of contents needs only H2 and H3.
<RichTextEditor
  tools={[...RICH_TEXT_PRESETS.full, tool("toc", { offsetVar: "--header-h", levels: [2, 3] })]}
  defaultValue={html}
/>

Table of contents state and commands

The state is read with useRichTextToolState(ref, "toc"), and the command is called on ref.current?.tool("toc").

State fieldMeaning
headingsThe headings in reading order, the same as in the strip and the list: top level and Wrappers, only the levels from levels, no empty ones. Each is { level, text, index }: a level 1–4, the text without markup, and the index of the list item, from 0. The list is returned even with one heading, although there is no gutter then.
currentThe index of the current section in headings, from 0; -1 means no headings. It follows scrolling. After the Document is edited, headings changes at once, while current catches up with a delay while the list is rebuilt.

The headings are read from the Document, not from the DOM: the list is ready on the first frame without waiting for the lazy Table of contents UI, and it changes together with the edit. The state has no DOM nodes or ProseMirror positions.

There is one command, jumpTo(index): go to a heading of the list, like a click on an item. The index is counted in the same list (with levels applied, from 0, empty headings skipped) and is taken from the state snapshot: right after the Document is edited, it leads to the heading that the snapshot names, even though the Table of contents UI rebuilds its list with a delay. While editing, the caret goes to the end of the heading; in readOnly, the heading itself gets focus; scrolling puts it under the sticky header (offsetVar) and the Toolbar, and the heading's highlight fades. false means there is no heading with that index, the Table of contents UI has not loaded yet, or Source mode is on. Fewer than two headings is not a reason to refuse: there is no gutter, but the list exists, and the jump works.

External navigation. The screen builds breadcrumbs, a minimap or a list of sections next to the field from the state, instead of parsing the Document's DOM a second time.

import type { RefObject } from "react";
import { useRichTextToolState } from "@olddevs/ui/editor";
import type { RichTextEditorHandle } from "@olddevs/ui/editor";

function SectionNav({ target }: { target: RefObject<RichTextEditorHandle | null> }) {
  const toc = useRichTextToolState(target, "toc");
  if (!toc) return null;

  return (
    <nav aria-label="Sections">
      <ul>
        {toc.headings.map((heading) => (
          <li
            key={heading.index}
            aria-current={heading.index === toc.current ? "location" : undefined}
          >
            <button
              type="button"
              onClick={() => target.current?.tool("toc")?.jumpTo(heading.index)}
            >
              {heading.text}
            </button>
          </li>
        ))}
      </ul>
    </nav>
  );
}

Handle (ref) and your own toolbar outside the field

The screen drives the field through ref (RichTextEditorHandle) and builds its own toolbar with the useRichTextEditorState hook. Both come from @olddevs/ui/editor:

import { RichTextEditor, useRichTextEditorState } from "@olddevs/ui/editor";
import type { RichTextEditorHandle } from "@olddevs/ui/editor";

ref methods

MethodWhat it does
insertHTML(html): booleanInserts HTML at the caret in place of the selection. To insert a Block, pass its HTML to this method.
insertText(text): booleanInserts text literally, without HTML parsing; a line break is a hard break (in a code block, a newline character).
getText()The Document's text without markup; Blocks are separated by an empty line, an Atom is its Atom text.
getSelectedText()The selected text; for a caret, "". An Atom is included only as a whole.
isEmpty(): booleanEmptiness by the kit's rule — the same one that decides required and what is written to the form as "": any Atom (hr, an image, a custom one), a hard break and a table (even with empty cells) are content; a Block without text (paragraph, heading, list, quote) is not.
focus(position?)"end" (the default), "start" or "restore": return focus to where the selection was, for example after your own dialog or menu.
blur()Remove focus from the Document.
undo(), redo()Undo and redo an edit; they work with the history Tool enabled.
tool(name)The commands of a Tool: tool("search")?.open(), tool("toc")?.jumpTo(2). null means the Tool is not in the set, has no commands, or the engine has not been created yet. See "Tool commands: handle.tool()".
openSearch({ replace? })Deprecated, removed in 5.0: the same as tool("search")?.open({ replace }); warns once in development.
canUndo(), canRedo()Whether undo and redo are available: false without history.
getHTML(), getMarkdown(), setMarkdown(md), clear()See "Public API" and "Markdown".
getJSON(), setJSON(document): booleanThe Document as a lossless JSON envelope, and replacing the Document with an envelope; false means the envelope was rejected. See "JSON".
editorThe underlying Tiptap Editor for commands of Marks, Blocks and custom Tools; its API follows Tiptap's major version, not the kit's contract.

Insertion. insertHTML and insertText return true if the Document changed and false if not: there is no engine yet, the field is read-only or disabled, the insertion would go past maxLength, or the Schema dropped everything inserted. The HTML goes through the Schema like an incoming value: a Block of a disabled Tool is dropped (the text inside it stays as an ordinary paragraph), and if nothing is left, nothing is inserted. An insertion that goes past maxLength is not performed at all and returns false: a template cut off in the middle is worse than a refusal; what to tell the user is up to the screen. The caret is placed after the inserted content; the method does not take focus itself — if the insertion comes from a button or a dialog, start with focus("restore"). In a field that has never been focused, the caret is at the start of the Document.

User edit and Programmatic replacement. Insertion, undo and redo count as User edits: a separate history step (undo removes the insertion alone, not together with the typing before it), onChange fires after changeDelay, and the maxLength limit applies. clear(), setMarkdown(), setJSON() and a new value count as Programmatic replacements, and the limit does not truncate them; onChange fires immediately for clear(), setMarkdown() and setJSON(), but is not called for a new value. In readOnly and in a disabled field, insertion returns false, and undo and redo do nothing.

Calling a method before Readiness is safe — on the server, before mount and while Tool Loaders are running (see the "Custom Tool" section). The engine is created in the browser after the first render and the Loaders, so a call at this moment neither throws nor queues.

  • Reads return a known value: getHTML() the incoming value, getText() and getSelectedText() "", getJSON() null, and isEmpty() evaluates the incoming value by the same rule as after mount (a custom Block before mount is always content: only its Extensions can tell whether it is an Atom).
  • Writes and focus do nothing.
  • Insertion and setJSON() return false, and canUndo() and canRedo() return false as well.

On the server ref.current is empty until the Editor mounts, so write ref.current?.….

Source mode. getText() applies the Source field's edit, like getHTML(); insertion applies it, inserts into the Document and overwrites the field; focus and blur act on the Source field; undo and redo do nothing (a textarea has its own undo); getSelectedText() returns "".

Your own toolbar: useRichTextEditorState

useRichTextEditorState(ref, selector) is a selector hook on top of Tiptap's useEditorState. The selector receives editor and returns a slice of state; the component re-renders only when the slice changes (compared by value, so you can return an object), and typing that does not change the slice does not touch the toolbar. While there is no engine — before mount and on the server — the hook returns null and the selector is not called; when the engine appears, the screen re-renders by itself.

The toolbar's commands go through ref.current.editor.chain().focus()…run() — the same command syntax as the commands of Tools. The kit has no command registry of its own.

import { useRef } from "react";
import { RichTextEditor, useRichTextEditorState } from "@olddevs/ui/editor";
import type { RichTextEditorHandle } from "@olddevs/ui/editor";

function Screen() {
  const ref = useRef<RichTextEditorHandle>(null);
  const state = useRichTextEditorState(ref, (editor) => ({
    bold: editor.isActive("bold"),
    // Without the `history` Tool the engine has no `undo` command.
    canUndo: editor.can().undo?.() === true,
  }));

  return (
    <>
      <button
        type="button"
        aria-pressed={state?.bold ?? false}
        // A click on the toolbar must not take focus out of the Document.
        onMouseDown={(event) => event.preventDefault()}
        onClick={() => ref.current?.editor?.chain().focus().toggleBold().run()}
      >
        Bold
      </button>
      <button
        type="button"
        disabled={!state?.canUndo}
        onMouseDown={(event) => event.preventDefault()}
        onClick={() => ref.current?.undo()}
      >
        Undo
      </button>
      <RichTextEditor ref={ref} aria-label="Text" />
    </>
  );
}

Recipe: the buttons of an external toolbar call preventDefault on mousedown. A click on a button moves focus to it, the field loses focus, and a command without .focus() in the chain would go astray. preventDefault on mousedown keeps focus in the Document, so the selection does not disappear either visually or for the floating Toolbar and the Bubble menu, which hide when focus is lost. ProseMirror's selection survives losing focus even without this, but the visibility of the floating Toolbar, the Bubble menu and the image panel depends on focus. The rule "a click on a custom toolbar does not clear the selection" is not part of the public contract: this is a recipe, not a property of the field. A button that opens its own dialog, where focus inevitably moves away, calls ref.current?.focus("restore") when the dialog closes.

History with an external toolbar. The Handle provides undo() and redo() and their availability. For the disabled state of an "Undo" button, get availability from the hook's slice — editor.can().undo?.() === true: the slice re-renders the toolbar right after an edit. ref.current.canUndo() is a one-off read in a handler, and it is not subscribed to re-rendering. Without the history Tool the engine has no undo command (hence the ?.), and both buttons stay unavailable.

Tool state: useRichTextToolState

useRichTextToolState(ref, name, selector?) gives the screen the state of a Tool: a "3 of 12" counter from Find in the Status bar, or external navigation built from the headings of the Table of contents. The hook sits next to useRichTextEditorState and follows the Handle's engine in the same way, but it returns not a slice of the Tiptap engine but a typed snapshot of the kit's contract. The state fields of the built-in Tools are in the "Find and replace", "Table of contents", "Invisible characters", "Footnotes", "Block selection", "Text part language" and "Date mention" sections.

  • Name and type. name is a Tool from the tools set; the snapshot type is inferred from the RichTextTools map: search returns SearchToolState, toc returns TocToolState, invisibleCharacters returns InvisibleCharactersToolState, footnotes returns FootnotesToolState, blockSelection returns BlockSelectionToolState, language returns LanguageToolState. A name outside the map (a custom Tool without typing) gives unknown.
  • Re-renders only when the snapshot changes. The snapshot is recomputed on every engine transaction and on kit signals that the engine does not have: the find panel opening and closing, and the current section of the Table of contents changing on scroll. The screen re-renders when the result becomes different (plain data — primitives, arrays and plain objects — is compared by value, like useRichTextEditorState; Date, Map, Set and class instances are compared by reference), so typing that does not change the snapshot does not touch it. A custom Tool's state that creates such values anew on every call re-renders the screen on every transaction.
  • A selector. The third argument subscribes the screen to a slice: useRichTextToolState(ref, "search", (state) => state.total) re-renders it only when the number of matches changes. With null, the selector is not called.
  • null is what the hook returns before mount and in the screen's first render, on the server, after the Editor unmounts, and when the Tool is not in the set: Presets do not include toc, so you enable it by name or with a tool("toc") entry. This way the screen renders the same on the server and in the browser.
  • A snapshot is data: no DOM nodes, functions or ProseMirror positions. Do not mutate it.
  • Cost. The hook is not part of the RichTextEditor entry chunk: only a screen that imports it pays for it.

The state of a custom Tool is declared with defineTool (the state field) and read with the same hook: "Options, state and commands".

Tool commands: handle.tool()

ref.current?.tool(name) returns the commands object of a Tool: tool("search")?.open({ query: "TODO" }), tool("toc")?.jumpTo(2). The commands of the built-in Tools are described in the "Find and replace", "Table of contents", "Invisible characters", "Footnotes", "Block selection" and "Text part language" sections.

<button type="button" onClick={() => ref.current?.tool("search")?.open({ query: "TODO" })}>
  Find TODO
</button>
  • The type is inferred from the RichTextTools map, by the Tool's name. A name outside the map gives unknown.
  • null when the Tool is not in tools, has no commands, or the engine has not been created yet. That is why the commands of a disabled Tool are unavailable both in types (?.) and at run time.
  • Every command returns a boolean: done or not (Source mode, no matches, no such heading, a field that cannot be edited). A refusal is false, as with insertHTML, not an exception.
  • Take the object on every call instead of keeping it between renders: it is cheap, and this way you always work with the live engine.
  • The Handle gets no new method for each command. The commands of the built-in Tools go through tool(name), not through new methods; openSearch remains for compatibility only. Commands of Marks, Blocks and anything a Tool has not declared are still called through ref.current.editor.

Events

The screen learns about the Editor through callback props; there is no event bus. The decision is recorded in ADR-0058, section 9.

<RichTextEditor
  ref={ref}
  aria-label="Email"
  value={html}
  onChange={setHtml}
  onReady={() => ref.current?.insertHTML("<p>Hello!</p>")}
  onFocus={() => setEditing(true)}
  onBlur={() => save(ref.current?.getHTML() ?? "")}
/>
  • onReady() takes no arguments and is called once per mount, when the engine is created. By then ref is already usable: in the callback you can insert a template or set focus. It fires in readOnly and in disabled too; a re-render, a placeholder change or a change of the callback itself do not cause a second call. An error in the tools set (there is no engine, see "Custom Tool") and server rendering do not call onReady. Readiness means the engine is created and all Tool Loaders have run (see the "Custom Tool" section): onReady waits for them, and on a Loader failure it is not called — and after "Retry" it is called once, when the engine is created.
  • onFocus() and onBlur() report Field focus and take no arguments (the DOM event is not passed through). Here the field means the whole field: the Document, the Toolbar, popovers and kit dialogs (link, color, image, "Insert table"), the Source mode field. Moving between them does not lose Field focus: from the text to the Toolbar, to the link popover and back, neither onBlur nor onFocus fires — as with a composite form field. The Document's focus (the engine's focus and blur) is different: a click on the Toolbar removes it, while Field focus stays.
  • Before onBlur a pending onChange is flushed, wherever focus moves away from (the Document, the Toolbar, a popover), so autosave on onBlur gets the fresh Document. onBlur fires a tick after focus leaves: in that time focus could have come back into the field. If the Editor is unmounted with focus inside, onBlur is not called (a pending onChange is still delivered).

Paste and drop order

Only the Extensions of a custom Tool can intercept pasting from the clipboard and dropping — through the ProseMirror plugins transformPastedHTML, transformPasted, handlePaste and handleDrop in engine. The Editor has no hooks or props of its own named onPaste and onDrop.

  • The handlers of custom Tools see the event before the built-in ones — Markdown paste, image upload, Column layout and Paste from Office (pasteCleanup) — wherever a custom Tool appears in tools. Every transformPastedHTML runs in turn, so the cleanup of pasteCleanup works on what a custom Tool's transformPastedHTML returned. A handlePaste or handleDrop that returns true takes the whole event: the built-in ones never get it. This way a link to a video can be turned into a custom Block before Markdown parses it.
  • Schema parsing and the limit always apply. What a paste brought beyond the Schema (<script>, onclick, unknown tags, values that break the attribute rules) is dropped, as with an incoming value; HTML cleanup (transformPastedHTML) happens before the Schema and cannot weaken it. A transaction of your own handler that takes the text beyond maxLength is rejected entirely; tail trimming exists only in the built-in paste from the clipboard (a transaction flagged paste).
  • Files other than images are handled by a custom Tool in handlePaste and handleDrop: its own upload function and its own upload URL, set through the options of its extension. The Editor has no general onUploadFile. A file that no handler claims reaches the kit: an image is uploaded through onUploadImage, and anything else gets the message "name is not an image" (editor.imageNotImage in the message catalog).
const PdfDrop = Extension.create({
  name: "acme_pdfDrop",
  addProseMirrorPlugins: () => [
    new Plugin({
      key: new PluginKey("acme_pdfDrop"),
      props: {
        handlePaste: (_view, event) => takePdf(event.clipboardData?.files),
        handleDrop: (_view, event) => takePdf(event.dataTransfer?.files),
      },
    }),
  ],
});

// A Tool without a Block: behavior only.
export const pdfTool: CustomTool = { name: "acme_pdfDrop", engine: [PdfDrop] };

On this page