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

Menus and handles

Draw every popup, menu, toolbar, panel and handle with your own typed Svelte snippet; the plugins own the behavior, the keyboard and the accessibility, and ship no markup of their own.

Edytor’s chrome is headless: the slash menu, the mention and page link menus, the block menu, the selection toolbar and its link card, the menu a pasted URL opens, the image toolbar, the empty image and media blocks, a table’s grips, menus and + bars, a code block’s header and language list, the callout icon picker, the equation editor, the comment cards, the suggestion bar, the version history, the block handles and the marquee’s rectangle are drawn by your snippets. The package ships the behavior: when the UI opens, where its anchor is, the keys it claims, the commands it runs, and the keyboard and ARIA your markup takes through a few attachments its controller hands you. It ships no markup for them.

Without its snippet, a surface renders nothing, and its controller still works: with createSlashMenuPlugin() and no menu, typing /divider and Enter still inserts a divider, and nothing shows. A plugin whose main job is a kind (code, table, image, the media kinds, equations) keeps its blocks; only its chrome is yours. The controls inside a block (a to-do’s checkbox, a callout’s icon, a bookmark’s card…) are drawn by the package and take your snippet in their place: see Controls inside blocks.

The examples below are the short version of each surface. The complete Notion-style markup of every surface, in shadcn-svelte, is the edytor-chrome registry item, copied into your app with npx shadcn-svelte@latest add https://edytor.dev/r/edytor-chrome.json, as plugins you list: see Ready-made menus. Its files are then yours to start from (chrome.svelte holds the snippets, plugins.ts passes them to each factory).

The pattern

Every element is customized the same way:

  • Where. A snippet option in the plugin’s factory options (createBlockMenuPlugin({ menu })). The version history is a controller you make in your component (new VersionHistory(…)).
  • Naming. A whole surface is named by what it is: menu, toolbar, card, bar, empty, header, panel, box, picker; a control by what it is: grip, add, handle. One surface, one snippet: your snippet draws its rows.
  • Typing. A snippet takes one object argument whose type is exported from edytor: Snippet<[BlockMenuController]>. A whole surface receives its controller: its state, its actions, readonly, and a way to close it; the words are your markup’s. A controller that builds its rows hands them in the shape every list shares, MenuItemPayload: { item, id, selected, run, select, option } (a table menu’s items, a code language list’s items).
  • Attach what the editor needs, render what you show. A payload holds two kinds of things. Its attachments ({@attach menu.popup}, {@attach menu.option(index)}, {@attach box.control}) give an element what the editor needs of it: its id and role, the ARIA it keeps in step, its keys, its presses, its marker. Everything else is a value you render (state, words, a URL: selected, label, card.url) or a function you call (run, pick, toggle). Nothing is spread. A snippet that attaches them gets the keys and the ARIA the accessibility tests prove (the demo’s markup is the one they run), and the same holds for a control inside a block: a custom checkbox is written exactly as a custom menu row.
  • Style what you render. An attachment’s attributes are set in the browser, after your markup: Svelte’s scoped CSS does not see them (a selector on aria-selected would be dropped) and a server render does not have them. Draw a row’s highlight from its value (data-selected={item.selected}, or menu.index === index) and style that.
Attachment Put it on What it does
{@attach controller.popup} The list (listbox or menu), or the toolbar Gives the element its id, and its role and name unless you set them; keeps the focus where it is on a press; publishes the popup to the editor’s root (aria-controls, aria-haspopup, aria-activedescendant when the root holds the keyboard) while it is in the page, and withdraws it when it goes
{@attach controller.keys} The element that holds the keyboard: the block menu’s or the + menu’s field (or the + menu itself), the toolbar, a table’s grip menu, the code language list’s search field, the callout icon picker Takes the menu’s keys (arrows, Home, End, Enter, Escape, …), focuses the element when it mounts, and makes it name the list and its highlighted row
{@attach controller.option(index)} Each row Its id, role, aria-selected (or aria-checked), tabindex="-1", and scrolls the keyboard’s row into view. A row payload carries it as option; its look is yours, from selected
{@attach controller.flyoutMenu} The block menu’s open flyout Its id, role and name
{@attach controller.linkField} The toolbar’s link field Its id (unique per editor, for a label’s for), the focus when the panel opens, Enter applies, Escape closes
{@attach toolbar.bar}, {@attach toolbar.altField} The image toolbar and its alt field The toolbar’s role and name; the alt field’s focus, keys, and closing when the focus leaves
{@attach empty.field} An empty block’s link field Enter embeds the link
{@attach payload.grip} A table’s row or column grip The drag (the row or the column moves where it is dropped), the click that opens its menu, ↓ opens it too and Escape gives the keys back to the editor; its name, aria-haspopup, aria-expanded and aria-controls
{@attach header.button} A code block’s language button Opens the language list on a click, ↓ or ↑ (Alt+F10 at a caret in the block reaches it), Escape gives the keys back to the code; its name, aria-haspopup, aria-expanded and aria-controls
{@attach find.field}, {@attach find.replaceField} The find bar’s query and replacement fields The query field’s focus on each Mod+F; Enter goes to the next match (Shift+Enter the previous one) or replaces, Escape closes
{@attach handle.grip}, {@attach handle.plus} A block handle’s grip and + The grip’s drag, the click that opens the block menu and the Alt+arrow moves (aria-keyshortcuts); the +’s click (add, under it); both keep the focus on a press and carry the ARIA of the menu they opened (aria-expanded, aria-controls, aria-haspopup)
{@attach editor.field} The equation editor’s source field The focus when the editor opens, the caret at the end; Enter and Escape close the editor (Shift+Enter is a newline in a block equation), and so does the focus leaving the panel
{@attach history.option(index)}, {@attach history.keys} A version’s row, the versions list The row’s role="option", id, aria-selected and the list’s one tab stop; the list’s arrows, Home and End move the selection and the focus

Two rules hold for every snippet:

  • Keep the selection. A press on a menu must not move the caret. popup cancels the mousedown of every press in its element but on a field; on anything else that acts on the text (a +, a button outside the list), call preventDefault on mousedown. The toolbar’s host does it for every press but in a field.
  • Place it yourself, by its anchor. The package places no menu or popup: each controller has an anchor, a virtual element read live (getBoundingClientRect(), contextElement: Floating UI’s shape) standing for the caret (the slash and trigger menus; a + menu, its +), the selection (the toolbar; cardAnchor, the hovered link, for the link card), the handle (the block menu), the pasted line, the editor (the find bar), the grip (a table menu), the image (its toolbar), the language button, the callout’s icon, the equation, or the commented text. With Floating UI, autoUpdate(anchor, menu, () => computePosition(anchor, menu, { strategy: 'fixed', middleware: [offset(8), flip(), shift({ padding: 8 })] }).then(({ x, y }) => Object.assign(menu.style, { left: `${x}px`, top: `${y}px` }))); with bits-ui, <Popover.Content customAnchor={controller.anchor}>. The ready-made menus do it in one attachment, float (Ready-made menus).
UI Option Receives Attachments
Slash menu createSlashMenuPlugin({ menu }) SlashMenuController popup, option(index); keys in a + menu
Mention, page link, any trigger createMentionPlugin({ menu }), createPageLinkPlugin({ menu }), a trigger’s menu TriggerMenuController<T> popup, option(index)
Block menu createBlockMenuPlugin({ menu }) BlockMenuController keys, popup, option(index), flyoutMenu
Toolbar and link card createToolbarPlugin({ toolbar, card }) ToolbarController popup, keys, linkField
URL paste menu createEmbedPlugin({ menu }), createBookmarkPlugin({ menu }) UrlPasteController popup, option(index)
Image toolbar createImageToolbarPlugin({ toolbar }) ImageToolbar bar, altField
Empty image and media blocks createMediaEmptyPlugin({ empty }) MediaEmptyController field
Table grips, menu and + createTablePlugin({ grip, menu, add }) TableGripPayload, TableChrome (rows: TableMenuItem), TableAddPayload grip; popup, keys, option(index)
Code header and language list createCodePlugin({ header, menu }) CodeHeader, LanguageMenu (rows: LanguageMenuItem) button; keys, popup, option(index)
Callout icon picker createCalloutIconsPlugin({ picker }) CalloutIconPicker keys, popup, option(index)
Equation editor createEquationPlugin({ panel }) EquationEditor field
Comment cards createCommentsPlugin({ card, header }) CommentCardPayload, CommentsController
Suggestion bar createSuggestionBarPlugin({ bar }) SuggestionBarPayload
Version history new VersionHistory({ client, document }) your component reads it option(index), keys
Block handle createBlockHandlesPlugin({ handle }) BlockHandleSnippetPayload grip, plus
Marquee rectangle createMarqueePlugin({ box }) MarqueeBoxPayload

Your markup writes its own words and names its menus, bars and fields (aria-label): the controllers carry no words and name none of your elements; the words the package itself shows are the view’s labels (Localization). Your markup renders in the plugin’s host and places itself by its controller’s anchor; its look is all yours.

A snippet declared at the top level of a component’s markup can be used in its <script>, so you build the plugins there, as every example below does.

Slash menu

menu draws the menu while controller.isOpen. It opens on / (the editor’s root keeps the keyboard: its ↑/↓, Enter and Escape are the plugin’s) or from a block handle’s + (controller.addition is set: the menu holds the keyboard, through the element you give keys). controller.commands are the rows, in their groups’ order (command.group, named by controller.groupName). See Slash menu.

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

	const plugins = [createSlashMenuPlugin({ menu })];
</script>

{#snippet menu(slash: SlashMenuController)}
	<div class="menu">
		{#if slash.addition}
			<!-- The `+` menu: this field holds the keyboard. -->
			<input
				role="combobox"
				aria-expanded="true"
				aria-controls={slash.listId}
				aria-label="Filter block commands"
				placeholder="Type to filter…"
				value={slash.query}
				oninput={(event) => slash.search(event.currentTarget.value)}
				{@attach slash.keys}
			/>
		{/if}
		<ul {@attach slash.popup}>
			{#each slash.commands as command, index (command.id)}
				<li
					data-selected={slash.index === index}
					{@attach slash.option(index)}
					onmousemove={() => (slash.index = index)}
					onclick={() => void slash.run(command)}
				>
					{command.label}
					{#if command.hint}<kbd>{command.hint}</kbd>{/if}
				</li>
			{:else}
				<li role="presentation">No results</li>
			{/each}
		</ul>
	</div>
{/snippet}

<Edytor {plugins} />

In a + menu, keys goes on the element that holds the keyboard: your field, as above, or the menu element itself (give it tabindex="-1"): then typing and Backspace edit controller.query. controller.commands holds only the commands that can run in the block being added; controller.dismiss() closes the menu with the selection given back.

A trigger (@ for mentions, [[ for page links, or your plugin’s own) takes menu, the whole menu: a TriggerMenuController<T> whose items are the rows (labelOf(item) their words, pick(item) picks one). The editor’s root keeps the keyboard; popup names the list and its highlighted row from it.

<script lang="ts">
	import {
		Edytor,
		createMentionPlugin,
		type MentionItem,
		type TriggerMenuController
	} from 'edytor';

	const people: MentionItem[] = [
		{ id: 'ada', label: 'Ada Lovelace' },
		{ id: 'alan', label: 'Alan Turing' }
	];
	const plugins = [
		createMentionPlugin({
			items: (query) => people.filter((person) => person.label.toLowerCase().includes(query)),
			menu
		})
	];
</script>

{#snippet menu(mentions: TriggerMenuController<MentionItem>)}
	<ul {@attach mentions.popup} aria-busy={mentions.loading}>
		{#each mentions.items as person, index (person.id)}
			<li {@attach mentions.option(index)} onclick={() => void mentions.pick(person)}>
				{person.label}
			</li>
		{:else}
			<li role="presentation">{mentions.loading ? 'Searching…' : 'No results'}</li>
		{/each}
	</ul>
{/snippet}

<Edytor {plugins} />

Block menu

menu renders while controller.isOpen, beside the grip that opened it. Its field holds the keyboard: keys gives it the menu’s keys (↑/↓, Home/End, → opens a row’s flyout and ← closes it, Enter runs the row, Delete removes the blocks while the query is empty, Escape closes the flyout, then the menu) and makes it name the menu, or the open flyout, and its highlighted row. controller.rows are the keyboard’s rows (the actions, then the kinds and the colours a query names); run(row) runs a row of either (Enter runs the highlighted one). See Block menu.

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

	const plugins = [createBlockMenuPlugin({ menu })];
</script>

{#snippet menu(blockMenu: BlockMenuController)}
	<div class="panel" data-edytor-block-menu>
		<input
			aria-label="Search actions"
			placeholder="Search actions…"
			value={blockMenu.query}
			oninput={(event) => blockMenu.search(event.currentTarget.value)}
			{@attach blockMenu.keys}
		/>
		<div {@attach blockMenu.popup}>
			{#each blockMenu.rows as row, index (`${index}:${row.id}`)}
				<button
					type="button"
					{@attach blockMenu.option(index)}
					onmousemove={() => (blockMenu.index = index)}
					onclick={() => {
						blockMenu.index = index;
						blockMenu.run(row);
					}}>{row.label}</button
				>
			{/each}
		</div>
		{#if blockMenu.flyout}
			<div class="flyout" {@attach blockMenu.flyoutMenu}>
				{#each blockMenu.flyoutRows as row, index (row.id)}
					<button
						type="button"
						{@attach blockMenu.option(index, true)}
						onclick={() => {
							blockMenu.flyoutIndex = index;
							blockMenu.run(row);
						}}>{row.label}</button
					>
				{/each}
			</div>
		{/if}
	</div>
{/snippet}

<Edytor {plugins} />

option(index) gives each row its role: menuitem, a kind’s switch menuitemcheckbox, a colour menuitemradio with its ✓ as aria-checked, and a row that opens a flyout aria-haspopup and aria-expanded. Every action closes the menu and returns the caret to the block (a block holding no text stays selected).

toolbar renders while controller.isVisible, above the selection. On the bar, popup publishes it to the root (with Alt+F10 as its shortcut); keys makes it one tab stop: Alt+F10 focuses it, ←/→, Home and End walk its buttons, Escape gives the focus back to the editor over the same selection. linkField is the link panel’s field. card draws the card shown under a hovered link (without it, no card). See Toolbar.

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

	const plugins = [createToolbarPlugin({ toolbar, card })];
</script>

{#snippet toolbar(bar: ToolbarController)}
	<div class="frame">
		<div class="bar" {@attach bar.popup} {@attach bar.keys}>
			{#each bar.marks as { mark, label, icon } (mark)}
				<button aria-label={label} aria-pressed={bar.isActive(mark)} onclick={() => bar.toggleMark(mark)}
					>{icon}</button
				>
			{/each}
			<button aria-expanded={bar.panel === 'link'} onclick={() => bar.togglePanel('link')}
				>Link</button
			>
		</div>
		{#if bar.panel === 'link'}
			<label for={bar.linkFieldId}>Link URL</label>
			<input
				placeholder="Paste link"
				value={bar.linkUrl}
				oninput={(event) => bar.setLinkUrl(event.currentTarget.value)}
				{@attach bar.linkField}
			/>
		{/if}
	</div>
{/snippet}

{#snippet card(links: ToolbarController)}
	<div class="card" role="toolbar" aria-label="Link">
		<span>{links.hoveredHref}</span>
		<button onclick={() => links.editHovered()}>Edit</button>
		<button onclick={() => links.removeHovered()}>Remove</button>
	</div>
{/snippet}

<Edytor {plugins} />

No press on the toolbar or the card takes the editor’s focus (their hosts cancel each mousedown but in a field), so your buttons need no mousedown handler.

URL paste menu

With the embed or bookmark plugin, a bare URL pasted on an empty line becomes a link and opens a menu: Link, Embed, Bookmark. menu draws it (the view’s one menu takes the first menu its embed and bookmark plugins pass; without one, the link stays and nothing shows). It renders while controller.open, under the line; the editor keeps the keyboard (↑/↓, Enter picks, Escape keeps the link).

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

	const plugins = [createEmbedPlugin({ menu })];
</script>

{#snippet menu(paste: UrlPasteController)}
	<ul {@attach paste.popup}>
		{#each paste.open?.options ?? [] as option, index (option.id)}
			<li
				{@attach paste.option(index)}
				onmousemove={() => (paste.index = index)}
				onclick={() => paste.pick(option)}
			>
				{option.icon} {option.id}
			</li>
		{/each}
	</ul>
{/snippet}

<Edytor {plugins} />

Image toolbar

createImageToolbarPlugin({ toolbar }): toolbar draws the alignment buttons and the alt text field over the hovered (or selected) image; it renders at the image’s top right while the chrome shows and no resize handle drags. The resize handles are the plugin’s. bar marks it so a press on it keeps the alt field open (its Alt button toggles it); altField focuses the field when it opens, closes it on Enter or Escape (the editor takes its keys back) and when the focus leaves it. See Image.

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

	const plugins = [createImageToolbarPlugin({ toolbar })];
</script>

{#snippet toolbar(image: ImageToolbar)}
	<div class="image-toolbar" {@attach image.bar}>
		<button aria-pressed={image.box?.align === 'left'} onclick={() => image.align('left')}
			>Align left</button
		>
		<button aria-pressed={image.box?.align === 'center'} onclick={() => image.align('center')}
			>Align center</button
		>
		<button aria-expanded={image.editing !== null} onclick={image.toggleAlt}>Alt text</button>
		{#if image.editing !== null && image.editing === image.box?.id}
			<input
				aria-label="Alt text"
				placeholder="Describe the image…"
				value={image.alt}
				oninput={(event) => image.setAlt(event.currentTarget.value)}
				{@attach image.altField}
			/>
		{/if}
	</div>
{/snippet}

<Edytor {plugins} />

Empty image and media blocks

createMediaEmptyPlugin({ empty }): one empty snippet draws every empty block of the view: the image’s “Add an image” and its link panel, and the same for the embed, bookmark, file, video and audio blocks, a readonly view’s placeholder included: one snippet shape, one controller (MediaEmptyController) per empty block of any of these kinds: kind (image, embed, bookmark, file, video, audio: your words for it), icon, open, draft (bind your field to it), failed (why the last link or upload was not embedded: invalid, inline for an inline image over MAX_INLINE_IMAGE_BYTES, upload), embed(value?), upload(file) (when the kind’s plugin has an upload, canUpload; the picker’s accept), pending, the upload of a pasted, dropped or picked file (status; while uploading, its name, size, progress and preview), preview (an uploading image’s local object URL, else null) and progress (0 to 1, null until reported), and readonly (no control may write: show a placeholder).

<script lang="ts">
	import {
		Edytor,
		createImagePlugin,
		createMediaEmptyPlugin,
		createVideoPlugin,
		MAX_INLINE_IMAGE_BYTES,
		type MediaEmptyController
	} from 'edytor';

	const plugins = [
		createImagePlugin({ upload: (file) => upload(file) }),
		createVideoPlugin({ upload: (file) => upload(file) }),
		// One snippet for every empty block: by its kind.
		createMediaEmptyPlugin({ empty })
	];
</script>

{#snippet empty(panel: MediaEmptyController)}
	{#if panel.kind === 'image'}{@render emptyImage(panel)}{:else}{@render emptyMedia(panel)}{/if}
{/snippet}

{#snippet emptyImage(image: MediaEmptyController)}
	{#if image.readonly}
		<p>Image</p>
	{:else}
		<input aria-label="Image link" bind:value={image.draft} {@attach image.field} />
		<button onclick={() => image.embed()}>Embed image</button>
		{#if image.failed === 'inline'}
			<small>Inline images are limited to {MAX_INLINE_IMAGE_BYTES} bytes.</small>
		{:else if image.failed}
			<small>That doesn't look like an image link.</small>
		{/if}
	{/if}
{/snippet}

{#snippet emptyMedia(media: MediaEmptyController)}
	{#if media.pending?.status === 'uploading'}
		<progress value={media.pending.progress ?? undefined} max="1"></progress>
	{:else if media.readonly}
		<p>{media.icon} Embed a {media.kind}</p>
	{:else}
		<input aria-label="Paste the link…" bind:value={media.draft} {@attach media.field} />
		<button onclick={() => media.embed()}>Embed</button>
		{#if media.canUpload}
			<input
				type="file"
				accept={media.accept}
				onchange={(event) => {
					const file = event.currentTarget.files?.[0];
					if (file) void media.upload(file);
				}}
			/>
		{/if}
		{#if media.failed}<small>{media.failed === 'upload' ? 'The upload failed.' : 'That link is not one.'}</small>{/if}
	{/if}
{/snippet}

<Edytor {plugins} />

upload here is your own upload function, the view’s uploader for every kind that takes files. The markup renders inside the block (the block’s own contenteditable="false" region), so its fields keep their keys and presses.

Table grips, menu and +

The table plugin’s chrome shows over the hovered table (its column resize bands are the plugin’s). grip draws the grip of the hovered row (left of the table) and of the hovered column (above it): the plugin renders it centered where the grip stands, and {@attach payload.grip} gives it the drag, the click that opens its menu and the keys (↓ opens the menu, Escape gives the keys back to the editor). A press on a grip is never prevented: that would stop the native drag.

menu draws the grip’s menu, under the grip while chrome.menu is set: popup and keys on its element make it a menu that takes the focus, its ↓/↑ walk the rows that can run, Home/End reach the ends, Enter runs the row, Escape closes it. chrome.items are the rows (Insert above, Insert below, Move up, Move down, Delete row, or the column’s), each a MenuItemPayload with disabled (Move up on the first row, aria-disabled) and danger; item.item.id names the row (insert-above, move-down, delete-column, …) for your icons.

add draws the + under the table (a row at its end) and beside it (a column): the plugin lays it along that edge, as wide (tall) as the table shows, and keeps the editor’s selection on a press.

<script lang="ts">
	import {
		Edytor,
		createTablePlugin,
		type TableAddPayload,
		type TableChrome,
		type TableGripPayload
	} from 'edytor';

	const plugins = [createTablePlugin({ grip, menu, add: plus })];
</script>

{#snippet grip(handle: TableGripPayload)}
	<button type="button" class="grip" {@attach handle.grip}>{handle.kind === 'row' ? '⋮⋮' : '⋯'}</button>
{/snippet}

{#snippet menu(table: TableChrome)}
	<div class="menu" {@attach table.popup} {@attach table.keys}>
		{#each table.items as item (item.item.id)}
			<button
				type="button"
				{@attach item.option}
				class:danger={item.danger}
				onmousemove={item.select}
				onclick={item.run}>{item.item.id}</button
			>
		{/each}
	</div>
{/snippet}

{#snippet plus({ kind, add }: TableAddPayload)}
	<button type="button" class="add {kind}" aria-label="Add a {kind}" onclick={add}>+</button>
{/snippet}

<Edytor {plugins} />

<style>
	.grip {
		width: 20px;
		height: 20px;
		cursor: grab;
	}
	.menu [data-selected='true'] {
		background: #f1f1ef;
	}
	.add.row {
		width: 100%;
	}
	.add.column {
		height: 100%;
	}
</style>

payload.toggle() opens or closes a grip’s menu, payload.expanded and payload.dragging say whether it is open or the grip is dragging; chrome.close() closes the menu with the keys given back to the editor.

Code header and language list

The code plugin’s header draws the header above each code block (the language’s button and Copy), inside the block’s non-editable part (the plugin places it at the block’s top). It receives the block’s CodeHeader: language (its id) and label, editable (false in a readonly view and a suggestion’s preview: show the label only), expanded, toggle(), copy() and copied (true for a moment after a copy), and labels. {@attach header.button} makes your button open the view’s language list under it, with the keys and the ARIA.

menu draws that list (the first code plugin listed in a view owns it). It renders under the button while menu.open is set; keys on its search field makes it the combobox that holds the keys (↓/↑ move the highlighted row, Enter picks it, Escape closes: the keys go back to the button when they opened the list, else to the editor), popup on the list makes it the listbox the root names, and each row of menu.items attaches its option (current marks the block’s language, selected the keyboard’s row).

<script lang="ts">
	import { Edytor, createCodePlugin, type CodeHeader, type LanguageMenu } from 'edytor';

	const plugins = [createCodePlugin({ header, menu })];
</script>

{#snippet header(code: CodeHeader)}
	{#if code.editable}
		<button type="button" {@attach code.button}>{code.label} ▾</button>
	{:else}
		<span>{code.label}</span>
	{/if}
	<button type="button" onmousedown={(event) => event.preventDefault()} onclick={() => void code.copy()}
		>{code.copied ? 'Copied' : 'Copy'}</button
	>
{/snippet}

{#snippet menu(languages: LanguageMenu)}
	<div class="languages">
		<input
			placeholder="Search for a language…"
			value={languages.query}
			oninput={(event) => languages.search(event.currentTarget.value)}
			{@attach languages.keys}
		/>
		<ul {@attach languages.popup}>
			{#each languages.items as item (item.item.id)}
				<li {@attach item.option} onmousemove={item.select} onclick={item.run}>
					{item.item.label}{#if item.current}&nbsp;✓{/if}
				</li>
			{/each}
		</ul>
		{#if languages.items.length === 0}<p role="status">No results</p>{/if}
	</div>
{/snippet}

<Edytor {plugins} />

Callout icon picker

A callout’s icon opens the view’s icon picker, the callout icons plugin’s (the first one listed owns it); createCalloutIconsPlugin({ picker }) draws it, under the icon while picker.isOpen. keys and popup on its element make it the menu that takes the focus and the keys (the arrows walk a grid of picker.columns icons per row, Enter picks, Escape closes); each row attaches picker.option(index) and runs picker.pick(index) on its click, index in picker.icons and picker.icons.length for Remove icon.

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

	const plugins = [createCalloutIconsPlugin({ picker })];
</script>

{#snippet picker(icons: CalloutIconPicker)}
	<div class="picker" {@attach icons.keys} {@attach icons.popup}>
		<div class="grid" role="none" style:--columns={icons.columns}>
			{#each icons.icons as icon, index (index)}
				<button type="button" {@attach icons.option(index)} onclick={() => icons.pick(index)}>{icon}</button>
			{/each}
		</div>
		<button type="button" {@attach icons.option(icons.icons.length)} onclick={() => icons.pick(icons.icons.length)}>Remove icon</button>
	</div>
{/snippet}

<Edytor {plugins} />

<style>
	.grid {
		display: grid;
		grid-template-columns: repeat(var(--columns), 32px);
	}
</style>

Equation editor

The equation plugin’s panel draws the editor that opens under an equation (its TeX source, KaTeX’s error, Done). It renders while editor.target is set, under the equation (centered under a block one). It receives the view’s EquationEditor: expression and set(value) (each keystroke one write, the typing one undo step), display (a block equation), error and close(). {@attach editor.field} on the source’s field gives it the focus when the editor opens and its keys: Enter and Escape close the editor (Shift+Enter is a newline in a block equation), as does the focus leaving the panel.

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

	const plugins = [createEquationPlugin({ panel })];
</script>

{#snippet panel(equation: EquationEditor)}
	<div class="panel" role="dialog" aria-label="Equation">
		<textarea
			aria-label="Equation"
			placeholder="E = mc^2"
			rows={equation.display ? 3 : 1}
			value={equation.expression}
			oninput={(event) => equation.set(event.currentTarget.value)}
			{@attach equation.field}
		></textarea>
		{#if equation.error}<p role="status">{equation.error}</p>{/if}
		<button type="button" onmousedown={(event) => event.preventDefault()} onclick={() => equation.close()}
			>Done</button
		>
	</div>
{/snippet}

<Edytor {plugins} />

Comment cards

card draws a card of the comments sidebar; the plugin places each card beside its text (under it, on a narrow screen). It receives a CommentCardPayload: the thread (its comments, quote, resolved), or null for the comment being written (its text comments.draft.quote: post it with comments.submit(body), give it up with comments.cancel()), the view’s comments controller (reply, resolve, reopen, remove, mayDelete, userOf) and whether the thread is the active one. header draws the top of the margin (Notion’s “Resolved (2)” toggle: comments.resolved, comments.showResolved); the cards stack under it. Without card, no sidebar shows: the threads are still highlighted and kept. See Comments.

<script lang="ts">
	import {
		Edytor,
		createCommentsPlugin,
		createMemoryCommentsClient,
		type CommentCardPayload
	} from 'edytor';

	const plugins = [
		createCommentsPlugin({ client: createMemoryCommentsClient({ user: 'ada' }), user: 'ada', card })
	];
</script>

{#snippet card({ thread, comments, active }: CommentCardPayload)}
	{#if thread}
		<article class:active>
			<blockquote>{thread.quote}</blockquote>
			{#each thread.comments as comment (comment.id)}
				<p><strong>{comments.userOf(comment.author).name ?? comment.author}</strong> {comment.body}</p>
			{/each}
			{#if thread.resolved}
				<button onclick={() => void comments.reopen(thread.id)}>Re-open</button>
			{:else}
				<button onclick={() => void comments.resolve(thread.id)}>Resolve</button>
			{/if}
		</article>
	{:else}
		<form
			onsubmit={(event) => {
				event.preventDefault();
				const field = new FormData(event.currentTarget).get('body');
				void comments.submit(String(field ?? ''));
			}}
		>
			<textarea name="body" aria-label="Add a comment…"></textarea>
			<button type="button" onclick={() => comments.cancel()}>Cancel</button>
			<button>Comment</button>
		</form>
	{/if}
{/snippet}

<Edytor {plugins} />

Suggestion bar

createSuggestionBarPlugin({ bar }): bar draws the bar under each block suggestion and under the last block a shared suggestion changes; the plugin keeps its placement, the default suggestions plugin its keys (Mod+Enter accepts, Escape discards a view-local one; without a bar, the keys still do). It receives a SuggestionBarPayload: the suggestion, accept, discard, reject, retry (when the app passed onRetry), readonly, canDecide (this view may accept or reject it), author (a shared one’s { id, name?, color? }) and mac (Mod is ⌘).

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

	const plugins = [createSuggestionBarPlugin({ bar })];
</script>

{#snippet bar({ suggestion, accept, discard, retry, readonly }: SuggestionBarPayload)}
	<div class="bar">
		<span>{suggestion.label ?? 'Suggestion'}</span>
		{#if !readonly}<button onmousedown={(e) => e.preventDefault()} onclick={accept}>Accept</button>{/if}
		<button onmousedown={(e) => e.preventDefault()} onclick={discard}>Discard</button>
		{#if retry}<button onclick={retry}>Try again</button>{/if}
	</div>
{/snippet}

<Edytor {plugins} />

Version history

The version history is a controller you make in your component: new VersionHistory({ client, document }) lists the room’s versions (versions, newest first), previews one (select(key), selected, preview, previewPlugins, diff against the live document), restores it (restore(), undo(), busy, undoable, status, failed) in your words (status is a code; dateOf(version) and timeOf(version) format a version’s day and time, version.slot its half of the day, version.editors who edited it). Each row attaches option(index): an option of your listbox, its one tab stop when selected; the list’s {@attach history.keys} walks them (↑/↓, Home, End). Make it in the component’s script: its effects list the versions and follow the document.

<script lang="ts">
	import { untrack } from 'svelte';
	import { Edytor, VersionHistory, createHistoryClient, type EdytorDocument } from 'edytor';

	let { room, document }: { room: string; document: EdytorDocument } = $props();
	const client = createHistoryClient({ server: 'https://example.com/history', room });
	const history = untrack(() => new VersionHistory({ client, document }));
</script>

<ul role="listbox" aria-label="Versions" {@attach history.keys}>
	{#each history.versions ?? [] as version, index (version.key)}
		<li role="presentation">
			<button type="button" {@attach history.option(index)} onclick={() => void history.select(version.key)}>
				{history.dateOf(version)} <small>{version.editors.join(', ')}</small>
			</button>
		</li>
	{/each}
</ul>
{#if history.preview}
	{#key history.previewKey}
		<Edytor readonly value={history.preview} plugins={history.previewPlugins} />
	{/key}
{/if}
<button disabled={history.busy || !history.shown} onclick={() => void history.restore()}>
	Restore version
</button>
<p role="status">{history.status}</p>

Block handle

handle draws the + and the grip beside each block: list createBlockHandlesPlugin({ handle }) (without a handle, no handle shows). {@attach handle.grip} gives any element the grip’s behavior: dragging (every block the selection covers when it covers this one, with the count preview), a click that selects the block and opens the block menu (its edytor-block-activate event), and the Alt+arrow moves (its aria-keyshortcuts). {@attach handle.plus} makes an element the +: its click opens the slash menu under it (Alt+click above, or a column beside a block in a column), which adds nothing until a row is picked, and its press keeps the editor’s focus; add(alt?, anchor?) does the same from your own code. Both attachments keep the ARIA of the menu they opened (aria-expanded, aria-controls, aria-haspopup) while it is open. beside says that Alt+click adds a column; name the buttons in your words after label. Placement beside the block’s first line and the hover fade are the plugin’s.

A drag’s drop indicator is placed by the plugin too, and painted by the theme: [data-edytor-drop-indicator] (the 4px bar where the blocks land) and [data-edytor-drop-backdrop] (the future parent’s row; data-shown while the drop nests). Without the theme, style them yourself, as below. See Block handles.

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

	const plugins = [createBlockHandlesPlugin({ handle })];
</script>

{#snippet handle({ label, grip, plus, readonly }: BlockHandleSnippetPayload)}
	{#if !readonly}
		<button class="add" aria-label={`Add a block below ${label}`} {@attach plus}>+</button>
		<button class="grip" aria-label={`${label} block`} {@attach grip}>⠿</button>
	{/if}
{/snippet}

<Edytor {plugins} />

<style>
	:global([data-edytor-drop-indicator]) {
		background: rgba(35, 131, 226, 0.43);
	}
</style>

Marquee rectangle

box draws the rectangle of the marquee while it selects blocks (without it, the blocks are selected and no rectangle shows). It renders in the plugin’s host, which the plugin places and sizes to the rectangle (it takes no pointer), so fill it. It receives a MarqueeBoxPayload: rect (the rectangle in viewport coordinates, a DOMRectReadOnly), count (the blocks selected, the ones Shift or Mod kept included), ids (theirs) and adding (Shift or Mod was held at the press). The gesture, the selection, the keys and the auto-scroll stay the plugin’s; the rectangle has no keyboard or ARIA of its own (the selected blocks are the editor’s selection).

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

	const plugins = [createMarqueePlugin({ box })];
</script>

{#snippet box({ count, adding }: MarqueeBoxPayload)}
	<div class="band" class:adding>{count || ''}</div>
{/snippet}

<Edytor {plugins} />

<style>
	.band {
		width: 100%;
		height: 100%;
		border: 1px solid #2383e2;
		background: rgba(35, 131, 226, 0.1);
	}
	.band.adding {
		border-style: dashed;
	}
</style>

Controls inside blocks

The controls inside a few kinds are different: they belong to the block’s content, so the package draws them by default, and each takes your snippet instead. One option per control, typed by an exported payload, written the way a menu is: it carries the control’s state, its action (which still writes through the document, or reaches your callback), the words and URLs it reads, which you render, and an attachment for your element, {@attach payload.control} (a media link’s {@attach payload.link}): its marker, its ARIA, the press that keeps the caret and the click that runs the action. The kind keeps its element, its void wrapper and when the control shows.

A readonly view can be server-rendered: only what your markup renders is in that HTML, and the attachment adds the rest in the browser. Render what a reader needs before the page runs (a link’s href, the words), as the default markup does.

Control Option Receives
A to-do’s checkbox createRichTextPlugin({ checkbox }) TodoCheckboxPayload
A callout’s icon createRichTextPlugin({ calloutIcon }) CalloutIconPayload
An empty body’s hint createRichTextPlugin({ emptyBody }) EmptyBodyPayload
An empty equation, an unreadable one createEquationPlugin({ placeholder, error }) EquationPlaceholderPayload, EquationErrorPayload
A bookmark’s card createBookmarkPlugin({ card }) BookmarkCardPayload
A file’s row createFilePlugin({ row }) FileRowPayload
An embed no provider plays createEmbedPlugin({ fallback }) EmbedFallbackPayload
A table of contents’ entries, its empty text createTocPlugin({ entry, empty }) TocEntryPayload, TocEmptyPayload
A page block’s link createPagePlugin({ link }) PageBlockLinkPayload

Each plugin’s page has the payload and an example: rich text, equations, bookmark, file, embed, table of contents, page. The block content itself (the text, KaTeX’s drawing, the image, the players, the embed’s frame, the table’s grid) stays the package’s: restyle a kind’s whole markup through its snippet instead (Restyling a kind).

Was this page helpful?