Writing plugins
The full plugin contract, every definition field and hook with its payload, and how to type snippets in your own plugins.
This page lists everything a plugin can return and when each hook runs. The operation hooks, which see and can veto every edit, have their own page: Operations. For a complete plugin built from these pieces, see Example plugin.
The contract
import type { Plugin } from 'edytor';
export const myPlugin: Plugin = (edytor) => {
// Runs once, when the editor is created. Keep plugin state here.
return {
blocks: {},
marks: {},
inlineBlocks: {},
hotkeys: {},
commands: [],
onBeforeOperation: (change) => {},
onChange: (value) => {}
};
};
Definitions
blocks?Record<string, BlockDefinition | Snippet>
Block kinds by type name. A bare snippet is shorthand for { snippet }. See Blocks.
Record<string, BlockDefinition | Snippet>marks?Record<string, MarkDefinition | Snippet>
Text marks by name. A bare snippet is shorthand for { snippet }. See Marks.
Record<string, MarkDefinition | Snippet>inlineBlocks?Record<string, InlineBlockDefinition | Snippet>
Inline atoms by type name. See Inline blocks.
Record<string, InlineBlockDefinition | Snippet>hotkeys?Partial<Record<HotKeyCombination, HotKey>>
Key bindings such as 'mod+shift+k'. See Hotkeys.
Partial<Record<HotKeyCombination, HotKey>>commands?EditorCommand[]
Named commands. The slash menu lists them next to the block kinds.
EditorCommand[]placeholder?string | ((view) => string | null)
Text shown in empty blocks; the first plugin that declares one wins. See Placeholder.
string | ((view) => string | null)Input rules and triggers are wired into the plugin’s own hooks: return withRulesAndTriggers(edytor, definitions, { inputRules, triggers }) (Input rules and triggers).
Hooks
onBeforeOperation?(change) => payload | void
Before every edit, on the command and each step it plans. Can veto, replace or rewrite it.
(change) => payload | voidonAfterOperation?(change) => void
Once per command, after it was written.
(change) => voidonChange?(value: JSONDoc) => void
After every commit that changed the visible document.
(value: JSONDoc) => voidonSelectionChange?(selection: EdytorSelection) => void
After the selection value changed.
(selection: EdytorSelection) => voidonEdytorAttached?({ node }) => (() => void) | void
When the editor element mounts. May return a cleanup.
({ node }) => (() => void) | voidonBlockAttached?({ node, block }) => (() => void) | void
When a block element mounts. May return a cleanup.
({ node, block }) => (() => void) | voidonTextAttached?({ node, text }) => (() => void) | void
When a text segment element mounts. May return a cleanup.
({ node, text }) => (() => void) | voidonBeforeInput?({ e, prevent }) => void
Before the editor performs a beforeinput it handles itself.
({ e, prevent }) => voidonCopy?({ e, prevent }) => void
Before the editor writes the clipboard on copy.
({ e, prevent }) => voidonCut?({ e, prevent }) => void
Before the editor writes the clipboard and deletes on cut.
({ e, prevent }) => voidonPaste?({ e, prevent }) => void
Before the editor imports external clipboard data or dropped files.
({ e, prevent }) => voidonDeleteSelectedBlocks?({ selectedBlocks, prevent }) => void
Before any gesture removes a block selection: Backspace or Delete (a word or line delete too), a cut, the block menu's Delete, or typing, a composition or a paste over it (Enter, Shift+Enter and a drop remove nothing, so they never run it).
({ selectedBlocks, prevent }) => voidThe prevent function
Every hook whose payload has prevent can stop what the editor was about to do. Hotkeys use the same function:
prevent()stops the default behavior. Nothing is written.prevent(() => { ... })stops it and runs your callback in its place.
prevent records the veto and returns: the rest of your hook still runs, so return after it when nothing else should happen. Within one hook the first call decides (a later prevent(cb) neither replaces its callback nor runs). The first plugin in list order that calls it wins; later plugins are not asked. The callback runs as a command of its own: if one of its edits is refused by another plugin, that edit is skipped and the callback continues.
A try/catch around prevent changes nothing, since it throws nothing. A hook that throws PreventionError itself (the earlier way to veto) still vetoes; PreventionError and isPrevention(error) are exported from edytor for that transition.
Lifecycle hooks
onEdytorAttached, onBlockAttached and onTextAttached run when the element mounts and may return a cleanup function, called when it unmounts. Anything else they return (nothing, a promise) is ignored. Use them to attach listeners or third-party libraries to the DOM.
import type { Plugin } from 'edytor';
export const anchorsPlugin: Plugin = () => ({
// Give every block element an id so it can be linked to.
onBlockAttached: ({ node, block }) => {
node.id = `block-${block.id}`;
return () => node.removeAttribute('id');
}
});
onEdytorAttached({ node })receives the contenteditable root. The overlay layer for your own chrome exists at this point asedytor.overlay.layer.onBlockAttached({ node, block })runs once per block element. An element is re-created when its tag changes or the block moves, and the hook runs again for the new one.onTextAttached({ node, text })runs for each text segment element, the span that holds a run of text between inline atoms.
Attributes you add to a block element are left alone. Do not add or remove nodes inside the text elements: the editor restores the DOM it owns. See Styling.
Change and selection hooks
import type { Plugin } from 'edytor';
export const statsPlugin: Plugin = () => ({
onChange: (value) => {
// value is the whole document: { type: 'root', data?, children: [...] }
localStorage.setItem('draft', JSON.stringify({ data: value.data, children: value.children }));
},
onSelectionChange: (selection) => {
console.log(selection.value.kind); // 'none' | 'text' | 'atom' | 'blocks'
}
});
onChange(value)runs after every commit that changed the visible document: local edits, remote edits and undo or redo.valueis the full JSON export, computed only when anonChangeconsumer exists. It is the same value the<Edytor onChange>prop receives.onDocChange(change)runs after the same commits with the change report (DocChange: the blocks added, removed, moved, retyped or edited) and exports nothing, so a plugin that reacts to some blocks pays for those only. The report is shared with every other consumer and view, so it is read-only. A hook that throws is logged and the other consumers still run, as foronChange.onSelectionChange(selection)runs after the selection value changed. A remote edit that only shifts where the selection is drawn does not trigger it.selectionis the editor’sEdytorSelection:selection.valueis the value,selection.projectionits blocks and offsets,selection.caretthe caret as{ block, offset }.
Input and clipboard hooks
These hooks receive the DOM event as e and a prevent function.
onBeforeInput runs for the beforeinput events the editor performs itself instead of letting the browser apply them: Enter and Shift + Enter, deletions that are not a simple edit inside one text, the formatting input types (formatBold and the others that browser menus and iOS send), insertLink, insertOrderedList, insertUnorderedList and insertHorizontalRule. It runs after the key bindings and before the editor’s own handling. The event’s default is already prevented, so prevent() means nothing happens unless your callback does something. Plain typing that the browser performs is not seen here: it reaches onBeforeOperation as an insertText operation. Paste and drop do not reach this hook; use onPaste.
onCopy and onCut run before the editor writes its clipboard data. prevent() stops the editor from writing anything and prevents the event’s default; write your own data in the callback with e.clipboardData.setData(...). A prevented cut also deletes nothing. Cut does not run in a readonly editor.
onPaste runs after the editor checked for its own fragment format (content copied from an Edytor pastes without asking plugins), and before it imports external HTML or plain text. Pasted files reach the editor only through this hook: unclaimed files insert nothing. The hook also runs for dropped files and HTML, with an e that carries only clipboardData; for files dropped from outside it also gets at, where the drop indicator showed them landing ({ block, position }). A Shift-paste of plain text skips it.
import type { Plugin } from 'edytor';
export const noFilesPlugin: Plugin = () => ({
onPaste: ({ e, prevent }) => {
if (e.clipboardData?.files.length) {
prevent(() => alert('Upload files with the media button.'));
}
}
});
onDeleteSelectedBlocks runs before any gesture removes a block selection, with the blocks that go, in document order. prevent() keeps them and refuses the gesture: nothing is inserted, a cut still writes the clipboard, and edytor.dispatcher.last reports refused.
- The gestures. Backspace or Delete (with Alt, Mod or Ctrl too: a word or line delete removes the blocks as a plain one does), a cut, the block menu’s Delete, and typing, a composition or a paste over the selection (each replaces the blocks with what it inserts).
- Not a removal. A drop over a block selection inserts at the drop point, and Enter or Shift+Enter leaves the selection for the caret at the end of the first selected block’s line, as in Notion (over selected dividers alone, it inserts a line after them): neither removes anything, so the hook does not run.
- The blocks named (
edytor.selection.selectedMembers): the selected blocks, a selected list or code block with its whole subtree (a closed toggle’s hidden body in it too); any other selected block’s unselected children stay, promoted into its place (Block selection). - Not named. An unselected container that shows no text of its own (a list) left with no child goes with them but is not named; a plugin that tracks containers reads the command’s
effect.removesinonBeforeOperation. A code block is an island: it stays even when all of its lines go.
To guard blocks against every command, including headless ones such as edytor.deleteBlocks, veto the operations whose effect.removes names them in onBeforeOperation (Refusing an edit).
For the clipboard formats and paste rules, see Clipboard.
Commands
commands adds named actions that menus can list and run. The slash menu shows every command next to the block kinds, sectioned by group.
import type { Plugin } from 'edytor';
export const todoCommandsPlugin: Plugin = () => ({
commands: [
{
id: 'todo.toggle',
label: 'Toggle to-do',
icon: '☑',
keywords: ['check', 'done'],
isEnabled: (edytor) => edytor.selection.caret?.block.type === 'todo-item',
run: (edytor) => {
const block = edytor.selection.caret?.block;
if (block) block.data.checked = !block.data.checked;
}
}
]
});
idstring
Unique id. The first plugin to register an id wins.
stringlabelstring
Shown in menus.
stringicon?string
A short text icon.
stringkeywords?string[]
Extra search terms.
string[]group?string
The menu section. The slash menu lists 'Basic blocks' first, then groups in first-seen order; a command without one gets no heading.
stringhint?string
A shortcut shown right-aligned in the slash menu row, such as '##' or '⌘D'.
stringisEnabled?(edytor) => boolean
Hide or disable the command. Read the selection from the edytor passed: a + menu passes a view of the block being added.
(edytor) => booleanrun(edytor) => unknown
The action. May be async.
(edytor) => unknownisEnabled hides the command wherever it answers false: the slash menu does not list it and edytor.runCommand(id) answers false without running it. Read the selection from the edytor it receives, not from an editor your plugin captured: the menu the block handle’s + opens asks it of the block being added, through an edytor whose selection.caret is at the start of that block, an empty block of the parent’s default kind (a stand-in with that type and the real parent, since the block does not exist yet). So todo.toggle above is not listed in a + menu: the block a + adds beside a to-do is a paragraph. A command that checks the parent (caret?.block.parent?.type === 'callout') is listed beside a callout’s children. See From the block handle.
Run a command by id with edytor.runCommand(id). Block kinds with presets generate commands too, see Blocks. See also Commands.
Typing snippets
The package exports the payload and instance types:
import type {
BlockSnippetPayload,
MarkSnippetPayload,
InlineBlockSnippetPayload,
EdytorInstance // the editor a plugin, hotkey or `bind:edytor` receives
} from 'edytor';
The UI plugins’ snippets have their own types (SlashMenuController, ToolbarController, BlockMenuController, BlockHandleSnippetPayload, …); see Menus and handles.