import { node as getNode } from '../editor/node'; import { nodes as getNodes } from '../editor/nodes'; import { readTextEdge } from '../editor/point'; import type { CreateEditorOptions, AnyEditor as Editor, EditorCommit, EditorCoreStateView, EditorDocumentValue, EditorLeafOptions, EditorMarks, EditorNodeGetOptions, EditorNodesOptions, EditorNodesReadOptions, EditorParentOptions, EditorPathOptions, EditorPointOptions, EditorSelectionBlockOptions, EditorSnapshot, EditorStateField, EditorStateFragmentApi, EditorStateMarksApi, EditorStateNodesApi, EditorStateSelectionApi, EditorStateSliceApi, EditorStateView, EditorTransactionSpecBuilder, EditorUniqueHolder, ElementIdTarget, NodeKey, NodeTarget, RootKey, Selection, SnapshotIndex, TextTarget, TransactionSpec, Value, } from '../interfaces/editor'; import type { Element } from '../interfaces/element'; import { type Location, LocationApi, type Span } from '../interfaces/location'; import { type Ancestor, type Descendant, type DescendantIn, NodeApi, type NodeEntry, type NodeMatch, type NodeTypeSelector, type Node as PliteNode, } from '../interfaces/node'; import { type Path, PathApi } from '../interfaces/path'; import { type Point, PointApi } from '../interfaces/point'; import { type Range, RangeApi } from '../interfaces/range'; import { type EditorSelection, type NodeSelection, SelectionApi, } from '../interfaces/selection'; import type { Text } from '../interfaces/text'; import { getDefined } from '../internal/get-defined'; import { readNamedRootChildren, stripLocationRoots, } from '../internal/root-location'; import type { MaximizeMode } from '../types/types'; import { getNodeKeyForNode, getOrCreateNodeKey, getStoredCopy, inheritNodeKey, withSpecNodeKeyOverlay, } from '../utils/node-keys'; import { normalizeNodeMatch } from '../utils/node-match'; import { getActiveScopeFrame, withActiveScopeFrame } from './active-scope'; import { assertDocumentRootKey, documentChangeWritesOnlyElementProperties, getInternalDocumentChangeEntries, valueRootIndex, } from './change/document-change'; import { childAtPathIndex, DocumentIndex, type NodeList, rootNodesOf, } from './change/document-index'; import { copyRoot, lazyRootOf, visitRootNames } from './change/lazy-root'; import { coversContent } from './change/range-content'; import { PROPERTY_SECTION_LENGTH } from './change/tokens'; import type { PropertyModification } from './change/transform'; import { registerValueIdLookup } from './change/v4/lower'; import { cloneFrozen, freezeOwnedJsonValue, isStructurallyImmutable, rememberDocumentNode, rememberDocumentNodes, } from './clone'; import { isInCommandFrame } from './command-frame'; import { isEditorContent } from './content'; import { ContentSlice } from './content-slice'; import type { AdmittedDocument } from './document-admission'; import { getEditorDocumentValue, readStoredDocumentRevision, readStoredElementRevision, } from './document-revisions'; import { isEditorNodeSelectable, projectEditorExportSlice, projectEditorGetSlice, } from './editor-read-execution'; import { type EditorRuntimeCarrier, getEditorRuntime, getEditorRuntimeOwner, getEditorSchema, hasEditorRuntime, type InternalEditorRuntime, } from './editor-runtime'; import { getContentSlice } from './get-content-slice'; import { getFragment } from './get-fragment'; import { topologyHolding } from './identity-owner'; import { normalizeEditorValue } from './initial-value'; import { canWrapAtTarget } from './inline-wrap'; import { initializeListenerState } from './listener-state'; import { childrenOf, type ChildrenSource, EMPTY_CHILDREN, getActiveUpdateRoot, getCurrentChildrenRoot, getEditorChildrenRoot, getEditorRecordsJson, getEditorUpdateRoot, getNodeSelectionRoot, getOwnerStore, getReadProjection, getTransactionSnapshot, getTransactionSpecContext, getVersion, hasInitializedOwnerStore, isInTransaction, localizeLocation, type NodeMatchOptions, type NodeTargetOptions, type NormalizedNodeMatchOptions, peekOwnerStore, type ResolvedNodeTargetOptions, rootsOfValue, rootSourceOf, savesMetaKey, savesStateKey, setRoot, type TransactionSnapshot, type TransactionSpecContext, withEditorUpdateRoot, withRoot, } from './owner-store'; import { getCompiledEditorSchema, getPluginRegistry, type PluginRegistry, } from './plugin-registry'; import { profileCoreDuration } from './profiling'; import { getPublicExplicitLocationRoot, getReadLocationRoot, MAIN_ROOT_KEY, usesImplicitSelectionLocation, } from './public-root'; import { collectLiveStore, collectRecordStore, EMPTY_RECORD_STORE, getValueRecords, type RecordStore, showValueRecords, withValueRecords, } from './record-store'; import { readRootEntries } from './root-entries'; import type { CompiledEditorSchema } from './schema-compiler'; import { assertSelectionSupported, getSelectionRanges, isValidEditorSelection, } from './selection-protocol'; import { getSelectionStateCaret, setSelectionStateCaret, } from './selection-state'; import { bootstrapCaret } from './set-root'; import { createSliceFitTransactionSpec } from './slice-fit'; import { getSnapshotIndexElementEntries, indexSurelyHoldsNodeKey, publishSnapshotIndex, readRootOwnerPlaces, seedSnapshotIndex, snapshotIndexOf, uniqueTopologyOf, } from './snapshot-index'; import { getStateFieldValue } from './state-field-runtime'; import { initializeStateFieldMap } from './state-fields'; import { getStateFieldRuntime } from './state-handles'; import { clearSnapshotCache, deserializeLocalAndLegacySharedMeta, enterEditorRead, getCachedSnapshot, getCurrentMarks, getCurrentSelection, getCurrentSelectionRoot, getEditorProjectionSnapshotIndex, getKnownTransactionIndex, getPublicSelection, getReadProjectionLane, getStoredRootChildrenSource, getTypedMarks, initializeVersionState, migrateLegacySharedMetaToRecords, nodeAtPath, noteKeyRead, setCachedSnapshot, storeCaret, VIEW_ROOT_CHILDREN_OVERRIDE_DEPTH, withActiveSchemaReadScope, withEditorDocumentProjection, withEditorRootChildren, withEditorRootChildrenGenerator, withEditorUpdateRootChildren, } from './transaction-runner'; import { createTransactionSpec, extendTransactionSpec, } from './transaction-spec'; import { lookupElementId, readUniqueHolder, registerDocumentValueRoots, shownRootIndex, } from './unique-directory'; import { areEditorJsonValuesEqual, snapshotEditorJsonValue, } from './value-codec'; import { setStatePresentation, type ViewPresentation, } from './view-presentation'; import { getEditorViewState, isModelEditorViewing, setEditorMaxLength, STATE_VIEW_OWNERS, } from './view-state'; import { countCoreWork } from './work'; const STATE_VIEW_TRANSFORMS = new WeakMap< Editor, (state: Record) => void >(); const STATE_VIEW_CACHE = new WeakMap< Editor, { registry: PluginRegistry; transformGeneration: number; view: EditorStateView; } >(); const CONSTRUCTING_STATE_VIEWS = new WeakSet(); const incrementStateViewTransformGeneration = (editor: Editor) => { getOwnerStore(editor).stateViewTransformGeneration += 1; }; /** * Install one host-owned projection before a state view freezes. * * @internal */ export const setEditorStateViewTransform = ( editor: Editor, transform: ((state: Record) => void) | undefined ) => { const owner = getEditorRuntimeOwner(editor); const previous = STATE_VIEW_TRANSFORMS.get(owner); if (transform) { STATE_VIEW_TRANSFORMS.set(owner, transform); } else { STATE_VIEW_TRANSFORMS.delete(owner); } incrementStateViewTransformGeneration(owner); return () => { if (STATE_VIEW_TRANSFORMS.get(owner) !== transform) return; if (previous) { STATE_VIEW_TRANSFORMS.set(owner, previous); } else { STATE_VIEW_TRANSFORMS.delete(owner); } incrementStateViewTransformGeneration(owner); }; }; /** @internal */ export const resolveLocationRoot = ( editor: Editor, target: NodeTarget | NodeSelection | undefined ): RootKey => { if (target === undefined) return getEditorUpdateRoot(editor); if (typeof target === 'object' && target !== null) { if (SelectionApi.isNode(target)) { return target.root ?? getEditorUpdateRoot(editor); } const locationRoot = getReadLocationRoot( target as Location | Span | undefined ); if (locationRoot !== undefined) return locationRoot; } const route = routeNodeTarget(editor, target); return route?.root ?? getEditorUpdateRoot(editor); }; const DOCUMENT_VALUES = new WeakMap< object, Readonly<{ editor: Editor; fields: ReadonlyMap; meta: Record | undefined; records: RecordStore; value: EditorDocumentValue; }> >(); /** One element a commit writes stored properties on, as it stood before. */ export type ElementPropertyWrite = Readonly<{ element: Element; modifications: readonly PropertyModification[]; path: Path; root: RootKey; }>; /** @internal */ export const readElementPropertyWrites = ( editor: Editor, { before, commit, }: Readonly<{ before: EditorDocumentValue; commit: EditorCommit }> ): readonly ElementPropertyWrite[] | null => { const fields = getPluginRegistry(editor).stateFieldIdentities; if ( commit.changed.hasAny('configuration') || commit.dirtyStateKeys.some((key) => savesStateKey(fields, key)) || !documentChangeWritesOnlyElementProperties(commit.changes, before) ) { return null; } const writes: ElementPropertyWrite[] = []; for (const [root, rootChange] of getInternalDocumentChangeEntries( commit.changes )) { let document: DocumentIndex | undefined; let position = 0; for (let at = 0; at < rootChange.sections.length; at += 2) { if (rootChange.sections[at + 1] === PROPERTY_SECTION_LENGTH) { document ??= valueRootIndex(before, root); const { path } = getDefined(document.nodeStartingAt(position)); writes.push( Object.freeze({ element: document.node(path) as Element, modifications: rootChange.data[ at / 2 ] as readonly PropertyModification[], path: Object.freeze([...path]), root, }) ); } position += getDefined(rootChange.sections[at]); } } return Object.freeze(writes); }; export const createEditorDocumentValue = ({ editor, fields, meta, records, roots, }: { editor: Editor; fields: ReadonlyMap>; meta: Record | undefined; records: RecordStore; roots: Readonly>; }): EditorDocumentValue => { const known = DOCUMENT_VALUES.get(roots); if ( known?.editor === editor && known.meta === meta && known.records === records && known.fields.size === fields.size && [...fields].every(([key, field]) => known.fields.get(key) === field) ) { return known.value as EditorDocumentValue; } countCoreWork('documentValues'); const extraRoots: Record = {}; let hasExtraRoots = false; for (const root of visitRootNames(roots)) { if (root === MAIN_ROOT_KEY) continue; copyRoot(extraRoots, root, roots, root); hasExtraRoots = true; } const persistentMetaKeys = Object.keys(meta ?? {}).filter( (key) => meta?.[key] !== undefined && savesMetaKey(fields, key) ); const hasPersistentMeta = persistentMetaKeys.length > 0; const persistentMeta = hasPersistentMeta ? (() => { const result: Record = {}; // State codecs can be much larger than the visible document. Resolve // each immutable field only if persisted metadata is actually read. for (const key of persistentMetaKeys) { const field = fields.get(key); const item = meta?.[key]; let encoded: unknown; let resolved = false; Object.defineProperty(result, key, { enumerable: true, get: () => { if (!resolved) { encoded = field ? getStateFieldRuntime(field).serialize(item) : cloneFrozen(item); resolved = true; } return encoded; }, }); } return freezeOwnedJsonValue(result); })() : undefined; const value: Record = {}; if (Object.hasOwn(roots, MAIN_ROOT_KEY)) { copyRoot(value, 'children', roots, MAIN_ROOT_KEY); } else { value.children = Object.freeze([]); } if (persistentMeta) value.meta = persistentMeta; showValueRecords(value, records, (store) => getEditorRecordsJson(editor, store) ); if (hasExtraRoots) value.roots = Object.freeze(extraRoots); const documentValue = Object.freeze(value) as EditorDocumentValue; registerDocumentValueRoots(documentValue, roots); if (Object.isFrozen(roots)) { const owner = getEditorRuntimeOwner(editor); const lane = getReadProjectionLane(owner); registerValueIdLookup(documentValue, (id) => { const currentRoots = getEditorDocumentRoots(owner); for (const root of visitRootNames(roots)) { const source = rootSourceOf(roots, root); const snapshotIndex = snapshotIndexOf(owner, source, lane) ?? (currentRoots === roots ? runtimeRootIndex(owner, root) : undefined); if (!snapshotIndex) continue; const topology = uniqueTopologyOf(owner, snapshotIndex, source); const holding = topology && topologyHolding(topology, 'id', id); const first = holding?.all()[0]; if (first) { return { path: first.path, root }; } } return null; }); DOCUMENT_VALUES.set(roots, { editor, fields, meta, records, value: documentValue, }); } return documentValue; }; const withLocationRootRead = ( editor: Editor, location: Location | Span | undefined, fn: () => T, options?: { selectionFallback?: boolean } ): T => { const root = getReadLocationRoot(location) ?? getEditorChildrenRoot(editor) ?? (options?.selectionFallback && getCurrentSelection(editor) ? getCurrentSelectionRoot(editor) : undefined); return root ? withRoutedCallerScope(editor, () => withEditorRootChildren(editor, root, fn) ) : fn(); }; const withOptionsRootRead = ( editor: Editor, options: { at?: Location | NodeSelection | Span } | undefined, fn: () => T, queryOptions?: { selectionFallback?: boolean } ): T => { if (SelectionApi.isNode(options?.at)) { const { root = getCurrentChildrenRoot(editor) } = options.at; return withRoutedCallerScope(editor, () => withEditorRootChildren(editor, root, fn) ); } return withLocationRootRead(editor, options?.at, fn, queryOptions); }; const withOptionsRootGenerator = ( editor: Editor, options: { at?: Location | NodeSelection | Span } | undefined, create: () => Iterable, queryOptions?: { selectionFallback?: boolean } ): Generator => (function* rootedReadGenerator() { if (SelectionApi.isNode(options?.at)) { yield* withRoutedCallerScopeGenerator( editor, withEditorRootChildrenGenerator( editor, options.at.root ?? getCurrentChildrenRoot(editor), create ) ); return; } const root = getReadLocationRoot(options?.at) ?? getEditorChildrenRoot(editor) ?? (queryOptions?.selectionFallback && getCurrentSelection(editor) ? getCurrentSelectionRoot(editor) : undefined); if (root) { yield* withRoutedCallerScopeGenerator( editor, withEditorRootChildrenGenerator(editor, root, create) ); return; } yield* create(); })(); const assertPathShape = (path: Path) => { if (!PathApi.isPath(path)) { throw new Error('Got non-numeric path index'); } }; const assertLocationPathShape = (location: Location | Span) => { if (LocationApi.isSpan(location)) { return; } if (PathApi.isPath(location)) { return; } if (Array.isArray(location)) { throw new Error('Got non-numeric path index'); } if (LocationApi.isPoint(location)) { assertPathShape(location.path); return; } assertPathShape(location.anchor.path); assertPathShape(location.focus.path); }; export const hasLocationPath = ( editor: Editor, location: Location | Span ): boolean => { assertLocationPathShape(location); if (LocationApi.isSpan(location)) { return NodeApi.has(editor, location[0]) && NodeApi.has(editor, location[1]); } if (PathApi.isPath(location)) { return NodeApi.has(editor, location); } if (LocationApi.isPoint(location)) { return NodeApi.has(editor, location.path); } return ( NodeApi.has(editor, location.anchor.path) && NodeApi.has(editor, location.focus.path) ); }; const hasReadableNodeCollection = ( editor: Editor, options: { at?: Location | NodeSelection | Span } | undefined ): boolean => options?.at === undefined || SelectionApi.isNode(options.at) || hasLocationPath(editor, options.at); const readNodeEntry = ( editor: Editor, at: Location ): NodeEntry | undefined => { if (!hasLocationPath(editor, at)) return undefined; return getNode(editor, at) as NodeEntry; }; const readNodePath = ( editor: Editor, at: Location, options: EditorPathOptions = {} ): Path | undefined => { if (!hasLocationPath(editor, at)) return undefined; const path = getEditorRuntime(editor).path(at, options); assertPathShape(path); if (NodeApi.has(editor, path)) return path; return undefined; }; export const resolveNodeTargetLocation = ( editor: Editor, target: TextTarget ): Location | undefined => { if (typeof target === 'string') { return getPathByNodeKey(editor, target) ?? undefined; } if (!NodeApi.isDescendant(target)) { const { path } = target as { path?: unknown }; if ( !Array.isArray(target) && !('offset' in target) && Array.isArray(path) ) { return path as Path; } const location = target as Location; assertLocationPathShape(location); return location; } const owner = getEditorRuntimeOwner(editor); const lane = getReadProjectionLane(owner); const readPath = () => { const nodeKey = getNodeKeyForNode(target, owner, lane); return nodeKey ? (getPathByNodeKey(editor, nodeKey) ?? undefined) : undefined; }; const path = readPath(); if (path || !getReadProjection(owner)) return path; // Nodes of a projected document register their keys when its index // materializes, as in `getEditorNodeKeyForNode`. getCurrentRuntimeIndex(owner).entries(); return readPath(); }; const getOptionsNodeTarget = (options: object | undefined) => options && 'at' in options ? (options as NodeTargetOptions).at : undefined; const getLookupIndex = ( owner: Editor, transactionSnapshot: TransactionSnapshot, root: string ) => { const known = getKnownTransactionIndex(transactionSnapshot, root); if (known) return known; const children = readNamedRootChildren(transactionSnapshot.roots, root); return children ? snapshotIndexOf(owner, children, getReadProjectionLane(owner)) : null; }; export const getRuntimeTargetRoot = ( editor: Editor, nodeKey: NodeKey ): string | undefined => { const owner = getEditorRuntimeOwner(editor); const transactionSnapshot = getReadProjection(editor) ? undefined : getTransactionSnapshot(editor); const holds = (root: string) => transactionSnapshot ? getLookupIndex(owner, transactionSnapshot, root)?.pathOf(nodeKey) : withEditorRootChildren(editor, root, () => getPathByNodeKey(editor, nodeKey) ); const likely = new Set([ getCurrentChildrenRoot(editor), MAIN_ROOT_KEY, peekOwnerStore(owner)?.lastTargetRoot ?? MAIN_ROOT_KEY, ]); const root = [...likely].find(holds) ?? getEditorRuntimeRootKeys(editor).find( (key) => !likely.has(key) && holds(key) ); if (root !== undefined) getOwnerStore(owner).lastTargetRoot = root; return root; }; /** @internal */ export const UNPLACED_TARGET: ElementIdTarget = Object.freeze({ id: '' }); export const elementIdOf = (target: unknown): string | undefined => { if (typeof target !== 'object' || target === null || Array.isArray(target)) { return undefined; } const keys = Reflect.ownKeys(target); if (keys.length !== 1 || keys[0] !== 'id') return undefined; const { id } = target as ElementIdTarget; return typeof id === 'string' ? id : undefined; }; type NodeTargetRoute = Readonly<{ path?: Path; root: string | undefined; target: Exclude | NodeKey; }>; const routeNodeTarget = < TTarget extends NodeTarget | NodeSelection | Span | undefined, >( editor: Editor, target: TTarget ): NodeTargetRoute | null => { if (target === UNPLACED_TARGET) return null; const id = elementIdOf(target); if (id === undefined) { return { root: getNodeTargetRoot(editor, target), target: target as Exclude, }; } const holder = lookupElementId(editor, id); if (!holder) return null; const { viewReadRoot } = getActiveScopeFrame(editor); if (viewReadRoot !== undefined && holder.root !== viewReadRoot) return null; return { path: holder.path, root: holder.root, target: holder.key }; }; export const getNodeTargetRoot = ( editor: Editor, target: NodeTarget | NodeSelection | Span | undefined ) => { if (typeof target === 'string') { return getRuntimeTargetRoot(editor, target); } if (NodeApi.isDescendant(target)) { const owner = getEditorRuntimeOwner(editor); const key = getNodeKeyForNode(target, owner, getReadProjectionLane(owner)); const root = key && getRuntimeTargetRoot(editor, key); if (root) return root; const found = resolveEditorNodeKeyForNode(editor, target); return found ? getRuntimeTargetRoot(editor, found) : undefined; } return undefined; }; export const getSelectionNodeTargetRoot = ( editor: Editor, target: Descendant | NodeKey ) => { if (typeof target === 'string') return getRuntimeTargetRoot(editor, target); const owner = getEditorRuntimeOwner(editor); const nodeKey = getNodeKeyForNode( target, owner, getReadProjectionLane(owner) ); return nodeKey ? getRuntimeTargetRoot(editor, nodeKey) : undefined; }; const inTargetRoot = ( editor: Editor, root: string | undefined, fn: () => T ): T => root ? withRoutedCallerScope(editor, () => withEditorRootChildren(editor, root, fn) ) : fn(); const readAtNodeTarget = ( editor: Editor, target: NodeTarget, miss: T, read: (at: Location, root: string | undefined, callerRoot: string) => T ): T => { const callerRoot = getEditorChildrenRoot(editor) ?? MAIN_ROOT_KEY; const route = routeNodeTarget(editor, target); if (!route) return miss; const targetRoot = route.root ?? (LocationApi.isLocation(route.target) ? getReadLocationRoot(route.target) : undefined); return inTargetRoot(editor, targetRoot, () => { const at = route.path ?? resolveNodeTargetLocation(editor, route.target); return at ? read(at, targetRoot, callerRoot) : miss; }); }; const assertInTargetRoot = ( callerRoot: string, root: string | undefined, location: Location | undefined ) => { if (!location) return; const otherRoot = getReadLocationRoot(location) ?? callerRoot; const targetRoot = root ?? callerRoot; if (otherRoot !== targetRoot) { throw new Error('Cannot read an editor location across multiple roots.'); } }; const routeOptions = ( options: TOptions, { target }: NodeTargetRoute ): TOptions => getOptionsNodeTarget(options) === target ? options : { ...options, at: target }; const readAtOptionsTarget = ( editor: Editor, options: TOptions, miss: T, read: (options: TOptions) => T ): T => { const route = routeNodeTarget(editor, getOptionsNodeTarget(options)); return route ? inTargetRoot(editor, route.root, () => read(routeOptions(options, route))) : miss; }; const withReadGeneratorScope = ( editor: Editor, iterable: Iterable ): Generator => (function* scopedReadGenerator() { const iterator = iterable[Symbol.iterator](); let done = false; try { while (true) { const exitRead = enterEditorRead(editor); let result: IteratorResult; try { result = iterator.next(); } finally { exitRead(); } if (result.done) { done = true; return; } yield result.value; } } finally { if (!done) { const exitRead = enterEditorRead(editor); try { iterator.return?.(); } finally { exitRead(); } } } })(); const readAtOptionsTargetGenerator = ( editor: Editor, options: TOptions, create: (options: TOptions) => Iterable ): Generator => { const inRead = !isInTransaction(editor); const route = routeNodeTarget(editor, getOptionsNodeTarget(options)); if (!route) return (function* missedNodeTarget() {})(); const routed = routeOptions(options, route); const generator = route.root ? withRoutedCallerScopeGenerator( editor, withEditorRootChildrenGenerator(editor, route.root, () => create(routed) ) ) : (function* unscopedNodeTargetGenerator() { yield* create(routed); })(); return inRead ? withReadGeneratorScope(editor, generator) : generator; }; const readElementEntry = ( editor: Editor, { key, path, root }: EditorUniqueHolder ) => Object.freeze({ key, node: withEditorRootChildren(editor, root, () => getNode(editor, path)[0]), path, ...(root !== MAIN_ROOT_KEY && { root }), }); export const normalizeNodeMatchOption = ( editor: Editor, options: TOptions ): NormalizedNodeMatchOptions => { const callerOptions = keepCallbacksInCallerScope(editor, options); if (!('match' in callerOptions) && !('type' in callerOptions)) { return callerOptions; } const { match: optionMatch, type, ...rest } = callerOptions as TOptions & NodeMatchOptions; const match = normalizeCallerMatch(editor, type, optionMatch); return { ...rest, match }; }; type CallerCallbackOptions = { compare?: (...args: never[]) => unknown; merge?: (...args: never[]) => unknown; split?: { match?: NodeMatch }; }; const keepCallbacksInCallerScope = ( editor: Editor, options: TOptions ): TOptions => { const { compare, merge, split } = options as TOptions & CallerCallbackOptions; if (!compare && !merge && !split?.match) return options; return { ...options, ...(compare && { compare: inCallerScope(editor, compare) }), ...(merge && { merge: inCallerScope(editor, merge) }), ...(split?.match && { split: { ...split, match: inCallerScope(editor, split.match) }, }), }; }; const resolveNodeTargetOptions = ( editor: Editor, options: TOptions | undefined ): null | ResolvedNodeTargetOptions | undefined => { if (!options || options.at === undefined) { return options ? (normalizeNodeMatchOption( editor, options ) as ResolvedNodeTargetOptions) : undefined; } const at = resolveNodeTargetLocation(editor, options.at as TextTarget); if (at === undefined) return null; return normalizeNodeMatchOption(editor, { ...options, at, }); }; type NodeTargetOrSpanOptions = { at?: NodeSelection | NodeTarget | Span; }; type ResolvedNodeTargetOrSpanOptions = Omit, 'at'> & { at?: Location | NodeSelection | Span; }; const rangeCoversBlock = ( schema: Pick, 'isBlock' | 'isVoid'>, block: Element, path: Path, start: Point, end: Point ): boolean => { let firstText: Path | null = null; let hasContent = false; for (const [index, child] of block.children.entries()) { const childPath = path.concat(index); if (NodeApi.isElement(child) && schema.isBlock(child)) { if (!rangeCoversBlock(schema, child, childPath, start, end)) { return false; } hasContent = true; continue; } const texts = NodeApi.isText(child) ? [[child, []] as const] : NodeApi.texts(child); for (const [text, relative] of texts) { const textPath = childPath.concat(relative); const parent = relative.length > 0 ? NodeApi.parent(child, relative) : block; const isVoid = NodeApi.isElement(parent) && schema.isVoid(parent); const length = isVoid ? 1 : text.text.length; firstText ??= textPath; if (length === 0) continue; hasContent = true; const fromStart = PathApi.compare(textPath, start.path); const toEnd = PathApi.compare(textPath, end.path); if (fromStart < 0 || toEnd > 0) return false; if (isVoid) continue; if (fromStart === 0 && start.offset > 0) return false; if (toEnd === 0 && end.offset < length) return false; } } if (hasContent) return true; if (firstText) { const place = { offset: 0, path: firstText }; return ( PointApi.compare(start, place) <= 0 && PointApi.compare(end, place) >= 0 ); } return ( PathApi.compare(start.path, path) < 0 && PathApi.compare(end.path, path) > 0 ); }; const narrowCoveredBlocks = ( entries: ReadonlyArray>, mode: 'all' | 'highest' | 'lowest' | undefined ) => { if (mode === 'highest') { let top: Path | null = null; return entries.filter(([, path]) => { if (top && PathApi.isAncestor(top, path)) return false; top = path; return true; }); } if (mode === 'lowest') { return entries.filter( ([, path], index) => !entries[index + 1] || !PathApi.isAncestor(path, entries[index + 1][1]) ); } return entries; }; const resolveNodeTargetOrSpanOptions = < TOptions extends NodeTargetOrSpanOptions, >( editor: Editor, options: TOptions | undefined ): null | ResolvedNodeTargetOrSpanOptions | undefined => { if (!options || options.at === undefined) { return options ? (normalizeNodeMatchOption( editor, options ) as ResolvedNodeTargetOrSpanOptions) : undefined; } if (SelectionApi.isNode(options.at)) { return normalizeNodeMatchOption( editor, options ) as ResolvedNodeTargetOrSpanOptions; } if (LocationApi.isSpan(options.at)) { return normalizeNodeMatchOption( editor, options ) as ResolvedNodeTargetOrSpanOptions; } const at = resolveNodeTargetLocation(editor, options.at as TextTarget); if (at === undefined) return null; return normalizeNodeMatchOption(editor, { ...options, at, }); }; const readNodeChildren = ( editor: Editor, at: Location = [] ): readonly PliteNode[] => { if (!hasLocationPath(editor, at)) { return []; } if (Array.isArray(at) && at.length === 0) { return getChildren(editor) as readonly PliteNode[]; } const [node] = getNode(editor, at); return 'children' in node && Array.isArray(node.children) ? node.children : []; }; const readNodeFirst = (editor: Editor, at: Location): NodeEntry | undefined => { if (!hasLocationPath(editor, at)) return undefined; return getEditorRuntime(editor).first(at); }; const readNodeLeaf = ( editor: Editor, at: Location, options: EditorLeafOptions = {} ): NodeEntry | undefined => { if (!hasLocationPath(editor, at)) return undefined; return getEditorRuntime(editor).leaf(at, options); }; const readNodeParent = ( editor: Editor, at: Location, options: EditorParentOptions = {} ): NodeEntry | undefined => { if (PathApi.isPath(at) && at.length === 0) return undefined; if (!hasLocationPath(editor, at)) return undefined; const { match: _match, type: _type, ...pathOptions } = options; return getEditorRuntime(editor).parent(at, pathOptions); }; const withActiveRootPoint = (editor: Editor, point: Point): Point => { const root = getEditorChildrenRoot(editor); return root && root !== MAIN_ROOT_KEY && point.root !== root ? { ...point, root } : point; }; const withActiveRootRange = (editor: Editor, range: Range): Range => ({ anchor: withActiveRootPoint(editor, range.anchor), focus: withActiveRootPoint(editor, range.focus), }); export const readPoint = ( editor: Editor, at: Location, options: EditorPointOptions = {} ): Point | undefined => { if (!hasLocationPath(editor, at)) return undefined; if (!PathApi.isPath(at)) { return withActiveRootPoint( editor, getEditorRuntime(editor).point(at, options) ); } const edge = readTextEdge(editor, at, options.edge ?? 'start'); if (!edge) return undefined; return withActiveRootPoint(editor, edge); }; export const readPointEdge = ( editor: Editor, at: Location, edge: 'start' | 'end' ): Point | undefined => readPoint(editor, at, { edge }); const hasLocationTextEdge = (editor: Editor, at: Location): boolean => hasLocationPath(editor, at) && (!PathApi.isPath(at) || readTextEdge(editor, at, 'start') !== null); const readAdjacentPoint = ( editor: Editor, at: Location, direction: 'after' | 'before', options = {} ): Point | undefined => { if ( !hasLocationTextEdge(editor, at) || readTextEdge(editor, [], 'start') === null ) { return undefined; } const adjacent = direction === 'after' ? getEditorRuntime(editor).after(at, options) : getEditorRuntime(editor).before(at, options); return adjacent ? withActiveRootPoint(editor, adjacent) : undefined; }; const readRangeEdges = ( editor: Editor, at: Location ): readonly [Point, Point] | undefined => { if (!hasLocationTextEdge(editor, at)) return undefined; const [start, end] = getEditorRuntime(editor).edges(at); return [ withActiveRootPoint(editor, start), withActiveRootPoint(editor, end), ] as const; }; const readRange = ( editor: Editor, at: Location, to?: Location ): Range | undefined => { if ( !hasLocationTextEdge(editor, at) || (to && !hasLocationTextEdge(editor, to)) ) { return undefined; } return withActiveRootRange(editor, getEditorRuntime(editor).range(at, to)); }; const readRangeFromEntries = ( editor: Editor, entries: readonly NodeEntry[] ): Range | undefined => { const first = entries[0]; const last = entries.at(-1); if (!first || !last) return undefined; return readRange(editor, first[1], last[1]); }; const getImplicitSelectionRoot = (editor: Editor): string | undefined => getCurrentSelection(editor) ? getCurrentSelectionRoot(editor) : undefined; export const getActiveMutationRoot = (editor: Editor): string | undefined => getEditorChildrenRoot(editor) ?? getActiveUpdateRoot(editor); export const getMutationRoot = ( editor: Editor, options?: { at?: Location | NodeSelection } ): string | undefined => { if (options?.at !== undefined) { if (SelectionApi.isNode(options.at)) { return options.at.root ?? getCurrentChildrenRoot(editor); } return ( getPublicExplicitLocationRoot(options.at) ?? getActiveMutationRoot(editor) ?? MAIN_ROOT_KEY ); } const activeRoot = getActiveMutationRoot(editor); const selectionRoot = getImplicitSelectionRoot(editor); if (!selectionRoot) { return activeRoot; } if (!activeRoot || activeRoot === selectionRoot) { return selectionRoot; } const transactionSnapshot = getTransactionSnapshot(editor); return transactionSnapshot && transactionSnapshot.selectionRoot !== selectionRoot ? selectionRoot : activeRoot; }; export const getLocationMutationRoot = ( editor: Editor, location: Location ): string | undefined => getPublicExplicitLocationRoot(location) ?? getActiveMutationRoot(editor) ?? MAIN_ROOT_KEY; export const runWithMutationRoot = ( editor: Editor, root: string | undefined, fn: () => T ): T => profileCoreDuration('mutation-root', () => root ? withRoutedCallerScope(editor, () => withEditorUpdateRoot(editor, root, () => withEditorUpdateRootChildren(editor, root, fn) ) ) : fn() ); export const runInTargetRoot = ( editor: Editor, at: NodeSelection | NodeTarget, selectionRoot: (selection: NodeSelection) => string, fn: (at: NodeSelection | Location, root: string | undefined) => T, miss: T ): T => { if (SelectionApi.isNode(at)) { const root = selectionRoot(at); return runWithMutationRoot(editor, root, () => fn(at, root)); } const route = routeNodeTarget(editor, at); if (!route) return miss; const { root } = route; if (root) { return runWithMutationRoot(editor, root, () => { const location = route.path ?? resolveNodeTargetLocation(editor, route.target); return location ? fn(location, root) : miss; }); } const location = resolveNodeTargetLocation(editor, route.target); const locationRoot = location && getLocationMutationRoot(editor, location); return location ? runWithMutationRoot(editor, locationRoot, () => fn(location, locationRoot) ) : miss; }; export const runAtOptionsTarget = < TOptions extends NodeTargetOptions, T, TMiss, >( editor: Editor, options: TOptions | undefined, childrenRoot: string | undefined, run: ( localOptions: ResolvedNodeTargetOptions | undefined, root: string | undefined ) => T, miss: TMiss ): T | TMiss => { const route = routeNodeTarget(editor, options?.at); if (!route) return miss; const routed = options && routeOptions(options, route); const runtimeRoot = childrenRoot ?? route.root; const preResolvedOptions = runtimeRoot ? undefined : resolveNodeTargetOptions(editor, routed); if (preResolvedOptions === null) return miss; const root = runtimeRoot ?? getMutationRoot(editor, preResolvedOptions); return runWithMutationRoot(editor, root, () => { const resolvedOptions = runtimeRoot ? resolveNodeTargetOptions(editor, routed) : preResolvedOptions; if (resolvedOptions === null) return miss; return run( resolvedOptions?.at === undefined ? resolvedOptions : { ...resolvedOptions, at: localizeLocation(resolvedOptions.at) }, root ); }); }; type RootScope = Readonly< Pick< TransactionSpecContext, 'activeChildrenRoot' | 'activeUpdateRoot' | 'currentChildrenRoot' > >; const readRootScope = (context: TransactionSpecContext): RootScope => ({ activeChildrenRoot: context.activeChildrenRoot, activeUpdateRoot: context.activeUpdateRoot, currentChildrenRoot: context.currentChildrenRoot, }); const isSameRootScope = (left: RootScope, right: RootScope) => left.activeChildrenRoot === right.activeChildrenRoot && left.activeUpdateRoot === right.activeUpdateRoot && left.currentChildrenRoot === right.currentChildrenRoot; const withRoutedCallerScope = (editor: Editor, fn: () => T): T => { const owner = getEditorRuntimeOwner(editor); const context = getTransactionSpecContext(owner); if (!context || getActiveScopeFrame(owner).routedCallerScope !== undefined) { return fn(); } return withActiveScopeFrame( owner, { routedCallerScope: readRootScope(context) }, fn ); }; const withRoutedCallerScopeGenerator = ( editor: Editor, routed: Iterable ): Generator => (function* routedCallerScopeGenerator() { const iterator = routed[Symbol.iterator](); let done = false; try { while (true) { const result = withRoutedCallerScope(editor, () => iterator.next()); if (result.done) { done = true; return; } yield result.value; } } finally { if (!done) withRoutedCallerScope(editor, () => iterator.return?.()); } })(); export const inCallerScope = ( editor: Editor, fn: (...args: TArgs) => TResult ) => (...args: TArgs): TResult => { const owner = getEditorRuntimeOwner(editor); const caller = getActiveScopeFrame(owner).routedCallerScope; const context = getTransactionSpecContext(owner); if (!caller || !context) return fn(...args); const routed = readRootScope(context); if (isSameRootScope(caller, routed)) return fn(...args); return withActiveScopeFrame(owner, { routedCallerScope: undefined }, () => { Object.assign(context, caller); try { return fn(...args); } finally { Object.assign(context, routed); } }); }; export const normalizeCallerMatch = ( editor: Editor, type: NodeTypeSelector | undefined, match: NodeMatch | undefined ) => normalizeNodeMatch(type, match && inCallerScope(editor, match)); const getCurrentRuntimeIndex = (editor: Editor): SnapshotIndex => { if (getReadProjection(editor)) { return getEditorProjectionSnapshotIndex(editor, getChildrenSource(editor)); } const root = getCurrentChildrenRoot(editor); const transactionSnapshot = getTransactionSnapshot(editor); if (transactionSnapshot) { return retainTransactionSnapshotIndex(editor, transactionSnapshot, root); } return getSnapshot(editor).index; }; export const getChildrenSource = (editor: Editor): ChildrenSource => { const projection = getReadProjection(editor); if (projection) { const root = getCurrentChildrenRoot(editor); return root === MAIN_ROOT_KEY ? (lazyRootOf(projection, 'children') ?? projection.children) : (lazyRootOf(projection.roots, root) ?? readNamedRootChildren(projection.roots, root) ?? EMPTY_CHILDREN); } const context = getTransactionSpecContext(editor); if (context) { const { value } = context.snapshot.builder; return context.currentChildrenRoot === MAIN_ROOT_KEY ? (lazyRootOf(value, 'children') ?? (value.children as readonly Descendant[])) : (lazyRootOf(value.roots, context.currentChildrenRoot) ?? (readNamedRootChildren(value.roots, context.currentChildrenRoot) as | readonly Descendant[] | undefined) ?? EMPTY_CHILDREN); } return getStoredChildrenSource(editor); }; export const getChildren = (editor: Editor): V => childrenOf(getChildrenSource(editor)) as V; /** @internal */ export const getChildList = (editor: Editor): NodeList => { const source = getChildrenSource(editor); return source instanceof DocumentIndex ? (source.nodes as NodeList) : source; }; const VIEW_CHILDREN_SOURCES = new WeakMap< InternalEditorRuntime, () => ChildrenSource >(); const VIEW_READ_SCOPES = new WeakMap< InternalEditorRuntime, (fn: () => T) => T >(); /** @internal */ export const setViewChildrenSource = ( view: Editor, owner: Editor, read: (fn: () => T) => T ) => { const runtime = getEditorRuntime(view); VIEW_READ_SCOPES.set(runtime, read); VIEW_CHILDREN_SOURCES.set(runtime, () => read(() => getChildrenSource(owner)) ); }; /** @internal */ export const withEditorViewRead = (editor: Editor, fn: () => T): T => { const read = hasEditorRuntime(editor) ? VIEW_READ_SCOPES.get(getEditorRuntime(editor)) : undefined; return read ? read(fn) : fn(); }; const readViewChildrenSource = (editor: Editor) => hasEditorRuntime(editor) ? VIEW_CHILDREN_SOURCES.get(getEditorRuntime(editor))?.() : undefined; export const getStoredChildrenSource = (editor: Editor): ChildrenSource => { const owner = getEditorRuntimeOwner(editor); if ( editor !== owner && (VIEW_ROOT_CHILDREN_OVERRIDE_DEPTH.get(editor) ?? 0) === 0 ) { const viewChildren = readViewChildrenSource(editor); if (viewChildren !== undefined) return viewChildren; } return ( peekOwnerStore(owner)?.children ?? ((editor.read?.children?.() ?? []) as readonly Descendant[]) ); }; export const getEditorDocumentRoots = ( editor: Editor ): Readonly> => { const projection = getReadProjection(editor); if (projection) { return rootsOfValue(projection); } const owner = getEditorRuntimeOwner(editor); const context = getTransactionSpecContext(owner); if (context) return rootsOfValue(context.snapshot.builder.value); const children = getStoredChildrenSource(owner); const storedRoots = peekOwnerStore(owner)?.roots; if (!storedRoots) return withRoot({}, MAIN_ROOT_KEY, children); const currentRoot = getCurrentChildrenRoot(owner); if (!Object.hasOwn(storedRoots, currentRoot)) { return storedRoots; } return rootSourceOf(storedRoots, currentRoot) === children ? storedRoots : withRoot(storedRoots, currentRoot, children); }; export const getEditorRootChildren = ( editor: Editor, root: string ): readonly unknown[] | undefined => { const value = getReadProjection(editor) ?? getTransactionSpecContext(editor)?.snapshot.builder.value; if (value) { return root === MAIN_ROOT_KEY ? value.children : readNamedRootChildren(value.roots, root); } const owner = getEditorRuntimeOwner(editor); const storedRoots = peekOwnerStore(owner)?.roots; if (!storedRoots) { return root === MAIN_ROOT_KEY ? childrenOf(getStoredChildrenSource(owner)) : undefined; } if (!Object.hasOwn(storedRoots, root)) return undefined; return childrenOf( root === getCurrentChildrenRoot(owner) ? getStoredChildrenSource(owner) : rootSourceOf(storedRoots, root) ); }; export const getLiveNode = ( editor: Editor, path: Path ): PliteNode | undefined => { if (path.length === 0) { return editor; } let node: PliteNode | undefined; let children: NodeList = getChildList(editor); for (let index = 0; index < path.length; index += 1) { node = childAtPathIndex(children, path[index]); if (!node) { return undefined; } if (index === path.length - 1) { return node; } if (!('children' in node) || !Array.isArray(node.children)) { return undefined; } ({ children } = node); } return node; }; export const getLiveText = (editor: Editor, path: Path): Text | null => { const node = getLiveNode(editor, path); return node && 'text' in node && typeof node.text === 'string' ? (node as Text) : null; }; // Typed by the runtime carrier alone: relating a schema-typed editor to // `AnyEditor` depends on TypeScript's variance measurement order. export const getLiveSelection = (editor: EditorRuntimeCarrier): Selection => getCurrentSelection(getEditorRuntimeOwner(editor)); export const getNodeKey = ( editor: Editor, path: Path ): NodeKey | null => path.length === 0 ? null : getCurrentRuntimeIndex(editor).keyAt(path); /** * Query runtime-backed element entries in one explicit root. * * @internal */ export const getEditorRuntimeElementEntries = ( editor: Editor, types: readonly string[], root: RootKey ) => withEditorRootChildren(editor, root, () => getSnapshotIndexElementEntries(getCurrentRuntimeIndex(editor), types) ); /** @internal */ export const getEditorRootOwnerPlaces = (editor: Editor, root: RootKey) => withEditorRootChildren(editor, root, () => readRootOwnerPlaces( editor, getCurrentRuntimeIndex(editor), getChildrenSource(editor) ) ); /** * Read current root keys without traversing document content. * * @internal */ export const getEditorRuntimeRootKeys = (editor: Editor): readonly RootKey[] => Object.freeze(Object.keys(getEditorDocumentRoots(editor))); export const hasEditorRuntimeRoot = ( editor: Editor, root: RootKey ): boolean => { if (root === MAIN_ROOT_KEY) return true; const owner = getEditorRuntimeOwner(editor); const projection = getReadProjection(owner); if (projection) { return ( projection.roots !== undefined && Object.hasOwn(projection.roots, root) ); } const context = getTransactionSpecContext(owner); if (context) { const { roots } = context.snapshot.builder.value; return roots !== undefined && Object.hasOwn(roots, root); } const storedRoots = peekOwnerStore(owner)?.roots; return storedRoots !== undefined && Object.hasOwn(storedRoots, root); }; const currentRootIndex = (owner: Editor, root: string): SnapshotIndex => { const cached = peekOwnerStore(owner)?.snapshotCache.get(root); return cached && rootNodesOf(cached, 'children') === rootNodesOf(getEditorDocumentRoots(owner), root) ? cached.index : getCurrentRootSnapshot(owner, root).index; }; /** @internal */ export const resolveEditorNodeKeyForNode = ( editor: Editor, node: Descendant ): NodeKey | null => { const owner = getEditorRuntimeOwner(editor); const lane = getReadProjectionLane(owner); let nodeKey = getNodeKeyForNode(node, owner, lane); const index = getCurrentRuntimeIndex(owner); const resolvesIn = (candidate: SnapshotIndex) => { if (nodeKey && candidate.pathOf(nodeKey)) return true; candidate.entries(); nodeKey = getNodeKeyForNode(node, owner, lane); return Boolean(nodeKey && candidate.pathOf(nodeKey)); }; if (resolvesIn(index)) return getDefined(nodeKey); const currentRoot = getCurrentChildrenRoot(owner); for (const root of getEditorRuntimeRootKeys(owner)) { if (root === currentRoot) continue; if (resolvesIn(runtimeRootIndex(owner, root))) return getDefined(nodeKey); } const copy = getStoredCopy(node, owner); return copy ? resolveLiveCopyKey(owner, copy) : null; }; export const runtimeRootIndex = ( owner: Editor, root: string ): SnapshotIndex => { if (root === getCurrentChildrenRoot(owner)) { return getCurrentRuntimeIndex(owner); } if (getReadProjection(owner)) { return shownRootIndex(owner, root); } const transactionSnapshot = getTransactionSnapshot(owner); return transactionSnapshot ? retainTransactionSnapshotIndex(owner, transactionSnapshot, root) : currentRootIndex(owner, root); }; export const resolveLiveCopyKey = (owner: Editor, copy: object) => { const roots = getEditorDocumentRoots(owner); const lane = getReadProjectionLane(owner); for (const root of Object.keys(roots)) { const index = runtimeRootIndex(owner, root); let nodeKey = getNodeKeyForNode(copy, owner, lane); let path = nodeKey ? index.pathOf(nodeKey) : null; if (!path) { index.entries(); nodeKey = getNodeKeyForNode(copy, owner, lane); path = nodeKey ? index.pathOf(nodeKey) : null; } const rootChildren = readNamedRootChildren(roots, root); if (path && rootChildren && nodeAtPath(rootChildren, path) === copy) { return nodeKey; } } return null; }; export const getEditorNodeKeyForNode = ( editor: Editor, node: Descendant ): NodeKey => { const nodeKey = resolveEditorNodeKeyForNode(editor, node); if (nodeKey) return nodeKey; throw new Error( `Node key requires a live node in this editor; received ${ 'text' in node ? 'text' : `"${node.type}" element` }.` ); }; export const getPathByNodeKey = ( editor: Editor, nodeKey: NodeKey ): Path | null => { const path = getCurrentRuntimeIndex(editor).pathOf(nodeKey); return path ? ([...path] as Path) : null; }; export const findLiveNodeKeys = ( owner: Editor, nodeKeys: readonly NodeKey[] ): ReadonlySet => { if (nodeKeys.length === 0) return new Set(); const snapshot = getDefined(getTransactionSnapshot(owner)); const store = peekOwnerStore(owner); const roots = getEditorDocumentRoots(owner); const committedRoots = store?.roots; const currentRoot = getCurrentChildrenRoot(owner); let committedCurrentIndex: SnapshotIndex | null | undefined; const heldHereAtCommit = (nodeKey: NodeKey) => { committedCurrentIndex ??= store?.snapshotCache.get(currentRoot)?.index ?? null; return ( !!committedCurrentIndex && indexSurelyHoldsNodeKey(owner, committedCurrentIndex, nodeKey) ); }; const pending = new Set(nodeKeys); const live = new Set(); for (const root of Object.keys(roots)) { if (pending.size === 0) break; const unchangedSinceCommit = root !== currentRoot && !!committedRoots && rootNodesOf(roots, root) === rootNodesOf(committedRoots, root); const keys = [...pending].filter( (nodeKey) => !(unchangedSinceCommit && heldHereAtCommit(nodeKey)) ); if (keys.length === 0) continue; const index = retainTransactionSnapshotIndex(owner, snapshot, root); for (const nodeKey of keys) { if (!index.pathOf(nodeKey)) continue; pending.delete(nodeKey); live.add(nodeKey); } } if (pending.size > 0 && isInCommandFrame(owner)) { const contexts = store?.draft.specContexts; const frameIndex = contexts ? contexts.findLastIndex((context) => context.isCommandFrame) : -1; const outer = frameIndex > 0 ? contexts?.[frameIndex - 1] : undefined; const storedRoots = outer ? rootsOfValue(outer.snapshot.builder.value) : committedRoots; if (storedRoots) { for (const root of Object.keys(storedRoots)) { if (pending.size === 0) break; if ( Object.hasOwn(roots, root) && rootNodesOf(storedRoots, root) === rootNodesOf(roots, root) ) { continue; } const index = outer ? withSpecNodeKeyOverlay(owner, outer.specKeyOverlay ?? null, () => retainTransactionSnapshotIndex(owner, outer.snapshot, root) ) : (store?.snapshotCache.get(root)?.index ?? withSpecNodeKeyOverlay(owner, null, () => snapshotIndexOf(owner, rootSourceOf(storedRoots, root), 'stored') )); for (const nodeKey of [...pending]) { if (!index.pathOf(nodeKey)) continue; pending.delete(nodeKey); live.add(nodeKey); } } } } return live; }; export const getLastCommit = (editor: Editor): EditorCommit | null => { const commit = peekOwnerStore(editor)?.lastCommit ?? null; const mapSelection = getTransactionSnapshot(editor)?.frameSelection; if (!commit || !mapSelection || !commit.selectionAfter) return commit; return { ...commit, selectionAfter: mapSelection(commit.selectionAfter), }; }; const equalMarkValue = (left: unknown, right: unknown): boolean => { if (Object.is(left, right)) return true; if (Array.isArray(left) || Array.isArray(right)) { return ( Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => equalMarkValue(value, right[index])) ); } if ( typeof left !== 'object' || left === null || typeof right !== 'object' || right === null ) { return false; } const leftRecord = left as Record; const rightRecord = right as Record; const keys = Object.keys(leftRecord); return ( keys.length === Object.keys(rightRecord).length && keys.every( (key) => Object.hasOwn(rightRecord, key) && equalMarkValue(leftRecord[key], rightRecord[key]) ) ); }; export const getSelectionMarks = ( editor: Editor ): EditorMarks | null => { const marks = getCurrentMarks(editor); const selection = getCurrentSelection(editor); if (!selection) { return null; } const typed = marks ?? getTypedMarks(editor); if (typed) { return typed as EditorMarks; } if (SelectionApi.isNode(selection)) { return withEditorRootChildren( editor, selection.root ?? MAIN_ROOT_KEY, () => { let common: Record | undefined; let commonKeys: string[] = []; for (const path of selection.paths) { for (const [text] of getNodes(editor as unknown as Editor, { at: path, match: NodeApi.isText, })) { if (!common) { common = { ...text }; delete common.text; commonKeys = Object.keys(common); if (commonKeys.length === 0) { return {}; } continue; } let remaining = 0; for (const key of commonKeys) { if ( Object.hasOwn(text, key) && equalMarkValue(common[key], text[key]) ) { commonKeys[remaining] = key; remaining += 1; } else { delete common[key]; } } commonKeys.length = remaining; if (remaining === 0) { return {}; } } } if (!common) return {}; // Dependent package configs preserve the generic mark projection even // when the root type-aware lint sees the assertion as redundant. // oxlint-disable-next-line typescript/no-unnecessary-type-assertion return common as EditorMarks; } ); } if (!RangeApi.isRange(selection)) { return null; } return withEditorRootChildren(editor, getCurrentSelectionRoot(editor), () => { let { anchor, focus } = selection; if (RangeApi.isExpanded(selection)) { if (RangeApi.isBackward(selection)) { [focus, anchor] = [anchor, focus]; } const anchorEnd = readPointEdge(editor, anchor.path, 'end'); if (anchorEnd && PointApi.equals(anchor, anchorEnd)) { const after = getEditorRuntime(editor).after(anchor); if (after) { anchor = after; } } const [match] = getNodes(editor as unknown as Editor, { at: { anchor, focus }, match: NodeApi.isText, }); if (match && NodeApi.isText(match[0])) { const [node] = match; const { text, ...rest } = node; // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- [P0 behavior-boundary] This restores the caller's generic text-mark shape after runtime NodeApi narrowing. return rest as EditorMarks; } return {}; } const { path } = anchor; if (!getEditorRuntime(editor).hasPath(path)) { return null; } const [node] = getEditorRuntime(editor).leaf(path); const { text, ...nodeProperties } = node; const rest: Record = { ...nodeProperties }; if (anchor.offset === node.text.length) { for (const key of Object.keys(rest)) { if ( getEditorSchema(editor).getTextPropertyAt( key, path, anchor.root ?? getCurrentSelectionRoot(editor) )?.lifecycle.inclusive === false ) { delete rest[key]; } } } // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- [P0 behavior-boundary] This restores the caller's generic text-mark shape after property filtering. return rest as EditorMarks; }); }; const createNodesToArray = ( editor: Editor ): EditorStateNodesApi['toArray'] => { const toArray = ( options: EditorNodesReadOptions = {} ): readonly NodeEntry[] => readAtOptionsTarget(editor, options, [], (routedOptions) => { const resolvedOptions = resolveNodeTargetOrSpanOptions( editor, routedOptions ); if (resolvedOptions === null) return []; return withOptionsRootRead( editor, resolvedOptions, () => hasReadableNodeCollection(editor, resolvedOptions) ? Array.from( getNodes( editor as unknown as Editor, resolvedOptions as EditorNodesOptions ) ) : [], { selectionFallback: usesImplicitSelectionLocation(resolvedOptions), } ); }); return toArray as EditorStateNodesApi['toArray']; }; type SelectionBlockState = Pick< EditorCoreStateView, 'nodes' >; type SelectionQueryState = Pick< EditorCoreStateView, 'nodes' | 'ranges' >; export const getSelectionNodeEntries = ( editor: Editor, state: Pick, 'nodes'>, selection: Selection, fallbackRoot: string = MAIN_ROOT_KEY ): ReadonlyArray>> => { if (!SelectionApi.isNode(selection)) return []; const root = selection.root ?? fallbackRoot; const entries = withEditorRootChildren(editor, root, () => selection.paths.flatMap((path) => { const entry = state.nodes.get(path, { match: (node): node is DescendantIn => NodeApi.isDescendant(node), }); return entry ? [entry] : []; }) ); return Object.freeze(entries); }; const WHITESPACE_OR_END_REGEX = /^(?:\s|$)/; const resolveSelectionQueryRange = ( state: Pick, selection: Range | null, at: TextTarget | null | undefined ): Range | null => { if (at === null) return null; if (at === undefined) return selection; return state.ranges.get(at) ?? null; }; const getSelectionBlockEntries = ( state: SelectionBlockState, selection: Range | null, options: EditorSelectionBlockOptions = {} ) => { if (!selection) { return { endBlock: undefined, startBlock: undefined, }; } const [startPoint, endPoint] = RangeApi.edges(selection); return { endBlock: state.nodes.block({ at: endPoint, match: options.match, type: options.type, }), startBlock: state.nodes.block({ at: startPoint, match: options.match, type: options.type, }), }; }; export const isSelectionWithinBlock = ( state: SelectionQueryState, selection: Range | null, options: EditorSelectionBlockOptions = {} ) => { const range = resolveSelectionQueryRange(state, selection, options.at); const { endBlock, startBlock } = getSelectionBlockEntries( state, range, options ); return !!( startBlock && endBlock && PathApi.equals(startBlock[1], endBlock[1]) ); }; export const isSelectionAcrossBlocks = ( state: SelectionQueryState, selection: Range | null, options: EditorSelectionBlockOptions = {} ) => { const range = resolveSelectionQueryRange(state, selection, options.at); const { endBlock, startBlock } = getSelectionBlockEntries( state, range, options ); if (!startBlock && !endBlock) return false; if (!startBlock || !endBlock) return true; return !PathApi.equals(startBlock[1], endBlock[1]); }; export const isSelectionAtBlockStart = ( state: SelectionQueryState & Pick, 'points'>, selection: Range | null, options: EditorSelectionBlockOptions = {} ) => { const range = resolveSelectionQueryRange(state, selection, options.at); const { startBlock } = getSelectionBlockEntries(state, range, options); if (!range || !startBlock) return false; const [startPoint, endPoint] = RangeApi.edges(range); return ( state.points.isStart(startPoint, startBlock[1]) || (RangeApi.isExpanded(range) && state.points.isStart(endPoint, startBlock[1])) ); }; export const isSelectionAtBlockEnd = ( state: SelectionQueryState & Pick, 'points'>, selection: Range | null, options: EditorSelectionBlockOptions = {} ) => { const range = resolveSelectionQueryRange(state, selection, options.at); const { endBlock } = getSelectionBlockEntries(state, range, options); if (!range || !endBlock) return false; const endPoint = RangeApi.end(range); if (state.points.isEnd(endPoint, endBlock[1])) return true; if (!state.points.isEnd(endPoint, endPoint.path)) return false; const pointAfter = state.points.after(endPoint, { unit: 'offset' }); const nextBlock = pointAfter ? state.nodes.block({ at: pointAfter, match: options.match, type: options.type, }) : undefined; return !!nextBlock && !PathApi.equals(endBlock[1], nextBlock[1]); }; export const doesSelectionIntersect = ( state: Pick, selection: Selection, target: NodeTarget, selectionRanges: readonly Range[] = RangeApi.isRange(selection) ? [selection] : [] ) => { if (!selection) return false; const range = state.ranges.get(target); return ( !!range && selectionRanges.some( (selectionRange) => !!RangeApi.intersection(selectionRange, range) ) ); }; export const doesSelectionContain = ( state: Pick, selection: Selection, target: NodeTarget, selectionRanges: readonly Range[] = RangeApi.isRange(selection) ? [selection] : [] ) => { if (!selection) return false; const range = state.ranges.get(target); return ( !!range && selectionRanges.some((selectionRange) => RangeApi.surrounds(selectionRange, range) ) ); }; const isReadMethodRecord = (value: object) => { const prototype = Object.getPrototypeOf(value); if (prototype === null) return true; const objectConstructor = Object.getOwnPropertyDescriptor( prototype, 'constructor' )?.value; return ( Object.getPrototypeOf(prototype) === null && typeof objectConstructor === 'function' && objectConstructor.name === 'Object' ); }; const READ_METHOD_FUNCTION_INTRINSIC_KEYS = new Set([ 'arguments', 'caller', 'length', 'name', 'prototype', ]); const isValidFunctionIntrinsicDescriptor = ( key: string, descriptor: PropertyDescriptor ) => { if (!('value' in descriptor) || descriptor.enumerable) return false; switch (key) { case 'length': { return ( typeof descriptor.value === 'number' && descriptor.writable === false ); } case 'name': { return ( typeof descriptor.value === 'string' && descriptor.writable === false ); } case 'arguments': case 'caller': { return ( descriptor.value === null && descriptor.writable === false && descriptor.configurable === false ); } case 'prototype': { return ( typeof descriptor.value === 'object' && descriptor.value !== null && descriptor.configurable === false ); } default: { return false; } } }; const freezeReadMethodTree = ( groupName: string, value: unknown, path: readonly string[] = [], visited = new WeakSet() ): unknown => { if (typeof value !== 'function' && (typeof value !== 'object' || !value)) { throw new TypeError( `Editor read group "${groupName}" must return a callable method tree; "${[ groupName, ...path, ].join('.')}" is a data value.` ); } if (Array.isArray(value)) { throw new TypeError( `Editor read group "${groupName}" must return a callable method tree; arrays are not supported.` ); } if (visited.has(value)) { throw new TypeError( `Editor read group "${groupName}" must return a callable method tree; cycles are not supported.` ); } if (typeof value !== 'function' && !isReadMethodRecord(value)) { throw new TypeError( `Editor read group "${groupName}" must return a callable method tree; only plain records and methods are supported.` ); } visited.add(value); for (const key of Reflect.ownKeys(value)) { const descriptor = getDefined(Object.getOwnPropertyDescriptor(value, key)); if ( typeof value === 'function' && typeof key === 'string' && READ_METHOD_FUNCTION_INTRINSIC_KEYS.has(key) ) { if (!isValidFunctionIntrinsicDescriptor(key, descriptor)) { throw new TypeError( `Editor read group "${groupName}" must return a callable method tree; function intrinsic property "${key}" was redefined.` ); } continue; } if (typeof key === 'symbol') { throw new TypeError( `Editor read group "${groupName}" must return a callable method tree; symbol properties are not supported.` ); } if (key === 'then' || key === 'toJSON') { throw new TypeError( `Editor read group "${groupName}" method "${[...path, key].join( '.' )}" uses a reserved protocol name.` ); } if ('get' in descriptor || 'set' in descriptor) { throw new TypeError( `Editor read group "${groupName}" must return a callable method tree; accessors are not supported.` ); } if (!descriptor.enumerable) { throw new TypeError( `Editor read group "${groupName}" must return a callable method tree; non-enumerable properties are not supported.` ); } freezeReadMethodTree(groupName, descriptor.value, [...path, key], visited); } visited.delete(value); return Object.freeze(value); }; const createReadFactoryState = ( state: Record ) => { let constructing = true; const cache = new WeakMap(); const guard = (value: unknown): unknown => { if ( (typeof value !== 'object' || value === null) && typeof value !== 'function' ) { return value; } const existing = cache.get(value); if (existing) return existing; const target = typeof value === 'function' ? () => {} : Object.create(Reflect.getPrototypeOf(value)); const synchronizedKeys = new Set(); const synchronizeOwnProperty = (key: PropertyKey) => { if (synchronizedKeys.has(key)) return; const descriptor = Reflect.getOwnPropertyDescriptor(value, key); if (!descriptor) { synchronizedKeys.add(key); return; } const targetDescriptor = Reflect.getOwnPropertyDescriptor(target, key); if (targetDescriptor && !targetDescriptor.configurable) { synchronizedKeys.add(key); return; } Object.defineProperty( target, key, 'value' in descriptor ? { configurable: true, enumerable: descriptor.enumerable, value: guard(descriptor.value), writable: descriptor.writable, } : { configurable: true, enumerable: descriptor.enumerable, get: descriptor.get ? (guard(descriptor.get) as () => unknown) : undefined, set: descriptor.set ? (guard(descriptor.set) as (value: unknown) => void) : undefined, } ); synchronizedKeys.add(key); }; const synchronizeOwnProperties = () => { for (const key of Reflect.ownKeys(value)) synchronizeOwnProperty(key); }; const proxy = new Proxy(target, { apply(_target, thisArg, args) { if (constructing) { throw new Error( 'Editor read factories cannot read document state while constructing read groups. Return methods that read state when invoked.' ); } return Reflect.apply( value as (...args: unknown[]) => unknown, thisArg, args ); }, get(_target, key) { return guard(Reflect.get(value, key, value)); }, getOwnPropertyDescriptor(_target, key) { synchronizeOwnProperty(key); return Reflect.getOwnPropertyDescriptor(target, key); }, has(_target, key) { return Reflect.has(value, key); }, ownKeys() { synchronizeOwnProperties(); return Reflect.ownKeys(target); }, preventExtensions() { synchronizeOwnProperties(); return Reflect.preventExtensions(target); }, }); cache.set(value, proxy); return proxy; }; return { finish: () => { constructing = false; }, state: guard(state) as T, }; }; export const getStateView = < V extends Value, TPlugins extends readonly unknown[] = readonly [], >( editor: Editor ): EditorStateView => { const registry = getPluginRegistry(editor); const owner = getEditorRuntimeOwner(editor); const transformGeneration = peekOwnerStore(owner)?.stateViewTransformGeneration ?? 0; const cached = STATE_VIEW_CACHE.get(editor); if ( cached?.registry === registry && cached.transformGeneration === transformGeneration ) { return cached.view as unknown as EditorStateView; } if (CONSTRUCTING_STATE_VIEWS.has(editor)) { throw new Error( 'editor.read cannot be called while constructing read groups' ); } CONSTRUCTING_STATE_VIEWS.add(editor); try { let state!: EditorStateView; const fragmentApi = Object.freeze(((options = {}) => withOptionsRootRead( editor, options, () => { if (options.at && !hasLocationPath(editor, options.at)) { return []; } return getFragment(editor, options) as ReturnType< EditorStateFragmentApi >; }, { selectionFallback: usesImplicitSelectionLocation(options) } )) satisfies EditorStateFragmentApi); const marksApi = Object.freeze((() => getSelectionMarks(editor)) satisfies EditorStateMarksApi); const getSlice: EditorStateSliceApi['get'] = (options = {}) => { const selection = getCurrentSelection(editor); const target = options.at ?? selection; const read = () => { if ( target && RangeApi.isRange(target) && !hasLocationPath(editor, target) ) { return ContentSlice.empty; } return getContentSlice( editor, SelectionApi.isNode(target) || RangeApi.isRange(target) ? target : null ); }; const slice = SelectionApi.isNode(target) ? withEditorRootChildren( editor, getNodeSelectionRoot( editor, target, options.at === undefined ? 'stored' : 'target' ), read ) : withOptionsRootRead(editor, options as { at?: Range }, read, { selectionFallback: options.at === undefined, }); return projectEditorGetSlice(editor, slice, options); }; const sliceApi = Object.freeze({ export: (options = {}) => projectEditorExportSlice(editor, getSlice(options), options), fit: ( slice: import('../interfaces/editor').ContentSlice, options?: Parameters['fit']>[1] ) => createSliceFitTransactionSpec(editor, slice, options), fitContent: ( slice: import('../interfaces/editor').ContentSlice, options: Parameters['fitContent']>[1] ) => { if (options.root === MAIN_ROOT_KEY) { throw new Error('Omit root to use the primary document context.'); } const scopedRoot = getCurrentChildrenRoot(editor); const root = options.root ?? (scopedRoot === MAIN_ROOT_KEY ? undefined : scopedRoot); return getEditorSchema(editor).fitContent( ContentSlice.fromJSON(slice), { parent: options.parent, ...(root === undefined ? {} : { root }), } ) as ReadonlyArray> | null; }, get: getSlice, }) satisfies EditorStateSliceApi; const selectionNodes = () => getSelectionNodeEntries( editor, state, getCurrentSelection(editor), getCurrentSelectionRoot(editor) ); const selectionApi = Object.freeze( Object.assign(() => getPublicSelection(editor), { contains: (target: NodeTarget) => { const selection = getCurrentSelection(editor); return doesSelectionContain( state, selection, target, getSelectionRanges( editor, selection, getEditorDocumentValue(editor), getCurrentSelectionRoot(editor) ) ); }, intersects: (target: NodeTarget) => { const selection = getCurrentSelection(editor); return doesSelectionIntersect( state, selection, target, getSelectionRanges( editor, selection, getEditorDocumentValue(editor), getCurrentSelectionRoot(editor) ) ); }, isAcrossBlocks: (options?: EditorSelectionBlockOptions) => isSelectionAcrossBlocks(state, getPublicSelection(editor), options), isAtBlockEnd: (options?: EditorSelectionBlockOptions) => isSelectionAtBlockEnd(state, getPublicSelection(editor), options), isAtBlockStart: (options?: EditorSelectionBlockOptions) => isSelectionAtBlockStart(state, getPublicSelection(editor), options), isCollapsed: () => { const selection = getPublicSelection(editor); return selection ? RangeApi.isCollapsed(selection) : false; }, isExpanded: () => { const selection = getPublicSelection(editor); return selection ? RangeApi.isExpanded(selection) : false; }, isValid: (value: unknown) => isValidEditorSelection( editor, value, getEditorDocumentValue(editor), getCurrentChildrenRoot(editor) ), isWithinBlock: (options?: EditorSelectionBlockOptions) => isSelectionWithinBlock(state, getPublicSelection(editor), options), nodeMode: () => { const selection = getCurrentSelection(editor); return SelectionApi.isNode(selection) ? selection.mode : null; }, nodes: selectionNodes as EditorStateSelectionApi< EditorSelection, V >['nodes'], ranges: () => getSelectionRanges( editor, getCurrentSelection(editor), getEditorDocumentValue(editor), getCurrentSelectionRoot(editor) ), value: () => getCurrentSelection(editor), }) satisfies EditorStateSelectionApi ); const findNode = ( options: EditorNodesReadOptions = {} ): NodeEntry | undefined => readAtOptionsTarget(editor, options, undefined, (routedOptions) => { const resolvedOptions = resolveNodeTargetOrSpanOptions( editor, routedOptions ); if (resolvedOptions === null) return undefined; return withOptionsRootRead( editor, resolvedOptions, () => { if (!hasReadableNodeCollection(editor, resolvedOptions)) { return undefined; } const [entry] = getNodes( editor as unknown as Editor, resolvedOptions ); return entry; }, { selectionFallback: usesImplicitSelectionLocation(resolvedOptions), } ); }); const readBlock = (( options: { at?: NodeTarget; match?: NodeMatch; mode?: MaximizeMode; type?: NodeTypeSelector; voids?: boolean; } = {} ) => readAtOptionsTarget(editor, options, undefined, (routedOptions) => { const resolvedOptions = resolveNodeTargetOptions(editor, routedOptions); if (resolvedOptions === null) return undefined; const nextOptions = resolvedOptions ?? {}; const { at, match } = nextOptions; if ( at && !withLocationRootRead(editor, at, () => hasLocationPath(editor, at)) ) { return undefined; } const exact = PathApi.isPath(at) ? readNodeEntry(editor, at) : undefined; if ( exact && NodeApi.isElement(exact[0]) && getEditorSchema(editor).isBlock(exact[0]) && (match?.(exact[0], exact[1]) ?? true) ) { return exact as NodeEntry; } const entry = getEditorRuntime(editor).above({ ...nextOptions, match: (node, path) => NodeApi.isElement(node) && getEditorSchema(editor).isBlock(node) && (match?.(node, path) ?? true), }); return entry && NodeApi.isElement(entry[0]) ? (entry as NodeEntry) : undefined; })) as EditorStateNodesApi['block']; const readBlocks = (( inputOptions: Parameters['blocks']>[0] = {} ) => { const target = inputOptions.at ?? getCurrentSelection(editor) ?? undefined; if (!target) return []; const match = normalizeCallerMatch( editor, inputOptions.type, inputOptions.match ); const matchesBlock = (node: PliteNode, path: Path) => NodeApi.isElement(node) && getEditorSchema(editor).isBlock(node) && (match?.(node, path) ?? true); if (SelectionApi.isNode(target)) { return withEditorRootChildren( editor, getNodeSelectionRoot( editor, target, inputOptions.at === undefined ? 'stored' : 'target' ), () => { const entries: Array> = []; const seen = new Set(); const { at: _at, coverage, reverse: _reverse, ...queryOptions } = inputOptions; const full = coverage === 'full'; for (const path of target.paths) { if (!NodeApi.has(editor, path)) continue; const selectedBlocks = ( Array.from( getNodes(editor as unknown as Editor, { ...queryOptions, at: path, match: matchesBlock, mode: full ? 'all' : (queryOptions.mode ?? 'lowest'), }) ) as Array> ).filter( ([, blockPath]) => !full || PathApi.equals(path, blockPath) || PathApi.isAncestor(path, blockPath) ); const fallbackBlock = selectedBlocks.length === 0 && !full ? readBlock({ at: path, match: matchesBlock }) : undefined; const blocks = selectedBlocks.length > 0 ? selectedBlocks : fallbackBlock ? [fallbackBlock as NodeEntry] : []; for (const block of blocks) { const key = block[1].join(','); if (!seen.has(key)) { seen.add(key); entries.push(block); } } } const read = full ? narrowCoveredBlocks( entries.toSorted(([, a], [, b]) => PathApi.compare(a, b)), queryOptions.mode ) : entries; return Object.freeze( inputOptions.reverse ? read.toReversed() : read ); } ); } const { coverage, ...targetOptions } = inputOptions; return readAtOptionsTarget( editor, { ...targetOptions, at: target }, Object.freeze([]) as ReadonlyArray>, (routedOptions) => { const resolvedOptions = resolveNodeTargetOrSpanOptions( editor, routedOptions ); if (resolvedOptions === null) return []; const queryOptions = resolvedOptions ?? {}; const full = coverage === 'full'; const { at } = queryOptions; const coveredPath = full && PathApi.isPath(at) ? at : null; const coveredRange = !full || !at || coveredPath || SelectionApi.isNode(at) ? null : LocationApi.isSpan(at) ? readRange(editor, at[0], at[1]) : readRange(editor, at); if (coveredRange === undefined) return []; if (coveredRange && RangeApi.isCollapsed(coveredRange)) return []; return withOptionsRootRead(editor, queryOptions, () => { if (!hasReadableNodeCollection(editor, queryOptions)) return []; const entries = Array.from( getNodes(editor as unknown as Editor, { ...queryOptions, match: matchesBlock, mode: full ? 'all' : (queryOptions.mode ?? 'lowest'), reverse: !full && queryOptions.reverse, }) ) as Array>; if (!full) return Object.freeze(entries); const schema = getEditorSchema(editor); const [rangeStart, rangeEnd] = coveredRange ? RangeApi.edges(coveredRange) : []; const covered = entries.filter(([block, path]) => coveredPath ? PathApi.equals(coveredPath, path) || PathApi.isAncestor(coveredPath, path) : !rangeStart || !rangeEnd || rangeCoversBlock(schema, block, path, rangeStart, rangeEnd) ); const read = narrowCoveredBlocks(covered, queryOptions.mode); return Object.freeze( queryOptions.reverse ? read.toReversed() : read ); }); } ); }) as EditorStateNodesApi['blocks']; function getStateNodeKey(node: Descendant): NodeKey; function getStateNodeKey(at: Location): NodeKey | null; function getStateNodeKey(target: Descendant | Location): NodeKey | null { const key = NodeApi.isDescendant(target) ? getEditorNodeKeyForNode(editor, target) : withLocationRootRead(editor, target, () => { const path = readNodePath(editor, target); return path ? getNodeKey(editor, path) : null; }); if (key) noteKeyRead(editor, key); return key; } const coreState = { children: () => (getEditorDocumentRoots(editor)[MAIN_ROOT_KEY] ?? []) as unknown as ReturnType['children']>, fragment: fragmentApi, getField: (field: EditorStateField) => getStateFieldValue(editor, field), key: getStateNodeKey, lastCommit: () => getLastCommit(editor) as EditorCommit | null, marks: marksApi, nodes: Object.freeze>({ above: ((options = {}) => readAtOptionsTarget(editor, options, undefined, (routedOptions) => { const resolvedOptions = resolveNodeTargetOptions( editor, routedOptions ); if (resolvedOptions === null) return undefined; return getEditorRuntime(editor).above(resolvedOptions) as | [Ancestor, Path] | undefined; })) as EditorStateNodesApi['above'], block: readBlock, blocks: readBlocks, byId: ((id: string) => { const holder = lookupElementId(editor, id); return holder && readElementEntry(editor, holder); }) as EditorStateNodesApi['byId'], children( target: NodeTarget = [] ): ReturnType['children']> { return readAtNodeTarget( editor, target, [] as ReturnType['children']>, (at) => withLocationRootRead(editor, at, () => readNodeChildren(editor, at) ) as ReturnType['children']> ); }, elementReadOnly: (options = {}) => readAtOptionsTarget(editor, options, undefined, (routedOptions) => { const resolvedOptions = resolveNodeTargetOptions( editor, routedOptions ); if (resolvedOptions === null) return undefined; return getEditorRuntime(editor).elementReadOnly( resolvedOptions ) as ReturnType['elementReadOnly']>; }), first: (target: NodeTarget) => readAtNodeTarget(editor, target, undefined, (at) => withLocationRootRead(editor, at, () => readNodeFirst(editor, at)) ) as ReturnType['first']>, get: (( target: NodeTarget, options: EditorNodeGetOptions = {} ) => readAtNodeTarget(editor, target, undefined, (at) => withLocationRootRead(editor, at, () => { const entry = readNodeEntry(editor, at); const match = normalizeCallerMatch( editor, options.type, options.match ); if (!entry) return undefined; return !match || match(entry[0], entry[1]) ? entry : undefined; }) )) as EditorStateNodesApi['get'], isContent: (node: import('../interfaces/node').Node) => isEditorContent(editor, node), isSelectable: (element: import('../interfaces/node').Node) => isEditorNodeSelectable(editor, element), isEmpty: (element: import('../interfaces/element').Element) => getEditorRuntime(editor).isEmpty(element), last: (target: NodeTarget, options = {}) => readAtNodeTarget(editor, target, undefined, (at) => getEditorRuntime(editor).last(at, options) ) as ReturnType['last']>, leaf: (target: NodeTarget, options: EditorLeafOptions = {}) => readAtNodeTarget(editor, target, undefined, (at) => withLocationRootRead(editor, at, () => readNodeLeaf(editor, at, options) ) ) as ReturnType['leaf']>, levels: (options = {}) => readAtOptionsTargetGenerator(editor, options, (routedOptions) => { const resolvedOptions = resolveNodeTargetOptions( editor, routedOptions ); if (resolvedOptions === null) return []; return hasReadableNodeCollection(editor, resolvedOptions) ? getEditorRuntime(editor).levels(resolvedOptions) : []; }) as Generator<[T, Path], void, undefined>, path: (target: NodeTarget, options: EditorPathOptions = {}) => { // A Path has no root discriminator. Keep this lookup scoped to the // current editor/view root; use a root view for a named-root path. const id = elementIdOf(target); const holder = id === undefined ? null : lookupElementId(editor, id); const at = id === undefined ? resolveNodeTargetLocation(editor, target as TextTarget) : holder?.root === getCurrentChildrenRoot(editor) ? holder.path : undefined; if (!at) return undefined; return withLocationRootRead(editor, at, () => readNodePath(editor, at, options) ); }, entries: (options = {}) => readAtOptionsTargetGenerator(editor, options, (routedOptions) => { const resolvedOptions = resolveNodeTargetOrSpanOptions( editor, routedOptions ); if (resolvedOptions === null) return []; return withOptionsRootGenerator( editor, resolvedOptions, () => hasReadableNodeCollection(editor, resolvedOptions) ? getNodes(editor as unknown as Editor, resolvedOptions) : [], { selectionFallback: usesImplicitSelectionLocation(resolvedOptions), } ); }) as Generator<[T, Path], void, undefined>, find: findNode as EditorStateNodesApi['find'], some: (options = {}) => findNode(options) !== undefined, toArray: createNodesToArray(editor), next: ((options = {}) => readAtOptionsTarget(editor, options, undefined, (routedOptions) => { const resolvedOptions = resolveNodeTargetOptions( editor, routedOptions ); if (resolvedOptions === null) return undefined; return ( hasReadableNodeCollection(editor, resolvedOptions) ? getEditorRuntime(editor).next(resolvedOptions) : undefined ) as [PliteNode, Path] | undefined; })) as EditorStateNodesApi['next'], previous: ((options = {}) => readAtOptionsTarget(editor, options, undefined, (routedOptions) => { const resolvedOptions = resolveNodeTargetOptions( editor, routedOptions ); if (resolvedOptions === null) return undefined; return ( hasReadableNodeCollection(editor, resolvedOptions) ? getEditorRuntime(editor).previous(resolvedOptions) : undefined ) as [PliteNode, Path] | undefined; })) as EditorStateNodesApi['previous'], parent: ((target: NodeTarget, options: EditorParentOptions = {}) => readAtNodeTarget(editor, target, undefined, (at) => withLocationRootRead(editor, at, () => { const entry = readNodeParent(editor, at, options); const match = normalizeCallerMatch( editor, options.type, options.match ); if (!entry) return undefined; return !match || match(entry[0], entry[1]) ? entry : undefined; }) )) as EditorStateNodesApi['parent'], revision: (id: string) => readStoredElementRevision(editor, id, getCurrentChildrenRoot(editor)), void: (options = {}) => readAtOptionsTarget(editor, options, undefined, (routedOptions) => { const resolvedOptions = resolveNodeTargetOptions( editor, routedOptions ); if (resolvedOptions === null) return undefined; return getEditorRuntime(editor).void(resolvedOptions) as ReturnType< EditorStateNodesApi['void'] >; }), }), points: Object.freeze({ after: (target: NodeTarget, options = {}) => readAtNodeTarget(editor, target, undefined, (at) => readAdjacentPoint(editor, at, 'after', options) ), before: (target: NodeTarget, options = {}) => readAtNodeTarget(editor, target, undefined, (at) => readAdjacentPoint(editor, at, 'before', options) ), end: (target: NodeTarget) => readAtNodeTarget(editor, target, undefined, (at) => readPointEdge(editor, at, 'end') ), get: (target: NodeTarget, options: EditorPointOptions = {}) => readAtNodeTarget(editor, target, undefined, (at) => readPoint(editor, at, options) ), isEdge: (point, target) => readAtNodeTarget(editor, target, false, (at, root, callerRoot) => { assertInTargetRoot(callerRoot, root, point); return ( hasLocationTextEdge(editor, at) && getEditorRuntime(editor).isEdge(point, at) ); }), isEnd: (point, target) => readAtNodeTarget(editor, target, false, (at, root, callerRoot) => { assertInTargetRoot(callerRoot, root, point); return ( hasLocationTextEdge(editor, at) && getEditorRuntime(editor).isEnd(point, at) ); }), isStart: (point, target) => readAtNodeTarget(editor, target, false, (at, root, callerRoot) => { assertInTargetRoot(callerRoot, root, point); return ( hasLocationTextEdge(editor, at) && getEditorRuntime(editor).isStart(point, at) ); }), isWordEnd: (point) => { const after = state.points.after(point); if (!after) return true; const range = state.ranges.get(point, after); return ( !!range && WHITESPACE_OR_END_REGEX.test(state.text.string(range)) ); }, positions: (options = {}) => readAtOptionsTargetGenerator(editor, options, (routedOptions) => { const resolvedOptions = resolveNodeTargetOptions( editor, routedOptions ); if ( resolvedOptions === null || !hasReadableNodeCollection(editor, resolvedOptions) ) { return []; } const root = getEditorChildrenRoot(editor); const iterable = getEditorRuntime(editor).positions(resolvedOptions); if (!root || root === MAIN_ROOT_KEY) return iterable; return (function* positions() { for (const point of iterable) { yield point.root === root ? point : { ...point, root }; } })(); }), start: (target: NodeTarget) => readAtNodeTarget(editor, target, undefined, (at) => readPointEdge(editor, at, 'start') ), }), ranges: Object.freeze({ edges: (target: NodeTarget) => readAtNodeTarget(editor, target, undefined, (at) => readRangeEdges(editor, at) ), fromEntries: (entries) => readRangeFromEntries(editor, entries), get: (target: NodeTarget, to?: Location) => readAtNodeTarget( editor, target, undefined, (at, root, callerRoot) => { assertInTargetRoot(callerRoot, root, to); return readRange(editor, at, to); } ), isEmpty: (range) => withLocationRootRead(editor, range, () => { const source = getChildrenSource(editor); const index = source instanceof DocumentIndex ? source : DocumentIndex.fromValue(source); const from = index.positionAt(range.anchor); const to = index.positionAt(range.focus); return !coversContent( index, Math.min(from, to), Math.max(from, to), getEditorSchema(editor) ); }), unhang: (range, options = {}) => getEditorRuntime(editor).unhangRange(range, options), }), revision: () => readStoredDocumentRevision(editor), root: (root: RootKey) => { if (root === MAIN_ROOT_KEY) { throw new Error( 'editor.read.root("main") is invalid. Use editor.read.children().' ); } assertDocumentRootKey(root); return (readNamedRootChildren(getEditorDocumentRoots(editor), root) ?? []) as ReturnType['root']>; }, roots: () => readRootEntries(editor), runtime: Object.freeze({ snapshot: () => getSnapshot(editor) as EditorSnapshot, }), schema: getEditorSchema(editor), selection: selectionApi, slice: sliceApi, text: Object.freeze({ string: (target?: NodeSelection | NodeTarget, options = {}) => { const resolvedTarget = target ?? getCurrentSelection(editor); if (!resolvedTarget) return ''; if (SelectionApi.isNode(resolvedTarget)) { return withEditorRootChildren( editor, getNodeSelectionRoot( editor, resolvedTarget, target === undefined ? 'stored' : 'target' ), () => resolvedTarget.paths .filter((path) => NodeApi.has(editor, path)) .map((path) => getEditorRuntime(editor).string(path, options)) .join('') ); } return readAtNodeTarget(editor, resolvedTarget, '', (at) => withLocationRootRead(editor, at, () => hasLocationPath(editor, at) ? getEditorRuntime(editor).string(at, options) : '' ) ); }, }), unique: Object.freeze({ holder: (property: string, value: unknown) => readUniqueHolder(editor, property, value), }), persisted: (options?: Readonly<{ selection?: boolean }>) => { const document = withEditorDocumentProjection(editor, undefined, () => getEditorDocumentValue(editor) ) as unknown as ReturnType['value']>; const schema = getEditorSchema(editor).identity(); if (!options?.selection) { return Object.freeze({ document, schema }); } const selection = withEditorDocumentProjection(editor, undefined, () => withEditorViewSelectionRead(editor, undefined, () => { const current = getCurrentSelection(editor); if (!current) return null; const root = getCurrentSelectionRoot(editor); if (root === MAIN_ROOT_KEY) return current; if (SelectionApi.isNode(current)) { return SelectionApi.nodes(current.paths, { anchorPath: current.anchorPath, focusPath: current.focusPath, mode: current.mode, root, }); } return SelectionApi.text( { anchor: { ...current.anchor, root }, focus: { ...current.focus, root }, }, { ...(current.affinity === undefined ? {} : { affinity: current.affinity }), ...(current.marks === undefined ? {} : { marks: current.marks }), } ); }) ); return Object.freeze({ document, schema, selection }); }, value: () => withEditorDocumentProjection(editor, undefined, () => getEditorDocumentValue(editor) ) as unknown as ReturnType['value']>, view: Object.freeze({ isComposing: () => getEditorViewState(editor, 'composing'), isFocused: () => getEditorViewState(editor, 'focused'), isReadOnly: () => getEditorViewState(editor, 'readOnly'), isViewing: () => isModelEditorViewing(editor), root: () => undefined, }), } satisfies EditorCoreStateView; const stateRecord = coreState as unknown as Record; stateRecord.transaction = Object.assign( (fn: (transaction: EditorTransactionSpecBuilder) => void) => createTransactionSpec(editor, fn), { extend: ( base: TransactionSpec, fn: (transaction: EditorTransactionSpecBuilder) => void ) => extendTransactionSpec(editor, base, fn), } ); STATE_VIEW_TRANSFORMS.get(owner)?.(stateRecord); for (const [groupName, registration] of getPluginRegistry(editor as Editor) .stateGroups) { const factoryState = createReadFactoryState(stateRecord); try { stateRecord[groupName] = freezeReadMethodTree( groupName, registration.factory(factoryState.state, editor as Editor) ); } finally { factoryState.finish(); } } state = Object.freeze(stateRecord) as EditorStateView; STATE_VIEW_OWNERS.set(state, owner); STATE_VIEW_CACHE.set(editor, { registry, transformGeneration, view: state as unknown as EditorStateView, }); return state; } finally { CONSTRUCTING_STATE_VIEWS.delete(editor); } }; /** * Read the full state view without suspending an active draft. * * @internal */ export const getEditorStateView = < V extends Value, TPlugins extends readonly unknown[] = readonly [], >( editor: Editor ): EditorStateView => getStateView(editor); export const createEditorViewReadState = ( editor: Editor, core: T, presentation: ViewPresentation ): T => { const state = { ...core } as Record; setStatePresentation(state, presentation); for (const [name, registration] of getPluginRegistry(editor).stateGroups) { const factoryState = createReadFactoryState(state); setStatePresentation(factoryState.state, presentation); try { state[name] = freezeReadMethodTree( name, registration.factory(factoryState.state, editor) ); } finally { factoryState.finish(); } } return Object.freeze(state) as T; }; export const evaluateSchemaCanWrap = ( editor: Editor, element: Element, options: Readonly<{ at?: Location; replace?: boolean; root?: RootKey; split?: boolean; }> = {} ): boolean => { const run = (): boolean => { if (options.root !== undefined) { assertDocumentRootKey(options.root); } const owner = getEditorRuntimeOwner(editor); const scopedRoot = options.root ?? getActiveScopeFrame(owner).viewReadRoot ?? getActiveUpdateRoot(owner); const target = options.at ?? (scopedRoot !== undefined ? withEditorViewSelectionRead(editor, scopedRoot, () => getCurrentSelection(editor) ) : getCurrentSelection(editor)); if (!target || SelectionApi.isNode(target)) return false; if (options.root !== undefined) { const explicitRoot = options.root; return withRoutedCallerScope(editor, () => withEditorRootChildren(editor, explicitRoot, () => hasLocationPath(editor, target) ? canWrapAtTarget( editor as unknown as Editor, element, stripLocationRoots(target), { replace: options.replace, root: explicitRoot, split: options.split, } ) : false ) ); } return withLocationRootRead( editor, target, () => hasLocationPath(editor, target) ? canWrapAtTarget( editor as unknown as Editor, element, stripLocationRoots(target), { replace: options.replace, root: getCurrentChildrenRoot(editor), split: options.split, } ) : false, { selectionFallback: options.at === undefined } ); }; return withActiveSchemaReadScope(editor, run); }; export const hasInternalEditorState = (value: unknown): value is Editor => typeof value === 'object' && value !== null && hasInitializedOwnerStore(value as Editor); export const getSnapshot = (editor: Editor): EditorSnapshot => { const projection = getReadProjection(editor); if (projection) { const root = getCurrentChildrenRoot(editor); const owner = getEditorRuntimeOwner(editor); const lane = getReadProjectionLane(owner); const store = getOwnerStore(owner); let projections = store.projectionSnapshots; if (!projections) { projections = new WeakMap(); store.projectionSnapshots = projections; } let snapshots = projections.get(projection); if (!snapshots) { snapshots = new Map(); projections.set(projection, snapshots); } const cacheKey = `${lane}:${root}`; const previous = snapshots.get(cacheKey); const selection = getRootScopedSelection( getCurrentSelection(editor), getCurrentSelectionRoot(editor), root ); const version = getVersion(editor); if ( previous?.version === version && SelectionApi.equals(previous.selection, selection) ) { return previous; } const children = getChildrenSource(editor); const storedChildren = lane === 'accepted' || lane === 'proposed' ? getStoredRootChildrenSource(owner, root) : undefined; let index: SnapshotIndex | undefined; const snapshot: Record = { selection, version }; setRoot(snapshot, 'children', children); Object.defineProperty(snapshot, 'index', { enumerable: true, get: () => (index ??= getEditorProjectionSnapshotIndex( owner, children, lane, storedChildren )), }); const frozen = Object.freeze(snapshot) as unknown as EditorSnapshot; snapshots.set(cacheKey, frozen); return frozen; } const owner = getEditorRuntimeOwner(editor); const usesViewChildrenSource = editor !== owner && (VIEW_ROOT_CHILDREN_OVERRIDE_DEPTH.get(editor) ?? 0) === 0 && hasEditorRuntime(editor) && VIEW_CHILDREN_SOURCES.has(getEditorRuntime(editor)); if (!usesViewChildrenSource) { const cached = getCachedSnapshot(editor); if (cached) { return cached; } } const live = getChildrenSource(editor); const children = live instanceof DocumentIndex || isStructurallyImmutable(live) ? live : rememberDocumentNodes(cloneFrozen(live)); const selection = getRootScopedSelection( getCurrentSelection(editor), getCurrentSelectionRoot(editor), getCurrentChildrenRoot(editor) ); let index: SnapshotIndex | undefined; const snapshot: Record = {}; setRoot(snapshot, 'children', children); snapshot.selection = selection; snapshot.version = getVersion(editor); Object.defineProperty(snapshot, 'index', { enumerable: true, get: () => (index ??= snapshotIndexOf(owner, children)), }); const frozen = Object.freeze(snapshot) as unknown as EditorSnapshot; if (!usesViewChildrenSource) { setCachedSnapshot(editor, frozen); } return frozen; }; const getSnapshotNode = ( children: readonly Descendant[], path: Path ): Descendant | undefined => { let nodes = children; let node: Descendant | undefined; for (const index of path) { node = nodes[index]; if (!node) return undefined; nodes = NodeApi.isElement(node) ? node.children : []; } return node; }; const shareSnapshotNode = ( editor: Editor, node: Descendant, path: Path, previousSnapshot: EditorSnapshot ): Descendant => { const nodeKey = getOrCreateNodeKey(node, editor); const previousPath = previousSnapshot.index.pathOf(nodeKey); const previousNode = previousPath ? getSnapshotNode(previousSnapshot.children, previousPath) : undefined; if (previousNode && areEditorJsonValuesEqual(previousNode, node)) { return previousNode; } const props = Object.fromEntries( Object.entries(node) .filter(([key]) => key !== 'children') .map(([key, value]) => [key, cloneFrozen(value)]) ); const nextNode = rememberDocumentNode( NodeApi.isElement(node) ? Object.freeze({ ...props, children: Object.freeze( node.children.map((child, index) => shareSnapshotNode( editor, child, [...path, index] as Path, previousSnapshot ) ) ), }) : Object.freeze(props) ); inheritNodeKey(nextNode, node, editor); return nextNode as Descendant; }; const snapshotChildren = ( owner: Editor, liveChildren: readonly Descendant[], previousSnapshot: EditorSnapshot | undefined ) => previousSnapshot ? shareSnapshotChildren(owner, liveChildren, previousSnapshot) : rememberDocumentNodes(cloneFrozen(liveChildren)); const shareSnapshotChildren = ( editor: Editor, children: readonly Descendant[], previousSnapshot: EditorSnapshot ): readonly Descendant[] => Object.freeze( children.map((node, index) => shareSnapshotNode(editor, node, [index], previousSnapshot) ) ); export const getSelectionOnlySnapshot = ( editor: Editor, previousSnapshot: EditorSnapshot, version = getVersion(editor) ): EditorSnapshot => { const snapshot = { children: previousSnapshot.children, selection: getRootScopedSelection( getCurrentSelection(editor), getCurrentSelectionRoot(editor), MAIN_ROOT_KEY ), version, }; // Share the lazy index without retaining a getter chain through every selection. Object.defineProperty( snapshot, 'index', getDefined(Object.getOwnPropertyDescriptor(previousSnapshot, 'index')) ); return Object.freeze(snapshot) as unknown as EditorSnapshot; }; const getRootScopedSelection = ( selection: Selection, selectionRoot: string, root: string ): Selection => selectionRoot === root ? snapshotEditorJsonValue(selection, 'Editor value') : null; export function retainTransactionSnapshotIndex( editor: Editor, transactionSnapshot: TransactionSnapshot, root: string ): SnapshotIndex { const existingIndex = getKnownTransactionIndex(transactionSnapshot, root); if (existingIndex) { return existingIndex; } const index = snapshotIndexOf( getEditorRuntimeOwner(editor), readNamedRootChildren(transactionSnapshot.roots, root) ?? [] ); transactionSnapshot.rootIndexes.set(root, index); transactionSnapshot.baseRuntimeIndexes.set(root, () => index); return index; } export const getTransactionBeforeRootSnapshot = ( editor: Editor, transactionSnapshot: TransactionSnapshot, root: string ): EditorSnapshot => { const children = readNamedRootChildren(transactionSnapshot.roots, root) ?? []; const index = transactionSnapshot.baseRuntimeIndexes.get(root)?.() ?? retainTransactionSnapshotIndex(editor, transactionSnapshot, root); return Object.freeze({ children: isStructurallyImmutable(children) ? children : rememberDocumentNodes(cloneFrozen(children)), index, selection: getRootScopedSelection( transactionSnapshot.selection, transactionSnapshot.selectionRoot, root ), version: transactionSnapshot.previousVersion, }) as unknown as EditorSnapshot; }; export const getCurrentRootSnapshot = ( editor: Editor, root: string, previousSnapshot?: EditorSnapshot, knownIndex?: SnapshotIndex, version = getVersion(editor) ): EditorSnapshot => { countCoreWork('rootSnapshots'); const owner = getEditorRuntimeOwner(editor); const live = rootSourceOf(getEditorDocumentRoots(editor), root); const selectionRoot = getCurrentSelectionRoot(editor); const children = live instanceof DocumentIndex || isStructurallyImmutable(live) ? live : profileCoreDuration( 'snapshot-clone-children', snapshotChildren.bind(undefined, owner, live, previousSnapshot) ); const snapshot: Record = {}; setRoot(snapshot, 'children', children); snapshot.selection = getRootScopedSelection( getCurrentSelection(editor), selectionRoot, root ); snapshot.version = version; if (!(children instanceof DocumentIndex)) DocumentIndex.fromValue(children); if (knownIndex) publishSnapshotIndex(owner, children, knownIndex); Object.defineProperty(snapshot, 'index', { enumerable: true, get: snapshotIndexReader(owner, () => children, knownIndex), }); return Object.freeze(snapshot) as unknown as EditorSnapshot; }; const snapshotIndexReader = ( owner: Editor, children: () => ChildrenSource, known: SnapshotIndex | undefined ) => { let index = known; return () => { index ??= snapshotIndexOf(owner, children()); return index; }; }; export const getListenerSnapshot = ( editor: Editor, change?: EditorCommit ): EditorSnapshot => change?.after ?? withEditorRootChildren(editor, MAIN_ROOT_KEY, () => getSnapshot(editor)); const CORE_STATE_VIEWS = new WeakMap>(); /** * Remove transaction and plugin groups from a public state view. * * @internal */ export const toEditorCoreStateView = ( state: EditorCoreStateView ): EditorCoreStateView => { const cached = CORE_STATE_VIEWS.get(state); if (cached) return cached as EditorCoreStateView; const core = Object.freeze({ children: state.children, fragment: state.fragment, getField: state.getField, key: state.key, lastCommit: state.lastCommit, marks: state.marks, nodes: state.nodes, persisted: state.persisted, points: state.points, ranges: state.ranges, revision: state.revision, root: state.root, roots: state.roots, runtime: state.runtime, schema: state.schema, selection: state.selection, slice: state.slice, text: state.text, unique: state.unique, value: state.value, view: state.view, }) satisfies EditorCoreStateView; CORE_STATE_VIEWS.set(state, core); return core; }; export const initializePublicState = < V extends Value, TPlugins extends readonly unknown[] = readonly [], >( editor: Editor, options: CreateEditorOptions = {} ) => { const initialValue = normalizeEditorValue(options.initialValue); const initialChildren = initialValue.children; const initialRoots = initialValue.roots; if (!NodeApi.isNodeList(initialChildren)) { throw new Error('initialValue is invalid! Expected a list of elements.'); } for (const [key, children] of Object.entries(initialRoots)) { if (!NodeApi.isNodeList(children)) { throw new Error( `initialValue.roots.${key} is invalid! Expected a list of elements.` ); } } const store = getOwnerStore(editor); store.children = initialChildren; store.roots = initialRoots; store.records = EMPTY_RECORD_STORE; if (initialValue.savedRecordStore !== undefined) { store.unloadedRecordStore = initialValue.savedRecordStore; store.unloadedRecords = undefined; store.hasUnloadedRecords = false; } else if (initialValue.savedRecords !== undefined) { store.unloadedRecordStore = undefined; store.unloadedRecords = initialValue.savedRecords; store.hasUnloadedRecords = true; } else { store.unloadedRecordStore = undefined; store.unloadedRecords = undefined; store.hasUnloadedRecords = false; } store.currentChildrenRoot = MAIN_ROOT_KEY; store.documentState = initialValue.meta; store.baseComposing = false; store.baseFocused = false; setEditorMaxLength(editor, options.maxLength); store.modelReadOnly = options.readOnly ?? false; const initialEditorSelection = options.initialSelection !== undefined && options.initialSelection !== null && options.initialSelection !== 'start' && options.initialSelection !== 'end' ? options.initialSelection : null; if ( initialEditorSelection !== null && !SelectionApi.isSelection(initialEditorSelection) ) { assertSelectionSupported(editor, initialEditorSelection); } const initialSelectionRoot = initialEditorSelection !== null ? (SelectionApi.root(initialEditorSelection) ?? MAIN_ROOT_KEY) : MAIN_ROOT_KEY; setSelectionStateCaret( editor, bootstrapCaret(initialSelectionRoot, initialEditorSelection) ); initializeListenerState(editor); store.lastCommit = null; initializeStateFieldMap(editor); initializeVersionState(editor); clearSnapshotCache(editor); return Object.freeze({ explicit: initialValue.explicit }); }; /** @internal */ export const loadOpenedRecords = ( editor: Editor, schema: CompiledEditorSchema | undefined ) => { const store = peekOwnerStore(editor); if (!store) return; const savedStore = store.unloadedRecordStore; if (savedStore !== undefined) { store.unloadedRecordStore = undefined; store.records = collectLiveStore( savedStore, schema?.recordSets ?? new Map() ); clearSnapshotCache(editor); return; } if (!store.hasUnloadedRecords) return; const json = store.unloadedRecords; store.unloadedRecords = undefined; store.hasUnloadedRecords = false; store.records = collectRecordStore(json, schema?.recordSets ?? new Map()); clearSnapshotCache(editor); }; export const initializeEditorSchemaDocument = ( editor: Editor, value: AdmittedDocument, schema: CompiledEditorSchema, preserveState = false ) => { adoptEditorSchemaDocument(editor, value, schema, preserveState); }; export const saveEditorSchemaDocument = (editor: Editor) => { const document = getEditorDocumentValue(editor); return () => { adoptEditorSchemaDocument( editor, document, getCompiledEditorSchema(editor) ); }; }; export const saveEditorSchemaSelection = (editor: Editor) => { const owner = getEditorRuntimeOwner(editor); const caret = getSelectionStateCaret(owner); return () => { storeCaret(owner, caret); clearSnapshotCache(owner); }; }; const adoptEditorSchemaDocument = ( editor: Editor, value: EditorDocumentValue, schema: CompiledEditorSchema, preserveState = false ) => { const records = getValueRecords(value); const document = withValueRecords( snapshotEditorJsonValue(value, 'Editor value'), records ); getEditorSchema(editor).adoptDocumentBaseline(document); const roots = Object.freeze({ [MAIN_ROOT_KEY]: document.children, ...document.roots, }); const store = getOwnerStore(editor); store.children = getDefined(readNamedRootChildren(roots, MAIN_ROOT_KEY)); store.roots = roots; store.currentChildrenRoot = MAIN_ROOT_KEY; if (!preserveState) { const { legacySharedMeta, localMeta } = deserializeLocalAndLegacySharedMeta( editor, document.meta, { markHydrated: true } ); const adoptedRecords = migrateLegacySharedMetaToRecords( editor, records, legacySharedMeta ); store.documentState = Object.keys(localMeta).length === 0 ? undefined : localMeta; store.records = adoptedRecords; } else { store.records = records; } const { owner } = store; store.rootDirectory = undefined; for (const children of Object.values(roots)) { seedSnapshotIndex(owner, children, schema); } clearSnapshotCache(editor); }; export const withActiveReadViewScope = ( editor: Editor, wrap: ((fn: () => R) => R) | undefined, read: () => T ): T => withActiveScopeFrame(editor, { activeReadViewWrapper: wrap }, read); export const withEditorViewSelectionRead = ( editor: Editor, root: string | undefined, read: () => T ): T => withActiveScopeFrame(editor, { viewReadRoot: root }, read);