Skip to content

Creating extensions ​

Rector v2 uses immutable definitions. A definition is reusable configuration plus schemas and pure capabilities; mutable editor state is created by setup(), and mutable block state is created by runtime.create().

Block definition ​

ts
interface BlockPluginDefinition<Data> {
  readonly type: string
  readonly label: { key: string, fallback: string }
  readonly icon: string
  readonly styles?: readonly string[]
  readonly toolbox?: readonly ToolboxItemDefinition<Data>[]
  readonly schema: BlockDataSchema<Data>
  readonly capabilities?: BlockCapabilities<Data>
  setup(context: BlockPluginRuntimeContext): BlockPluginRuntime<Data>
}
MemberMeaning
typeStable machine identifier persisted in documents.
labelLocalizable UI label key and fallback.
iconTrusted extension-owned icon markup.
stylesStyle URLs owned by the definition.
toolboxOptional insertion variants.
schemaVersioned canonical data contract.
capabilitiesPure optional behavior contracts.
setupCreates one per-editor runtime.

Translations ​

Block and inline setup() contexts expose t(key, fallback, params). Keys resolve under plugin.<type>.* or inlinePlugin.<type>.*. Pass an own enumerable numeric params.count to select a plural form, for example context.t('filesCount', 'files', { count: files.length }). English and Russian primary locales, including their regional tags, select their own grammar; other language codes use the existing English rule. English fallback entries retain English grammar. A string count and calls without a numeric count retain ordinary translation behavior.

Own enumerable interpolation values are captured once. Inherited values are ignored, and missing keys return the fallback without reading parameter getters. Empty translations and translations equal to their key are preserved; inserted parameter text is not interpreted as another template.

Runtime and block instance ​

BlockPluginRuntime has create(initial, context) and destroy(). Each create() returns one BlockInstance.

read() supplies current collection membership/order and control values. editableFields() lists only mounted fields; mapRichText() must enumerate every rich field, including hidden fields, under unique nonempty stable keys. Every returned editable field must be an HTMLElement inside that block instance's own root and in the editor's ownerDocument; text, comment, SVG and other non-HTML nodes cannot act as editable hosts. Referencing another block's field or an application's external DOM node rejects before any field address is registered. Mounted keys must be unique across modes, elements cannot be shared between keys, and every mounted rich field must exist in the candidate data. Invalid addressing rejects synchronization and restores the committed projection.

During DOM synchronization, mounted rich fields come from their DOM, hidden existing fields retain their committed canonical value (including empty strings), and new hidden fields retain their candidate value. Removed fields stay removed. Model-first updateData() can deliberately change hidden values. Flush pending DOM input with commitDomMutation(() => {}) before presentation controls unmount its field; never copy rendered widget labels into a canonical rich-text cache.

A BlockInstance exposes element, read(), optional update(next, previous), optional editableFields(), optional afterProjection(field), setReadOnly(readOnly), optional focus(target), and destroy(). The element must belong to the context's ownerDocument and be detached, with no parent, when returned by create(). It must be an HTMLElement in that document's realm; other node types (including comments, text nodes and SVG elements) are not valid block roots. Each simultaneously live block instance owns a different DOM root; returning an existing application node or a root still owned by another block is rejected.

BlockInstanceContext provides:

MemberUse
ownerDocumentCreate DOM and browser objects in the editor's realm.
signalLifetime signal for releasing this block occurrence's resources.
restoringCaptured at creation: true when reconstructing history or recovering failed projection. Later updates of that instance do not change the flag. Do not repeat automatic author-side metadata requests for restored snapshots; resources needed to display accepted content may still be acquired. Explicit user actions retain their current scoped authority.
getData()Read current canonical block data while the original block occurrence still owns its root and shell.
getFieldText(fieldKey)Read plain text of a canonical rich field declared by schema.mapRichText(), including an unmounted field.
updateData(producer)Commit a synchronous model-first block-data transaction.
beginTask()Start one revocable task for a persisted result from an active, editable scope in a healthy, idle runtime.
commitDomMutation(operation)Commit an unavoidable plugin-owned DOM mutation through canonical history.
requestSplit()Ask core structural editing to split the block.
requestExit()Ask core to exit an empty structured block.
isReadOnly()Reports effective read-only mode, revocation of this scope or destruction of the editing runtime.

The inherited createId(prefix) allocator creates nested stable identities.

isReadOnly() can become true before the lifetime signal aborts. Check it at UI entry and again after cancelling work that can call application code. beginTask() independently verifies the current phase, generation and parent scope. It throws AbortError when authority is unavailable and reports errors from protected phases of a live runtime. See the task example.

getData() validates that original block owner before reading and after capturing its immutable snapshot. Construction and update candidates may read their prospective data, and read-only blocks retain ordinary read access. A retained context cannot authorize a fresh asynchronous view update after its root or shell is adopted elsewhere. Report that failed read without retrying the same view write from the error handler.

Canonical text for unmounted fields ​

Use context.getFieldText(fieldKey) for auxiliary labels that need a rich field's canonical text before its author DOM is mounted. Person uses it for profile tabs. The query reads the same scoped record as getData(), including the prospective record during construction, update and history projection. It does not flush pending native input or create an editing field, widget instance, popup or provider request. An unknown field key throws; use a stable key declared by schema.mapRichText().

Registered inline definitions can supply a pure synchronous toText(data). The common rich-text parser substitutes that plain text for actual references and decodes HTML entities once. Unknown definitions, definitions without toText, unmatched tokens and explicit literal tokens retain their token text. A returned widget string is inserted as text without another HTML parse or placeholder scan.

A successful query opts the current block instance into its existing update(next, previous) when canonical inline data changes. next and previous block data may be equal in that case; recompute auxiliary labels while retaining unaffected author fields and native controls. An instance without update follows the existing replacement path. The query itself creates no transaction or history entry. Native source projection keeps its existing DOM/caret handling and field completion.

The query is protected synchronous extension work. Its inline callback receives an owned, deeply frozen decoded payload. It cannot acquire nested mutation, control or task authority. A stale occurrence, adopted block root or recursive query rejects before the extension callbacks; ownership is checked again after callbacks. Errors and thenables propagate to the current construction, canonical/history or mode recovery boundary.

Canonical text describes accepted payloads and a prospective projection, so it does not include a transient widget preview or mode-specific label. Use afterProjection below when auxiliary output depends on the actual completed mounted field. Only write to auxiliary nodes still owned by the block occurrence.

Derived presentation after a rich field settles ​

Implement optional synchronous afterProjection(field: EditableField): void when auxiliary presentation depends on the final visible text of a rich field. For example, an image's alternative text must include the rendered labels of its inline widgets. update() runs before that inline projection is complete; reading the caption there can still return canonical placeholders.

The editor captures the method once with its original instance receiver. It passes the frozen descriptor of the exact affected mounted rich field after attachment and inline hydration, before accepting a canonical change or history replay. This includes ordinary native author text: the changed source field completes while its DOM, widgets and caret are retained. An unchanged input notification adds no completion or history. Native inline normalization also delivers when final DOM changes but canonical data and history remain unchanged; successful finalization is not replayed just because the same source field is subsequently synchronized. Mode changes deliver after inline mode hooks and scope cancellation. A standalone field replacement or recovery delivers only fields actually projected; an untouched sibling or repeated field query does not deliver again. A discarded detached candidate never receives completion.

Use only the instance's captured, still-owned auxiliary nodes. This fragment belongs in the object returned by create(); caption, image, container and wrapper are exact nodes created for that occurrence:

js
afterProjection(field) {
  if (context.signal.aborted || field.key !== 'caption' || field.element !== caption) return
  if (caption.parentNode !== container || image.parentNode !== container || container.parentNode !== wrapper) return
  image.alt = caption.textContent?.trim() ?? ''
}

The callback may read the field and current public data, but must not rewrite author DOM, change canonical data/history, move focus, change mode, destroy the editor or start a data task. It is synchronous projection work, so a thrown value or thenable rejects the owning attempt. Canonical/native changes recover without adding history; a standalone failure disables only its failed field and preserves healthy fields. Repeated queries do not retry that failed completion. Recovery recomputes derived presentation; core does not promise to undo arbitrary auxiliary DOM writes made by a callback that then throws. Omit the method when it is unnecessary: no completion-specific DOM scan or callback is added for such an instance.

Schema ​

Payload generics use D extends object = object: ordinary interfaces do not need index signatures. Schemas, definitions, contexts/tasks and paired renderers accept the same interface type, including host insertion/update inputs. This typing does not relax JSON validation: root arrays, class instances, cycles, undefined properties and nonfinite numbers still reject.

Schema/capability hooks, setup(), create() and instance methods must complete synchronously. Promise/callable-thenable results and throwing then getters fail at their owner; projection changes recover before canonical commit. Void hooks may return ignored synchronous values. Keep asynchronous persisted work in beginTask(); declared paste resolvers retain their asynchronous contract. Lifecycle cleanup revokes authority first and contains failures without skipping independent cleanup.

BlockDataSchema owns currentVersion, createDefault(), exact-version decode(), encode(), and optional mapRichText().

Decode external input once at the boundary. Encode every model-first update before commit. mapRichText() identifies every HTML-bearing field by a stable logical field key; it is also the boundary used by inline widgets, structural selection and partial conversion.

Capabilities ​

BlockCapabilities can contain empty, formatting, merge, conversion, htmlImport, clipboard, selectionSlice, inlineControls, settings, paste, and shortcuts.

  • empty.isEmpty(data) defines structural empty-block behavior.
  • formatting.inlineTools is true or an allowlist.
  • merge.merge(target, source, context) is a pure data merge. The optional context.ownerDocument supplies the editor's DOM realm for rich-text checks.
  • conversion exports/imports neutral ConversionPayload. Its selectionMode controls cross-block conversion: 'single' (the default) replaces the selected interval with one default target; 'per-block' imports each selected source fragment separately. Caption import does not imply text-style grouping. Both modes preserve unselected endpoint data and use one Undo action. Declare 'per-block' only when each fragment is meaningful as an independent target; unsupported imports reject before mutation. The host supplies conversion.import(payload, { ownerDocument }) when invoking an importer; the second argument is optional in the public type for pure non-DOM importers. Rich-text importers should use the supplied owning document to decode markup instead of treating HTML tags as literal text or using the global document. A single target may declare joinSelection(payloads, { ownerDocument }) to aggregate the selected author content before import. Code uses this hook to create one block with decoded text and line breaks. The registry snapshots the method; core validates the result and rejects inline-widget loss before any mutation. Already matching text owners retain their local fields, metadata and identities rather than being re-imported through neutral text.
  • selectionSlice.slice(...) describes partial structured selection without mutating DOM.
  • inlineControls reuses model-first settings actions inside the inline toolbar.
  • settings is either an actions capability or a model-first panel.

Settings and inline-control action apply() receives createId() and the UI's ownerDocument. Use that document to parse rich-text fields in their owning realm. The document is optional in the type for direct pure-data calls; host UI always provides it. Direct data operations without a DOM retain literal-string joining. The host UI also supplies getFieldText(fieldKey) to read the current record's rich-text field as plain text, including registered inline widget labels. Call it synchronously within apply().

  • htmlImport.matchesRoot/importRoot synchronously imports one safe structural HTML root into local current data for that block type; it must consume the whole root and have no side effects. Optional inlineWhenSingleRoot: true lets the importer opt into replacing a selected rich-text range when that root is the sole content in the clipboard. The default is false, so third-party importers keep their block semantics. The flag is captured and validated at registration; multi-root imports remain structural.
  • ClipboardCapability (clipboard.slice(data, context)) lets a composite block return exported parts, the canonical remaining value after Cut, and an optional focus. context.field(key) exposes only actually selected rich-text intervals (before/selected/after/whole). Export and remaining come from the same pure capability, so core never guesses the block's data shape.
  • paste routes only text/file inputs to block or rich-text results; structural HTML is not passed to it.
  • shortcuts returns structural/model actions to the single core keyboard router.

Shortcut decisions run under the shared preparation guard with detached input/data, captured canonical rich fields and one mounted field-length table. splitField() keeps that captured text even if the callback is retained; fieldLength() returns zero for missing/unmounted fields. Allocation uses the session allocator. Return null for generic handling, native for owned native handling, or consume to cancel without an edit. update, exit and focus cancel native default before application. A thrown/invalid/thenable result or failing accessor cancels the owned key and reports the error without generic/native fallback.

Settings, paste and shortcuts ​

SettingsActionCapability has kind, actions(data, context), and apply(data, actionId, context). Its optional localized label names the group in the inline toolbar; actions with a boolean active expose their selected state as radio menu items.

SettingsPanelCapability has kind: 'panel' and render(context); its context exposes getData() and updateData(). The context belongs to that panel and mounted block instance. Closing the panel, replacing its owner, entering read-only mode, destruction, or a failed factory revokes it permanently: retained producers are not invoked, and getData() returns only its last owned snapshot.

HtmlImportCapability has matchesRoot(element), importRoot(element, context), and optional inlineWhenSingleRoot: boolean. Its context exposes ownerDocument, createId(), and serializeRichText(element) using the normal rich-text codec. The built-in Paragraph importer opts in to v1's single-paragraph inline Paste; custom importers must opt in explicitly or their prepared block remains authoritative. Core sanitizes and plans the complete HTML input first; if any accepted root fails, the entire import is rejected before mutation.

PasteCapability has accepts(input) and resolve(input, context) for text/file input only. The resolver receives AbortSignal, ownerDocument, createId() and createObjectURL(file). Use the latter for local blob-backed media (such as pasted videos) instead of calling the global URL API: the clipboard transaction revokes uncommitted URLs after cancellation/failure and retains committed URLs for Undo/Redo until editor disposal. Object URLs are temporary; persist videos through an application uploader to support reload.

ClipboardCapability.slice(data, context) receives the owning ownerDocument alongside field slices and ID allocation. Use that DOM realm when distinguishing visible text from empty HTML residuals; a Cut should not leave a block containing only empty formatting marks. ShortcutCapability has one handle(input, data, context) method. Its context provides the editor's ownerDocument as well as createId(), fieldLength() and splitField(); use that document when evaluating rich-text HTML (including visually empty markup), never the ambient global document. Return native, consume, exit, focus, or update; core owns the structural transaction.

Its context provides createId(), splitField(fieldKey, range), and fieldLength(fieldKey). Field lengths use logical UTF-16 units, with one unit per line break or atomic widget. Use the original target field length to keep a merge caret at the join rather than the end of the merged text. An update action returns block data plus an optional focus target; core records that target for Undo/Redo. An exit action without data converts the current block to the default type. With data, it updates the retained block and inserts a default block immediately after it as one history entry; list-like tools use this to exit their last empty item.

SelectionSliceCapability has slice(data, start, end, context) and returns before, a neutral selected payload, and after.

Its optional split(data, start, end, context) owns Enter across different rich fields within the same block. It returns { data, focus: { fieldKey, offset } }, or null to use the default block split. The synchronous preparation context provides ownerDocument, createId() and sliceField(); core validates the returned data and focus and commits one history action. List and Checklist preserve the unselected endpoint item IDs and focus the surviving suffix, without adding a default block below them. sliceField() also supplies the original logical field length. Item selection slicing uses that boundary to discard empty formatting wrappers at fully selected edges; authored breaks and unselected empty items remain. The length property is optional for compatibility with older independently supplied contexts.

Minimal definition ​

js
export function createCalloutPlugin() {
  const schema = Object.freeze({
    currentVersion: 1,
    createDefault: () => ({ text: '' }),
    decode({ dataVersion, data }) {
      if (dataVersion !== 1) throw new RangeError('Unsupported callout dataVersion')
      if (!data || typeof data.text !== 'string') throw new TypeError('Invalid callout')
      return { dataVersion: 1, data: { text: data.text } }
    },
    encode(data) {
      if (typeof data.text !== 'string') throw new TypeError('Invalid callout')
      return { dataVersion: 1, data: { text: data.text } }
    },
    mapRichText(data, transform) {
      return { ...data, text: transform(data.text, 'text') }
    },
  })

  return Object.freeze({
    type: 'callout',
    label: Object.freeze({ key: 'title', fallback: 'Callout' }),
    icon: '<svg viewBox="0 0 24 24">...</svg>',
    styles: Object.freeze([new URL('./callout.css', import.meta.url).href]),
    schema,
    capabilities: Object.freeze({
      formatting: Object.freeze({ inlineTools: true }),
      empty: Object.freeze({ isEmpty: data => data.text.trim() === '' }),
    }),
    setup() {
      return {
        create(initial, context) {
          const element = context.ownerDocument.createElement('aside')
          element.contentEditable = context.isReadOnly() ? 'false' : 'true'
          element.textContent = initial.text
          return {
            element,
            read: () => ({ text: element.innerHTML }),
            editableFields: () => [{ key: 'text', element, mode: 'rich-text' }],
            setReadOnly(value) { element.contentEditable = value ? 'false' : 'true' },
            focus() { element.focus() },
            destroy() {},
          }
        },
        destroy() {},
      }
    },
  })
}

Ownership rules ​

Definitions are immutable and reusable. Per-editor timers, caches and subscriptions belong to BlockPluginRuntime; per-block listeners, observers, requests and object URLs belong to BlockInstance and its signal.

Keep persisted data in the model. Synchronous controls call updateData(), and core reconciles native editable-field input. For asynchronous work that changes persisted data, acquire a task with beginTask(), pass task.signal to the external operation and finish with task.commit(current => next). The producer runs only with current instance authority and receives the latest committed data. Replacement, destruction, a generation change or entry into read-only mode revokes the task permanently. Call the idempotent cancel() in finally. Presentation-only requests can use the instance's lifetime signal.

For an asynchronous result that completes the immediately preceding edit of the same data field, a plugin may explicitly call task.commit(producer, { mergeWithPreviousField: 'url' }). The task captures its starting canonical revision. Core joins the completion to that Undo step only if no other edit or history replay intervened and the preceding transaction actually changed the named field. A change that does not meet these conditions creates its own history step. The task's usual revocation checks still apply.

Renderer pairing ​

A new persisted block type should have a read-only renderer with the same type/schema semantics. Renderer DOM is independent from editor BlockInstance DOM.

Rector is released under the MIT License.