/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import type {EditorState} from './LexicalEditorState'; import type {GeneratedJSON, GeneratedJSONFactory} from './LexicalGeneratedJSON'; import type {RootNode} from './nodes/LexicalRootNode'; import invariant from '@lexical/internal/invariant'; import { $createTextNode, $getPreviousSelection, $getSelection, $getTextNodeOffset, $isDecoratorNode, $isElementNode, $isLineBreakNode, $isRangeSelection, $isRootNode, $isTabNode, $isTextNode, CONTROL_OR_META, DecoratorNode, DEFAULT_EDITOR_DOM_CONFIG, type ElementFormatType, ElementNode, HISTORY_MERGE_TAG, type LineBreakNode, normalizeClassNames, type UpdateTag, } from '.'; import {$detachNode} from './caret/LexicalCaretTree'; import { CAN_USE_DOM, IS_APPLE, IS_APPLE_WEBKIT, IS_IOS, IS_SAFARI, } from './environment'; import { COMPOSITION_START_CHAR, COMPOSITION_SUFFIX, CONTROL_OR_OTHER_KEY, DOM_DOCUMENT_FRAGMENT_TYPE, DOM_DOCUMENT_TYPE, DOM_ELEMENT_TYPE, DOM_TEXT_TYPE, ELEMENT_TYPE_TO_FORMAT, HAS_DIRTY_NODES, LTR_REGEX, NO_DIRTY_NODES, NODE_STATE_KEY, PROTOTYPE_CONFIG_METHOD, RTL_REGEX, TEXT_TYPE_TO_FORMAT, } from './LexicalConstants'; import {type DOMSlot, ElementDOMSlot} from './LexicalDOMSlot'; import { type AnyLexicalCommand, type CommandPayloadArgs, type CommandPayloadType, type DOMSlotForNode, type EditorConfig, type EditorDOMRenderConfig, type EditorThemeClasses, type Klass, LexicalEditor, type MutatedNodes, type MutationListeners, type NodeMutation, type RegisteredNode, type RegisteredNodes, } from './LexicalEditor'; import {flushRootMutations} from './LexicalMutations'; import { $isEphemeral, $isLexicalNode, $markEphemeral, LexicalNode, type LexicalParseJSON, type LexicalPrivateDOM, type NodeKey, type NodeMap, type SerializedLexicalNode, type SerializedPartial, type StaticNodeConfigValue, } from './LexicalNode'; import { $setState, $updateStateFromJSON, type AnyStateConfig, } from './LexicalNodeState'; import {$normalizeSelection} from './LexicalNormalization'; import { type AnySerializationSchema, type ComposedSchemaFields, hasOwnKey, isSchemaField, type SchemaFieldBase, type SchemaGetterField, type SchemaSetterField, } from './LexicalSchema'; import { $clampRangeSelectionToSlotFrame, type BaseSelection, type PointType, type RangeSelection, } from './LexicalSelection'; import { $getSlot, $getSlotHostKey, $isSlotChild, $isSlotHost, } from './LexicalSlot'; import { errorOnInfiniteTransforms, errorOnReadOnly, getActiveEditor, getActiveEditorState, internalGetActiveEditor, internalGetActiveEditorState, isCurrentlyReadOnlyMode, triggerCommandListeners, } from './LexicalUpdates'; import { $createParagraphNode, type ParagraphNode, } from './nodes/LexicalParagraphNode'; import {TabNode} from './nodes/LexicalTabNode'; import {type TextFormatType, TextNode} from './nodes/LexicalTextNode'; const __DEV__ = process.env.NODE_ENV !== 'production'; export const emptyFunction = () => { return; }; let pendingNodeToClone: null | LexicalNode = null; export function setPendingNodeToClone(pendingNode: null | LexicalNode): void { pendingNodeToClone = pendingNode; } export function getPendingNodeToClone(): null | LexicalNode { const node = pendingNodeToClone; pendingNodeToClone = null; return node; } // Internal, module-private sentinel passed as the second argument to an // auto-synthesized clone (see injectSynthesizedStatics) by the internal clone // wrappers ($cloneWithProperties / $copyNode). Those wrappers are contractually // responsible for calling `afterCloneFrom(node)` on the result exactly once, so // they pass this sentinel to tell the synthesized clone NOT to call it too. // // An auto-synthesized clone has no explicit body, so when it is called *without* // this sentinel — i.e. directly as `NodeClass.clone(node)`, a documented and // idiomatic pattern before the $config() port — it must copy the source node's // properties itself, otherwise callers silently get a default-constructed node // with lost state (e.g. HeadingNode's tag reverting to 'h1'). // // The signal is per-call rather than a module global, so it is unaffected by // reentrancy: a clone (or afterCloneFrom) that happens to clone another node, // even in another editor, does not accidentally suppress that node's own // afterCloneFrom. It is also un-spoofable by external callers because the // sentinel is not exported. afterCloneFrom is not guaranteed idempotent (some // nodes accumulate state there, e.g. a version counter), so it is critical that // it runs exactly once per clone regardless of call path. const INTERNAL_SKIP_AFTER_CLONE_FROM: unique symbol = Symbol( 'INTERNAL_SKIP_AFTER_CLONE_FROM', ); let keyCounter = 1; /** Resets the internal key counter, primarily for deterministic test output. */ export function resetRandomKey(): void { keyCounter = 1; } export function generateRandomKey(): string { return '' + keyCounter++; } /** * @internal */ export function getRegisteredNodeOrThrow( editor: LexicalEditor, nodeType: string, ): RegisteredNode { const registeredNode = getRegisteredNode(editor, nodeType); if (registeredNode === undefined) { invariant(false, 'registeredNode: Type %s not found', nodeType); } return registeredNode; } /** * @internal */ export function getRegisteredNode( editor: LexicalEditor, nodeType: string, ): undefined | RegisteredNode { return editor._nodes.get(nodeType); } export const isArray = Array.isArray; /** @internal */ export const scheduleMicroTask: (fn: () => void) => void = typeof queueMicrotask === 'function' ? queueMicrotask : fn => { // No window prefix intended (#1400) Promise.resolve().then(fn); }; /** Returns true if the active element (resolved from the anchor's root) is a decorator's own input (e.g. an input, textarea, or foreign contentEditable) rather than Lexical-managed content. */ export function $isSelectionCapturedInDecoratorInput( anchorDOM: Node, preResolvedActiveElement?: Element | null, ): boolean { const activeElement = preResolvedActiveElement !== undefined ? preResolvedActiveElement : (() => { const root = anchorDOM.getRootNode(); return isDOMDocumentNode(root) || isDOMShadowRoot(root) ? getActiveElementDeep(root) : null; })(); if (!isHTMLElement(activeElement)) { return false; } // @experimental named-slots. A slot container is contentEditable inside an // otherwise non-editable decorator host, but its content is Lexical-managed — // not a foreign editor input — so it must stay under Lexical's DOM-selection // control instead of being treated as captured. if (activeElement.hasAttribute('data-lexical-slot')) { return false; } const nearestNode = $getNearestNodeFromDOMNode(activeElement); const nodeName = activeElement.nodeName; return ( $isLexicalNode(nearestNode) && (nodeName === 'INPUT' || nodeName === 'TEXTAREA' || (activeElement.contentEditable === 'true' && getEditorPropertyFromDOMNode(activeElement) == null)) ); } /** * Returns true if an event comes from an input embedded in a node's DOM, read * from its composed target: an ``, a `