Blocks
Define block kinds with a BlockDefinition, render them with snippets, mark chrome as void, and declare presets for menus and markdown shortcuts.
A block kind is a named definition in a plugin’s blocks map. It decides the element the core renders, the markup inside it, how the kind behaves structurally, how it is created from menus, and how it is copied and pasted. For what blocks, content and children are, see Blocks.
A block kind
<script module lang="ts">
import type { Plugin } from 'edytor';
import type { BlockSnippetPayload } from 'edytor';
export const calloutPlugin: Plugin = () => ({
blocks: {
tip: {
snippet: tip,
element: 'aside',
presets: [{ label: 'Tip', icon: '💡', keywords: ['hint'] }]
}
}
});
</script>
{#snippet tip({ content, children }: BlockSnippetPayload)}
<div class="tip-text">{@render content()}</div>
{#if children}
<div class="tip-children">{@render children()}</div>
{/if}
{/snippet}
The core renders <aside data-edytor-block data-edytor-type="tip" …> and the snippet renders inside it. A bare snippet is shorthand for a definition with only snippet: blocks: { tip }.
Options
snippet?Snippet<[BlockSnippetPayload]>
The markup inside the block element. Without one, the element renders empty. Never rendered for elements that take no content (hr, img, input, br).
Snippet<[BlockSnippetPayload]>element?string | { tag, attributes? } | ((data, id) => …)
The element the core renders: a tag, a tag with attributes, or a function of the block's data and id. The id keys view state the kind keeps per block (the columns plugin previews a column's width while a resize drags); reactive state the function reads re-renders the element; HTML import, which reads a kind's tag for data alone, passes no id. It wraps the block's children too: a kind that can hold children and wants a heading or text-level tag (h1, p, span) declares it as contentElement instead.
string | { tag, attributes? } | ((data, id) => …)'div'contentElement?string | { tag, attributes? } | ((data, id) => …)
The element the core wraps around the block's own text, where the snippet renders content(): a tag, a tag with attributes, or a function of the block's data and id. Children stay outside it. The rich text heading's h1–h3 and the quote's blockquote are declared this way, so a plugin that restyles them with its own snippet keeps them. HTML import finds the kind by this tag when it has no html form and its element is a div.
string | { tag, attributes? } | ((data, id) => …)viewState?string[]
Attributes of the element the browser or the user own, such as 'open' on a details element. The editor never reverts them.
string[]rendersContent?boolean
false for a container that renders only its children (a list, a code block, a column). Its content slot gets no caret, no block merges into it, and it never merges as a whole. See [Kinds that render no content](#kinds-that-render-no-content) for what it holds and how keys act around it. A development warning fires if the snippet disagrees.
booleantruedefaultChild?string
The kind a new child of this block takes: Enter inside a child, a split, an island merged out into it. On an island it does not flatten the children; only `lines` does that.
stringitemKind?string
On a list container: the flat kind its items show as (`numbered-list-item` for `ordered-list`). The menus and the toolbar name an item by it, turning an item into it keeps the item in its list, and a pasted line of it landing in the list (an `<ol>` pasted into an ordered list) becomes an item.
stringcontinues?boolean
A list-like kind: Enter at the start or end of a non-empty block opens another block of this kind, and Enter in an empty one ends the run. See Continuing kinds below.
booleanfalsecontainer?boolean
A header over its children (a toggle, callout or quote): Enter at the end of one with children, or of an open `<details>` header, opens a first child. See Containers below.
booleanfalsebody?boolean
A container whose body shows even while it is empty (a callout): Enter at the end of its header opens its first child, as an open toggle's does, and a paste there leads that body. Needs `container`.
booleanfalsevoid?boolean
Not editable as a whole and never merged. Takes no children. Text it renders (a caption) stays editable.
booleanfalseisland?boolean
Editable, but structurally sealed: nothing merges across its edge, and blocks cannot be moved in or out. Its children keep their kinds and nesting (a table of rows of cells, a callout).
booleanfalselines?boolean
An island of lines, like the code block. Every direct child shows as `defaultChild` and holds no children, even after an undo or a peer's edit. Needs `island` and `defaultChild`; a development warning fires if either is missing. Give the lines a kind of their own: outside such an island a block of that kind shows as its parent's default child. Its first line never merges into it when `rendersContent` is false.
booleanfalselayout?boolean
A layout, like the columns plugin's `columns`: its `defaultChild` is its item kind (a column: a container with `rendersContent: false` that holds any block), shown side by side. Needs `rendersContent: false` and `defaultChild`. It holds only its items, no layout goes inside an item, and the document shows it by its role on every replica: a block stored directly in it shows right after it, an item showing no block does not show, a layout showing one item or none shows as that item's blocks, and an item outside a layout shows as its blocks. Edits write the same (an emptied item goes, a one-item layout dissolves), merges cross items in reading order, and the beside drop bands, `placeBeside` and `wrapInLayout` use the layout kind. See [Layouts](/docs/concepts/blocks#layouts) and [Columns](/docs/plugins/columns).
booleanfalsetable?boolean
A table, like the table plugin's `table`: its `defaultChild` is its row kind (a container with `rendersContent: false`), whose own `defaultChild` is its cell kind (an island that renders its text). Needs `rendersContent: false` and `defaultChild`. The table lists its columns in `data.columns` (`{ id, width? }`) and each cell names its column in `data.column`; the document shows every row's cells in that order, a cell of no listed column or a second cell for one, a row showing no cell and a table showing no row do not show, and a cell never moves, merges or splits. See [Tables](/docs/concepts/blocks#tables) and [Table](/docs/plugins/table).
booleanfalseatomic?(string | string[])[]
Data paths written as one value: a top-level key (`'link'`), or an array of keys for a nested one (`['media', 'source']`). Setting `block.data.link`, or a key inside it, writes the whole `link` as one property, so two people setting it at once end with one of their two values, never a mix of both (properties elsewhere merge key by key). Every view of a document, a headless document and the room must declare the same paths: pass them to `semanticsOf` too. See [Properties](/docs/concepts/properties#how-concurrent-edits-merge).
(string | string[])[][]menu?(block: Block) => KindMenuAction[]
Rows the block menu adds for a block of this kind opened alone, after Color: `{ id, label, icon?, checked?, isEnabled?, run }`. A row with `checked` is a switch (`menuitemcheckbox`), like a table's Header row: `run` runs it and the menu stays open. Any other row closes the menu after `run`: a caret its action placed stays, else the menu gives its caret back (a table's Insert row below).
(block: Block) => KindMenuAction[]presets?KindPreset[]
One entry per way to create the kind. Feeds the slash menu, markdown shortcuts and block menus.
KindPreset[]empty?{ content?, children? }
The content and children a conversion into this kind creates. With it, a conversion turns only a block that holds nothing into this kind; a block with text or children stays intact and the new block is inserted after it. Without it, a conversion keeps the block's content and children.
{ content?, children? }html?string | ((block, content, children) => string)
Clipboard HTML. A tag wraps the content then the children. Default: <p>content</p> then children.
string | ((block, content, children) => string)plain?(block, content, children) => string
Clipboard plain text. Default: the content, then the children, one per line.
(block, content, children) => stringmarkdown?(block, content, children, context) => string
Markdown export (toMarkdown): content is the block's text as inline markdown, children its children's markdown; context gives index, indent(text, prefix) and inline(content). Default: the bundled kind's of that name (in edytor/export, not on the bundled records), else the plain form, else the text.
(block, content, children, context) => stringparse?(element: HTMLElement) => data | undefined
HTML import: this kind's data when a pasted element is this kind. Checked before tag matching.
(element: HTMLElement) => data | undefinedtransformText?({ text, block, content }) => JSONText[]
Decorate text on render (syntax highlighting). The result is never stored.
({ text, block, content }) => JSONText[]onFocus?({ block }) => void
The text selection entered the block.
({ block }) => voidonBlur?({ block }) => void
The text selection left the block, or it left a block selection.
({ block }) => voidonSelect?({ block }) => void
The block joined a block selection.
({ block }) => voidonDeselect?({ block }) => void
The block left a block selection.
({ block }) => voidnormalizeContent?({ block }) => (() => void) | void
Fix the block's content at the end of an operation that rewrote it.
({ block }) => (() => void) | voidnormalizeChildren?({ block }) => (() => void) | void
Fix the block's children at the end of an operation that changed them.
({ block }) => (() => void) | voidThe roles (void, island, lines, layout, atomic, rendersContent, defaultChild) belong to the document once an editor adopts them. Two plugins that declare different defaultChild values for one kind make the editor throw at creation.
Every replica must read the same roles, the room and headless documents included, and those have no plugins. Write a kind’s roles once, spread them into its record, and give the same table to the room through semanticsOf and mergeSemantics (see Block roles):
import { defaultSemantics, mergeSemantics, semanticsOf } from 'edytor';
export const widgetKinds = { widget: { void: true, rendersContent: false } };
// In the plugin: blocks: { widget: { ...widgetKinds.widget, snippet: widget, presets } }
// In the room and headless documents:
export const semantics = mergeSemantics(defaultSemantics, semanticsOf(widgetKinds));
Export and import
A kind’s html, plain and markdown forms and its parse hook are its export and import: the clipboard, toHTML, toMarkdown and fromHTML all read them, so a copy and an export of a block agree. Keep them in an object of their own and spread it into the kind record, and the same object serves edytor/export on a server (your own kinds), where a record’s snippet cannot load.
Kinds that render no content
A kind with rendersContent: false (a list, a code block, a columns layout and its columns) shows only its children. Its content slot gets no caret, no block merges into it, and it never merges as a whole.
| Gesture or state | What happens |
|---|---|
mergeBackward on its first child |
The child moves out of it. A child of its defaultChild kind becomes its new parent’s default child, unless it stays inside an outer container of that kind: a nested list’s first item stays a list item. |
mergeForward from the block above |
It pulls in its first child. |
| A text range across it | It keeps its later children. |
| Shift+Tab on a middle child | It splits in two around that child, and keeps the children after it. |
| It is left with no child | It is removed. A child a collaborator adds to one meanwhile shows as its new parent’s default child. |
What it holds. When its defaultChild is a kind of its own (a list’s list-item), it holds only children of that kind and containers of them:
- a move of another kind into it is refused (a block already in it still moves among its children);
- Tab after it nests under its last child (and does nothing when that child holds no children, such as an image);
- a block of the document’s default kind (a paragraph) that a merge, delete, outdent or paste puts in it becomes that kind (one a concurrent edit or an explicit write leaves in it shows as that kind);
- any other block (an image, a code block, a heading) keeps its kind and data, and an outdent that would put one in it is refused.
A kind whose defaultChild is the document’s, like a column, holds any block. No child is ever retyped to a kind that renders no content, so nested containers (columns of columns) keep their text (an island’s lines shed into a columns layout take the document’s default kind), and nothing but a column moves or outdents directly into a columns layout.
The snippet payload
A block snippet receives { block, content, children }:
block.id?string
The block's id.
stringblock.type?string
The kind name.
stringblock.data?object
The block's data as plain state: reactive at any depth, and writable (block.data.done = true). See Properties.
objectblock.selected?boolean
Part of a block selection. Reactive.
booleanblock.focused?boolean
Holds the caret or part of a text selection, and is not block-selected. Reactive.
booleanblock.handle?Block | undefined
The block's read-only handle, for its reads and its edytor (handle.edytor). Not reactive. undefined in a suggestion's preview, which is no block of the document.
Block | undefinedblock.void?action
use:block.void marks an element as non-editable chrome.
actioncontent?Snippet
Renders the block's inline content: text, marks and inline atoms.
Snippetchildren?Snippet | null
Renders the nested blocks, or null when there are none.
Snippet | nullRead values from block in the template, they update on every change. Write through the view, block.handle?.edytor, with the block’s id, for example block.handle?.edytor.setBlock(block.id, { type: 'quote' }); the handle’s getters read the document at call time and do not trigger re-renders. A suggestion’s preview renders your snippet with no handle: guard what reads or writes through it.
Render content() once, unless the kind declares rendersContent: false. Render children() in its own element, so nested blocks start on a new row:
{#snippet item({ content, children }: BlockSnippetPayload)}
<div class="text">{@render content()}</div>
{#if children}
<div class="nested">{@render children()}</div>
{/if}
{/snippet}
Chrome with use:block.void
Anything a snippet renders besides content() and children() is chrome: icons, headers, buttons, checkboxes. Mark it with use:block.void so it is non-editable and the caret never enters it:
{#snippet section({ block, content, children }: BlockSnippetPayload)}
<header use:block.void>
<span>Section</span>
<button type="button" onclick={() => block.handle?.edytor.deleteBlock(block.id)}>Remove</button>
</header>
<div>{@render content()}</div>
{@render children?.()}
{/snippet}
The action sets contenteditable="false", data-edytor-void="true" and user-select: none on the element. Native controls inside chrome keep their own clicks, and every form control (an input of any type, a textarea, a select, a button) or nested editable there keeps its own keys, paste, copy, cut, drops and selection, even while blocks are selected (Properties). The block handle of an island aligns with a direct child marked this way.
Presses on chrome
What a press on chrome does depends on the kind:
- A void kind (
void: true): the press selects the block, as Notion does. The block is block-selected and no caret is placed, so the selection’s keys act on it: Delete removes it, the arrows leave it, Enter goes below, copy copies it, Escape clears it. Shift or Mod adds it to a block selection. A press on the line of the block’s text (its caption), beside the words, puts the caret there. - Any other kind: the press puts the caret at the start of the block’s text.
- The block’s text (
content(), a void kind’s caption included): the browser’s caret, at the press.
Controls keep their whole press. A press on a control inside chrome is the control’s, with its clicks, double and triple clicks and its drag: the editor places no caret, starts no text selection and selects no block, and it leaves the control’s focus, its keys and its input alone. A control is a native form control (button, input, textarea, select), a link, an element whose role is interactive (button, link, checkbox, switch, menuitem, tab, option, slider, textbox, combobox) or that takes the focus (tabindex="0"), and any element you mark data-edytor-control. Mark a custom interactive element (a clickable div, a canvas, a color swatch) with data-edytor-control, or give it its role and tabindex, so the editor leaves it alone:
{#snippet widget({ block, content }: BlockSnippetPayload<{ count?: number }>)}
<div use:block.void class="card">
<button type="button" onclick={() => (block.data.count = (block.data.count ?? 0) + 1)}>
Clicked {block.data.count ?? 0} times
</button>
<div class="swatch" data-edytor-control onclick={() => pickColor(block)}></div>
</div>
<div class="caption">{@render content()}</div>
{/snippet}
An element you do not mark still gets its click (the editor never cancels a click), but its press also selects the block. Keep the caption out of the card you want a press to select: a press on the caption’s line is the caption’s. The demo’s widget (src/routes/DemoWidget.svelte in the repository) has a button, an input, a marked element and a caption.
Presets
A preset is one way to create the kind. Each preset becomes a row of the kind catalogue, edytor.kinds, which the slash menu, the markdown shortcuts plugin and block menus read.
labelstring
The menu label.
stringicon?string
A short text icon.
stringkeywords?string[]
Extra search terms for menus.
string[]data?object
The new block's data.
objectmarkdown?string[]
Prefixes that convert a block when typed at its start. The last character triggers. The first one is shown as the slash menu hint.
string[]markdownFrom?Record<string, string[]>
Prefixes that convert a block of a named kind into this preset, typed as markdown is: { toggle: ['# '] } makes a toggle a toggle heading. In a block of a named kind they come before every preset's markdown; when several presets answer, the one whose data shares the most values with the block's wins (a heading's level stays).
Record<string, string[]>group?string
The slash menu section. The image and code presets use 'Media'.
string'Basic blocks'Each row gets a command id: block.<type>, or block.<type>1, block.<type>2 and so on when the kind has several presets. The rich text heading has three presets, so its commands are block.heading1 to block.heading3.
Rows keep registration order: plugins in list order, kinds in the order a plugin declares them, presets in array order. The slash menu shows them in that order, grouped by group, with Basic blocks first.
Convert a block from code with convertToKind, or run the row’s command:
import { convertToKind } from 'edytor';
const row = edytor.kinds.find((kind) => kind.id === 'block.heading2');
const block = edytor.selection.caret?.block;
if (row && convertToKind(edytor, block, row)) {
// converted
}
// Or, on the block holding the caret:
await edytor.runCommand('block.heading2');
The command converts every selected block, or every block a text range touches, as one undo step that keeps the selection; a replacing kind converts only the block holding the selection’s start. Each block converts on its own: one the document refuses or a plugin vetoes keeps its kind, and the others convert.
A row has the preset’s fields plus id, value (the JSON the block is converted to) and replaces (true when the kind has an empty shape). For a menu of conversions that keep the text, filter out row.replaces.
convertToKind applies only to convertible blocks, those that are neither void nor island nor inside an island nor a list container, and returns whether it applied. A conversion keeps the block’s properties and sets the ones the row’s preset names (a to-do turned into a heading keeps checked and gains level). Each conversion is one step: a vetoed one changes nothing, lift out of a list included.
| Case | What the conversion does |
|---|---|
| A list’s item turned into another kind | It leaves the list (Containers). block.setBlock and block.type = retype it in place, so an item set to the document’s default kind (a paragraph) still shows as a list item: use convertToKind to take it out of the list. |
An item converted to its list’s itemKind |
It stays in its list. A list container’s itemKind names the flat kind its items show as (numbered-list-item for ordered-list), and the menus name an item by it. |
| A replacing kind on a block that holds nothing | It converts in place: no children, no text or inline block but a pending slash query (block.isEmpty without the query). The caret moves to the start of the converted block, or of its first child. |
| A replacing kind after text, an inline block such as a mention, or children | The same command inserts the new block after it instead and leaves the block intact (after a list’s item, outside the list, which splits there). |
| A kind that renders no content (a divider) | It cannot hold the caret: the same step adds a block of the default child kind where it lands after it, and the caret lands there. |
| A plugin rewrites the conversion’s payload | The kind it names is placed: rewritten to a list’s item, the block stays in its list. |
Continuing kinds
Set continues: true on a list-like kind, as the rich text plugin does for bulleted and numbered items, to-dos and toggles. Enter then opens another block of the same kind, with the data of the kind’s first preset (a new to-do starts unchecked because its first preset’s data is { checked: false }, also when Enter at the end of a to-do with children moves them to the new one), and Enter in an empty one ends the run. Enter and Backspace by role has the full rules.
blocks: {
step: {
snippet: step,
continues: true,
presets: [{ label: 'Step', data: { done: false } }]
}
}
Containers
Set container: true on a kind whose text is a header over its children, as the rich text plugin does for toggles, callouts and quotes. Enter at the end of one that has children opens a first child of its defaultChild kind, and Enter in the middle of its header moves the text after the caret into that first child, the children staying with the header. A header rendered as <details> does so while open, even without children, and adds a sibling (holding the text after the caret) while closed; the open state is the browser’s (viewState: ['open']), read from the block element. Add body: true for a header whose body is always there, as the callout’s: Enter at its end opens a first child even when it has none. See Enter and Backspace by role.
Backspace at the start
Backspace at the start of a block whose kind has presets and is not its parent’s default child turns the block into that default first, keeping its text and children; the next Backspace merges or moves out. Kinds without presets, such as list-item or codeLine, keep the structural behavior. See Enter and Backspace by role.
Normalization
normalizeContent and normalizeChildren run at the end of an operation’s transaction, inside it, for the blocks the operation touched. normalizeContent runs on every block whose content, kind or data an operation wrote (typing included, and a block it inserted); normalizeChildren runs on the parents whose children changed (an insertion, a move, a deletion, a split or a merge). Keep both cheap: they run on every keystroke in the block.
Write directly, or return a function: it runs in the same transaction, and the normalizer runs again on the block until it returns nothing (at most 50 more passes). The work is part of the same undo step, and peers never see the unnormalized state.
Override a snippet
To change only how an existing kind renders, list a plugin before the one that defines it, naming only its snippet. Definitions are first-wins field by field, so the kind keeps every other option, its element and contentElement included: below, content() still renders the quote’s text inside its blockquote.
<script lang="ts">
import { Edytor } from 'edytor';
import type { BlockSnippetPayload, Plugin } from 'edytor';
const myQuote: Plugin = () => ({ blocks: { quote: { snippet: quote } } });
</script>
{#snippet quote({ content, children }: BlockSnippetPayload)}
<div class="my-quote">{@render content()}</div>
{@render children?.()}
{/snippet}
<Edytor plugins={[myQuote]} />
The same works for marks (marks) and inline atoms (inlineBlocks), and for any kind name ('todo-item').
To replace a kind completely, define every field it needs in a plugin listed before the one that defines it.
Complete example: a task kind
A task with a checkbox that writes data.done, a markdown prefix, clipboard forms, and a normalizer that keeps its text on one line:
<script module lang="ts">
import type { Block, Plugin } from 'edytor';
import type { BlockSnippetPayload } from 'edytor';
// One property written: a collaborator's concurrent edit of another is kept.
const toggle = (task: Block) => (task.data.done = !task.data.done);
export const taskPlugin: Plugin = () => ({
blocks: {
task: {
snippet: task,
element: (data) => ({ tag: 'div', attributes: { 'data-done': data.done ? 'true' : undefined } }),
presets: [
{ label: 'Task', icon: '☐', keywords: ['todo', 'check'], data: { done: false }, markdown: ['>> '] }
],
html: (block, content, children) =>
`<li><input type="checkbox"${block.data?.done === true ? ' checked' : ''}>${content}${children}</li>`,
plain: (block, content, children) =>
[`${block.data?.done === true ? '[x]' : '[ ]'} ${content}`, children].filter(Boolean).join('\n'),
parse: (element) => {
const box = element.querySelector<HTMLInputElement>(':scope > input[type="checkbox"]');
return element.localName === 'li' && box ? { done: box.checked } : undefined;
},
// A task is one line: a line break typed with Shift+Enter is removed.
normalizeContent: ({ block }) => {
const text = block.firstText;
const at = text?.stringContent.indexOf('\n') ?? -1;
if (text && at !== -1)
return () => block.edytor.deleteText(block.id, text.segStart + at, 1);
}
}
}
});
</script>
{#snippet task({ block, content, children }: BlockSnippetPayload)}
<input
type="checkbox"
checked={Boolean(block.data.done)}
use:block.void
onchange={() => block.handle && toggle(block.handle)}
/>
<div class="task-text">{@render content()}</div>
{#if children}
<div class="task-children">{@render children()}</div>
{/if}
{/snippet}
[data-edytor-type='task'] {
display: grid;
grid-template-columns: 18px minmax(0, 1fr);
column-gap: 8px;
}
[data-edytor-type='task'] > .task-text,
[data-edytor-type='task'] > .task-children {
grid-column: 2;
}
[data-edytor-type='task'][data-done='true'] > .task-text {
text-decoration: line-through;
opacity: 0.6;
}