blockcn

API reference

Props and options for every public hook and component.

useEditor

import { useEditor, DEFAULT_EDITOR_CONTENT } from "@/components/editor/useEditor";

const editor = useEditor(options?, deps?); // Editor | null

It takes all of Tiptap's useEditor options. These have blockcn defaults:

Prop

Type

The editor element gets the class blockcn-editor, which editor.css styles. Set editorProps.attributes.class to replace it. Other attributes are merged, so a preset can keep spellcheck while a later call changes class.

useAutosave

import { useAutosave } from "@/components/editor/useAutosave";

const { status, lastSavedAt, error, flush } = useAutosave(editor, (json) => api.saveDoc(id, json), {
  debounceMs: 1000,
});

Saves the document after edits settle. Only one save runs at a time: edits made during a save are saved together right after it finishes. Pending changes are also saved on unmount (with the document as it was when the editor was destroyed, if that happened first), on beforeunload, and when the page becomes hidden. Your own undo/redo in a collaborative document counts as a change. A failed save sets status: "error" and error, and is retried on the next change or flush(). Collaborators' changes are ignored unless includeRemote: true. In a collaborative document, usually only one client (or your server) should save.

Prop

Type

createUseEditor

import { createUseEditor } from "@/components/editor/useEditor";

const useReadonlyEditor = createUseEditor({ editable: false });
const editor = useReadonlyEditor(options?, deps?);

Preset options sit under the options passed to the hook: defaults, then the preset, then that call. editorProps and editorProps.attributes are merged the same way as in useEditor, so one call can override a single attribute without dropping the rest.

createEditorExtensions

import { createEditorExtensions } from "@/editor-core/schema/extensions";

This builds the schema without React. The slash menu is a DOM list unless you pass slashRender, and code, callout, and toggle use their HTML unless you pass blockViews. createBlockcnEditor from the React preset passes both. Pages without React use mountBlockcnEditor(element) from editor-vanilla.

Prop

Type

Editor

import { Editor } from "@/components/editor/Editor";
ComponentPropsNotes
Editoreditor, messages?, dir?, className?, classNames?, childrenContext provider. Renders nothing while editor is null. className and classNames land on [data-blockcn-root] (display: contents). classNames may be a string or { root, frame, content }.
Editor.FrameclassName?, classNames?, childrenPositioned wrapper with room for the drag handle. [data-blockcn-frame]. A string classNames adds classes; an object uses frame. Classes from Editor classNames.frame apply too.
Editor.ContentTiptap EditorContent props (except editor), plus classNames?The editable document. [data-blockcn-content].
Editor.Chromechildren?Floating UI. With no children it renders SideMenu and FormattingToolbar. Hidden when read-only.
Editor.SideMenuturnInto?, menuItems?, items?, filterItems?, renderItem?, children?, onAdd?, editor?Drag handle and block menu. items reorders default ids. filterItems drops entries. renderItem replaces one row (undefined keeps the default). menuItems or children still replaces the dropdown.
Editor.FormattingToolbaronAskAI?, shouldShow?, children?, items?, filter?, editor?Toolbar shown on text selection. children replaces the default controls. items reorders or subsets them. filter drops ids from that list (or from the defaults). Parts: Bold, Italic, Underline, Strike, Code, Link, Color, Highlight, Align, TurnInto, AskAI, Separator, Button, plus Root, MarkToggle, AlignToggle, ColorPicker, HighlightPicker, LinkPopover, AskAIButton.
Editor.OutlinenoneHeading navigation.
Editor.StatsclassName?Optional footer: words, characters, reading time (200 words a minute, rounded up), remaining room when a limit is set, and the selected word count. Renders nothing when core.documentStats is false. [data-blockcn-stats]. useDocumentStats(editor) returns the same numbers, plus charactersNoSpaces, blocks, and selection (null when the caret is empty).
ExportMenueditor?, hooks?: ExportHandlersFrom export-menu. File menu: import .md, .html, .docx, or a paste, after a report (replace or insert, one undo step). Export HTML, Markdown, or Word, or print a PDF. Word and the importer load on first use. Uses the surrounding Editor when editor is omitted.
Editor.DefaultnoneShorthand for Frame, Content, Chrome and Outline.

useEditorContext(editor?) returns the editor you pass, or the one from Editor. TableHandleMenu, TableToolbar, MediaToolbars, and AskAI use it, so the editor prop is optional inside Editor.

Custom toolbar

children replaces the default buttons. Each part reads the editor from context:

import { Bold, Italic } from "lucide-react";

<Editor.FormattingToolbar>
  <Editor.FormattingToolbar.MarkToggle mark="bold" icon={Bold} label="Bold" shortcut="Mod-B" />
  <Editor.FormattingToolbar.MarkToggle mark="italic" icon={Italic} label="Italic" shortcut="Mod-I" />
  <Editor.FormattingToolbar.Separator />
  <Editor.FormattingToolbar.LinkPopover />
</Editor.FormattingToolbar>

Add a toolbar button

items sets the order and the subset. filter removes ids from that list, or from the defaults when items is omitted. children still replaces the row. A FormattingToolbar.Button uses the same toggle, label, and roving tabindex as the built-ins, so arrows, Home, End, Escape, and Alt+F10 include it. TurnInto is not in the default row; add "turnInto" to items to show it.

import { Pin } from "lucide-react";

<Editor.FormattingToolbar
  items={["bold", "italic", "separator", "link"]}
  filter={(id) => id !== "italic"}
>
  <Editor.FormattingToolbar.Bold />
  <Editor.FormattingToolbar.Button
    icon={Pin}
    label="Pin"
    isActive={pinned}
    disabled={!canPin}
    onClick={pinSelection}
  />
</Editor.FormattingToolbar>

children wins when it is set, so the example above shows Bold and Pin, not the items list. Omit children to use items and filter:

<Editor.FormattingToolbar items={["italic", "bold"]} filter={(id) => id !== "bold"} />

That row is only Italic. The default row is unchanged when both props are omitted, and it still hides a control whose mark or extension is not installed.

shouldShow on Editor.FormattingToolbar (or .Root) replaces the default check, which hides the toolbar on a node selection and on any node with storage.blockcn.hideTextToolbar.

ColorPicker and HighlightPicker accept a colors list. The built-in swatches are named colors (Default, Gray, Brown, Orange, Yellow, Green, Blue, Purple, Pink, Red). A named color is stored as var(--blockcn-text-red) or var(--blockcn-highlight-red), so it follows the light and dark theme. Default clears the color. The custom color input still stores a hex value. HTML export replaces the tokens with the light-theme color.

To drop Delete from the block menu:

import { defaultSideMenuItems } from "@/components/editor/SideMenu";

<Editor.SideMenu menuItems={defaultSideMenuItems().filter((item) => item.id !== "delete")} />

ExportHandlers

Prop

Type

Right-to-left

<Editor.Root dir="rtl"> sets dir on Editor.Frame and the editable element, and passes it to menus and popovers (a Radix DirectionProvider). Leave dir out to inherit the page's dir. In RTL:

  • The block handle sits on the right, and the gutter uses ps-14.
  • Lists, quotes, tables, the table of contents and the outline use logical (start/end) spacing.
  • Columns run right to left, and dragging or arrow-keying the divider follows the reading direction.
  • Text alignment is logical. The toolbar offers Align start / center / end, and a block with no alignment follows the reading direction. The alignment attribute also accepts start and end; existing left and right values are kept as they are.
  • HTML export writes the editor's direction on <html dir> and an explicit text-align on every paragraph and heading (start when the block has none), so the file reads the same wherever it is opened. serializeHtmlDocument(doc, title, drawings, schema, dir) and buildHtmlPreview(doc, handlers, schema, dir) take the direction; the export menu passes editorDirection(editor).
  • useDirection(editor) re-reads after mount and whenever a dir attribute changes on the page.
  • Slash, mention, emoji and Ask AI popups take the editor's direction.

The demo app switches to RTL with ?dir=rtl.

Accessibility

  • The formatting toolbar is a role="toolbar" with a roving tabindex. Alt+F10 moves focus into it from the editor, ←/→ (reversed in RTL), Home and End move between controls, and Escape returns to the editor with the selection intact. Closing a toolbar popover or the block menu also returns focus to the editor. Use useRovingToolbar(editor) for your own toolbars.
  • While the slash menu or a mention/emoji list is open, the editable element is a combobox with aria-expanded, aria-controls pointing at the listbox, and aria-activedescendant on the highlighted option. Otherwise it's a textbox named by messages.editor.label.
  • Every icon button, swatch and resize handle has an accessible name, and the column divider is a keyboard-operable role="separator" with aria-valuenow. All chrome shows a :focus-visible ring.

Messages (i18n)

Every user-facing string in the editor comes from a messages object: placeholders, slash items, menus, toolbar labels, the Ask AI panel, media and upload states, columns, the table of contents, toggles, callouts, mentions, emoji, export/import, and collaboration presence. Pass a partial object to Editor.Root. It is deep-merged over the English defaultMessages:

import { Editor } from "@/components/editor/Editor";
import type { PartialMessages } from "@/editor-core/i18n/messages";

const fr: PartialMessages = {
  placeholder: { paragraph: "Tapez « / » pour les commandes…", heading: "Titre" },
  toolbar: { bold: "Gras", italic: "Italique" },
  slash: { noResults: "Aucun bloc", items: { heading1: { label: "Titre 1", keywords: ["titre"] } } },
};

<Editor.Root editor={editor} messages={fr}>…</Editor.Root>;
  • Keep the object stable: define it at module scope, or wrap it in useMemo.
  • {name}-style placeholders in messages, for example "Uploading {name}…", are filled in by the editor.
  • Item lists are keyed by item id: slash.items, turnInto.items, ai.actions, ai.params, colors and emoji.names. Add keys for your own slash items and actions too. A missing key falls back to the item's own English text. Translated slash keywords are searched along with the English ones.
  • Components read messages with useMessages(). Code outside React (placeholders, slash and suggestion popups, upload notices) reads getMessages(editor), which Editor.Root keeps in sync through the I18n core extension. Without Editor.Root, pass them to createEditorExtensions({ messages }). Editor.Root without a messages prop leaves those in place and uses them for its components too; only an explicit prop replaces them.
  • useAskAI({ failedMessage }) sets its generic error text. AI tone and language params are still sent to the server in English; ai.params only changes how they're shown.
  • Exported documents (HTML, Markdown) are content, not chrome, and stay as written.

Add-on exports

Add-onExtensionsSlash categoryUI
Media (@/components/editor/…)mediaExtensions or createMediaExtensions({ uploadFile }) from mediaExtensionsMEDIA_SLASH_CATEGORY from mediaSlashItems<MediaToolbars /> from MediaToolbars
TablestableExtensions or createTableExtensions({ resizable, cellBackgrounds }) from tableExtensionsTABLE_SLASH_CATEGORY from tableSlashItems<TableHandleMenu /> from TableHandleMenu: the menu the row and column grips open. Grips drag to reorder, and the bars add a row or column. <TableToolbar /> is the older floating toolbar (merge, split, sort, move)
WhiteboardexcalidrawExtensions or createExcalidrawExtensions({ theme }) from excalidrawExtensionsEXCALIDRAW_SLASH_CATEGORY from excalidrawSlashItemsnone
Ask AIAskAI from @/editor-core/ai/AskAIExtensionAI_SLASH_CATEGORY or aiSlashItems(actions) from ai/aiSlashItems<AskAI endpoint? transport? actions? systemPrompt? /> from ai/AskAI. transport wins over endpoint. ai({ autocomplete: true }) adds ghost text (Tab accepts, Escape dismisses).
MathmathExtensions or createMathExtensions({ katexOptions }) from addons/mathMATH_SLASH_CATEGORYnone (KaTeX renders the nodes)
ColumnscolumnsExtensions or createColumnsExtensions({ min, max, resizable }) from addons/columnsCOLUMNS_SLASH_CATEGORYresize handles on the block
Mentions and emojicreateMentionExtensions({ fetchMentions, renderItem?, trigger? }) from addons/mentions. fetchMentions is required. emoji({ data, recent }) replaces the emoji set for one editorMENTION_SLASH_CATEGORY or mentionSlashCategory(trigger)@ and : suggestion lists. The : list and the callout grid have categories, skin tones, and recents
Table of contentstocExtensions or createTocExtensions({ levels }) from addons/tocTOC_SLASH_CATEGORYthe block lists headings from collectOutline, or from levels when set
Link previewcreateLinkPreviewExtensions({ fetchMetadata }) from linkPreview/linkPreviewnonea menu after a lone URL is pasted. Embed is shown when the host is on the media allowlist
PagescreatePageExtensions({ fetchPages, createPage, onNavigate }) from pages/pages. fetchPages is requiredPAGE_SLASH_CATEGORY[[ inserts an inline mention. The slash item inserts a block. The app owns routing
VersionscreateVersionExtensions({ storage, getCurrentUser, intervalMs?, maxVersions? }) from versions/versionExtensionnone<HistoryPanel /> from versions/HistoryPanel. See Version history.
SuggestionscreateSuggestionExtensions({ getCurrentUser, mode? }) from suggestions/suggestionExtensionnone<SuggestionModeToggle /> and <SuggestionCards />. The comments sidebar shows the cards when both add-ons are installed. See Suggestions.

createMediaExtensions

import { createMediaExtensions } from "@/components/editor/mediaExtensions";
import { createUploadFile } from "@/lib/mediaUpload";

Prop

Type

Returns the media extensions, including MediaUpload (file paste and drop). mediaExtensions is the same as createMediaExtensions().

createUploadFile({ endpoint, fieldName?, headers?, getHeaders?, withCredentials? }) builds an uploadFile that POSTs multipart/form-data with progress and cancel. It expects a JSON response of { url, name?, size?, mimeType? }, or { error } with a non-2xx status. getHeaders() (sync or async) runs before every upload and its headers are merged over headers; use it for a short-lived upload token.

New block attributes:

BlockAttributeDescription
imagewidthPixel width from the resize handles. null is natural size.
imagealign"left", "center" (default) or "right".
imagecaptionCaption text, or null. Exported as a figcaption.
imagerotateDegrees, applied with transform: rotate(). 0 is the default.
imagecropX, cropY, cropWidth, cropHeightCrop rectangle as percentages. Exported as clip-path: inset(). The source URL is unchanged.
galleryimages{ src, alt }[]. Reorder is one undo step. A blob: source shows in the editor and is omitted from export.
fileBlocksize, mimeTypeFilled in from the upload result.
image, videoBlock, audioBlock, fileBlockuploadId, uploaderClientId, uploadStartedAtSet while an upload is running: the upload, the uploader's Yjs clientID, and when it started (moved forward at most once a minute while it makes progress, and on Retry). Only one block holds an upload: duplicating, copying and pasting give the copy an empty block, and deleting the original aborts the upload. Never rendered to HTML. Spread uploadAttributes from mediaUpload.ts into custom media nodes.

AskAI

import { AskAI } from "@/components/editor/ai/AskAI";

Prop

Type

AskAIAction is { id, label, icon, group, needsSelection, params?, rewrites? }. needsSelection chooses the selection menu or the generate menu. params expands one action into a row per choice (tone, language). rewrites: false inserts the result below the selection; otherwise a selection action replaces it.

Built-in slash category ids are SLASH_CATEGORY_BASIC, SLASH_CATEGORY_MEDIA, SLASH_CATEGORY_ADVANCED, and SLASH_CATEGORY_AI ("basic", "media", "advanced", "ai"). Any other string is a valid category id. A query ranks matches inside each category (exact, then word start, then a substring, then a subsequence of at least two characters) and keeps ties in the original order. An empty query shows Recently used first (localStorage key blockcn-slash-recent, five items). SlashCommand option recent: false hides that group and does not write storage. An item can set aliases (searched, not shown) and shortcut (shown, not searched).

The extension also adds these commands:

CommandDescription
editor.commands.openAskAI({ mode, from?, to?, actionId?, param? })Opens the panel. mode is "selection" or "block". from/to default to the current selection. actionId runs that action immediately.
editor.commands.closeAskAI()Closes the panel.

AskAI loads its panel the first time it opens.

A response that stops after text has arrived is cut off, not finished. useAskAI reports status: "truncated" with truncation set to "max_tokens", "refusal" or "error", keeps the partial output, and the panel asks "Response was cut off — accept anyway?". Transports signal it by throwing AskAITruncatedError(message, reason). plainTextTransport reads the example server's trailer (X-Blockcn-Stream: v1), and sseTransport reads an event: error that has a reason. See Backend contract. useAskAI({ failedMessage }) sets the error text for a failure that has no message.

Collaboration

import { useCollaboration, useSeedCollaborativeContent } from "@/components/editor/collaboration/useCollaboration";
import { createCollaborationExtensions, createRandomCollaborationUser } from "@/components/editor/collaboration/collaborationExtensions";
import { CollaborationPresence } from "@/components/editor/collaboration/CollaborationPresence";

useCollaboration(options)

Prop

Type

token may be a string or () => string | Promise<string>. Use a function so tokens can be refreshed: the server closes a document's connection once its token has expired (a token-expired auth failure; the socket stays open) and asks for a new one shortly before that. onAuthenticationFailed(reason) runs when the server rejects the token and refreshing didn't help.

Returns { session, status, synced, connection, readOnly, authError }. session is { doc, provider }, or null until it's created. The session is recreated when url, room or a string token changes. connection is "connecting", "connected", "reconnecting", "offline" or "unauthorized". readOnly is true when the server granted read-only access. authError is the rejection reason, or null.

Helpers

FunctionDescription
createCollaborationExtensions(session, user)Collaboration and caret extensions. user is { name: string; color: string } (hex).
useSeedCollaborativeContent(editor, collaboration, content)Client-side seeding, for setups without a server seed: inserts content after the first sync if the room is empty and was never seeded (a seeded flag in the document). Skips read-only clients. Prefer the server's seed.
createRandomCollaborationUser()A demo user with a random name and color.

CollaborationPresence

Prop

Type

useSyncStatus(collaboration) returns { status, pendingChanges }. status is "connecting", "connected", "offline", "saving", or "saved". pendingChanges is the provider's unsynced update count. SyncStatus renders the label. A disconnected or rejected connection is offline. Pending updates while connected are saving. A finished sync with nothing pending is saved.

Example server (server/src/collaboration.ts)

createCollaboration({ storage, auth, seed?, tokenSweepMs?, tokenRefreshWindowMs? }):

OptionDescription
seed(room) => docJSON | null. Fills a brand-new room (nothing in storage) once, in onLoadDocument. COLLAB_SEED=demo uses the editor's demo document.
tokenSweepMsHow often open connections are checked for expired tokens. Default 30 s.
tokenRefreshWindowMsHow long before exp the client is asked for a fresh token. Default 60 s.

CollabContext.user is { id, name, readOnly, expiresAt }. TOKEN_EXPIRED_CLOSE_CODE (4401) is the close code onDisconnect hooks see for an expired document connection. signCollabToken({ permission: "upload" }, secret) mints an upload-only token for POST /api/upload. Room files are stored as room-<hex>.bin (or room-h-<sha256>.bin when the hex name would exceed the 255-byte file name limit), so names that differ only in case never share a file.

On this page