import type { EditorReadMethodTree, EditorToggleBlockOptions, Element, InternalCompiledPluginPublicationEntry, NodeInsertNodesOptions, NodeRemoveNodesOptions, NodeSetNodesOptions, RuntimePluginDefinitionInput, } from '../../facade'; import { compilePluginInput, isTxOnlyMethod, locateAt, schema as schemaDefinition, txLocate, } from '../../facade'; import type { AnyBasePlugin, Editor } from '../../lib'; import type { BlockInsertOptions, BlockUpsertOptions, } from '../../lib/editor/pluginRuntimeTypes'; import { createPlatePluginPortal, createPluginContext, withPluginViewStore, } from '../../lib/plugin/createPluginContext.internal'; import { failInvariant } from '../failInvariant'; import { getPluginSourceReferences } from '../utils/mergePlugins'; import { snapshotApiValue } from '../utils/snapshotApiValue'; import { applyBlockInsertion, hasInsertionTarget, matchesGeneratedBlockInsertion, } from './blockInsertion'; import { type CompiledPlateModel, getPlateModelPublication, } from './compilePlateModel'; import { getCaretInline, selectAfterInline } from './inlineInsertion'; import { mergePluginCapabilities } from './mergePluginCapabilities'; import { getResolvedPluginCapabilities, type ResolvedPluginCapabilityContribution, } from './resolvePlugin'; export type ShortcutApiOwner = Readonly<{ api: Readonly>; }>; export type PlateRuntimePluginsResult = Readonly<{ entries: readonly InternalCompiledPluginPublicationEntry[]; resolveApiPublication: () => Readonly<{ apiByPlugin: Readonly>>>; shortcutApiByPlugin: Readonly>; }>; updateMethods: Readonly>; }>; const lifecycleKeys = ['commit', 'transactionChange'] as const; const flatChangeLifecycleKeys = ['nodeChange', 'textChange'] as const; export const isApiRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); const inspectPluginUpdateMethods = ( editor: Editor, pluginList: readonly AnyBasePlugin[], model: CompiledPlateModel ) => { const probe: unknown = new Proxy(() => probe, { apply: () => probe, get: () => probe, }); const updateMethods: Record = Object.create(null); pluginList.forEach((plugin) => { const binding = model.byName[plugin.name]; const names = new Set([ ...(binding?.elementType ? ['insert', 'remove', 'set'] : []), ...(binding?.kind === 'mark' ? ['clear', 'set', 'toggle'] : []), ]); if (typeof plugin.update !== 'function') { if (names.size > 0) { updateMethods[plugin.name] = Object.freeze([...names]); } return; } let group: object; try { group = Reflect.apply(plugin.update, undefined, [ Object.assign(Object.create(createPluginContext(editor, plugin)), { context: probe, tx: probe, }), ]) as object; } catch (error) { throw new Error( `Plate update namespace "${plugin.name}" could not be inspected. Update factories must construct commands without executing document work.`, { cause: error } ); } if (isTxOnlyMethod(group)) { names.clear(); } else { Object.entries(group).forEach(([name, value]) => { if (typeof value !== 'function') return; if (isTxOnlyMethod(value)) { names.delete(name); } else { names.add(name); } }); } updateMethods[plugin.name] = Object.freeze([...names]); }); return Object.freeze(updateMethods); }; const resolvePluginCapability = ( owner: string, kind: 'read' | 'update', pluginContext: object, contributions: readonly ResolvedPluginCapabilityContribution[], context: object ) => { const values = contributions.map(({ factory, kind: innerKind }) => Reflect.apply(factory, undefined, [ innerKind === 'native' ? context : Object.assign(Object.create(pluginContext), context), ]) ); return mergePluginCapabilities({ kind, owner }, ...values); }; const createPluginLifecycleHandlers = ( editor: Editor, plugin: AnyBasePlugin ) => { const handlers: Record unknown> = Object.create(null); lifecycleKeys.forEach((name) => { const handler = plugin.on?.[name]; if (typeof handler !== 'function') return; handlers[name] = (context) => Reflect.apply(handler, undefined, [ Object.assign( Object.create(createPluginContext(editor, plugin)), context ), ]); }); flatChangeLifecycleKeys.forEach((name) => { const handler = plugin.on?.[name]; if (typeof handler !== 'function') return; handlers[name] = (context) => Reflect.apply(handler, undefined, [ { ...createPluginContext(editor, plugin), ...context, editor, plugin, }, ]); }); return handlers; }; /** * Lower every resolved Plate plugin to one runtime plugin. * * Plate-only schema/render/store fields stay in the Plate publication. Native * behavior and the plugin-owned api/read/update namespaces install directly. */ export const createPlateRuntimePlugins = ( editor: Editor, pluginList: readonly AnyBasePlugin[], model: CompiledPlateModel, lowerNodeType: (type: unknown) => unknown, options: Readonly<{ includeSchemaContributions?: boolean }> = {} ): PlateRuntimePluginsResult => { const apiSnapshots = new WeakMap(); const entries: InternalCompiledPluginPublicationEntry[] = []; const fallbackApiByPlugin = new Map< string, Readonly> >(); pluginList.forEach((plugin) => { if (plugin.api !== undefined && !isApiRecord(plugin.api)) { throw new Error( `Plate plugin "${plugin.name}" API must resolve to an object before lowering.` ); } const authoredApi = plugin.api ?? {}; const frozenPluginApi = snapshotApiValue(authoredApi, apiSnapshots); const capabilities = getResolvedPluginCapabilities(plugin); const apiContributions = capabilities.api; const exposesApi = apiContributions.length > 0 || Reflect.ownKeys(frozenPluginApi).length > 0; const { conflicts, dependencies } = plugin; // Public plugin types expose dependency metadata, while runtime values keep // the original branded references required by Plite's identity graph. const runtimeConflicts = conflicts as NonNullable< RuntimePluginDefinitionInput['conflicts'] >; const runtimeDependencies = dependencies as NonNullable< RuntimePluginDefinitionInput['dependencies'] >; const on = createPluginLifecycleHandlers(editor, plugin); const pluginContext = createPluginContext(editor, plugin); const getRuntimePluginContext = (targetEditor: Editor) => targetEditor === editor ? pluginContext : withPluginViewStore( createPluginContext(targetEditor, plugin), targetEditor, plugin ); const stateFields = plugin.stateFields ?? []; const effectTypes = plugin.effectTypes ?? []; const binding = model.byName[plugin.name]; const elementType = binding?.elementType; const markKey = binding?.kind === 'mark' ? binding.propertyKey : null; const markIsBoolean = markKey !== null && binding?.properties.some( (property) => property.placement === 'text' && schemaDefinition.handle.property(property).id === binding.textPropertyId && property.value.kind === 'boolean' ); const definition: RuntimePluginDefinitionInput = { ...(plugin.enabled === false ? { enabled: false } : {}), ...(dependencies.length > 0 ? { dependencies: runtimeDependencies } : {}), ...(conflicts.length > 0 ? { conflicts: runtimeConflicts } : {}), ...(exposesApi ? { api: (context) => { let resolvedApi: Record = {}; if (apiContributions.length === 0) { resolvedApi = mergePluginCapabilities( { kind: 'api', owner: plugin.name }, resolvedApi, frozenPluginApi ) as Record; } else { for (const contribution of apiContributions) { const value = contribution.kind === 'definition' ? context.editor === editor ? contribution.value : Reflect.apply(contribution.factory, undefined, [ Object.create( withPluginViewStore( createPluginContext( context.editor as Editor, plugin ), context.editor as Editor, plugin ), { api: { value: snapshotApiValue(resolvedApi) }, } ), ]) : Reflect.apply(contribution.factory, undefined, [ context, ]); if (!isApiRecord(value)) { throw new Error( `Plate plugin "${plugin.name}" API factories must return an object.` ); } resolvedApi = mergePluginCapabilities( { kind: 'api', owner: plugin.name }, resolvedApi, value ) as Record; } } return snapshotApiValue(resolvedApi, apiSnapshots); }, } : {}), ...(markKey || capabilities.read.length > 0 || typeof plugin.read === 'function' ? { read: (context) => { const activePluginContext = getRuntimePluginContext( context.editor ); const authoredRead = capabilities.read.length > 0 ? resolvePluginCapability( plugin.name, 'read', activePluginContext, capabilities.read, context ) : typeof plugin.read === 'function' ? Reflect.apply(plugin.read, undefined, [ Object.assign( Object.create(activePluginContext), context ), ]) : {}; if (!markKey) { return mergePluginCapabilities( { kind: 'read', owner: plugin.name }, authoredRead ) as EditorReadMethodTree; } if (!isApiRecord(authoredRead)) { throw new Error( `Plate mark plugin "${plugin.name}" read factories must return an object.` ); } const defaultRead = { isActive: (expected?: unknown) => { const current = context.state.marks()?.[markKey]; if (expected !== undefined) return current === expected; return markIsBoolean ? current === true : current !== undefined; }, value: () => context.state.marks()?.[markKey], }; return mergePluginCapabilities( { kind: 'read', owner: plugin.name }, defaultRead, authoredRead ) as EditorReadMethodTree; }, } : {}), ...(elementType || markKey || capabilities.update.length > 0 || typeof plugin.update === 'function' ? { update: (context) => { const activePluginContext = getRuntimePluginContext( context.editor ); const authoredSource = capabilities.update.length > 0 ? resolvePluginCapability( plugin.name, 'update', activePluginContext, capabilities.update, context ) : typeof plugin.update === 'function' ? Reflect.apply(plugin.update, undefined, [ Object.assign( Object.create(activePluginContext), context ), ]) : {}; if (!isApiRecord(authoredSource)) { throw new Error( `Plate plugin "${plugin.name}" update factories must return an object.` ); } const authoredUpdate = capabilities.update.length > 0 ? authoredSource : (mergePluginCapabilities( { kind: 'update', owner: plugin.name }, authoredSource ) as Record); const hasAuthoredToggle = typeof authoredUpdate.toggle === 'function'; const hasAuthoredInsert = typeof authoredUpdate.insert === 'function'; const hasGenericToggle = getPlateModelPublication( editor )?.genericElementToggles.includes(plugin.name) === true; const applyGeneratedInsert = ( mode: 'insert' | 'upsert', properties: Readonly> = {}, insertOptions: BlockInsertOptions | BlockUpsertOptions = {} ) => { if (!hasInsertionTarget(context.tx, insertOptions)) { return isBlockElement ? false : undefined; } const element = context.tx.schema.create( elementType ?? failInvariant('Expected value to be defined'), properties ); if (!context.tx.schema.isBlock(element)) { context.tx.nodes.insert( element, insertOptions as NodeInsertNodesOptions ); const inline = context.tx.schema.element(element.type)?.behavior.void && !( 'at' in insertOptions && insertOptions.at !== undefined ) && !( 'select' in insertOptions && insertOptions.select !== undefined ) ? getCaretInline(context.tx, element.type) : null; if (inline) selectAfterInline(context.tx, inline); return undefined; } return applyBlockInsertion({ editor, insert: (blockOptions) => context.tx.blocks.insert(element, blockOptions) !== undefined, matches: (source) => matchesGeneratedBlockInsertion({ editor, pluginName: plugin.name, properties, source, target: element, tx: context.tx, }), mode, options: insertOptions, tx: context.tx, }); }; const isBlockElement = typeof elementType === 'string' && context.tx.schema.element(elementType)?.behavior.inline === false; const defaultUpdate = { ...(elementType ? { insert: txLocate( locateAt(1, 'at', 'after', 'before'), ( properties: Readonly> = {}, insertOptions?: BlockInsertOptions ) => applyGeneratedInsert( 'insert', properties, insertOptions ) ), ...(!hasAuthoredInsert && isBlockElement ? { upsert: txLocate( locateAt(1, 'after', 'before'), ( properties: Readonly< Record > = {}, insertOptions?: BlockUpsertOptions ) => applyGeneratedInsert( 'upsert', properties, insertOptions ) ), } : {}), remove: txLocate( locateAt(0), ( removeOptions?: Omit< NodeRemoveNodesOptions, 'match' | 'type' > ) => { context.tx.nodes.remove({ ...removeOptions, type: elementType, }); } ), set: txLocate( locateAt(1), ( properties: Readonly>, setOptions?: Omit< NodeSetNodesOptions, 'match' | 'type' > ) => { context.tx.nodes.set(properties, { ...setOptions, type: elementType, }); } ), ...(hasGenericToggle && !hasAuthoredToggle ? { toggle: txLocate( locateAt(0), ( toggleOptions: Omit< EditorToggleBlockOptions, 'wrap' > = {} ) => { const { collapse, ...blockOptions } = toggleOptions; const toggled = context.tx.blocks.toggle( { type: elementType }, blockOptions ); if (toggled && collapse) { context.tx.selection.collapse( collapse === true ? undefined : collapse ); } return toggled; } ), } : {}), } : {}), ...(markKey ? { clear: () => { context.tx.marks.remove(markKey); }, set: txLocate(false, (value: unknown) => { context.tx.marks.add(markKey, value); }), toggle: txLocate(false, (value?: unknown) => { if (!markIsBoolean && value === undefined) { throw new TypeError( `Plate mark plugin "${plugin.name}" requires a value to toggle.` ); } context.tx.marks.toggle( markKey, markIsBoolean ? true : value ); }), } : {}), }; for (const method of Object.values(defaultUpdate)) { Object.freeze(method); } return Object.freeze({ ...defaultUpdate, ...authoredUpdate }); }, } : {}), ...(plugin.readMiddleware ? { readMiddleware: plugin.readMiddleware as RuntimePluginDefinitionInput['readMiddleware'], } : {}), ...(plugin.commands ? { commands: plugin.commands as RuntimePluginDefinitionInput['commands'], } : {}), ...(plugin.corrections ? { corrections: ( plugin.corrections as NonNullable< RuntimePluginDefinitionInput['corrections'] > ).map((correction) => { const { query } = correction; if ( !query || query === 'root' || typeof query !== 'object' || !('type' in query) ) { return correction; } return { ...correction, query: { ...query, type: lowerNodeType(query.type) }, }; }) as RuntimePluginDefinitionInput['corrections'], } : {}), ...(stateFields.length > 0 ? { stateFields: stateFields as RuntimePluginDefinitionInput['stateFields'], } : {}), ...(effectTypes.length > 0 ? { effectTypes: effectTypes as RuntimePluginDefinitionInput['effectTypes'], } : {}), ...(plugin.contributions ? { contributions: plugin.contributions as RuntimePluginDefinitionInput['contributions'], } : {}), ...(Reflect.ownKeys(on).length > 0 ? { on } : {}), ...(plugin.activate ? { activate: plugin.activate as RuntimePluginDefinitionInput['activate'], } : {}), ...(plugin.validate ? { validate: plugin.validate, } : {}), ...(options.includeSchemaContributions !== false && model.contributions[plugin.name] ? { schema: model.contributions[plugin.name] } : {}), }; // The resolved graph has no static tuple; its authoring contracts are checked before lowering. const sourceReferences = [ ...new Set([ ...getPluginSourceReferences(plugin), ...capabilities.nativeSources, ]), ]; const entry = compilePluginInput(plugin, definition, { createPortal: createPlatePluginPortal, editor, sources: sourceReferences, }); entries.push(entry); fallbackApiByPlugin.set(plugin.name, frozenPluginApi); }); const updateMethods = inspectPluginUpdateMethods(editor, pluginList, model); return Object.freeze({ entries: Object.freeze(entries), resolveApiPublication: () => { const apiByPlugin: Record< string, Readonly> > = Object.create(null); const shortcutApiByPlugin: Record = Object.create(null); pluginList.forEach((plugin) => { const candidate = Reflect.get(editor.api, plugin.name); const api = isApiRecord(candidate) ? candidate : (fallbackApiByPlugin.get(plugin.name) ?? failInvariant('Expected value to be defined')); apiByPlugin[plugin.name] = api; shortcutApiByPlugin[plugin.name] = Object.freeze({ api }); }); return Object.freeze({ apiByPlugin: Object.freeze(apiByPlugin), shortcutApiByPlugin: Object.freeze(shortcutApiByPlugin), }); }, updateMethods, }); };