Custom Tool
Tools and Presets
preset="full" (default) is everything in the release except the Table of contents toc, Typography typography, formulas mathematics and video youtube, twitch: the Table of contents changes the layout of the field, Typography changes the text being typed, formulas pull in the lazy KaTeX chunk, and video calls a third-party service (CSP and privacy), so they are switched on only explicitly. preset="basic" is for comments and short descriptions. tools is an exact list and takes precedence over a Preset; descriptions of custom Tools can be mixed in with the kit's names (see the "Custom Tool" section). The type of a tools element is Tool (a kit name, a Configured Tool from tool(…), a defineTool(…) definition or a CustomTool), the type of a kit name is ToolName; both are exported from @olddevs/ui/editor.
Presets are also exported as arrays of names — RICH_TEXT_PRESETS.full and RICH_TEXT_PRESETS.basic — so that you can assemble your own set from them: tools={[...RICH_TEXT_PRESETS.full, mergeTagTool]}. The arrays are frozen. A Preset's content is "what the kit considers the full set", not a frozen list: a new built-in Tool arrives in a Preset in a minor version. If you need a stable set, pass an exact list of names.
A disabled Tool removes both the button and the Schema extension. Its Block or Mark cannot be created with a keyboard shortcut, a Markdown shortcut or a paste, and from value they arrive without Block markup, and the text stays.
Tool | Button | Markup | Shortcut | Markdown while typing | basic |
|---|---|---|---|---|---|
heading | "¶": Heading 2–4 | h2, h3, h4 | Ctrl/⌘+Alt+2…4 | ## , ### , #### | — |
heading1 | "¶": adds Heading 1 | h1 | Ctrl/⌘+Alt+1 | # | — |
history | Undo, Redo | — | Ctrl/⌘+Z, +Shift+Z | — | yes |
bold | Bold | strong | Ctrl/⌘+B | **text** | yes |
italic | Italic | em | Ctrl/⌘+I | *text* | yes |
underline | "…": Underline | u | Ctrl/⌘+U | — | — |
strike | Strikethrough | s | Ctrl/⌘+Shift+S | ~~text~~ | yes |
code | "…": Inline code | code | Ctrl/⌘+E | `text` | yes |
superscript | "…": Superscript | sup | Ctrl/⌘+. | — | — |
subscript | "…": Subscript | sub | Ctrl/⌘+, | — | — |
clearFormatting | "…": Clear formatting | — (removes Marks) | Ctrl/⌘+\ | — | — |
link | Link (URL popover) | a[href] | Ctrl/⌘+K | [text](url) on paste | yes |
color | Color ▾ (Bubble menu): "Text color" | span[data-color], span[style] | — | — | — |
highlight | Highlight ▾ (Toolbar), "Color ▾" | mark[data-color], mark[style] | — | — | — |
align | Alignment ▾ (menu) | p, h2–h4 with data-align | Ctrl/⌘+Shift+L, +E, +R | — | — |
language | "…": Language › | span[lang] | — | — | — |
bulletList | Lists ▾: Bulleted list | ul, li | Ctrl/⌘+Shift+8 | - or * | yes |
orderedList | Lists ▾: Numbered list | ol, li | Ctrl/⌘+Shift+7 | 1. | yes |
taskList | Lists ▾: Checklist | ul[data-type=taskList] and items | Ctrl/⌘+Shift+9 | [ ] or [x] | — |
blockquote | "…": Quote | blockquote | Ctrl/⌘+Shift+B | > | yes |
codeBlock | "…": Code block | pre, code class="language-*" | Ctrl/⌘+Alt+C | ``` | — |
horizontalRule | "+": Divider | hr | — | --- | — |
table | Table ▾ (menu) | table, tbody, tr, th, td, colgroup, col | Tab, Shift+Tab, Alt+↓ in a table | — | — |
image | Image (URL popover) | figure, img, figcaption | Ctrl/⌘+Shift+L, +E, +R on a selected image |  on paste | — |
emoji | Emoji (popover with a grid) | — (plain text) | — | — | — |
source | HTML or Markdown (mode toggle) | — (edits the Document's source) | — | — | — |
search | Find (find and replace panel) | — (searches the Document) | Ctrl/⌘+F, Ctrl/⌘+Alt+F | — | yes |
invisibleCharacters | "…": Invisible characters | — (draws marks over the Document) | — | — | — |
blockSelection | "⋮": Select | — (selects whole Blocks) | Esc, Shift+↑/↓, Shift+click | — | — |
fullscreen | "…": Fullscreen, Full width; Collapse | — (a layer over the window) | Esc — collapse | — | — |
focus | "…": Focus mode | — (dims Blocks around the Block) | — | — | — |
layout | "+": Layout | div with data-block and data-layout | Tab, Shift+Tab, arrow keys at the column edge | — | — |
wrapper | "+": Wrapper | div[data-block=wrapper] | Enter in an empty last paragraph — exit | — | — |
details | "+": Collapsible block | details, summary, div[data-type=detailsContent] | Enter in the title and at the empty end of the content | — | — |
mathematics | "+": Formula, Block formula | span, div with data-type and data-latex | Enter on a selected formula | $$x$$, $$$x$$$ | — |
date | "+": Date | time[datetime] | Enter on a selected mention | — | — |
footnotes | "+", "…": Footnote | sup[data-footnote-ref], section[data-block=footnotes] | Enter on a reference and in a footnote — jump | — | — |
insertMenu | "+" Slash menu | — (Blocks of other Tools) | — | / | — |
pasteCleanup | — (cleans a paste from Word, Excel, Google Docs) | — (markup of other Tools) | — | — | yes |
toc | Table of contents in the left gutter (not in full) | — (reads the headings) | — | — | — |
typography | — (replacements while typing; not in full) | — (plain characters) | Backspace right after a replacement — undo | --, ..., ", -> | — |
youtube | «+»: Video (not in full) | div[data-block=video] with a link | Enter after a link in a paragraph — a Block | a bare link | — |
twitch | «+»: Video (not in full) | div[data-block=video] with a link | Enter after a link in a paragraph — a Block | a bare link | — |
A paragraph is always there; a hard break is Shift+Enter. insertMenu and emoji, like clearFormatting, have no markup of their own: insertMenu provides access to other Tools' Blocks, and it is disabled where / is an ordinary character (paths, "and/or"); basic lacks it for the same reason. emoji inserts plain text — the Schema, the sanitizer and Markdown do not change because of it (see the "Emoji" section); basic lacks it: in a comment the OS's own palette is easier to reach, and a button would take up room in a short row. source is the Source mode (see the "Source mode" section): it has no markup of its own either, both source formats go through the Schema with the enabled Tools; basic lacks it — in a comment an "HTML" button is superfluous unless the screen explicitly asks for it. invisibleCharacters (see the "Invisible characters" section) has no markup either: it draws marks as decorations over the Document, and the Schema, the sanitizer and Markdown do not change; basic lacks it — a comment does not need a proofreading mode. blockSelection (see the "Block selection" section) has no markup either; basic lacks it because it takes the first Esc in the text, and a comment field in a Dialog keeps "one Esc closes the window". fullscreen and focus (see the "Fullscreen mode" and "Focus mode" sections) have no markup either: the first moves the field into a layer over the window, the second draws decorations, and basic lacks both. pasteCleanup (see the "Paste from Office" section) has no markup or UI either: it only changes what the Schema reads from a paste out of an office application, so it is in both Presets; comments get pasted from Word too.
The level-one heading is heading1 (an add-on to heading): full has it, basic does not. With it the Block levels are 1–4: Ctrl/⌘+Alt+1 and # with a space give H1, <h1> from value, defaultValue and paste stays H1, and the "¶" menu on the Toolbar offers "Heading 1". Without it the old behavior holds: # while typing stays text, Ctrl/⌘+Alt+1 does nothing, and <h1> in incoming HTML becomes a paragraph. Disable heading1 on a screen where the page heading already sits above the Editor: a second H1 breaks the page structure. Without the heading Tool there is no H1, even if heading1 is passed.
Earlier, "no H1 in the Document" was a kit decision (the page heading sits outside the Editor); now it is the screen's decision — ADR-0053 revises the earlier decision, and ADR-0050 links to ADR-0053.
A name enters the Tool type together with the Tool itself, not earlier: widening the input type does not break the consumer, whereas a name without an implementation would compile and do nothing. That is how link arrived — straight into the basic Preset too — and color, highlight, align, table, image, emoji, layout, wrapper, details, mathematics, footnotes, invisibleCharacters, blockSelection, fullscreen, focus, language, source, toc, typography, youtube, twitch, pasteCleanup; there are no reserved names now. Unknown names in tools (from JS without types) are dropped silently.
preset and tools are read when the engine is created: the Schema of a live ProseMirror cannot be changed. To change the set on a mounted field, remount it with a key (key) — the edit history is lost in the process.
Options of a built-in Tool: tool()
Eleven built-in Tools have options: search, toc, details, mathematics, youtube, twitch, typography, invisibleCharacters, focus, language and date. You set them with the tool(name, options) helper, which returns a Configured Tool: an entry for tools that sits next to the names and the descriptions of custom Tools (ADR-0069).
import { RICH_TEXT_PRESETS, RichTextEditor, tool } from "@olddevs/ui/editor";
// Build the set once per module, not in a render: `tools` is read when the engine is created.
const tools = [
...RICH_TEXT_PRESETS.full,
tool("toc", { offsetVar: "--header-h", levels: [2, 3] }),
tool("search", { matchCase: true }),
];
<RichTextEditor tools={tools} defaultValue={html} />;- An entry switches the Tool on.
tool("toc", …)enablestocwithout the"toc"string. Iftoolsalso holds the bare name (for example,searchfromfull), the Configured Tool wins: there is still one Find button and one find panel. - Pass only what you change. The remaining options come from the kit's defaults. Nested objects are merged and arrays are replaced whole:
levels: [2, 3]means exactly these levels, not an addition to the default. - The position in the UI does not change. A configured built-in Tool sits where it would sit by name; a custom Tool sits in
toolsorder. - Types infer the options from the name.
tool("toc", { matchCase: true })andtool("bold", {})do not compile:tool()accepts only Tools that have options, which today meanssearch,toc,details,mathematics,youtube,twitch,typography,invisibleCharacters,focus,languageanddate. - Two
tool()entries with the same name are a set error, like two custom Tools with the same name: a field error ("The editor couldn't start") and aconsole.errorin development. - A wrong value (from JS without types:
levels: [5],offsetVar: "header") is replaced with the default, with a singleconsole.errorper Tool in development; the field keeps working. - Options are read once, together with the
toolsset, when the engine is created. To change them on a mounted field, remount it with a key (key) — the edit history is lost in the process. - Server.
tool()andRICH_TEXT_PRESETSpull neither Tiptap nor React into the module, so atoolsset such as[...RICH_TEXT_PRESETS.full, tool("search", { matchCase: true })]can be built in a server module: the presets are plain arrays, not client references. A configured built-in Tool is made of data, and if its options are data, you can pass it to a client component as a prop.
The options of each Tool are described in its own section: "Find and replace", "Table of contents", "Details", "Formulas", "Video by link", "Typography", "Invisible characters", "Focus mode", "Text part language" and "Date mention". The options of a custom Tool are set by defineTool ("Options, state and commands").
Custom Tool
A custom Tool is the description of one Editor capability: its Blocks and Marks, Schema rules as data, and Extensions (Tiptap extensions). It is passed in tools mixed with the kit's names and follows the same rules: a Tool that is not passed removes its Blocks and Marks from the Schema — they do not pass through value, paste or commands; a Block unwraps into its content and an Atom disappears. The decision is ADR-0058, sections 1 and 2.
import { Node } from "@tiptap/core";
import { RICH_TEXT_PRESETS, RichTextEditor, type CustomTool } from "@olddevs/ui/editor";
// The Extensions: behavior only. The kit sets the group, HTML parsing and attributes.
const MergeTag = Node.create({
name: "acme_mergeTag",
atom: true,
addAttributes: () => ({ acme_key: { default: null } }),
renderText: ({ node }) => `{{${node.attrs.acme_key ?? ""}}}`,
});
export const mergeTagTool: CustomTool = {
name: "acme_mergeTag",
engine: [MergeTag],
blocks: {
acme_mergeTag: {
kind: "inline",
attributes: { acme_key: { kind: "pattern", pattern: "[a-z_]+" } },
},
},
};
<RichTextEditor
tools={[...RICH_TEXT_PRESETS.full, mergeTagTool]}
value={html}
onChange={setHtml}
/>;The description (CustomTool). Required: a name, Extensions, and Schema rules for every Node and Mark they define. The rest has defaults: an ordinary Block with no Block traits, no buttons of its own and no menu items.
| Field | What it is |
|---|---|
name | The Tool's name with a Consumer prefix, unique within tools |
engine | Extensions — an array of Tiptap extensions (Node, Mark, Extension, plugins, a React node view; Node and Mark at the top level) or a Loader that returns such an array (below) |
blocks | Block Schema rules — by Node name (CustomBlock) |
marks | Mark Schema rules — by Mark name (CustomMark) |
buttons | Toolbar buttons — see the "Custom Tool's button" section (CustomToolButton) |
insertItems | Slash menu items (CustomInsertItem) — see the "Insert items and Block actions" section |
blockActions | Block actions in the Block handle menu (CustomBlockAction) — the same section |
textCards | Text cards (CustomTextCard) — see the "Text card" section |
trigger | A custom Trigger character (CustomTrigger) — see the "Custom Trigger character" section |
Consumer prefix. The names of the Tool, its Blocks, Marks and attributes start with a prefix followed by an underscore: acme_mergeTag, the attribute acme_size. The kit's names never contain an underscore, so custom and built-in names never collide, either in the set or in a saved Document. Attribute names are lowercase: HTML loses the case of an attribute name. A built-in Tool is not replaced: disable it in tools and put a custom one under its own name.
HTML convention. The kit writes and reads it; the Extensions set behavior only:
- a block-level Block is
<div data-block="acme_card">…</div>, an inline Atom is<span data-block="acme_mergeTag"></span>; - a custom Mark is
<span data-mark="acme_comment">…</span>; - a custom attribute
acme_sizeisdata-acme_size; a custom Block and Mark have no other attributes.
The kit completes the Node and Mark from the Extensions: it sets the group (block, inline or top level) and inline-ness from the Block's kind; it parses HTML strictly according to this convention (the kit's tags p, table and img cannot be taken by a custom Block); and for attributes from the rules it parses and outputs data-* with value validation. You may keep your own renderHTML (for example, to put text into an Atom), but it must produce the same tag and data-block. You do not have to declare custom attributes on the Node: the kit adds them from the rules.
Schema rules are data, without functions. The kit's code validates them, and Extensions cannot weaken the validation: a value outside the rules does not reach the Document's HTML from value, paste or a command. When parsing, the attribute gets its default value, and on output it is not written.
CustomBlock field | Value |
|---|---|
kind | "block" — block-level (div) or "inline" — inline (span). Required |
place | "anywhere" (default) — wherever a Block can appear; "top" — only the top level of the Document, like a Column layout |
attributes | Custom attributes: name → value kind (CustomAttribute) |
container | The "container" Block trait: Blocks inside get their own Block handle, as in the Wrapper |
turnInto | The "can be turned into" Block trait: the Block handle's "Format ›" is available for this Block too |
plainAtom | The "Atom without a formatting menu" Block trait: a selected Block has no Bubble menu and no floating Toolbar above it |
island | The Block's Island in RichTextView — a client component from a module with "use client" (CustomIslandProps); the Editor does not read the field |
CustomMark has only attributes. The kind of an attribute value (CustomAttribute):
{ kind: "list", values: ["s", "m", "l"] }— one of the values of the list;{ kind: "pattern", pattern: "[0-9]{3}" }— a regular expression as a string for the whole value (the kit adds^…$itself);{ kind: "url" }— a URL under the kit's protocol policy, as for a link: an absolute URL with anhttp,httpsormailtoprotocol.
An attribute cannot contain HTML: a value with < does not pass any rule, and the content of a non-editable Block is stored as the Document's markup inside the Block.
Block traits are off by default: an ordinary Block is not a container, has no "Turn into", and has the Bubble menu. It has a Block handle, like any Block: "Add ›", "Format ›" (unavailable), "Up", "Down", "Duplicate", "Delete". The kit copies the traits into the node spec itself; their vocabulary belongs to the kit, not to Tiptap.
A failed validation when the set is assembled is a field error. The set is validated once, when the engine is created; with Loaders, after they have run, based on what they returned. It is an error if:
- the name of a Tool, Block, Mark or attribute lacks a Consumer prefix;
- two Tools have the same name, or two have the same Block or Mark name;
- the Extensions disagree with the rules: a Node or Mark without a rule, a rule without a top-level Node or Mark in
engine, a node attribute without a rule, arenderHTMLthat breaks the convention, a Schema the engine did not build; - a button has no
idor icon, twoidvalues in one Tool coincide, or exactly one ofrunandpopoveris not set (the same for an Insert item and a Block action).
On an error the engine is not created: under the field's frame there is a role="alert" line "The editor couldn't start. The document is unchanged." (editor.toolsFailed), the hidden form field and getHTML() return the incoming value, onChange stays silent, and ref.current.editor is null. The cause is in console.error in development mode, with the Tool's name. This way data loss is visible before the first save, not on the server. An unknown string in tools is still dropped silently: the error applies only to descriptions of custom Tools.
Buttons, Slash menu items, Block actions and Text cards are described in the sections below; a Tool can report an error to the author with the showNotice command (see the "Status bar and Field notice" section). The whole extension API and the boundary of its stability (what falls under semver, what counts as breaking) are described on the Editor extension API page. If a Tool has settings and the screen needs its state and commands, describe it with defineTool: "Options, state and commands".
Extensions Loader
Instead of the engine array of a custom Tool you can pass a function with a dynamic import — it returns a promise of the same array (ADR-0058, items 1.3 and 11.3–11.6). That way the module with the description can also be imported on the server (Schema rules are data), while Tiptap and React of the Extensions go to a separate chunk:
// acme-merge-tag.ts — no Tiptap in the graph: only the Extensions chunk pulls it in.
export const mergeTagTool: CustomTool = {
name: "acme_mergeTag",
engine: () => import("./acme-merge-tag-engine.js").then((module) => module.engine),
blocks: {
acme_mergeTag: {
kind: "inline",
attributes: { acme_key: { kind: "pattern", pattern: "[a-z_]+" } },
},
},
};-
Readiness waits for the Loaders. The engine is created when the Loaders of all the set's Tools have run: the Schema is fixed at creation, and Blocks from
valuewithout their Extensions would be lost on parsing. Until then the Handle's methods are silent,ref.current.editorisnull, andonReadyhas not been called (see the "Events" section). -
Loading starts from the first render in the browser, before mount, not in an effect; on the server the Loader is not called. The promise is cached on the Loader function itself: a second Editor on the page with the same Tool does not wait for anything and does not call the Loader. So the Loader is one function per module, not a new arrow function on every render.
-
A load failure (network, a stale chunk after a deploy) is a field error "The editor couldn't start. The document is unchanged." and a "Retry" button (
editor.retry). It calls the Loaders that failed again; successful ones stay in the cache. The Document stays visible as a Skeleton the whole time. The Editor does not start without the Tool: its Blocks would vanish from the Document.onReadyis not called on a failure, and the cause is inconsole.errorin development mode. -
The kit does not publish preloads. For the chunk to arrive with the page rather than after its script, add
modulepreloadfor it yourself. The chunk's hashed URL comes from the bundler manifest (in Vite,build.manifest):<link rel="modulepreload" href="/assets/acme-merge-tag-engine-3f9a1c.js" />In React 19 the same tag is set by
preloadModule(url)fromreact-dom. Without a preload the chunk starts loading from the Editor's first render — the Skeleton covers that time.
Skeleton
Every Editor has a Skeleton (ADR-0058, item 11.4), with Loaders and without: until Readiness and after a Loader failure the field renders the frame, the space for the fixed Toolbar, and the Document as static HTML — with the same class and rhythm as the engine's Document, without input and without the textbox role. The engine takes its place without a height jump.
- The Skeleton's Document is
valuecleaned by the Schema, not the raw string: the kit parses it in an inert browser document (scripts and handlers do not run there) against the Schema of the set's built-in Tools and of custom Tools whose Extensions have already arrived, and serializes it back to HTML. Anything the Schema does not recognize (<script>,on*,javascript:, unknown tags and attributes) does not reach the page even before Readiness (see the "Schema and security" section). A Block of a custom Tool whose Loader has not run yet is visible as text: the Schema removes its markup, and once the Extensions have arrived, the engine parsesvalueagain. - The code block and the table in
fullare lazy too (ADR-0058, item 11.1): they are not inbasic, and their Extensions are larger than 10 kB gzipped, so they arrive as a separate chunk through the same Loader as in a custom Tool. The "Table" menu, the "Insert table" dialog and the code block header arrive with them.basicloads no chunks and is ready at once. - Footnotes in
fullare lazy as well (ADR-0058, item 11.1): thefootnotesTool's nodes with their node view, the keys, the list's upkeep and the Markdown rules arrive as a chunk through the same Loader, andonReadywaits for it too. The Skeleton draws the reference and the list fromvaluein the saved markup (sup[data-footnote-ref]andsection[data-block="footnotes"], with the list's name in the interface language), so the field does not jump when the chunk arrives. An Editor without the Tool never requests the chunk. See the "Footnotes" section. - Block selection is lazy too: the extension of the
blockSelectionTool (Esc, the keys, the highlighting) is its own small chunk through the same Loader; the Block handle and theBlockSelectionclass stay in the start chunk. The chunk has no Blocks, so the Skeleton shows nothing for it. - Until the chunks arrive, an Editor with them is a Skeleton, and
onReadywaits for all of them. Their Blocks are visible in the Skeleton by their shape (the code block with a header, the table with cells), so the field does not jump when the chunks arrive. For the chunks to arrive with the page, putmodulepreloadon them, as on a custom Tool's chunk. The size of "start" and "full" is in the "Import size" table in getting-started. - On the server and before hydration the Skeleton is only the frame and the space for the Toolbar, without a Document: parsing against the Schema happens in the browser DOM. The Document appears after mount, so on an SSR page the field's height changes once, as before the Skeleton. In client rendering the Skeleton's Document exists from the first frame.
The look of the Skeleton is not part of the contract.
Atom text
One rule for built-in and custom Atoms (ADR-0058, section 4): the Atom text is what renderText in the Extensions returns; an Atom with no content and no renderText yields an empty string, an Atom with content inside (an image with a caption) yields the text of its children. The kit builds from it everything that produces text:
- The count toward
maxLengthequals the Atom text length, so the counter matchesgetText()without Block separators. For built-ins: a horizontal rule counts as 0, a hard break as 1, an image as the caption length; the Merge Tag from the example above counts as the length of{{key}}. There is no separate count field: it would drift from the text. The kit has no server counter — the count depends on the Extensions. getText(),getSelectedText(), text on copy andgetMarkdown()return the same Atom text; an Atom is included in the selected text only as a whole. An Atom withoutrenderMarkdownis exported to Markdown as its Atom text; only an Atom without text disappears; the Extensions' ownrenderMarkdownwins.- Emptiness is a kit rule, with no description field. Any Atom, custom or built-in, is content for
required,isEmpty()andgetHTML(): inserting a video without a caption passes the required check. An empty non-Atom Block (a paragraph without text) does not count as content. - Pasting from the clipboard beyond
maxLengthcuts the tail by characters, not by positions. An Atom is not cut: one that does not fit is dropped whole, together with everything pasted after it; if the limit is still exceeded, the paste is rejected entirely.
Outside the Editor: server, Markdown and View
The same tools array is understood by server sanitization and the View (ADR-0058, item 2.3 and section 3).
- The server passes the same
toolsarray to sanitization:sanitizeRichText(html, DOMPurify, tools)lets custom Blocks, Atoms and Marks through by their rules and strips everything else, andrichTextSchema(tools)returns these rules as data. Names of kit Tools do not narrow the allowlist; without the third argument sanitization is as before. Both names exist in@olddevs/ui/editorand in the lightweight@olddevs/ui/editor/schema; the lightweight entry point's graph still has neither Tiptap nor React, and the description of a custom Tool is data that the server reads without the Extensions. Details are in RichTextView, "Custom Tools: the third argument". - Markdown. Custom rules live in the Extensions, as in any Tiptap extension:
renderMarkdown, and for parsingmarkdownTokenizerandparseMarkdown; with them a Block survives thegetMarkdown()→setMarkdown()round trip. Without themgetMarkdown()does not lose text: a Block is exported as its content (a container as its Blocks), an Atom as its Atom text fromrenderText(escaped, like any text), a Mark as its text; only an Atom without text disappears. Such a Block is not created back from Markdown — its text lands as paragraphs. In development mode there is oneconsole.warnper Tool when this default first kicks in. RichTextViewshows a custom Block as sanitized HTML with the paragraph's vertical rhythm — and nothing more; the look is set by your CSS: selectors ondata-blockand the kit's tokens (RichTextView, "Custom Block"). You can bring a Block to life in the View with an Island — the Block'sislandfield;RichTextViewreceives the sametools(RichTextView, "Custom Block's Island").
Custom Tool's button
A custom Tool describes a button as data in the buttons field, and the kit renders it with roles, the Toolbar's single Tab stop and arrow-key navigation along it, aria-pressed, a tooltip with Kbd, and a popover with a frame, layer and focus return. Arbitrary React is allowed only inside the popover's content. The decision is ADR-0058, sections 5 and 6.
import { RichTextEditor, type CustomTool } from "@olddevs/ui/editor";
import { SparkleIcon } from "@olddevs/ui/icons";
export const stampTool: CustomTool = {
name: "acme_stamp",
engine: [], // a button needs neither its own Schema nor Extensions
buttons: [
{
id: "stamp",
label: ({ locale }) => (locale.startsWith("ru") ? "Штамп" : "Stamp"),
icon: SparkleIcon,
can: (editor) => editor.state.selection.$to.parent.inlineContent,
run: (editor) => void editor.chain().focus().insertContent("★").run(),
shortcut: ["mod", "shift", "Y"],
},
],
};| Field | What it is |
|---|---|
id | The button's key, unique within its Tool. It does not collide with the id values of the kit and of other Tools: the kit prepends the Tool's name to it |
label | Required. The label — a string or a function that receives { locale }. The button's name for the screen reader, the tooltip text and the popover's name |
icon | A component with the IconProps contract, either from the kit's icon set or your own. Required: icon names are not supported, and there is no fallback icon |
can | Required. Whether the button is available now. An unavailable one is aria-disabled, stays in the arrow-key order, and a click or shortcut does nothing |
isActive | If present, the button is a toggle with aria-pressed; if absent, a one-off action without aria-pressed |
isVisible | A visibility predicate that depends on context: the button is hidden while it returns false. If absent, always visible |
selectionMenu | true — the button also appears in the Bubble menu (toolbar="bubble") |
shortcut | A shortcut: mod, alt, shift and a key — ["mod", "shift", "Y"] |
run | (editor) => void — runs on a click or the shortcut |
popover | ({ editor, close }) => ReactNode — a popover instead of an action. Exactly one of run and popover |
- Placement. Custom buttons appear on the Toolbar as one group before "Undo" and "Redo", after the kit's groups, in
toolsorder andbuttonsarray order. The fixed and the floating Toolbar show the same set. The kit sets the order of its own buttons; a built-in one can be hidden only by disabling its Tool, and to get a short Toolbar, narrowtools. A disabled Tool removes both its buttons and its shortcut. - State.
can,isActiveandisVisibleare read on every transaction, like the kit's buttons, so they can use the Document's state:editor.isActive("acme_pin"). In a non-editable field (readOnly,disabled) the kit disables the buttons itself. - Popover. The kit manages the frame: the
Popoverlayer, an anchor at the button, the Escape stack (inside aDialog, Escape closes the popover, not the dialog), and the frame's name is the button's label. The content is mounted again each time the popover opens.closecloses the popover the same way as Escape. Closing returns focus and selection to the Document, not to the button; a click elsewhere does not touch focus. A popover triggered by the shortcut opens at the caret, not at the button: the button may not be on screen at all (toolbar="none"). - The shortcut is the single source of truth. The kit itself binds the shortcut to
run(or opens the popover), writes it into the tooltip withKbd, into the button'saria-keyshortcutsand into the Keyboard shortcuts popover: custom rows appear there as a separate group without a heading after the kit's groups, intoolsorder. An unavailable button does not take the key, and the key passes on into the Document. Keyboard shortcuts bound by the Extensions (addKeyboardShortcuts) do not appear in the Keyboard shortcuts popover: set the button's shortcut with theshortcutfield, not with an extension. - Label. The function receives
{ locale }(theUiProviderlocale), and the label re-renders when it changes; in a single-language app a string is enough. Label overrides go through the Tool factory's options (for example, alabelsfield; the recipe is Extension API, "Labels through factory options"); theUiProvidermessage catalog is not extended for the consumer's own Tools. If the label is empty, development mode logs aconsole.errorwith the Tool's and button's names, and the Tool's name is used in place of the label in the button's name, the tooltip and the popover's name. - Menu buttons (with radio items or a submenu) are not available to custom Tools: a popover is enough for choosing from a list.
Insert items and Block actions
A custom Tool adds an item to the Slash menu and an action to the Block handle menu by description, without editing the menu: the kit renders, the consumer describes (ADR-0058, sections 5 and 6). A disabled Tool removes its items and actions everywhere.
import { ColumnLayoutIcon } from "@olddevs/ui/icons";
export const calloutTool: CustomTool = {
name: "acme_callout",
engine: [Callout],
blocks: { acme_callout: { kind: "block", container: true } },
insertItems: [
{
section: "insert",
// A string is for a single language; a function receives { locale } from UiProvider.
label: ({ locale }) => (locale.startsWith("ru") ? LABELS.ru : LABELS.en),
icon: ColumnLayoutIcon,
aliases: ["note", "tip"],
shortcut: ["mod", "alt", "N"],
run: (chain) =>
chain.insertContent({ type: "acme_callout", content: [{ type: "paragraph" }] }),
},
],
blockActions: [
{
label: "Unwrap callout",
icon: ColumnLayoutIcon,
blocks: ["acme_callout"],
isVisible: (editor, pos) => editor.state.doc.nodeAt(pos)?.type.name === "acme_callout",
run: (editor, pos) => unwrapCallout(editor, pos),
},
],
};Insert item (CustomInsertItem).
| Field | What it is |
|---|---|
section | "insert" ("Insert" — a new Block after the current one) or "turnInto" ("Turn into" — change the current Block, keeping its text). Required |
label | The label: a string or a function that receives { locale } (the UiProvider locale), as for a button. Required |
icon | A component with the IconProps contract from @olddevs/ui/icons or your own. Required: there is no fallback icon |
aliases | An array of strings in any language — search words in addition to the label |
shortcut | A shortcut in the Toolbar's notation: ["mod", "alt", "N"]. It is the only source of the key: the kit binds it and shows it in the item's row and in the Keyboard shortcuts popover |
run | (chain, editor) => chain — a chain command: return the chain with the Block's command; the kit calls .run() |
popover | ({ editor, close }) => ReactNode — a popover at the caret instead of a command. Exactly one of run and popover is required |
- Where the item appears. It shows up in "/", the Toolbar's "+", and the Block handle's "Add ›" and "Format ›" automatically: the
turnIntosection goes into both "Format ›" and "¶"; "Add ›" holds the items of both sections (a new empty Block below, as with built-ins). Custom items appear at the end of their section, intoolsorder; inside a Tool, the array order. Without an enabledinsertMenuthe item does not appear, as with built-ins. - One edit, one undo. The section decides what happens to the Document, and
rundecides which Block: ininsertthe kit prepares an empty paragraph (the current one if empty, otherwise a new one after the Block), inturnIntoit removes the list or quote around the Block. The preparation andrungo in one transaction. - Search in "/" matches the label in the current locale, the label when called with
en-US, andaliases, as with built-ins. A function label is called at render time: aUiProviderlocale change re-renders the item. - The shortcut hint in the row is the shortcut's
Kbd; keyboard support in the menu is the same as for built-ins (arrow keys,Enter,Escape, the first letter). The shortcut fires at the caret the same way as choosing the item in "/". - An empty label logs a
console.errorin development that names the Tool and the UI contribution, and the menu shows the Tool's name instead. - A popover (
popover) is for when the Block needs a choice before insertion (a symbol, a template, a URL). The popover is the same as for a button: the kit'sPopoverin the Escape stack (inside aDialog, Escape closes the popover, not the dialog), its accessible name is the item's label, and closing returns focus and selection to the Document. Choosing the item in "/", "+", "Add ›" or "Format ›" closes the menu and opens the popover at the caret. From "/", the popover appears where the "/" was typed, and the typed "/command" is removed, as with an ordinary item. The item's shortcut opens the same popover at the caret. The kit does not prepare the Document — no empty paragraph, no removed list or quote around the Block: the Block inserts its content througheditorin a single transaction, so there is one undo.
Block action (CustomBlockAction).
| Field | What it is |
|---|---|
label | The label — a string or a function that receives { locale }. Required |
icon | A component with the IconProps contract. Required |
blocks | Names of Blocks for which the action is shown: the name of the Block the handle is open on, or of the container that directly holds this Block. Required, a non-empty array |
run | (editor, pos) => void — pos is the position of the Block the handle is open on. The edit is one transaction: one undo |
popover | ({ editor, close, pos }) => ReactNode — a popover at the Block instead of an action; pos is the position of that Block. Exactly one of run and popover |
isVisible | (editor, pos) => boolean — a predicate that decides visibility from the context; if absent, the action is visible for all its blocks |
shortcut | A shortcut in the Toolbar's notation: it acts on the Block under the caret and only where the action is visible in the handle menu; on another Block the key goes to the Document |
Custom actions appear in the Block handle menu in their own section before "Delete", in tools order. An action with a popover opens the popover at the Block — the popover, Escape and focus return are the same as for a button, and the popover's accessible name is the action's label: a choice in the handle menu opens it at the handle's Block, a shortcut at the Block under the caret. pos follows Document edits while the popover is open. The shortcut is in the item's row (as with built-ins, and only when the shortcut does the same thing as the item) and in the Keyboard shortcuts popover: the Tool's rows are a separate group without a heading after the kit's groups.
Tool set validation adds field errors for UI contributions: insertItems/blockActions is not an array or an item is not an object; no label or icon; not exactly one of run and popover; the section is not insert/turnInto; aliases is not an array of strings; blocks is empty; isVisible is not a function; the shortcut is shorter than two keys (a modifier and a key).
Custom Trigger character
A custom Tool opens the same list as "/" with its own character: @ for mentions, # for tags. The decision is ADR-0064. The kit renders the list — the same component as the Slash menu: a popover at the caret, search by what is typed, arrow keys, Enter, Escape, the "Nothing found" row; focus stays in the Document. The consumer describes the character, the items on demand and what happens when an item is picked.
import { RichTextEditor, type CustomTool } from "@olddevs/ui/editor";
import { MentionIcon } from "@olddevs/ui/icons";
const mentionTool: CustomTool = {
name: "acme_mention",
engine: [Mention], // the `acme_mention` Atom with an `acme_id` attribute
blocks: {
acme_mention: {
kind: "inline",
attributes: { acme_id: { kind: "pattern", pattern: "[a-z]+" } },
},
},
trigger: {
char: "@",
// Items on demand: returned immediately or as a promise; the consumer filters.
items: (query) =>
PEOPLE.filter((person) => person.name.toLowerCase().includes(query.toLowerCase())).map(
(person) => ({ id: person.id, label: person.name, icon: MentionIcon })
),
// Picking replaces the typed `@query` with a custom node.
onSelect: (item, { editor, range }) =>
void editor
.chain()
.focus()
.insertContentAt(range, [
{ type: "acme_mention", attrs: { acme_id: item.id } },
{ type: "text", text: " " },
])
.run(),
},
};Trigger (CustomTrigger).
| Field | What it is |
|---|---|
char | The character: one printable character, not / and not a space (@, #, :). Unique in tools. Required |
items | (query) => TriggerItem[] | Promise<TriggerItem[]> — items on demand. Called on every change of the query, including "" right after the character. Required |
onSelect | (item, { editor, range, query }) => void — an item is picked: the handler replaces range with your own node. Required |
label | The list's name for a screen reader: a string or a function that receives { locale }. If absent, "Suggestions" from the message catalog (editor.triggerList) |
Item (TriggerItem): id (unique within one items result) and label — the row text; icon — an icon with the IconProps contract (if absent, the row has no icon); data — any consumer data, the kit does not read it and hands it to onSelect. The label arrives already in the interface language: the consumer filters and translates it.
Selection context (TriggerContext): editor — the raw Tiptap for inserting a custom node; range — { from, to }, the typed text together with the character (@gr); query — the query without the character (gr). The kit does not delete the typed text: the handler does, replacing range with a node in one transaction — then there is one undo, and Ctrl/⌘+Z brings @query back. After onSelect is called the kit closes the list.
- When it opens. The same rules as "/": the character is at the start of a Block or after a space (a non-breaking one counts as a space), and the query ends at a space. Inside a word (
a@b.com), in a code block and in inline code the list does not open. A space ends the query: the list closes and the text stays. - Keyboard. As with "/":
↓/↑move through the items, wrapping around,Enterpicks,Escapecloses and keeps what was typed (it does not reopen on the same character),Enteron an empty list is an ordinary line break. AnEnterthat confirms IME composition is handled by the IME, not by the list. - Asynchronous items. While a promise is pending, the previous list (or nothing) stays, and the "Nothing found" row does not flicker. The result of a stale query is discarded. A rejected promise gives an empty list and, in development, a
console.error. - Independence from "/". The trigger works without
insertMenuintools; only one list is open at a time, because the query begins with exactly one trigger character. It opens only while editing: inreadOnly,disabledand Source mode there is no list. - Accessibility. The field stays
role="textbox"and while the list is open getsaria-controlsandaria-activedescendant, as with "/"; the list isrole="listbox"named bylabel. - Tool set errors (the field shows an error, and the cause is reported with
console.errorin development): two Tools with onechar; acharthat is a space,/, or not one printable character;itemsoronSelectthat are not functions; alabelthat is neither a string nor a function. A custom Trigger character does not collide with built-in ones:/is taken by the Slash menu. - A mention is the consumer's node. The kit does not know what is inserted: a mention Atom, a link, a tag —
onSelectdecides. The Atom is described like any custom Block (Extensions, Schema rules,renderText— Atom text), so a mention reachesgetText(), Markdown andmaxLength.
Text card
The fourth kind of UI contribution (after a button, an Insert item and a Block action): a small card under the text range that contains the caret (for example, a comment card under a comment Mark). The kit renders the card, and the Tool describes the range and the body (ADR-0058, section 7, items 6–11).
import { Mark } from "@tiptap/core";
import { markRange, type CustomTool } from "@olddevs/ui/editor";
const Comment = Mark.create({ name: "acme_comment" });
export const commentTool: CustomTool = {
name: "acme_comment",
engine: [Comment],
marks: { acme_comment: {} },
textCards: [
{
// A string or a function that receives { locale }: the card's name and part of the screen reader announcement.
label: ({ locale }) => (locale.startsWith("ru") ? LABELS.ru : "Comment"),
// The range under the caret; for a Mark, the kit's ready-made helper.
rangeAt: markRange("acme_comment"),
render: ({ editor, range, close }) => (
<div>
<p>{editor.state.doc.textBetween(range.from, range.to)}</p>
<button type="button" onClick={close}>
Resolve
</button>
</div>
),
},
],
};UI contribution (CustomTextCard).
| Field | What it is |
|---|---|
label | The label: a string or a function that receives { locale }. The card's accessible name (role="dialog") and part of the announcement the kit sends to the screen reader when a Text card appears. The entry has no icon. Required |
rangeAt | (state, pos) => { from, to } | null — the range the Text card is attached to, if position pos (of the caret or of a click) lies in it; otherwise null. Required |
render | ({ editor, range, close }) => ReactNode — the Text card's body. range is the range from rangeAt on the current state (it follows edits), close hides the Text card the same way as Escape. Required |
markRange(markName) is a ready-made rangeAt for a Mark: the continuous stretch of text with this Mark and the same values of its attributes around pos. The edges are included: a caret right after a word or before it is still in the range (otherwise a click on the first letter would not open the Text card); between two stretches, the one that ends at pos wins, so text typed next continues that stretch. For a Block or any other range, write your own rangeAt — it reads only state and is called on every transaction, so it must be fast and free of side effects. The kit discards a range that lies outside the Document, has from > to, or consists of values that are not numbers; an exception in rangeAt does not crash the field, but writes console.error in development. markRange is also in the lightweight @olddevs/ui/editor/schema entry point: the description of a custom Tool with a Text card is data, and server sanitization reads it too, so the description module needs neither Tiptap nor React.
- When it is open. The caret (a collapsed selection) is inside the range, or a click on it. A Text card does not open on hover. An expanded selection closes the Text card: the Bubble menu works there. The range is recomputed on every transaction: the Text card follows the range when you edit, and closes when the range disappears. A field out of focus (except
readOnly) does not show the Text card, and neither dodisabledand Source mode. - One Text card. No more than one is open: the narrowest range under the caret wins, and with equal width, the contribution that comes earlier, that is, the Tool earlier in
tools(inside a Tool, earlier in the array). - The kit controls the card. The layer and the Escape stack work as for the kit's
Popover(ADR-0041: Escape closes the Text card, not theDialogorDraweraround the field); the card is anchored under the range, flips above the range at the bottom edge of the viewport, shifts away from the side edges and looks like the kit's popover. There is no heading and no buttons defined by data: the body is your React node, mounted again each time the card opens. - Non-modal. Focus stays in the Document, you can keep typing, and the Text card follows the range.
Alt+F10moves focus into an open Text card (to the body's first focusable element, otherwise to the card itself), as it moves focus to the panel of a selected image. Escape returns the caret to its place and hides the Text card. - Hidden. Escape and
closehide the Text card until the caret leaves the range: an edit and caret movement inside it do not bring it back. A click on the range opens it again. While it is hidden,Alt+F10moves focus to the Toolbar, as without a Text card. - Screen reader. The kit announces that a Text card has opened with the message catalog string
editor.textCardShown("Comment card opened. Press Alt+F10 to move into it." in the English locale; the Russian locale has a different string, "Открыта карточка «{label}». {shortcut} — перейти в неё."): the entry's label and the shortcut are substituted into it. Arole="status"live region is present in every Editor with Text cards and is empty while none is open. readOnly. Text cards work — comments can be read without editing; the engine itself blocks edits made fromrender. Such a field has no caret, so a click opens the Text card (the click position moves with edits), and a click outside the field, Escape and a mouse selection close it. From the keyboard a Text card cannot be opened inreadOnly: the Document does not accept a caret, andAlt+F10cannot be reached from it. Withdisabledthere are no Text cards.- A disabled Tool removes its Text cards as well.
RichTextViewhas no Text cards: it shows sanitized HTML without an engine; to read text with Text cards, use an Editor withreadOnly. - Tool set validation adds field errors:
textCardsis not an array or an item is not an object, no label,rangeAtorrender.