Skip to content
Nana UI

Forms & Inputs

Editor

A rich text editor on a tree document model: transactions and grouped undo, Markdown shortcuts, real tables, resizable images, extensions and collaborative editing.

View .md Download

A rich text editor that keeps its document as a tree of typed nodes. Every edit is a transaction of steps, so undo is grouped and exact, input never leaves the document in a shape the schema forbids, and the same steps can be sent to other people editing the same document.

beta since v0.0.14
0 words · 0 chars · 1 min read

Install the package for a versioned dependency:

npm install @nana-tec/ui-components

Or copy the source in and own it:

npx @nana-tec/ui add editor --framework web-components
npx @nana-tec/ui add editor --framework svelte

Lands in src/lib/components/ui/editor/ as NanaEditor.svelte and NanaEditorToolbar.svelte, styled with Tailwind classes that resolve to the design tokens. Requires Tailwind v4.

Extensions and collaboration import from @nana-tec/ui-core, which both targets already depend on.

Import the autoloader once, in your app's entry point. Every <nana-*> tag then works anywhere, and each component downloads only the first time a page uses it:

import "@nana-tec/ui-components/autoloader";
import "@nana-tec/ui-components/theme";

The second line gives every component the Nana look and the design tokens behind it. Leave it out to style the components entirely yourself.

Import a component directly when it must be ready at once: on screen at first paint, or when you call its methods straight away. The two mix freely:

import "@nana-tec/ui-components/editor";

Copied in with npx @nana-tec/ui add editor? Import your project's own @/lib/nana-ui/autoloader.js once instead; the CLI keeps it up to date.

<nana-editor value="<p>Hello</p>" show-word-count></nana-editor>
<script type="module">
const editor = document.querySelector('nana-editor');
editor.addEventListener('nana-change', (event) => {
const { html, markdown, wordCount } = event.detail;
});
</script>

Setting value replaces the document. The element does not write value back as you type; read the content from nana-change or the methods below.

<script lang="ts">
import { NanaEditor } from '$lib/components/ui/editor';
let value = $state('<p>Hello</p>');
</script>
<NanaEditor bind:value label="Notes" showWordCount />

value is bindable and is written back on every change. Pass onValueChange to receive the HTML with the word count, character count and reading time as a second argument.

Shortcuts apply as you type them. Backspace straight after one puts the typed characters back.

TypeBecomes
# to ###### Heading 1 to 6
> Quote
- , * or + Bullet list
1. Numbered list starting at that number; continues a list above it
[ ] or [x] Checklist item, open or done
```Code block
---Divider, with a paragraph after it
**text** or __text__Bold
*text* or _text_Italic; an underscore inside a word is left alone
~~text~~Strikethrough
==text==Highlight
`text`Inline code

No shortcut fires inside a code block.

Type / on an empty line to pick a block: paragraph, heading 1–3, bullet, numbered or checklist, quote, code block, divider, image or table. Keep typing to filter the list; arrows move, Enter inserts and Escape closes it.

Mod is Cmd on macOS and Ctrl elsewhere.

KeysAction
Mod+B / I / UBold, italic, underline
Mod+Shift+SStrikethrough
Mod+EInline code
Mod+Shift+HHighlight
Mod+Shift+X / ,Superscript, subscript
Mod+Alt+0–6Paragraph, heading 1–6
Mod+Alt+CCode block
Mod+Shift+7 / 8 / 9Numbered, bullet, checklist
Mod+Shift+BQuote, also in the toolbar
Mod+Shift+L / E / R / JAlign left, centre, right, justify
Tab / Shift+TabNext or previous table cell, or nest and lift a list item
Shift+EnterLine break
Mod+EnterLeave a code block
Mod+Z, Mod+Shift+Z or Mod+YUndo, redo

The toolbar runs from history to line spacing: undo and redo, the text style, the font and its size, inline formatting, colour, links and inserts, lists and quote, alignment, and line spacing.

  • Text style switches the current block between paragraph, the heading levels on offer and code block.
  • Font and Font size apply to the selected text, so one word can differ from the rest of its line. With nothing selected, they apply to what you type next.
  • Line spacing applies to every paragraph the selection touches.

Each of these is a combobox: it shows the value where the caret is, and typing into it narrows the list. A font that came in with pasted or loaded content stays listed under its own name, so the field never shows a value the text does not have.

When the toolbar is too narrow, the groups that do not fit are hidden from the end and a More button shows them on another row. Arrow keys move along the visible controls; inside a combobox, Down opens the list, Up and Down choose a value and Enter applies it.

The toolbar and slash menu offer headings 1–3 by default. Choose your own, from 1 to 6; a page whose title is already its <h1> usually wants 2–4. The Markdown shortcuts and keys still reach every level.

document.querySelector('nana-editor').headings = [2, 3, 4];
<NanaEditor bind:value headings={[2, 3, 4]} />

The font list defaults to the system sans serif, serif and monospace. Pass your own as a label and a CSS font-family; an empty value means the editor’s own font.

document.querySelector('nana-editor').fonts = [
{ label: 'Body', value: '' },
{ label: 'Display', value: "'Fraunces', Georgia, serif" },
{ label: 'Code', value: "'JetBrains Mono', monospace" },
];
<NanaEditor
bind:value
fonts={[
{ label: 'Body', value: '' },
{ label: 'Display', value: "'Fraunces', Georgia, serif" },
]}
/>

Fonts are saved as <span style="font-family:…"> and sizes as <span style="font-size:…">; only names, quotes, commas and plain lengths are accepted, so a value cannot carry other CSS.

Insert a table from the toolbar or the slash menu. While the caret is in a table, a table menu appears above the document with every action that applies; the rest are disabled.

  • Insert a row above or below, or a column left or right.
  • Delete the row, the column or the whole table.
  • Merge a cell with the one to its right or below, and split a merged cell.
  • Toggle the first row between header and body cells.

Tab moves to the next cell and adds a row after the last one. Merged cells keep their spans as rows and columns come and go: a column added inside a merged cell widens it rather than cutting it in two.

Press Mod+K or the link button to link the selection, or type an address followed by a space: https://, http://, mailto: and www. addresses become links as you type, without the full stop or bracket after them. Backspace straight away takes the link back off. Set autolink to false to turn this off.

To mark every link the editor makes, give it a rel. Only nofollow, ugc, sponsored, external, noopener and noreferrer are kept, and a link that opens a new tab always gets noopener noreferrer.

<nana-editor link-rel="nofollow ugc"></nana-editor>
<NanaEditor bind:value linkRel="nofollow ugc" />

Insert an image by address, upload one, paste it or drop it in. Uploads accept PNG, JPEG, GIF, WebP and AVIF up to 10 MB. Click an image to select it, then:

  • drag the handle at its corner to resize it, which is one undo step and keeps its proportions;
  • use the align buttons to place it left, centre or right.

An image keeps its width and height, so a page that shows the saved HTML reserves the space before the image loads.

To choose images from your own media library, take over the image request. You get an insert function; call it with the address, the alt text and, if you know them, the size. It returns false when the address is not a safe image URL.

editor.addEventListener('nana-image-request', async (event) => {
event.preventDefault();
const picked = await openMediaLibrary();
if (picked) event.detail.insert(picked.url, picked.alt, picked);
});
<NanaEditor
bind:value
onImageRequest={async (insert) => {
const picked = await openMediaLibrary();
if (picked) insert(picked.url, picked.alt, { width: picked.width, height: picked.height });
}}
/>

Pasted, dropped and uploaded image files are embedded as data by default. To store them yourself, take over the upload the same way: you get the file and the same insert function, and call it once you have the stored image’s address.

editor.addEventListener('nana-image-upload', async (event) => {
event.preventDefault();
const stored = await uploadToStorage(event.detail.file);
event.detail.insert(stored.url, stored.alt, stored);
});
<NanaEditor
bind:value
onImageUpload={async (file, insert) => {
const stored = await uploadToStorage(file);
insert(stored.url, stored.alt, { width: stored.width, height: stored.height });
}}
/>

The toolbar and table menu are hidden and the content is marked aria-readonly.

min-height (or minHeight in Svelte) sets the editing area’s minimum height; the --nana-editor-min-height property does the same from CSS.

MethodReturns
getHTML()The document as HTML
getMarkdown()The document as Markdown
getJSON() / getContent()The document in the block format, as a string or an object
getTree()The document tree as JSON, the lossless form to store
load(content)Replaces the document with a block document or its JSON string
clear()Empties the document
presence()This editor’s caret and selection for collaborators, or null without presence
receivePresence(peers) / removePeer(id)Show or stop showing other people’s cursors
runCommand(id, value?)Runs a toolbar action or an extension command; false when it does not apply
focus()Focuses the editing area (Svelte; on the element, view.focus())

The web component also exposes state and view for programmatic edits. In Svelte, bind the component to call these:

<script lang="ts">
import { NanaEditor } from '$lib/components/ui/editor';
let editor: NanaEditor;
</script>
<NanaEditor bind:this={editor} />
<button onclick={() => editor.runCommand('heading', '2')}>Heading</button>

Content is safe whatever its source: links keep only http, https, mailto, tel and relative addresses, images only http, https, blob, relative addresses and image data URLs, and event attributes are never rendered.

Besides its own tree, the editor reads and writes rich text JSON: the common document shape with camel-case names such as bulletList, codeBlock and hardBreak. An app that already stores documents this way can open and save them as they are. Paragraphs, headings, lists, task lists, quotes, code blocks, rules, hard breaks, images, tables, and the bold, italic, underline, strike, code, link, highlight and text style marks all carry over. A node the editor does not know keeps its text; a link or image with an unsafe address is dropped.

Stored documents often name a font rather than spell out its family. Pass fonts to say which CSS family each name means, and the same names are written back.

const fonts = { serif: 'ui-serif, Georgia, serif', mono: 'ui-monospace, monospace' };
editor.loadRichText(article.body, { fonts });
save(editor.getRichText({ fonts }));
<script lang="ts">
let editor: NanaEditor;
const fonts = { serif: 'ui-serif, Georgia, serif', mono: 'ui-monospace, monospace' };
onMount(() => editor.loadRichText(article.body, { fonts }));
</script>
<NanaEditor bind:this={editor} onValueChange={() => save(editor.getRichText({ fonts }))} />

An extension adds to the editor without forking it. It can bring nodes and marks, the HTML that reads into them, key bindings, Markdown shortcuts, plugins and named commands. Its bindings and shortcuts run before the built-in ones, so it can also change a default.

import { toggleMark } from '@nana-tec/ui-core/editor/model/editing';
import { defineExtension } from '@nana-tec/ui-core/editor/model/extensions';
import { markInputRule } from '@nana-tec/ui-core/editor/model/inputrules';
export const keyboardKeys = defineExtension({
name: 'kbd',
marks: { kbd: { toDOM: () => ['kbd', 0] } },
parseRules: [{ tag: 'kbd', mark: 'kbd' }],
keymap: (schema) => ({ 'Mod-k': toggleMark(schema.marks.kbd!) }),
inputRules: (schema) => [markInputRule(/\[\[([^\]]+)\]\]$/, schema.marks.kbd!)],
commands: (schema) => ({ kbd: () => toggleMark(schema.marks.kbd!) }),
});
const editor = document.querySelector('nana-editor');
editor.extensions = [keyboardKeys];
editor.runCommand('kbd');

Changing extensions keeps the document.

<NanaEditor bind:this={editor} bind:value extensions={[keyboardKeys]} />

Each part is optional:

FieldWhat it adds
nodes, marksSchema entries, appended after the built-in ones; a built-in name is replaced
parseRulesHow pasted HTML and HTML values read into those nodes and marks
keymap(schema)Key bindings, named like Mod-Shift-k
inputRules(schema)Markdown-style shortcuts
plugins(schema)Plugins with their own state, props or appended transactions
commands(schema)Commands by id, for runCommand and toolbar ids
nodeViewsHow a node is drawn in the editor, when its HTML output is not enough

A node view draws a node inside the editor differently from the HTML it saves as, such as a card with controls or a live embed. Define the extension with defineViewExtension from @nana-tec/ui-dom, which adds nodeViews to the fields above:

import { defineViewExtension } from '@nana-tec/ui-dom/editor-extension';
export const cards = defineViewExtension({
name: 'card',
nodes: {
card: {
group: 'block',
atom: true,
attrs: { title: { default: '' } },
toDOM: (node) => ['section', { 'data-card': String(node.attrs.title) }],
},
},
parseRules: [
{
tag: 'section[data-card]',
node: 'card',
attrs: (element) => ({ title: element.getAttribute?.('data-card') ?? '' }),
},
],
nodeViews: {
card: (node) => {
const dom = document.createElement('article');
dom.textContent = String(node.attrs.title);
return { dom };
},
},
});

A node view returns its dom, and a contentDOM when the node has editable content. It can also return update(node) to take a changed node without being redrawn, selectNode and deselectNode, stopEvent(event) to keep its own controls’ events from the editor, and destroy.

Once the schema is extended, HTML values, getHTML() and the change event go through the document tree, so extension nodes and marks survive. Give URL attributes a validate in the node’s attrs; rendering refuses script addresses in href, src and similar attributes as a backstop.

Several people can edit the same document through a server that orders their changes. Add the collab extension, send each editor’s unconfirmed steps to the server, and pass back what the server confirms. Work an editor has not had confirmed yet is rebased over steps that arrived first, and other people’s changes never enter the local undo history.

import { collabExtension } from '@nana-tec/ui-core/editor/model/collab';
editor.extensions = [collabExtension({ version, clientID: user.id })];
function send() {
const sendable = editor.sendableSteps();
if (sendable) socket.send(JSON.stringify(sendable));
}
editor.addEventListener('nana-change', send);
socket.addEventListener('message', (event) => {
const { steps, clientIDs } = JSON.parse(event.data);
editor.receiveSteps(steps, clientIDs);
send();
});

In Svelte, call the same sendableSteps() and receiveSteps() on the bound component, and send from onValueChange.

The server holds the steps in order. It accepts a batch only when the batch’s version equals the number of steps it already has, then sends the new steps, with the clientID of whoever sent each one, to every editor, including the sender, which recognises its own steps as confirmed. Rejected editors receive the steps they missed first and send again. version is the number of steps already applied to the document an editor starts from.

Add the presence extension beside collab to show where everyone else is. Each editor reports its own caret and selection, and shows the ones it is sent, with a name and a colour.

import { presenceExtension } from '@nana-tec/ui-core/editor/model/presence';
editor.extensions = [collabExtension({ version, clientID: user.id }), presenceExtension()];
editor.addEventListener('nana-presence-change', (event) => {
socket.send(JSON.stringify({ presence: { ...event.detail, name: user.name, color: user.color } }));
});
socket.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.presence) editor.receivePresence([message.presence]);
if (message.left) editor.removePeer(message.left);
});

In Svelte, pass onPresenceChange and call receivePresence() and removePeer() on the bound component.

A presence carries the version it was taken at, so positions always refer to a document both sides agree on: one from a version the editor is not at is ignored until the next one arrives, and work not yet confirmed is accounted for on both ends. Peers move with every edit after that. Names are cut to 64 characters and a colour that is not a plain CSS colour is dropped for the default.

The cursors sit in a layer the editor draws above the text and screen readers skip. Style them through the peer, peer-caret, peer-name and peer-selection parts, and --nana-editor-peer-color.

Properties

PropertyAttributeTypeDefaultDescription
autolink—booleantrueTurns an address into a link once you type a space after it
extensions—readonly ViewExtension[][]Editor extensions to load, such as collaboration or presence.
fonts—readonly EditorOption[]EDITOR_FONT_FAMILIESThe fonts offered in the toolbar, as a label and a CSS font-family; the first is usually the default with an empty value
headings—readonly number[]EDITOR_HEADING_LEVELSThe heading levels the toolbar and slash menu offer, from 1 to 6
linkRellink-relstring''The rel given to every link made in the editor, such as nofollow or ugc
minHeightmin-heightstring''Minimum height of the editing area, as a CSS length.
placeholderplaceholderstring'Start writing…'Shown while the document is empty.
readonlyreadonlybooleanfalseShows the document without letting it change.
showWordCountshow-word-countbooleanfalseShows a live word count under the editor.
valuevaluestring''The document as HTML.

Methods

MethodDescription
clear(): voidReplace the document with an empty one
getContent(): EditorDocumentThe document as an object
getHTML(): stringThe document serialised as HTML
getJSON(): stringThe document serialised as JSON
getMarkdown(): stringThe document serialised as Markdown
getRichText(options: RichTextOptions): RichTextDocumentThe document as rich text JSON, with camel-case node and mark names
getTree(): unknownThe document as its full-fidelity tree JSON
load(content: EditorDocument | string): voidReplace the document with a document object or its JSON string; an unreadable string loads an empty document
loadRichText(json: unknown, options: RichTextOptions): voidReplace the document with rich text JSON; fonts maps a stored font name to a CSS family
presence(): Presence | nullWhere this editor's caret and selection are, for the other people editing; null without the collab and presence extensions
receivePresence(peers: readonly PeerPresence[]): voidShow other people's carets and selections; positions from a version this editor is not at are ignored
receiveSteps(steps: readonly unknown[], clientIDs: readonly ClientID[]): voidApply steps confirmed by the collaboration server, rebasing any unconfirmed local work over them
removePeer(clientID: ClientID): voidStop showing a person who has left
runCommand(id: string, value?: string): booleanRun a toolbar action or an extension command by its id; false when it does not apply
sendableSteps(): { version: number; steps: StepJSON[]; clientID: ClientID } | nullSteps not yet confirmed by the collaboration server, as JSON; null without the collab extension or when there are none

Events

EventDescription
nana-changeDocument changed, { json, html, markdown, wordCount, charCount, readTime }
nana-image-uploadAn image file was pasted, dropped or chosen, { file, insert(src, alt?, size?) }; cancel it to store the file yourself and call insert with its address
nana-image-requestThe image button was pressed, { insert(src, alt?, size?) }; cancel it to show your own picker and call insert with the chosen image
nana-presence-changeThe local caret or selection moved, { clientID, version, anchor, head }; only with the collab and presence extensions

CSS parts

PartDescription
::part(content)The contenteditable editing surface; carries drag-over
::part(scroll)The scroll
::part(popover)The popover
::part(secondary)The secondary
::part(table-picker)The table picker
::part(grid)The grid
::part(label)The label
::part(slash-menu)The slash menu
::part(status-bar)The status bar
::part(output-tabs)The output tabs
::part(cell)The cell; carries selected
::part(slash-item)The slash item; carries active
::part(output-tab)The output tab; carries active
::part(toolbar)The toolbar
::part(link-input)The link address field; carries invalid when the address is refused
::part(link-apply)The button that applies a link
::part(image-input)The image address field; carries invalid when the address is refused
::part(image-apply)The button that inserts an image
::part(slash-label)The name of a slash command
::part(counts)The word and character counts
::part(table-menu)The row of table actions shown while the caret is in a table
::part(table-action)A table action button; carries disabled when it does not apply
::part(output)The exported content
::part(peers)The layer that holds other people's cursors
::part(peer)One person's cursor and selection
::part(peer-caret)Where another person's caret is
::part(peer-name)The name shown above another person's caret
::part(peer-selection)Part of the text another person has selected

CSS custom properties

PropertyDescription
--nana-editor-min-heightMinimum height of the editing area
--nana-editor-menu-zStacking order of the link, image, table and slash menus; defaults to --nana-z-index-popover
--nana-editor-peer-colorColour of another person's cursor; set from the colour their presence carries

NanaEditor

PropTypeDefault
valuebind:string''
placeholderstring'Start writing…'
readonlybooleanfalse
labelstring
minHeightstring
showWordCountbooleanfalse
showOutputbooleanfalse
extensionsreadonly ViewExtension[][]
fontsreadonly EditorOption[]EDITOR_FONT_FAMILIES
headingsreadonly number[]EDITOR_HEADING_LEVELS
autolinkbooleantrue
linkRelstring''
onValueChange(value: string, detail: EditorChangeDetail) => void
onPresenceChange(presence: Presence) => void
onImageRequest(insert: NanaImageInsert) => void
onImageUpload(file: File, insert: NanaImageInsert) => void

Also accepts Omit<HTMLAttributes<HTMLDivElement>, 'class'>.

NanaEditorToolbar

PropTypeDefault
attributesrequiredAttributes
marksrequiredReadonlySet<MarkType>
canUndorequiredboolean
canRedorequiredboolean
disabledbooleanfalse
currentReadonly<Partial<Record<EditorSelect['id'], string>>>{}
fontsreadonly EditorOption[]EDITOR_FONT_FAMILIES
headingsreadonly number[]EDITOR_HEADING_LEVELS
oncommandrequired(id: string, value?: string) => void