import { extendEditor, getFragment } from './core'; import { createEditorAnchorApi } from './core/anchor'; import { hasActiveAnchors } from './core/anchor-state'; import { authoredDocumentCapabilityPoint, type NativeAuthoredDocumentCapability, } from './core/authored-document-capability'; import type { DocumentChange } from './core/change/document-change'; import { createCommandDispatch } from './core/command-registry'; import { admitDocument, admitEditorDocument, documentAdmissionPoint, onlyDocumentAdmission, } from './core/document-admission'; import { assertNoDocumentViewRead } from './core/document-view-read'; import { createEditorReadApi, createEditorUpdateApi, } from './core/editor-lifecycle-api'; import { createEditorReadRuntime } from './core/editor-read-runtime'; import { type InternalPluginPublicationEntry, type InternalPluginRuntime, type InternalEditorRuntime, type InternalEditorSnapshotRuntime, type InternalEditorTransactionRuntime, getEditorSchema, setEditorRuntime, } from './core/editor-runtime'; import { createEditorSchema, type InternalEditorSchemaApi, } from './core/editor-schema'; import { createEditorViewPluginApis, destroyEditor, markEditorDormant, type PreparedEditorSchemaCompilation, prepareInitialPluginPublication, prepareScopedPluginPublication, setEditorLifecycleErrorSink, } from './core/plugin'; import { assertPluginPublicationInactive, createPluginRegistry, finalizePluginRegistry, getCompiledEditorSchema, getPluginContributions, getPluginRegistry, initializeBasePluginRegistry, registerEffectTypeInRegistry, } from './core/plugin-registry'; import { MAIN_ROOT_KEY } from './core/public-root'; import { getChildList, getChildren, getCurrentSelectionRoot, getEditorDocumentValue, getLastCommit, getLiveSelection, getPathByNodeKey, getNodeKey, getSnapshot, createTransactionSpec, applyTransactionSpecToDocument, initializeEditorSchemaSelection, initializeEditorSchemaDocument, initializeEditorSchemaSnapshot, invalidateEditorTransactionSpecs, initializePublicState, readEditor, repairEditorValue, saveEditorSchemaDocument, seedUniqueIndex, snapshotInitialDocumentState, subscribe, subscribeCommit, subscribeSource, transformEditorSnapshotInput, updateEditor, withEditorRootChildren, } from './core/public-state'; import { constructLoadedDocumentChange } from './core/representation'; import type { CompiledEditorSchema, EditorSchemaContract, } from './core/schema-compiler'; import { screenReaderAnnouncementEffect } from './core/screen-reader-announcement'; import { assertSelectionSupported, mapSelectionThroughChange, } from './core/selection-protocol'; import type { InternalEditorUpdateOptions } from './core/update-policy'; import type { AnyEditor, CreateEditorOptions, DescendantIn, Descendant, Editor, EditorKeyApi, EditorCommit, PluginInput, EditorSnapshot, EditorStateField, EditorStateView, EditorTransactionSpecBuilder, EditorUpdateContext, EditorUpdateTransaction, EditorValueFromPlugins, PluginsOf, SchemaPluginsOf, Location, SnapshotInput, ValueOf, Value, } from './interfaces'; import { assertEditorOptions, type CheckedEditorOptions, EDITOR_OPTION_KEYS, type UnknownEditorOptionTarget, } from './internal/editor-options'; let nextEditorId = 0; const PENDING_SCHEMA_BOOTSTRAP = new WeakSet(); const SCHEMA_BOOTSTRAP_DOCUMENT_CHANGED = new WeakSet(); const SCHEMA_BOOTSTRAP_CLEANUPS = new WeakMap void>(); const disarmSchemaBootstrap = (editor: AnyEditor) => { PENDING_SCHEMA_BOOTSTRAP.delete(editor); SCHEMA_BOOTSTRAP_DOCUMENT_CHANGED.delete(editor); SCHEMA_BOOTSTRAP_CLEANUPS.get(editor)?.(); SCHEMA_BOOTSTRAP_CLEANUPS.delete(editor); }; const armSchemaBootstrap = (editor: AnyEditor) => { PENDING_SCHEMA_BOOTSTRAP.add(editor); const cleanup = subscribeCommit(editor, (commit) => { if (commit.changes.empty) return; SCHEMA_BOOTSTRAP_DOCUMENT_CHANGED.add(editor); cleanup(); SCHEMA_BOOTSTRAP_CLEANUPS.delete(editor); }); SCHEMA_BOOTSTRAP_CLEANUPS.set(editor, cleanup); }; /** Plugin tuple inferred from a `createEditor` options object. */ export type PluginsFromOptions = TOptions extends { plugins: infer TPlugins extends readonly unknown[]; } ? TPlugins : readonly []; type ReadonlyJson = T extends (...args: any[]) => unknown ? T : T extends string ? string : T extends number ? number : T extends boolean ? boolean : T extends ReadonlyArray ? ReadonlyArray> : T extends object ? { readonly [TKey in keyof T]: ReadonlyJson } : T; type InitialValueFromOptions = TOptions extends { initialValue: infer TInitialValue; } ? ( TInitialValue extends { children: infer TChildren } ? TChildren : TInitialValue ) extends infer TChildren ? TChildren extends unknown[] ? TChildren extends Value ? TChildren : Value : ReadonlyJson extends infer V extends Value ? V : Value : Value : Value; /** Editor value inferred from installed schema or initial data. */ export type EditorValueFromOptions = [ SchemaPluginsOf>, ] extends [never] ? InitialValueFromOptions : EditorValueFromPlugins>; const createEditorId = () => `editor-${(nextEditorId += 1)}`; const publishInitialPlugins = ( editor: TEditor, input: PluginInput | readonly InternalPluginPublicationEntry[], explicitInitialDocument: boolean, options: Readonly<{ initialize?: ( transaction: EditorTransactionSpecBuilder< ValueOf, PluginsOf > ) => void; initialValue?: () => SnapshotInput>; }> = {}, compiledEntries = false ) => { if (hasActiveAnchors(editor)) { throw new Error( 'Editor schema initialization requires an editor without active anchors.' ); } const publication = compiledEntries ? prepareScopedPluginPublication( editor, input as readonly InternalPluginPublicationEntry[], { initialPublication: true, initializeDocument: !explicitInitialDocument, } ) : prepareInitialPluginPublication( editor, input as PluginInput, !explicitInitialDocument ); const restoreDocument = saveEditorSchemaDocument(editor); const initialSelection = getLiveSelection(editor); const initialSelectionRoot = getCurrentSelectionRoot(editor); const preparedDocumentValidated = publication.configurationChanged && explicitInitialDocument && publication.documentChange.empty; try { // Plugins activate on the document they publish. adoptInitialDocumentChange( editor, publication.documentChange, publication.schemaCompilation() ); publication.stage(); publication.commit(); const validatePublishedDocument = ( requireExplicitDocument = explicitInitialDocument, validateDocument = true ) => { const publishedDocument = getEditorDocumentValue(editor); if (requireExplicitDocument && publishedDocument.children.length === 0) { throw new Error( 'initialValue is invalid! Expected at least one element.' ); } assertSelectionSupported( editor, getLiveSelection(editor), publishedDocument ); if (validateDocument && publication.configurationChanged) { publication.validateDocument(publishedDocument); } else if (validateDocument) { const schema: InternalEditorSchemaApi = getEditorSchema(editor); schema.assertDocument(publishedDocument); } }; validatePublishedDocument( explicitInitialDocument, !preparedDocumentValidated ); if (options.initialValue) { initializeEditorSchemaSnapshot( editor, transformEditorSnapshotInput(editor, options.initialValue()) ); validatePublishedDocument(true); } if (options.initialize) { const spec = createTransactionSpec(editor, options.initialize); if ( spec.effects.length > 0 || spec.annotations.length > 0 || spec.tags.length > 0 ) { throw new Error( 'Editor schema initialization cannot publish effects, annotations, or tags.' ); } const initializedDocument = applyTransactionSpecToDocument( editor, spec, getEditorDocumentValue(editor) ); const admitted = admitEditorDocument(editor, initializedDocument); initializeEditorSchemaDocument(editor, admitted.document); if (spec.selection) { const root = spec.selection.root ?? 'main'; initializeEditorSchemaSelection( editor, mapSelectionThroughChange( editor, spec.selection.value, admitted.change, initializedDocument, admitted.document, root, { association: 'backward', preferPositionMapping: true } ).selection, root ); } validatePublishedDocument( explicitInitialDocument || !!options.initialValue ); } publication.beforePublish(); publication.finalize(); invalidateEditorTransactionSpecs(editor); } catch (error) { publication.rollback(); restoreDocument(); initializeEditorSchemaSelection( editor, initialSelection, initialSelectionRoot ); throw error; } publication.afterPublish(); seedUniqueIndex(editor); if (getPluginRegistry(editor).schemaContributions.records.size > 0) { disarmSchemaBootstrap(editor); } }; const adoptInitialDocumentChange = ( editor: AnyEditor, change: DocumentChange, compilation: PreparedEditorSchemaCompilation | null ) => { if (change.empty) return; const initialDocument = getEditorDocumentValue(editor); const initialSelection = getLiveSelection(editor); const initialSelectionRoot = getCurrentSelectionRoot(editor); const admitted = admitDocument( compilation && onlyDocumentAdmission(compilation.contributions(documentAdmissionPoint)), change.apply(initialDocument), compilation?.schema ?? getCompiledEditorSchema(editor) ); initializeEditorSchemaDocument(editor, admitted.document); if (!initialSelection) return; const mapped = mapSelectionThroughChange( editor, initialSelection, change.compose(admitted.change), initialDocument, admitted.document, initialSelectionRoot, { association: 'backward', preferPositionMapping: true } ).selection; if (!mapped) { throw new Error( 'Initial selection cannot be mapped through schema fitting.' ); } initializeEditorSchemaSelection(editor, mapped, initialSelectionRoot); }; const assertEditorSchemaBootstrap = (editor: AnyEditor) => { if (!PENDING_SCHEMA_BOOTSTRAP.has(editor)) { throw new Error( 'Editor schema initialization requires an editor without an installed schema.' ); } if (getPluginRegistry(editor).schemaContributions.records.size > 0) { disarmSchemaBootstrap(editor); throw new Error('Editor schema is already initialized.'); } const document = getEditorDocumentValue(editor); const hasDocument = document.children.length > 0 || Object.values(document.roots ?? {}).some((children) => children.length > 0); if (SCHEMA_BOOTSTRAP_DOCUMENT_CHANGED.has(editor)) { disarmSchemaBootstrap(editor); throw new Error( 'Editor schema initialization requires an unchanged document.' ); } return hasDocument; }; /** * Compile plugins against one unchanged raw editor without publishing them. * API factories and schema validators run; document defaults and activation do not. */ export const compileEditorSchemaContract = ( editor: AnyEditor, input: PluginInput ) => { assertPluginPublicationInactive(editor); const hasDocument = assertEditorSchemaBootstrap(editor); if (hasDocument || hasActiveAnchors(editor)) { throw new Error( 'Editor schema compilation requires an empty editor without active anchors.' ); } const publication = prepareInitialPluginPublication( editor, input, 'schema-contract' ); try { return publication.schemaContract(); } finally { publication.rollback(); } }; /** Compile owner-provided plugin entries without publishing them. @internal */ export const compileEditorSchemaContractEntries = ( editor: AnyEditor, entries: readonly InternalPluginPublicationEntry[] ) => { assertPluginPublicationInactive(editor); const hasDocument = assertEditorSchemaBootstrap(editor); if (hasDocument || hasActiveAnchors(editor)) { throw new Error( 'Editor schema compilation requires an empty editor without active anchors.' ); } const publication = prepareScopedPluginPublication(editor, entries, { initialPublication: true, validateDocument: false, }); try { return publication.schemaContract(); } finally { publication.rollback(); } }; /** Compile immutable schema and persistent-field authority without publishing it. @internal */ export const withCompiledEditorSchemaCapabilityEntries = ( editor: AnyEditor, entries: readonly InternalPluginPublicationEntry[], run: ( compilation: Readonly<{ authored?: NativeAuthoredDocumentCapability; contract: EditorSchemaContract; fields: ReadonlyArray>; schema: CompiledEditorSchema; }> ) => T ): T => { assertPluginPublicationInactive(editor); const hasDocument = assertEditorSchemaBootstrap(editor); if (hasDocument || hasActiveAnchors(editor)) { throw new Error( 'Editor schema compilation requires an empty editor without active anchors.' ); } const publication = prepareScopedPluginPublication(editor, entries, { initialPublication: true, validateDocument: false, }); try { const compilation = publication.schemaCompilation(); const authored = compilation.contributions(authoredDocumentCapabilityPoint); if (authored.length > 1) { throw new Error( 'Editor schema compilation received multiple authored document capabilities.' ); } return run( Object.freeze({ ...(authored[0] ? { authored: authored[0] } : {}), contract: publication.schemaContract(), fields: compilation.fields, schema: compilation.schema, }) ); } finally { publication.rollback(); } }; export const compileEditorSchemaCapabilityEntries = ( editor: AnyEditor, entries: readonly InternalPluginPublicationEntry[] ): Readonly<{ authored?: NativeAuthoredDocumentCapability; contract: EditorSchemaContract; fields: ReadonlyArray>; schema: CompiledEditorSchema; }> => withCompiledEditorSchemaCapabilityEntries( editor, entries, (result) => result ); /** Read the single published authored document capability, when installed. @internal */ export const getEditorAuthoredDocumentCapability = ( editor: AnyEditor ): NativeAuthoredDocumentCapability | undefined => { const capabilities = getPluginContributions( editor, authoredDocumentCapabilityPoint ); if (capabilities.length > 1) { throw new Error( 'Editor schema contains multiple authored document capabilities.' ); } return capabilities[0]; }; /** Replace the derived base schema on one unchanged raw editor. @internal */ export const initializePlugins = ( editor: TEditor, input: PluginInput, options: Readonly<{ initialize?: ( transaction: EditorTransactionSpecBuilder< ValueOf, PluginsOf > ) => void; /** Resolve one post-publication initial value for direct schema adoption. */ initialValue?: () => SnapshotInput>; }> = {} ) => { publishInitialPlugins( editor, input, assertEditorSchemaBootstrap(editor), options ); }; /** Publish owner-compiled plugin entries against one unchanged editor. @internal */ export const initializePluginEntries = ( editor: TEditor, entries: readonly InternalPluginPublicationEntry[], options: Readonly<{ initialize?: ( transaction: EditorTransactionSpecBuilder< ValueOf, PluginsOf > ) => void; initialValue?: () => SnapshotInput>; }> = {} ) => { publishInitialPlugins( editor, entries, assertEditorSchemaBootstrap(editor), options, true ); }; type NoPluginsEditorOptions = Omit< CreateEditorOptions, 'plugins' > & { plugins?: never; }; /** * Create a mutable Plite editor with schema, command, query, state, and * plugin runtime APIs installed. */ export function createEditor< const TOptions extends CreateEditorOptions & { plugins: readonly unknown[]; }, >( options: CheckedEditorOptions ): Editor, PluginsFromOptions>; export function createEditor< V extends Value, const TPlugins extends readonly unknown[], >( options: CreateEditorOptions & { plugins: TPlugins; } ): Editor; export function createEditor< const TOptions extends NoPluginsEditorOptions, >( options: CheckedEditorOptions ): Editor>; export function createEditor( options?: NoPluginsEditorOptions ): Editor; export function createEditor< const TOptions extends Partial>, >( options?: UnknownEditorOptionTarget ): Editor; export function createEditor< V extends Value = Value, const TPlugins extends readonly unknown[] = readonly [], >(options: CreateEditorOptions = {}): Editor { return createEditorImplementation(options, false); } /** @internal */ export const createDormantEditor = < V extends Value = Value, const TPlugins extends readonly unknown[] = readonly [], >( options: CreateEditorOptions = {} ): Editor => createEditorImplementation(options, true); const createEditorImplementation = < V extends Value, const TPlugins extends readonly unknown[], >( options: CreateEditorOptions, dormant: boolean ): Editor => { assertEditorOptions(options, EDITOR_OPTION_KEYS); let editor!: Editor; const runtimeEditor = () => editor; const schema: InternalEditorSchemaApi = createEditorSchema(runtimeEditor); const pluginRuntime = { schema, install: (plugin, pluginOptions) => extendEditor(editor, plugin, pluginOptions), preparePluginPublication: (entries, publicationOptions) => prepareScopedPluginPublication(editor, entries, publicationOptions), } satisfies InternalPluginRuntime; const snapshotRuntime = { getChildList: () => getChildList(editor), getChildren: () => getChildren(editor), getFragment: () => getFragment(editor) as Array>, getLastCommit: () => getLastCommit(editor) as EditorCommit | null, getPathByNodeKey: (nodeKey) => getPathByNodeKey(editor, nodeKey), getNodeKey: (path) => getNodeKey(editor, path), getSelection: () => getLiveSelection(editor), getSnapshot: () => getSnapshot(editor) as EditorSnapshot, } satisfies InternalEditorSnapshotRuntime; const runtimeBoundaryEditor = () => editor as unknown as Editor; const transactionRuntime = { read: (fn) => readEditor(runtimeBoundaryEditor(), fn), runCommand: createCommandDispatch(() => editor), subscribe: (listener) => subscribe(editor, listener), subscribeCommit: (listener) => subscribeCommit(editor, listener), subscribeSource: (source, listener) => subscribeSource(editor, source, listener), update: ( fn: ( transaction: EditorUpdateTransaction, context: EditorUpdateContext> ) => R, innerOptions?: InternalEditorUpdateOptions ) => updateEditor(runtimeBoundaryEditor(), fn, innerOptions), } satisfies InternalEditorTransactionRuntime; const anchorApi = createEditorAnchorApi(() => editor); const readMain = (fn: (state: EditorStateView) => T): T => withEditorRootChildren(editor, 'main', () => readEditor(editor, fn)); const read = createEditorReadApi((fn) => { assertNoDocumentViewRead(editor); return readMain(fn); }); // Schema queries read the shared model, not the document, so views reuse // them without the document-view guard. read.schema = createEditorReadApi(readMain).schema; const key = ((target: Descendant | Location) => { assertNoDocumentViewRead(editor); return withEditorRootChildren(editor, MAIN_ROOT_KEY, () => readEditor(editor, (state) => state.key(target as never)) ); }) as EditorKeyApi; const update = createEditorUpdateApi( (fn, policy) => updateEditor(editor, fn, { tags: policy.tags }), { hasTxGroup: (groupName) => getPluginRegistry(editor).txGroups.has(groupName), repairValue: () => updateEditor( editor, () => { repairEditorValue(editor); }, { tags: ['history-skip'], } ), } ); const baseEditor: Editor = { api: Object.create(null) as Editor['api'], anchor: anchorApi, id: options.id ?? createEditorId(), plugin: undefined as unknown as Editor['plugin'], key, read, subscribeCommit: (listener) => subscribeCommit(editor, listener), update, install: (plugin, pluginOptions) => extendEditor(editor, plugin, pluginOptions), destroy: () => destroyEditor(editor), }; editor = baseEditor; setEditorLifecycleErrorSink(editor, options.lifecycleErrorSink); const readRuntime = createEditorReadRuntime(editor); const runtime = { ...pluginRuntime, ...readRuntime, ...snapshotRuntime, ...transactionRuntime, } satisfies InternalEditorRuntime; setEditorRuntime(editor, runtime); if (dormant) markEditorDormant(editor); const baseRegistry = createPluginRegistry(); registerEffectTypeInRegistry( baseRegistry, 'core:screen-reader-announcement', screenReaderAnnouncementEffect ); initializeBasePluginRegistry(editor, finalizePluginRegistry(baseRegistry)); Object.assign(editor, createEditorViewPluginApis(editor, editor)); const initialState = initializePublicState(editor, options); armSchemaBootstrap(editor); if (options.plugins) { publishInitialPlugins( editor as AnyEditor, options.plugins as PluginInput, initialState.explicit ); } else { const initialDocument = getEditorDocumentValue(editor); if (initialState.explicit && initialDocument.children.length === 0) { throw new Error( 'initialValue is invalid! Expected at least one element.' ); } assertSelectionSupported(editor, getLiveSelection(editor), initialDocument); adoptInitialDocumentChange( editor as AnyEditor, constructLoadedDocumentChange(editor, initialDocument), null ); } snapshotInitialDocumentState(editor); return editor; };