blockcn

Blocks and export

Turn on tables, media blocks, the Excalidraw whiteboard and HTML/Markdown export.

Media, the whiteboard, export, and tables are separate installs. None of them appear until you register them. Export is a component you place yourself (<ExportMenu /> from export-menu), not part of editor-shell.

Each add-on has up to three parts:

PartExampleWhere it goes
Extensions arraymediaExtensions (or createMediaExtensions({ uploadFile }))Spread next to createEditorExtensions()
Slash categoryMEDIA_SLASH_CATEGORYcreateEditorExtensions({ slashCategories: [...] }) so / lists it
Toolbar<MediaToolbars />Inside Editor.Chrome

Install tables

Skip this step if you don't need tables.

npx shadcn@latest add https://blockcn.com/r/table-toolbar.json

Register the extensions

src/components/block-editor.tsx
"use client";

import { Editor } from "@/components/editor/Editor";
import { ExportMenu } from "@/components/editor/ExportMenu";
import { useEditor } from "@/components/editor/useEditor";
import { createEditorExtensions } from "@/editor-core/schema/extensions";
import { mediaExtensions } from "@/components/editor/mediaExtensions";
import { MEDIA_SLASH_CATEGORY } from "@/components/editor/mediaSlashItems";
import { MediaToolbars } from "@/components/editor/MediaToolbars";
import { tableExtensions } from "@/components/editor/tableExtensions";
import { TABLE_SLASH_CATEGORY } from "@/components/editor/tableSlashItems";
import { TableHandleMenu } from "@/components/editor/TableHandleMenu";
import { excalidrawExtensions } from "@/components/editor/excalidrawExtensions";
import { EXCALIDRAW_SLASH_CATEGORY } from "@/components/editor/excalidrawSlashItems";

const extensions = [
  ...createEditorExtensions({
    slashCategories: [
      MEDIA_SLASH_CATEGORY, 
      TABLE_SLASH_CATEGORY, 
      EXCALIDRAW_SLASH_CATEGORY, 
    ],
  }),
  ...mediaExtensions, 
  ...tableExtensions, 
  ...excalidrawExtensions, 
];

Add the toolbars and export menu

src/components/block-editor.tsx
export function BlockEditor() {
  const editor = useEditor({ extensions });
  if (!editor) return null;

  return (
    <Editor editor={editor}>
      <div className="mb-4 flex justify-end">
        <ExportMenu />
      </div>
      <Editor.Frame>
        <Editor.Content />
        <Editor.Chrome>
          <Editor.SideMenu />
          <Editor.FormattingToolbar />
          <MediaToolbars />
          <TableHandleMenu />
        </Editor.Chrome>
      </Editor.Frame>
      <Editor.Outline />
    </Editor>
  );
}
  • MediaToolbars and TableHandleMenu read the editor from context, so they render inside Editor. Pass editor only to override that. The early return is there because useEditor is null on the first render. Tables work like Notion's: hovering a cell shows a grip on its row's start edge and its column's top edge. Click a grip for its menu (Color with text and background colours, Insert above/below or left/right, Duplicate, Clear contents, Delete); the first row's menu toggles the header row and the first column's toggles the header column. Drag a grip to reorder, and the move is its own undo step. From the keyboard, Alt+F10 in a cell focuses the row grip, Tab switches to the column grip, Enter opens the menu, and Arrow keys move the line. Bars along the end and the bottom add a column or a row. The header row stays visible while the table scrolls. A column width is stored on the cells and written into the exported HTML, along with each cell's textColor and backgroundColor. In a right-to-left document, the resize handle sits on the inline end of the column. table({ resizable, cellBackgrounds }) turns column resizing and the Color submenu off. Both default to on. Duplicate, Clear contents, and drag skip a table that has a merged cell. The older floating TableToolbar (merge, split, sort, move buttons) is still exported if you want to render it yourself.

Try it

Type / and you'll see Media, Table and Whiteboard entries next to the basic blocks.

Only want some of them?

Leave out the add-on's extensions, slash category and toolbar. The unused files can stay in your repo.

Media blocks

Image, video, audio, file and link blocks store a URL. An empty block has two tabs: Upload and Embed link. You can also paste or drop files anywhere in the editor. Each file gets a placeholder block of the right type (image, video, audio or file) at the caret or drop point. The block shows progress and a cancel button, then switches to the uploaded URL. If an upload fails, the block stays and shows the error with Retry and Remove (or Dismiss for an Upload-tab block, which goes back to empty). Deleting a placeholder, or undoing its insertion, cancels its upload.

Pasting a file uploads it, unless the clipboard also has HTML (Office apps copy text plus a picture of it, and the text is kept) or plain text other than the files' names (Finder and Explorer put the names there).

Images have resize handles, left/center/right alignment in the toolbar, a caption field under the image, and an Alt text field in the image toolbar. While an image is selected, Rotate in the floating toolbar turns it by 90 degrees. Rotation is CSS transform on the same source, including in the HTML export. The caption exports as a figcaption. Gallery is a slash item: a grid of images, move-toward-start and move-toward-end, and a dialog lightbox. A blob: source shows in the editor and is left out of HTML and Markdown. createMediaExtensions({ pasteImagesAs }) is "upload" (the placeholder path), "dataUrl", or "objectUrl". A data URL over dataUrlMaxBytes (1 MB) is skipped. A file block whose name or type is a PDF shows that PDF in the card. media({ embedAllowlist: ["youtube.com"] }) adds an Embed slash item: the URL is shown in an iframe only when its host is on that list (or a subdomain of one). javascript: and every other host stay as text.

Store uploads

Pass an uploadFile function. It gets the file, a progress callback and an abort signal, and resolves with the stored URL:

src/components/block-editor.tsx
import { createMediaExtensions } from "@/components/editor/mediaExtensions";

const extensions = [
  ...createEditorExtensions({ slashCategories: [MEDIA_SLASH_CATEGORY] }),
  ...createMediaExtensions({
    async uploadFile(file, { onProgress, signal }) {
      const { uploadUrl, publicUrl } = await getSignedUrl(file, { signal }); // your API
      await fetch(uploadUrl, { method: "PUT", body: file, signal });
      onProgress(100);
      return { url: publicUrl, name: file.name, size: file.size, mimeType: file.type };
    },
  }),
];

To POST to an endpoint with real progress, use createUploadFile. It works with the example server's POST /api/upload:

import { createUploadFile } from "@/lib/mediaUpload";

createMediaExtensions({
  uploadFile: createUploadFile({ endpoint: "http://localhost:8001/api/upload" }),
});

The example server needs a token for uploads. Pass getHeaders, which runs before every upload, so a short-lived token stays fresh. See Uploads.

Limits and errors

Files are checked before they upload. Refused files never upload: one notice per paste or drop lists every refused file and the reason.

createMediaExtensions({
  uploadFile,
  // MIME types, `type/*` or `.ext`. Default with createUploadFile: the example server's list (DEFAULT_UPLOAD_ACCEPT); with your own uploadFile, none. null allows anything.
  accept: ["image/*", "application/pdf"],
  // Bytes. Default with createUploadFile: 10 MB, like the example server; with your own uploadFile, none. null for no limit.
  maxSize: 25 * 1024 * 1024,
  // Every failure, refused before upload or rejected by uploadFile.
  onUploadError: (error, file) => reportToSentry(error, { file: file.name }),
});

Keep accept and maxSize in step with your backend's limits; the server still has to enforce its own.

Without uploadFile, uploads are demo only

mediaExtensions (and createMediaExtensions() without uploadFile) keep files as object URLs (blob:…). They only work in the tab that added them, and only until it reloads. Exports point at nothing. An object URL is released when no block uses it any more, and recreated if undo brings the block back. In development the editor logs a warning on the first upload. Configure uploadFile before you ship.

In a collaborative document (the Collaboration extension is registered) there is no fallback. Without uploadFile, pasting or dropping a file shows "Uploads need an upload endpoint in shared documents", and only Embed link works.

Math, columns, mentions and contents

These are separate registry items. editor-shell does not copy them. Install the ones you want:

npx shadcn@latest add https://blockcn.com/r/math.json
npx shadcn@latest add https://blockcn.com/r/columns.json
npx shadcn@latest add https://blockcn.com/r/mentions.json
npx shadcn@latest add https://blockcn.com/r/toc.json

Math pulls in KaTeX. Columns, mentions and the table of contents are layout and reference blocks most documents do not need. Spread the extension array and pass the slash category, the same way as media:

import { mathExtensions, MATH_SLASH_CATEGORY } from "@/components/editor/addons/math";
import { columnsExtensions, COLUMNS_SLASH_CATEGORY } from "@/components/editor/addons/columns";
import { createMentionExtensions, MENTION_SLASH_CATEGORY } from "@/components/editor/addons/mentions";
import { tocExtensions, TOC_SLASH_CATEGORY } from "@/components/editor/addons/toc";

const extensions = [
  ...createEditorExtensions({
    slashCategories: [MATH_SLASH_CATEGORY, COLUMNS_SLASH_CATEGORY, MENTION_SLASH_CATEGORY, TOC_SLASH_CATEGORY],
  }),
  ...mathExtensions,
  ...columnsExtensions,
  ...createMentionExtensions({
    fetchMentions: async (query) => searchPeople(query),
  }),
  ...tocExtensions,
];

fetchMentions is required. It returns { id, label }[] (or a promise of that). There is no built-in directory. renderItem changes the label in the list, and trigger changes the character that opens it (@ by default). Typing : still opens the emoji list. math({ katexOptions }) is merged over { throwOnError: false }. $$ at the start of a block becomes a math block, and $E=mc^2$ becomes inline math; neither rule exists when math is not installed. Columns accept 2–5 columns and drag to resize; pass columns({ min, max, resizable }) to change that. The table of contents block reads the same heading list as the outline (collectOutline), unless you pass toc({ levels }). Each of these also registers a Turn into action.

Callouts (emoji and colour), toggles (open state is stored on the block) and syntax-highlighted code blocks are part of the core schema, so they are already in createEditorExtensions. A selected callout has a type (info, warning, success, danger, note, or custom) and a lucide icon. A preset sets the colour from the existing highlight tokens and exports a GitHub admonition (> [!WARNING]) plus class="callout-warning" in HTML. Pasting that admonition turns it back into a callout. A callout with no type stays the emoji quote. The slash menu ranks matches inside each category, shows Recently used on an empty query (stored in localStorage, and recent: false on the slash command opts out), and shows a markdown shortcut at the end of a row. An item's aliases are searched and not shown. A code block can store a filename, line numbers, wrapped lines, and highlighted lines such as 2, 4-6. Those controls appear while the block is selected. Tab indents by two spaces and Shift-Tab removes them. Escape, then Tab, leaves the block instead of indenting. HTML export keeps data-filename, data-highlight, and data-line-numbers. Markdown writes ```ts title="x.ts" {2,4-6}. A block drag can move the block under the pointer, including a paragraph between columns and into a toggle, callout, or quote. A columns block stays at the top level, and a drop into a list item or a table cell is ignored. Typing : searches the Unicode emoji set, which loads the first time the list or a callout's emoji grid opens. A short list shows until that load finishes. The callout grid has a search field, category tabs, a skin-tone row, and recent emoji, and it scrolls. Left and right arrow keys move through the grid (they follow dir) and, in the : list, change the skin tone. The tone and the recent list are stored in localStorage; if that throws, the picker still works. emoji({ data, recent }) replaces the set for that editor, and a custom set can include keywords. A joined emoji does not take a skin tone.

Columns, toggles and Turn into

  • Columns work like Notion's. Drag a block by its handle to the end edge of another block (or just inside its start edge): a vertical line shows, and the drop puts the two side by side. Beside a block that is already in a column, the drop adds a column next to that one and evens the widths out. A column whose last block is dragged away disappears, Backspace in an empty column removes it, and a row left with one column becomes plain blocks. Each of these is one undo step. There is no hover border or menu; the divider shows while the gap is hovered. A row holds 2 to 5 columns, and their widths always add up to 100. A row narrower than 32rem (a phone, a narrow pane) shows its columns stacked, top to bottom, and keeps their widths for wider screens. columns({ min, max, resizable }) changes that range and can hide the divider (min defaults to 2, max to 5, resizable to true). addColumn and removeLastColumn are single undo steps. Dragging the divider (or focusing it and using the arrow keys) writes one change when you let go. Content outside the range is repaired when loaded: a lone column is unwrapped, a short layout is padded, and extra columns are merged into the last. In a shared document, layouts that arrive from collaborators are repaired by one client only (the connected one with the lowest Yjs clientID, read from the provider's awareness), in its own change, so the fix syncs once. Columns don't nest: the slash menu leaves out Columns inside a column, and insertColumns refuses there (slash items can hide themselves with isAvailable(editor)). The divider is hidden, and side drops are off, while the editor is read-only or locked.
  • Toggles open and close for the current viewer only. Clicking the chevron doesn't change the document, so it adds no undo step, isn't sent to collaborators, and works while the editor is locked. The open attribute is only the starting state (and what exports use); setToggleOpen(open) changes it.
  • Turn into only offers conversions that keep the block's content. Each TurnIntoItem can have canApply(editor, block), and the side menu hides items that return false. Lists convert every item, and a quote, callout or toggle turned into a heading becomes a heading followed by paragraphs. A list or container that holds an image, table, math or other non-text block isn't offered the text types, since converting it would drop that block.

Loading KaTeX lazily

KaTeX is about 90 kB gzipped. The math node views call loadKatex() from lib/lazyKatex.ts, which shows the plain LaTeX and loads KaTeX (and its stylesheet) the first time a math node renders. No bundler alias is required, so a registry install splits it the same way. Code blocks register plaintext up front. The rest of lowlight's common set (JavaScript, TypeScript, JSON, CSS, HTML/XML, Bash, Python, Markdown, C, C++, Go, Rust, and more, with aliases like yml and c++) loads the first time a block uses one, each as its own small chunk.

linkPreview({ fetchMetadata }) (link-preview item, @/components/editor/linkPreview/linkPreviewAddon) watches for a paste that is only an http(s) URL. A menu offers Link, Mention, Bookmark, and Embed when media({ embedAllowlist }) allows that host. Mention is an inline chip. Bookmark is a card with the title, description, and image. The editor does not fetch the page. fetchMetadata does, and a failure falls back to the hostname. Escape inserts a plain link. Typing before you choose drops the URL.

The example server's GET /api/unfurl?url= reads Open Graph, then Twitter tags, then the document title. It allows only http: and https:, resolves DNS, and refuses a private, loopback, link-local, or metadata address, including one reached by a redirect. The body is capped, the request times out, and the content type must be HTML. A read, write, or upload token is required unless COLLAB_ALLOW_ANONYMOUS=true. A successful read is cached. Point the demo at it with VITE_UNFURL_URL. Without that, the demo uses the hostname as the title.

pages({ fetchPages, createPage, onNavigate }) (pages item, @/components/editor/pages/pagesAddon) adds a page mention and a page link. The app owns the page tree and the routing. fetchPages(query) supplies the titles. onNavigate(pageId) runs when someone opens a page. createPage(title) is optional.

Type [[ for an inline mention. The slash menu's Page item uses the same list and inserts a block. The title and icon are stored on the node, so HTML export and a static render still show them when the app is offline. They refresh once after the editor loads. A page the search does not return is marked missing and keeps its last title. A failed search leaves the cache alone. Export does not invent a URL. The HTML carries data-page-id and the cached title.

Export

<ExportMenu /> (from export-menu) opens a file menu inside Editor. Import… reads a .md, .html, or .docx file, and Paste reads HTML from the clipboard, or plain text as Markdown. Neither changes the document until you confirm. The dialog counts top-level blocks, unsupported blocks that were kept, and images that need re-upload (a data URL, a blob URL, or an http(s) URL). Replace document and Insert at cursor are each one undo step. When the media add-on can upload, those images go through it first; a failed fetch or upload keeps the original source. HTML previews a standalone file, Markdown downloads .md, and Word downloads .docx. PDF opens the browser print dialog on that same HTML, so you can save a PDF there. docx and mammoth load the first time you export or import Word, not with the editor.

While the editor is on the page, HTML and PDF copy it as it is painted, in the current theme. Blocks that have not painted yet because they are below the fold are rendered for the file: math through KaTeX, and other blocks through their serializer. A whiteboard is always the drawing as a PNG, without Excalidraw's toolbars, and an empty one is left out. A YouTube video becomes its thumbnail linking to the video, because YouTube does not play embeds on a page opened from disk. Editing controls are left out (a component can mark any element data-export="hide"), buttons that hold content become text, and to-do boxes are disabled. Toggles keep their state and still open and close in the file; printing opens them all. The file keeps only the CSS that applies to it and carries the fonts the editor loaded, so it looks the same opened from disk. A node serializer can add paint(node, inline), an async function that returns that HTML (math uses it to load KaTeX). With hooks.serializeHtml, or when the editor is not on the page, the inline-styled serializer is used instead.

Markdown writes a toggle as <details> with its title in <summary>, columns as a <table data-columns> that viewers show side by side, subscript and superscript as <sub> and <sup>, and an embed as a link inside its own markup. Markdown import reads those back, along with $…$ and $$…$$ math and <div style="text-align:…"> alignment, so a round trip keeps them. A callout without a type is written as a quote. HTML import keeps any element the schema parses, reads a list of checkbox items as a to-do list, and turns <details> into a toggle; galleries, video, and audio from an HTML file come back as unsupported blocks.

Word headings use Heading 1–6. Nested lists keep their numbering level. Tables, code, callouts (one shaded box), and images are included. PNG, JPEG, GIF, and BMP pictures are embedded as they are; in the browser, WebP, SVG, and other formats are redrawn as PNG, and a relative path is resolved against the page. Pictures keep their proportions. Gallery pictures are embedded, and video, audio, files, bookmarks, embeds, and page links become hyperlinks. Text colours, highlight colours, and table cell backgrounds carry over. Math is one Office Math run of the LaTeX source, not a drawn equation and not a picture: building the fraction tree or a PNG would pull KaTeX into the Word download. Columns are written one after another, because a column layout in Word is a property of the page. A tag Word's HTML has no block for becomes an unsupported block. The original JSON is not stored on that block.

PDF does not use a PDF library. pdfmake and jsPDF are hundreds of kilobytes even when loaded later, and the print dialog already paginates. The printed page is the exported HTML in a hidden frame, so the editor's menus are not on it. Headings stay with the following paragraph, and images, tables, code, and quotes do not split across a page.

When the Excalidraw addon is registered, drawings become embedded PNGs. Pass hooks.formats to add another download format, and hooks.onExport to observe the file. A Word export leaves content empty and sets bytes.

To change the filename, serialization or download, pass hooks:

<ExportMenu
  hooks={{
    getFilename: (title, format) => {
      const ext = format === "markdown" ? "md" : format === "docx" ? "docx" : "html";
      return `${title || "untitled"}.${ext}`;
    },
  }}
/>

To convert content without the menu, see Save and load content.

Light and dark mode

The whiteboard follows next-themes. Wrap your app in ThemeProvider with attribute="class" so Excalidraw and the rest of the page share one theme. next-themes is installed with excalidraw-block. excalidraw({ theme: "light" | "dark" | "system" }) forces a theme; "system" (the default) keeps following the app.

src/components/providers.tsx
"use client";

import { ThemeProvider } from "next-themes";

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
      {children}
    </ThemeProvider>
  );
}

In Next.js, also add suppressHydrationWarning to <html>.

Next: Ask AI.

On this page