Skip to content

Rendering documents ​

EditorRenderer converts saved Rector documents into DOM without mounting editing controls, history, selection, or toolbars. Use it for article pages, previews, exports, and any view that only needs the document result.

Follow the v2 installation steps in Getting started.

The synchronous entry imports the full built-in renderer preset and its Carousel, Expose, and Masonry dependencies. blockTypes selects which renderer instances to construct from that preset.

Basic usage ​

js
import { EditorRenderer } from '@shelamkoff/rector/renderer'

const renderer = new EditorRenderer({ theme: 'dark' })
renderer.renderTo(documentData, document.querySelector('#article'))

// When the view is removed:
renderer.destroy()

The renderer accepts the current document returned by editor.save() directly. The document version: '2.0.0' and blocks are required; every block needs a unique non-empty id, type, exact dataVersion, and valid plugin data. Only time is optional. See Document format for the complete contract.

Configuration ​

ts
interface RendererConfig {
  injectStyles?: boolean
  contentStyles?: readonly string[]
  classPrefix?: string
  throwOnUnknown?: boolean
  theme?: 'dark' | 'light' | 'graphite'
  onValidationError?: (issue: { readonly blockId?: string; readonly type: string; readonly reason: 'unsupported-document-version' | 'unsupported-data-version' | 'invalid-input' | 'invalid-data' }) => void | Promise<void>
  locale?: Record<string, LocaleValue>
  blockTypes?: BlockType[]
  blockConfigs?: {
    poll?: PollRendererConfig
    [type: string]: unknown
  }
  inlineRenderers?: InlineWidgetRenderer[]
}
OptionDefaultMeaning
injectStylestrueautomatically load base and registered-renderer styles on first render
contentStyles[]copied application-owned CSS text for rich text, derived author views, Raw and HTML Carousel content; independent of automatic UI styles
classPrefixeditornamespace used by generated renderer classes
throwOnUnknowntruethrow for an unregistered block instead of rendering a placeholder
themedarkchoose graphite to match the editor, or select light or dark
onValidationErrornonereceive an immutable, content-free { blockId?, type, reason } notice for invalid registered block data
localebuilt-in Englishflat renderer.* message dictionary
blockTypesall built-insconstruct only selected built-in renderers
blockConfigsnoneruntime configuration keyed by built-in block type
inlineRenderersnoneread-only inline widget projections validated through the same widget schemas as the editor

InlineWidgetRenderer.schema is the same versioned inline-widget schema used by the editor definition. The renderer decodes and validates the canonical payload through that schema before calling InlineWidgetRenderer.render(); unknown, malformed, or unsupported widget data is never activated as markup.

Every registered block renderer is likewise a BlockRendererDefinition with a schema. Built-in definitions are bound to the exact BlockDataSchema used by the matching editor plugin, so the current dataVersion, validation, and rich-text field traversal have one source of truth.

At registration, Rector reads each schema member once and captures its version and methods with their original receiver. Later method replacement does not change the registered contract; the application still owns mutable receiver state. Every decoded result must preserve the exact version and contain JSON object data. Inline style lists are also copied at registration.

The default fails explicitly when a renderer is missing. Set throwOnUnknown: false only when the host intentionally accepts an inert placeholder for an unregistered current-format block. The placeholder has the class <classPrefix>-unknown and a data-block-type attribute; it does not reproduce the missing content.

Before any registered renderer runs, Rector validates the current block envelope and exact dataVersion, then decodes the block through that renderer definition's schema. Malformed data or a version mismatch calls the content-free onValidationError observer and throws InvalidBlockDataError; it is never converted into an inert known block. onValidationError may return a Promise; synchronous throws and rejected Promises are isolated from rendering and do not change rejection. Custom renderers must provide an exact-version schema, so replacing a built-in renderer cannot bypass validation.

blockConfigs.poll accepts the same dataSource, compareRevisions, onError, and maxVoters runtime options as the Poll editor plugin. onError may return a Promise; callback failures are isolated from renderer state. compareRevisions(next, current) must return a positive value only when next is newer; without it, unequal opaque revisions follow arrival order. The renderer loads and subscribes to current results without changing the supplied document. Call destroy() to abort requests and unsubscribe.

TypeScript contracts ​

Import runtime values from @shelamkoff/rector/renderer. Document and built-in data contracts are shared by editing and rendering through @shelamkoff/rector/types; renderer-specific contracts have their own type-only entry:

ts
import { EditorRenderer } from '@shelamkoff/rector/renderer'
import type {
  EditorOutputData,
  EditorBlockData,
  EditorInlineWidget,
  ParagraphBlock,
} from '@shelamkoff/rector/types'
import type {
  BlockRenderer,
  BlockRendererDefinition,
  RendererConfig,
  InlineWidgetRenderer,
} from '@shelamkoff/rector/renderer/types'

The shared type entry exports the canonical document envelope EditorOutputData, generic block EditorBlockData, and inline record EditorInlineWidget. It also exports Block, BlockType, and the payload/item types and named block aliases for all 21 built-ins, including ParagraphBlock, ImageBlock, PollBlock, GalleryData, CarouselData, and PersonData. The neutral data types introduce no runtime editor dependency.

editor.save() returns EditorOutputData, which can be passed directly to renderer.render() or renderer.renderTo(). Use a named block alias for a known built-in payload or EditorBlockData<'callout', CalloutData> for an application-defined type. EditorOutputData<ParagraphBlock> can describe a document restricted to paragraphs; the generic default also supports custom block types.

The renderer type entry exports BlockRenderer, schema-bound BlockRendererDefinition, InlineParser, RendererContext, InlineWidgetRenderer, and RendererConfig. Poll callbacks and renderer options remain here as PollDataSource and PollRendererConfig; canonical initial/result data (PollData, PollResults, PollVoter) comes from the shared type entry.

When updating existing imports, use the canonical names below. These former aliases are removed from the current API:

Former typeCurrent type in @shelamkoff/rector/types
EditorDocument, renderer OutputDataEditorOutputData
renderer OutputBlockData<T, D>EditorBlockData<T, D>
renderer InlineWidget<T, D>EditorInlineWidget<T, D>
renderer built-in types such as ParagraphBlockSame name in the shared type entry

Rendering methods ​

renderBlock(block) returns one block element or follows the unknown-block policy. The returned element is owned by this renderer instance; release it with renderer.destroy(element) before discarding it.

render(data) returns a wrapper containing all rendered blocks. The caller chooses where to mount it, while the renderer retains cleanup ownership; release that result with renderer.destroy(wrapper).

renderTo(data, container) replaces renderer-owned output in a container and records the mounted block elements for later cleanup.

js
const wrapper = renderer.render(documentData)
preview.replaceChildren(wrapper)

Prefer renderTo() for a container that will be updated repeatedly because its cleanup ownership is explicit.

Incremental updates and block revisions ​

renderTo() matches blocks by stable id and current order. An unchanged block keeps the same DOM element and renderer-owned resources; a changed block alone is replaced. Re-registering or unregistering a renderer invalidates reuse for that block type.

When a block has no revision, Rector compares a deep signature of its type, data, tunes, and inline values. A producer that already maintains an authoritative content revision or stable hash may supply it as block.revision. Rector then compares that value in constant time instead of serializing the block data:

js
const block = {
  id: 'intro',
  revision: 'sha256:9f4c…',
  type: 'paragraph',
  dataVersion: 2,
  data: { text: 'Hello' },
}

Use a string or finite number for revision, and change it whenever data, tunes, or inline changes. Reusing a revision for different content deliberately tells the renderer that the block is unchanged. The editor preserves an incoming revision while the block remains untouched and removes it after the first local mutation because it cannot mint the producer's next revision.

Registering renderers ​

Built-in renderers are registered by default. A custom registration must bind rendering to a canonical schema:

js
renderer.registerRenderer({
  type: 'callout',
  schema: calloutDataSchema,
  render(block, parseInline, context) {
    const element = context.ownerDocument.createElement('aside')
    element.append(parseInline(block.data.text))
    return element
  },
})

renderer.hasRenderer('callout')       // true
renderer.getRegisteredTypes()         // string[]
renderer.unregisterRenderer('callout')

The schema is mandatory and is evaluated before render(). Registering the same type replaces the previous renderer for future output.

A block renderer must return a fresh HTMLElement in context.ownerDocument for each live result. The element must be disconnected when returned; do not borrow an element already mounted elsewhere in the application. Reusing one element across blocks or renderer instances is rejected; a renderer-owned result can be reused only after its previous result has been destroyed. If decorating the returned element fails, its destroy(element) hook releases the created resource. Release already mounted output before removing a renderer whose destroy(element) method owns resources.

Loading only used block types ​

For a smaller initial graph, create plugins and renderers from a document or explicit type list through asynchronous entry points.

js
import { createBlockPluginsAsync, loadBlockPluginDefinition } from '@shelamkoff/rector/plugins/async'
import { createDefaultRenderersAsync } from '@shelamkoff/rector/renderer/renderers/async'

const plugins = await createBlockPluginsAsync(documentData)
if (!plugins.some(plugin => plugin.type === 'paragraph')) {
  plugins.unshift(await loadBlockPluginDefinition('paragraph'))
}
const renderers = await createDefaultRenderersAsync('oe', {}, documentData)

The Paragraph definition supplies an editable default for an empty document or a document containing only non-text blocks. With a document input, the helpers select built-in types. Register any custom extensions separately. With an explicit list of types, an unknown name rejects the request.

Inline formatting and widgets ​

Every block renderer receives parseInline(text). It sanitizes supported inline markup and returns a DocumentFragment; append the fragment instead of assigning innerHTML.

Persistent widgets use an InlineWidgetRenderer with type, the same canonical widget schema as the editor extension, and render(id, data, context). Each call must return a fresh, detached HTMLElement belonging to context.ownerDocument. Returning connected, previously parented, foreign-document, or reused nodes is rejected so an inline projection cannot steal another UI's content.

HTML-bearing block fields are traversed by BlockDataSchema.mapRichText(). Rector therefore expands {{id}} placeholders through the same field map used by the editor instead of maintaining a second renderer-specific field contract.

Styles ​

With the default injectStyles: true, the first render automatically acquires the deduplicated base and registered-renderer stylesheet URLs. Destroying the last owned result or calling a full renderer.destroy() releases that automatic owner. getStyleUrls() exposes the URLs, and injectStyles() remains available for explicit preloading; it returns an independent release handle.

js
import '@shelamkoff/rector/styles/renderer.css'
import '@shelamkoff/rector/renderer/renderers/gallery/styles.css'

const renderer = new EditorRenderer({
  blockTypes: ['gallery'],
  injectStyles: false,
})
renderer.renderTo(documentData, container)

Do not import editor UI CSS for output-only content. Bundler-managed mode uses @shelamkoff/rector/styles/renderer.css plus each selected renderer/renderers/<type>/styles.css subpath. The all-in-one @shelamkoff/rector/styles.css is also available when bundle size is not a concern.

Cleanup ​

destroy(target) accepts a container previously passed to renderTo(), a wrapper returned by render(), or an element returned by renderBlock(). It invokes the owning block renderer's optional destroy(element), empties renderer-owned output, and forgets that result. destroy() without an argument releases every result owned by the instance.

Cleanup does not remove a container supplied by the application. It releases renderer-owned observers, listeners, and third-party instances and forgets the mount. Automatic styles are released when no owned result remains. A separate handle returned by an explicit injectStyles() call has its own lifetime and must still be released with its own destroy().

Security boundary ​

Renderer input may come from storage or another service and remains untrusted. Built-in renderers use the shared sanitizers for HTML, URLs, and styles. A custom renderer must use textContent, parseInline(), safe attribute setters, and explicit allowlists. Never assume that content was safe because it previously passed through an editor.

See the renderer catalog for exact block data and feature-specific dependencies.

Rector is released under the MIT License.