Skip to content
Edytor
Esc
↑↓navigate↵open⌘Jpreview
On this page

Rich text

The rich text plugin's block kinds, marks, Notion hotkeys, placeholders and formatting helpers, including link and color sanitization.

createRichTextPlugin() defines the everyday document: paragraphs, headings, lists, to-dos, toggles, toggle headings, callouts, quotes, dividers, and ten marks, with Notion’s shortcuts. The core defines no block kinds, so <Edytor> includes it by default, after your plugins:

<script lang="ts">
	import { Edytor } from 'edytor';
</script>

<!-- Rich text, with no plugins listed. -->
<Edytor />

createRichTextPlugin({ callout }) builds it with other callout icons (see Toggles and callouts), and createRichTextPlugin({ checkbox, calloutIcon, emptyBody }) with your markup for the controls inside its blocks (see Your markup for its controls). Its words (the presets, the toolbar’s mark buttons, the to-do checkbox, the placeholders) are the view’s richText labels, and its slash keywords the view’s keywords (see Localization). A listed instance replaces the default. List it yourself to translate it, to place it elsewhere in the order, or with defaultPlugins={false} (see Default plugins). To change one of its kinds, define a kind with the same name in any of your plugins, since they come before it, or override only its snippet (see Blocks).

Try it

Select text for the toolbar, type / for the slash menu, click a to-do’s checkbox, open the toggles and click the callout’s icon. The editor is local to this page: a reload resets it.

Customize

The to-do checkbox, the callout icon and the empty-toggle hint are your snippets (checkbox, calloutIcon, emptyBody), so they can look like anything. Here, a round check that fills in green, the icon on a tinted tile, and a dashed hint.

<script lang="ts">
	import {
		Edytor,
		createRichTextPlugin,
		type CalloutIconPayload,
		type EmptyBodyPayload,
		type JSONDoc,
		type Plugin,
		type TodoCheckboxPayload
	} from 'edytor';

	// The page's document and the rest of your editor's plugins.
	let { value, plugins = [] }: { value?: JSONDoc; plugins?: Plugin[] } = $props();

	// Rich text with its three controls drawn by the snippets below.
	const richText = createRichTextPlugin({ checkbox, calloutIcon, emptyBody });
</script>

<!-- A round check that fills in when done. -->
{#snippet checkbox(box: TodoCheckboxPayload)}
	<button type="button" class="check" data-done={box.checked} {@attach box.control}>
		{box.checked ? '✓' : ''}
	</button>
{/snippet}

<!-- The icon on a tinted tile. -->
{#snippet calloutIcon(icon: CalloutIconPayload)}
	{#if icon.editable}
		<button type="button" class="icon" {@attach icon.control}>{icon.icon || '+'}</button>
	{:else}
		<span class="icon" {@attach icon.control}>{icon.icon}</span>
	{/if}
{/snippet}

<!-- A dashed hint that says what a click does. -->
{#snippet emptyBody(hint: EmptyBodyPayload)}
	<p class="hint" {@attach hint.control}>+ Add a {hint.kind} body</p>
{/snippet}

<Edytor {value} plugins={[richText, ...plugins]} aria-label="Rich text demo" />

<style>
	.check {
		width: 18px;
		height: 18px;
		padding: 0;
		border: 2px solid #a8a5a0;
		border-radius: 50%;
		background: #fff;
		color: #fff;
		font: 700 11px/14px system-ui, sans-serif;
		cursor: pointer;
	}
	.check[data-done='true'] {
		border-color: #1a7f4b;
		background: #1a7f4b;
	}
	.icon.icon {
		display: inline-grid;
		place-items: center;
		width: 28px;
		height: 28px;
		padding: 0;
		border: 0;
		border-radius: 8px;
		background: #fff3c4;
		font-size: 16px;
		line-height: 1;
	}
	button.icon {
		cursor: pointer;
	}
	.hint {
		margin: 2px 0;
		padding: 2px 8px;
		border: 1px dashed #c9c6c0;
		border-radius: 6px;
		color: #8a8782;
		font-size: 13px;
		cursor: pointer;
	}
	.hint:hover {
		border-color: #8a8782;
		color: #45433f;
	}
</style>

Block kinds

Kind Element Data Presets (markdown)
paragraph div with a p inside none Text
heading div with an h1 to h3 { level: 'h1' } Heading 1 (# ), Heading 2 (## ), Heading 3 (### )
bulleted-list-item li none Bulleted list (- , * , + )
numbered-list-item li none Numbered list (1. , a. , i. )
todo-item div with a checkbox { checked: boolean } To-do list ([ ] , [] )
toggle details, content in summary none Toggle list (> )
toggle-heading details, an h1 to h3 in summary { level: 'h1' } Toggle heading 1, 2, 3 (> in a heading; # , ## , ### in a toggle)
callout div: icon, title, content { icon: string } Callout (icon 💡)
quote div with a blockquote none Quote (" )
divider hr, void, no content none Divider (---)

The kinds are listed in catalogue order, which the menus follow. Presets feed the slash menu (all under Basic blocks), markdown shortcuts and block menus. Their command ids are block.paragraph, block.heading1 to block.heading3, block.bulleted-list-item, block.numbered-list-item, block.todo-item, block.toggle, block.toggle-heading1 to block.toggle-heading3, block.callout, block.quote and block.divider.

The plugin also defines kinds without presets, for content that arrives from stored documents, the API or an Edytor fragment (an HTML paste gives flat bulleted and numbered items):

  • ordered-list and unordered-list: ol and ul containers that render only their children. A new child takes the list-item kind, and so does a pasted line of the list’s own flat kind (a numbered item in an ordered-list, a bulleted one in an unordered-list, their itemKind); any other kind keeps its kind.
  • list-item: an li.

Behavior worth knowing:

  • Bulleted and numbered items, to-dos and toggles are continuing kinds: Enter opens another of the same kind (an unchecked to-do), and in an empty one ends the list. Toggles, callouts and quotes are containers: Enter at the end of one with children, or of an open toggle, opens a first child, and in the middle of the header moves the rest of the text into that first child. Backspace at the start of any kind but a paragraph turns it into a paragraph first. Enter and Backspace by role has the full rules.
  • Headings have Notion’s three levels. A heading’s tag follows data.level, h1 to h3, and so does its copied HTML. Without a level it is h1; any other level (a stored h5, say) renders and copies as h3, as pasting h4 to h6 gives a level h3 heading.
  • The h1–h3 of a heading and the blockquote of a quote wrap the block’s own text only. The block element is a div, and nested blocks render after the tag, in a sibling div: the page’s heading styles do not reach them, and a screen reader does not read them as part of the heading. Style the text through [data-edytor-type='heading'] > h2, the block through [data-edytor-type='heading']. The tag is the kinds’ contentElement, so a plugin that restyles the heading or the quote with its own snippet keeps it around content() (Restyling a kind).
  • A toggle is a native <details>. The browser owns its open attribute, so opening and closing it is not an edit and is never reverted. Arrow keys skip the body of a closed toggle. A toggle you create (the slash menu, > , Turn into a block without children) opens, so you can write its content right away (see Toggles and callouts).
  • A toggle-heading is Notion’s toggle heading: a heading’s text as a toggle’s header, data.level as on a heading. It is a <details> whose summary holds the h1–h3, and behaves as a toggle: a container, whose closed body is hidden and skipped; Enter at the end of an open one opens a first child, of a closed one a paragraph after it (it does not continue itself, as a heading does not). Turn into moves between a heading, a toggle heading and a toggle keeping the text, the children and the level. As in Notion, > typed at a heading’s start makes it a toggle heading of its level, and # , ## or ### at a toggle’s (or a toggle heading’s) start a toggle heading of that level, so > # on a new line is a toggle heading 1 (markdown shortcuts). Its HTML is <details><summary><h2>…</h2></summary>…</details>, which pastes back as a toggle heading. The table of contents lists it with the headings.
  • Every block that shows its own text takes a colour and a background from the block menu (data.color, data.background).
  • The todo-item checkbox (data-edytor-todo-checkbox) shows data.checked. Clicking it, or Mod + Enter in the to-do (or over selected blocks, each shown to-do, while the toggles among them open or close), flips checked as one undo step. It does not change in a readonly editor.
  • A callout is an icon, a title and a content: see Toggles and callouts.
  • The paragraph element carries no classes of its own: style it through [data-edytor-type='paragraph'].
  • Pasted ol > li becomes a numbered item and other li a bulleted item.

Toggles and callouts

A toggle’s and a callout’s own text is a header; their children are a body that holds any blocks, nested any way. In an open toggle, and in a callout, an empty body shows a hint (“Empty toggle. Click or drop blocks inside.”, “Empty callout. Click or drop blocks inside.”). Clicking it starts the body: an empty paragraph as its first child, the caret in it, one undo step. A block dragged by its handle onto the hint goes inside. From the keyboard, Enter at the end of the header, or ArrowDown on its last line, goes into the body. The hint is not content: it is not editable, not copied, not read by assistive technology, and a readonly editor does not show it ([data-edytor-empty-body] styles it; the emptyBody option replaces its markup, see Your markup for its controls).

A callout is Notion’s: an icon, a title and a content.

  • Its title is its own text, semibold ([data-edytor-callout-title]), with the placeholder “Callout title” while empty (placeholders). Enter at the end of the title, or in the middle of it, goes into the content, whether or not it has blocks yet.
  • Its content is its children, any blocks. Copied, a callout is <div data-edytor-callout="💡"><p>Title</p>…</div>, which pastes back as the callout, its icon kept; as plain text, its title then its content.
  • Its icon is data.icon: the editor’s default when the callout has none (💡, or the callout.icon option), no icon when it is ''. A new callout takes the default. Set it from code as any data, block.data.icon = '🔥'.
  • With the callout icons plugin listed (createCalloutIconsPlugin({ picker, icons })), clicking the icon ([data-edytor-callout-icon], a button named “Change icon”, “Add icon” when the callout has none) opens the view’s icon picker under it: your picker snippet (without one, nothing shows; without the plugin, the icon is no button). Picking an icon, or Remove icon, is one undo step; Escape, Tab or a click elsewhere closes it unchanged. The arrows move through the icons (up and down by a row), Home and End go to the ends, Enter or Space picks, and the editor gets the keys back with its caret. The block menu of a callout has a Change icon row, the keyboard’s way to the picker. A readonly editor shows the icon only.
<script lang="ts">
	import { CALLOUT_ICONS, Edytor, createCalloutIconsPlugin, createRichTextPlugin } from 'edytor';

	// New callouts take 📌; the picker offers the default icons and a unicorn.
	const richText = createRichTextPlugin({ callout: { icon: '📌' } });
	const icons = createCalloutIconsPlugin({ icons: [...CALLOUT_ICONS, '🦄'] });
</script>

<Edytor plugins={[icons, richText]} />

picker is the picker’s markup. It receives the picker (CalloutIconPicker): the callout it is open on (block), the choices (icons), the icon the callout shows (current), set(icon), remove() and close(), and readonly; the words are your markup’s. Put {@attach picker.keys} and {@attach picker.popup} on its element, which then takes the focus and the keys and is announced to assistive technology, attach picker.option(i) to each row, as every menu’s rows (its id, role, aria-selected, aria-checked on the current icon; the highlight is yours, from picker.index === i), and run picker.pick(i) on its click; i === picker.icons.length is Remove icon. Lay the icons out picker.columns to a row (the arrows move up and down by that many). The editor places it under the icon.

<script lang="ts">
	import { Edytor, createCalloutIconsPlugin, type CalloutIconPicker } from 'edytor';

	const icons = createCalloutIconsPlugin({ picker: iconPicker });
</script>

{#snippet iconPicker(picker: CalloutIconPicker)}
	<div class="icons" aria-label="Callout icons" {@attach picker.keys} {@attach picker.popup}>
		{#each picker.icons as icon, index (index)}
			<button type="button" {@attach picker.option(index)} onclick={() => picker.pick(index)}>{icon}</button>
		{/each}
		<button
			type="button"
			{@attach picker.option(picker.icons.length)}
			onclick={() => picker.pick(picker.icons.length)}>Remove icon</button
		>
	</div>
{/snippet}

<Edytor plugins={[icons]} />

Your markup for its controls

Three controls sit inside the rich text blocks: a to-do’s checkbox, a callout’s icon and an empty body’s hint. The plugin draws them (a native checkbox, a button showing the icon, a div with the hint), and each option replaces one with your snippet, used wherever the view renders the kind, a suggestion’s preview included:

Option Snippet payload What it carries
checkbox TodoCheckboxPayload block (undefined in a suggestion’s preview), checked, label (the view’s richText.checkbox), toggle(), control
calloutIcon CalloutIconPayload block, icon ('': none), editable (the icon opens the view’s picker), expanded (the picker is open on it), label (“Change icon”, “Add icon”), toggle(), control
emptyBody EmptyBodyPayload block, kind ('toggle' or 'callout'), label (the view’s richText.emptyBody), open(), control

Give the control’s element {@attach payload.control}, as a menu’s row takes {@attach menu.option(index)}: it carries what the editor reads of it and what keeps it usable, and you render the rest from the payload’s values. The checkbox’s are its marker (data-edytor-todo-checkbox), contenteditable="false", its aria-label, a press that keeps the caret and a click that runs toggle(); on a button rather than an input type="checkbox" (give that one checked={box.checked}), it adds role="checkbox" and aria-checked. The icon’s are data-edytor-callout-icon (the picker opens under it), data-empty without an icon, and where it is editable, its name, aria-haspopup, aria-expanded, aria-controls, the press and the click that opens the picker; else aria-hidden. The hint’s are data-edytor-empty-body (a block dragged onto it drops inside), aria-hidden and the click that starts the body. Use a button or an input for a control the keyboard reaches: the editor leaves a form control’s keys to it.

The actions are the default markup’s: toggle() checks the to-do as one undo step (refused in a readonly view), the icon’s toggle() opens the callout icon picker, open() starts the body. The editor still decides when each shows: no hint in a readonly view or a closed toggle, no icon when the callout has none and none can be picked.

<script lang="ts">
	import {
		Edytor,
		createCalloutIconsPlugin,
		createRichTextPlugin,
		type CalloutIconPayload,
		type EmptyBodyPayload,
		type TodoCheckboxPayload
	} from 'edytor';

	const richText = createRichTextPlugin({ checkbox, calloutIcon, emptyBody });
	const icons = createCalloutIconsPlugin();
</script>

{#snippet checkbox(box: TodoCheckboxPayload)}
	<button type="button" class="check" {@attach box.control}>{box.checked ? '✓' : ''}</button>
{/snippet}

{#snippet calloutIcon(icon: CalloutIconPayload)}
	{#if icon.editable}
		<button type="button" class="icon" {@attach icon.control}>{icon.icon || '+'}</button>
	{:else}
		<span class="icon" {@attach icon.control}>{icon.icon}</span>
	{/if}
{/snippet}

{#snippet emptyBody(hint: EmptyBodyPayload)}
	<p class="hint" {@attach hint.control}>{hint.label}</p>
{/snippet}

<Edytor plugins={[icons, richText]} />

The first rich text plugin listed in a view gives its controls, as it gives the kinds.

Marks

Mark Element Value Toolbar button
bold strong true B
italic em true I
underline u true U
strike s true S
code code true </>
link a with href and target { href, target? } Link panel
superscript sup true
subscript sub true
color span with color a CSS color A ⌄ (text)
highlight span with background-color a CSS color A ⌄ (background)

Marks nest in this order, bold innermost. Typing at the end of a link extends it only when the caret is inside the link; typing at the edge of any other mark extends it.

Values are sanitized when rendered and copied. A link href keeps only http:, https:, mailto:, tel: and scheme-less URLs; any other scheme, such as javascript:, drops the href and leaves the text. A color that could inject CSS (it contains ;, braces, quotes, url( and similar) drops the style.

Pasted HTML maps b, i, u, strike and del to their marks, reads Google Docs’ styled spans for bold, italic, underline, strike, color and highlight, and turns mark into a yellow highlight.

Links work as in Notion. Everything below applies where the toolbar offers a link: a text selection or caret outside code blocks and void blocks. A URL here means one URL and nothing else: http: or https: with a host, or mailto:. Words, several URLs, a bare domain such as svelte.dev and a scriptable URL are not URLs.

Over selected text, pasting a URL (spaces around it ignored) sets the link mark with that URL on the selected text, across several blocks too, instead of replacing it. The text stays selected, and one undo gives the plain text back. A copied page link pastes the same way, since its plain text is the URL.

At a caret, pasting a URL inserts it as a link, the caret after it (link.autolink.pasted). The paste and the link are two undo steps: the first undo gives the plain URL back, the second removes it. A caret inside a link or inline code pastes the URL as plain text.

Anything else pastes as usual, and so does Shift+paste.

A URL typed before a space becomes a link when you type the space (link.autolink.typed): see https://svelte.dev links https://svelte.dev. The URL is the word before the space; trailing ., ,, ;, :, ! and ? stay out of the link, so https://svelte.dev. links https://svelte.dev. The space and what you type after it are plain text. The link is an undo step of its own after your typing: one undo gives the plain text back, the space kept. A word that already carries a link or inline code is left as it is, and nothing is linked in a code block.

Links are not followed by a plain click while you edit: a click places the caret. Mod+click opens the link in a new tab (link.mod-click; Mod is read as the keymap reads it: Meta, or Ctrl off a Mac). The tab opens with noopener and noreferrer, and an unsafe href opens nothing. The toolbar adds a card with Open, Edit and Remove over a hovered link, and Mod+K to link a selection.

Hotkeys

Keys Action
Mod + B Toggle bold
Mod + I Toggle italic
Mod + U Toggle underline
Mod + E Toggle inline code
Mod + Shift + S, Mod + Shift + X Toggle strikethrough
Mod + Shift + H Toggle red text color
Mod + Enter Check or uncheck the to-do (in a to-do, or the selected to-dos)

With a collapsed caret, a mark hotkey sets the mark for the next characters you type instead.

Notion’s “turn into” chords convert the block holding the caret, or, as in Notion, every block of a block selection or of a text range across blocks, as one undo step that keeps the selection (Code converts only the first):

Keys Turns into
Mod + Alt + 0 Text
Mod + Alt + 1 Heading 1
Mod + Alt + 2 Heading 2
Mod + Alt + 3 Heading 3
Mod + Alt + 4 To-do list
Mod + Alt + 5 Bulleted list
Mod + Alt + 6 Numbered list
Mod + Alt + 7 Toggle list
Mod + Alt + 8 Code (with the code plugin); a block with text or children keeps them, and the code block is inserted after it

Each runs the kind’s command (block.paragraph, block.heading1, …, block.code) and is claimed only when that command is registered.

The plugin also handles the formatting input types browsers send from their own menus and from iOS: bold, italic, underline, strikethrough, superscript, subscript, remove formatting, text and background color, insert link, ordered and unordered list (converts the block), and horizontal rule (inserts a divider at the caret, splitting the block when the caret is inside it; a block that holds nothing becomes the divider; in a list’s item, the divider goes out of the list as Turn into puts one: in the place of an item that holds nothing, else after the item, whose text stays whole; an inline block such as a mention counts as content, so a block holding only one keeps it; in an emptied document it creates the divider and a paragraph after it). insertDividerAtSelection() below does the same.

Formatting from code

richTextOperations(edytor) returns the helpers the hotkeys and the toolbar use. They act on the current selection:

import { richTextOperations } from 'edytor';

const format = richTextOperations(edytor);

format.setMarkAtRange('bold'); // toggle, or stage at a caret
format.setMarkValueAtRange('highlight', '#fff3a3'); // set, never toggle
format.removeMarkAtRange('highlight'); // remove one mark
format.setLinkAtRange({ href: 'https://svelte.dev', target: '_blank' });
format.removeLinkAtRange();
const text = block.firstText!; // a Text handle
format.linkText(text, 0, 4, 'https://svelte.dev'); // a range of one text, its own undo step
format.unlinkText(text, 0, 4); // one undo step; the selection stays
format.removeAllMarksAtRange();
format.insertDividerAtSelection();

setLinkAtRange and linkText ignore an unsafe href. setMarkValueAtRange ignores an unsafe color. removeMarkAtRange does nothing at a collapsed caret. linkText and unlinkText take a Text and offsets within it, and leave the selection alone; autolink and the link card use them.

Placeholders

richTextPlaceholder gives the kinds Notion’s placeholders (“Heading 1”, “Toggle heading 1”, “List”, “To-do”, “Type ‘/’ for commands” in a focused paragraph…). List it as a plugin’s placeholder: plugins={[() => ({ placeholder: richTextPlaceholder })]}. See Placeholder.

Placement. The package places no popup: your markup places itself by the callout icon picker’s picker.anchor (the callout’s icon), a virtual element read live. With Floating UI, computePosition(anchor, element, { strategy: 'fixed', middleware: [offset(8), flip(), shift({ padding: 8 })] }) under autoUpdate; with bits-ui, customAnchor={anchor}. See Menus and handles.

Was this page helpful?