import { create } from 'mutative'; import { getViewPresentation, onPresentationRelease, reportEditorLifecycleError, type ViewPresentation, } from 'plitejs/internal'; import type { AnyBasePluginDefinition, AnyBasePlugin, InferPluginStoreState, InferSelectors, PluginReference, PluginStore, } from '../../lib'; import type { Editor } from '../../lib/editor'; import { createZustandStore, type ZustandStoreApi, } from '../../lib/libs/zustand'; import type { InternalPluginDefinitionOf } from '../../lib/plugin/pluginDefinitionLookup.internal'; import { brandPluginDescriptor, freezePluginDataSnapshot, getPluginSchemaFamily, isImmutablePluginData, isNominalPluginDescriptor, } from '../utils/mergePlugins'; import { getPlateRuntimeOwner } from './plateRuntime'; type PluginStoreBase< C extends AnyBasePluginDefinition = AnyBasePluginDefinition, > = ZustandStoreApi>; export type InternalPluginStore< C extends AnyBasePluginDefinition = AnyBasePluginDefinition, > = { readonly base: PluginStoreBase; readonly public: PluginStore; readonly selectors: InferSelectors; }; export const createPluginStore = ( editor: object, plugin: AnyBasePlugin | PluginReference | C['name'], base: PluginStoreBase, selectors: InferSelectors ): InternalPluginStore => { // A view store outlives the view that first asked for it, so it keeps the owner. const owner = getPlateRuntimeOwner(editor); const name = typeof plugin === 'string' ? plugin : plugin.name; const state = base.store.getState(); for (const key of Object.keys(selectors)) { if (Object.hasOwn(state, key)) { throw new Error( `Plate plugin "${name}" defines "${key}" as both state and selector.` ); } } const replace = (value: InferPluginStoreState) => { base.set('state', snapshotPluginState(value, true)); }; const store: PluginStore = { get(key?: PropertyKey, ...args: unknown[]) { const current = base.store.getState(); if (key === undefined) return current; const selector = selectors[key as keyof InferSelectors]; if (typeof selector === 'function') { return selector(current, ...args); } if (Object.hasOwn(current, key)) { return current[key as keyof InferPluginStoreState]; } throw new Error( `Plate plugin "${name}" has no state field or selector "${String(key)}".` ); }, set(value) { const current = base.store.getState(); if (typeof value === 'function') { replace(create(current, value)); } else { replace({ ...current, ...value }); } }, subscribe: (listener) => base.store.subscribe((current, previous) => { try { listener(current, previous); } catch (error) { reportEditorLifecycleError({ cause: error, editor: owner, phase: 'snapshot-listener', pluginName: name, }); } }), } as PluginStore; return Object.freeze({ base, public: Object.freeze(store), selectors: Object.freeze({ ...selectors }) as InferSelectors, }); }; const isMinimalPluginReference = (value: object) => Object.isFrozen(value) && Reflect.ownKeys(value).every((key) => key === 'name'); type PluginStateSnapshotContext = Readonly<{ canonicalReferences?: WeakMap>; references: WeakMap; reuseSnapshots?: boolean; snapshots: WeakMap; }>; // Frozen caller objects can still contain mutable descendants. const ownedStateSnapshots = new WeakSet(); const snapshotPluginStateValue = ( value: unknown, context: PluginStateSnapshotContext ): unknown => { if (!value || typeof value !== 'object') return value; if (isImmutablePluginData(value)) return value; if (context.reuseSnapshots && ownedStateSnapshots.has(value)) return value; if (isNominalPluginDescriptor(value)) { const family = getPluginSchemaFamily(value); const canonicalByName = family ? context.canonicalReferences?.get(family) : undefined; const canonicalReference = canonicalByName?.get(value.name); if (canonicalReference) return canonicalReference; if (isMinimalPluginReference(value)) { if (context.canonicalReferences && family) { const byName = canonicalByName ?? new Map(); byName.set(value.name, value); context.canonicalReferences.set(family, byName); } return value; } const existingReference = context.references.get(value); if (existingReference) return existingReference; const reference = Object.freeze( brandPluginDescriptor({ name: value.name }, value) ); context.references.set(value, reference); if (context.canonicalReferences && family) { const byName = canonicalByName ?? new Map(); byName.set(value.name, reference); context.canonicalReferences.set(family, byName); } return reference; } const existing = context.snapshots.get(value); if (existing !== undefined) return existing; if (Array.isArray(value)) { const snapshot: unknown[] = []; context.snapshots.set(value, snapshot); snapshot.push( ...value.map((item) => snapshotPluginStateValue(item, context)) ); ownedStateSnapshots.add(snapshot); return freezePluginDataSnapshot(snapshot); } const prototype = Object.getPrototypeOf(value); if (prototype !== Object.prototype && prototype !== null) return value; const snapshot: Record = Object.create(prototype); context.snapshots.set(value, snapshot); for (const key of Reflect.ownKeys(value)) { const descriptor = Object.getOwnPropertyDescriptor(value, key); if (!descriptor) continue; if (!Object.hasOwn(descriptor, 'value')) { throw new Error( 'Plate plugin `initialState` must be data-only. Accessor properties are not supported; declare computed values as pure plugin selectors.' ); } Object.defineProperty(snapshot, key, { enumerable: descriptor.enumerable, value: snapshotPluginStateValue(descriptor.value, context), }); } ownedStateSnapshots.add(snapshot); return freezePluginDataSnapshot(snapshot); }; /** Own one initial-state graph without retaining caller-owned plain data. */ export const snapshotPluginState = (value: T, reuseSnapshots = false): T => snapshotPluginStateValue(value, { references: new WeakMap(), reuseSnapshots, snapshots: new WeakMap(), }) as T; /** Canonicalize resolved state graphs through one editor-local token set. */ export const createPluginStateSnapshot = () => { const context: PluginStateSnapshotContext = { canonicalReferences: new WeakMap(), references: new WeakMap(), snapshots: new WeakMap(), }; return (value: T): T => snapshotPluginStateValue(value, context) as T; }; type PluginStoreEntry = { plugins: Map; viewStoreCount: number; views: WeakMap>; }; const PLUGIN_STORES = new WeakMap(); const getPluginStoreEntry = (owner: object) => { let entry = PLUGIN_STORES.get(owner); if (!entry) { entry = { plugins: new Map(), viewStoreCount: 0, views: new WeakMap() }; PLUGIN_STORES.set(owner, entry); } return entry; }; export const clearPluginStores = (editor: object) => { PLUGIN_STORES.delete(getPlateRuntimeOwner(editor)); }; export const getViewStore = ( editor: object, plugin: AnyBasePlugin, presentation: ViewPresentation ): InternalPluginStore => { const entry = getPluginStoreEntry(getPlateRuntimeOwner(editor)); const stores = entry.views.get(presentation) ?? new Map(); if (!entry.views.has(presentation)) { entry.views.set(presentation, stores); onPresentationRelease(presentation, () => { entry.viewStoreCount -= stores.size; entry.views.delete(presentation); }); } let store = stores.get(plugin.name); if (!store) { store = createPluginStore( editor, plugin, createZustandStore( snapshotPluginState(plugin.initialViewState?.() ?? {}), { mutative: true, name: plugin.name } ), {} ); stores.set(plugin.name, store); entry.viewStoreCount += 1; } return store; }; export const getEditorViewStore = (editor: Editor, plugin: AnyBasePlugin) => getViewStore(editor, plugin, getViewPresentation(editor)); export const getViewStoreCount = (editor: object) => PLUGIN_STORES.get(getPlateRuntimeOwner(editor))?.viewStoreCount ?? 0; export function getPluginStore

( editor: object, plugin: P ): InternalPluginStore> | undefined; export function getPluginStore( editor: object, plugin: C['name'] ): InternalPluginStore | undefined; export function getPluginStore( editor: object, plugin: AnyBasePlugin | PluginReference | string ): InternalPluginStore | undefined; export function getPluginStore( editor: object, plugin: AnyBasePlugin | PluginReference | string ): unknown { const name = typeof plugin === 'string' ? plugin : plugin.name; return PLUGIN_STORES.get(getPlateRuntimeOwner(editor))?.plugins.get(name); } export const setPluginStore = ( editor: object, plugin: AnyBasePlugin | PluginReference | C['name'], store: InternalPluginStore ) => { const name = typeof plugin === 'string' ? plugin : plugin.name; getPluginStoreEntry(getPlateRuntimeOwner(editor)).plugins.set(name, store); };