@3kles/richtext-extensions
v1.4.1
Published
Rich-text commands and an extension registry for the native engine, independent of the DOM and Angular. This ESM package exposes an experimental API for the native JSON v1 profile. Its runtime dependencies are `@3kles/richtext-core`, `@3kles/richtext-tran
Keywords
Readme
@3kles/richtext-extensions
Rich-text commands and an extension registry for the native engine, independent of the DOM and Angular. This ESM package exposes an experimental API for the native JSON v1 profile. Its runtime dependencies are @3kles/richtext-core, @3kles/richtext-transactions, and @3kles/richtext-selection. The browser editor coordinates @3kles/richtext-history and reserves its basic commands.
createCoreExtensions() supplies the paragraphs, headings, basic-marks, links, lists, blockquotes, and code-blocks groups. createExtensionRegistry([]) creates an empty registry. Adding an extension registers its commands, shortcuts, and hooks. The browser editor uses the preset when extensions is omitted and honors the exact list when it is provided.
import { createCoreExtensions, createExtensionRegistry } from '@3kles/richtext-extensions';
const registry = createExtensionRegistry(createCoreExtensions());
const available = registry.canExecute(state, 'setHeading', { level: 2 });
const active = registry.isActive(state, 'heading2');
const plan = registry.planCommand(state, 'setHeading', { level: 2 });
// The session applies the plan with baseRevision: state.revision and manages its history.The pure functions planRichTextCommand, canExecuteRichTextCommand, and isRichTextCommandActive take the RichTextCommand union. The registry exposes its discriminants as command names and takes their fields as arguments. Pass { mark: { type: 'bold' } } to setMark, { href, title? } to setLink, and { listType, start? } to toggleList. Commands without arguments accept undefined.
Convenience aliases include bold, italic, underline, strike, code, paragraph, heading (level 2 by default), heading1 through heading6, codeBlock, blockquote, bulletList, and orderedList. Other commands include clearFormatting, unsetMark, unsetLink, extendLinkSelection, indentListItem, outdentListItem, splitListItem, exitEmptyListItem, and backspaceListBoundary. insertContentTransaction plans insertion of a validated native document at the current selection.
Define the types for custom options and arguments when you declare the extension. The registry verifies incoming unknown values at its boundary.
import { compareTextPoints } from '@3kles/richtext-core';
import { defineExtension, defineExtensionCommand } from '@3kles/richtext-extensions';
const signature = defineExtension({
name: 'signature',
options: { text: 'Kind regards' },
validateOptions: (value): value is { readonly text: string } =>
typeof value === 'object' && value !== null && 'text' in value && typeof value.text === 'string',
configure: (options) => ({
commands: [
defineExtensionCommand<{ suffix: string } | undefined>({
name: 'insertSignature',
validateArgs: (value): value is { readonly suffix: string } | undefined =>
value === undefined ||
(typeof value === 'object' &&
value !== null &&
'suffix' in value &&
typeof value.suffix === 'string'),
plan: (state, args) => {
const selection = state.selection;
if (selection.kind !== 'range' || compareTextPoints(selection.anchor, selection.focus) !== 0)
return undefined;
return {
steps: [{ type: 'insertText', at: selection.focus, text: options.text + (args?.suffix ?? '') }],
};
},
}),
],
keymaps: [{ shortcut: 'Mod-Shift-s', command: 'insertSignature' }],
}),
});The registry copies and deeply freezes configuration data, JSON options, and arguments. Options consist of finite, acyclic plain data. The registry rejects accessors, class instances, symbols, hidden properties, sparse arrays, and functions in those data values. Callbacks run as trusted JavaScript without a sandbox. The extension contract requires them to be pure and avoid mutating their closures.
Higher priorities run first, and ties follow declaration order. The registry rejects duplicate extension names, commands, and schema references across all priorities and reports conflicts in ExtensionConfigurationError.issue during creation. Names are case-sensitive. The browser editor reserves undo, redo, selectAll, insertText, insertParagraph, insertHardBreak, deleteBackward, deleteForward, deleteWordBackward, and deleteWordForward.
canExecute, isActive, and planCommand(state, name, args, { quiet: true }) query the registry without reporting errors, emitting events, running lifecycle hooks, or dispatching transactions. Planning validates a candidate against the immutable state and returns an owned, frozen plan. The session then applies the plan to the current revision. Planning, dispatch, and native command validation incur a cost that has yet to be qualified against a performance budget. The ordinary planCommand reports planning errors through onError and isolates exceptions raised by that callback. Planning returns undefined for unknown or unavailable commands.
Shortcut strings include Mod-b, Mod-Shift-8, and Mod-Alt-2. Mod means Meta on macOS and Ctrl on Windows and Linux. Shortcuts also accept Ctrl, Meta, Shift, Alt, and their common aliases. Modifiers must match exactly. The registry detects conflicts after normalization across all three platforms. Digits fall back to KeyboardEvent.code = DigitN on layouts where Shift or Alt produces a symbol. Ambiguities between a symbol and that fallback prevent the shortcut from matching. Composition and AltGraph are excluded. resolveShortcut(event, platform) returns a command name with undefined arguments. Binding a command that requires arguments needs a wrapper that accepts none. The browser editor checks explicit keymaps before its basic shortcuts, so an extension can bind Mod-z to its own command with a distinct name from the reserved undo.
Call create({ getState, dispatch? }) once, transaction(commit) after each accepted commit, and destroy() for idempotent cleanup. onCreate can return a cleanup function. The registry queues reentrant notifications with a bound. The session must reject reentrant dispatch during a commit. Cleanup functions and then onDestroy run in reverse order and isolate errors. Destruction disables commands and releases callbacks, hooks, and the reporter. Public name metadata remains available. The package is independent of browser listeners and resources.
schema.nodes and schema.marks declare the extension's references to types already present in the native v1 profile. These declarations describe extension composition. Removing a group preserves the existing document and still lets callers use native steps and other generic commands. The registry rejects unknown types and custom parsing or rendering definitions. An extensible schema, its parsing and rendering metadata, serialization, and renderers require a future versioned contract.
The tests alongside the source cover configuration, immutable data, stable order, conflicts, shortcuts, silent capability queries, atomic plans, lifecycle, error isolation, and preset commands. Tests for pure commands cover selections, structures, history, and generated properties. The workspace E2E suites cover DOM and keymap behavior and document their browser qualification limits.
