Skip to main content

Module: @lexical/utils

References

$splitNode

Re-exports $splitNode


isBlockDomNode

Re-exports isBlockDomNode


isHTMLAnchorElement

Re-exports isHTMLAnchorElement


isHTMLElement

Re-exports isHTMLElement


isInlineDomNode

Re-exports isInlineDomNode

Type Aliases

DFSNode

Ƭ DFSNode: Readonly<{ depth: number ; node: LexicalNode }>

Defined in

packages/lexical-utils/src/index.ts:166


DOMNodeToLexicalConversion

Ƭ DOMNodeToLexicalConversion: (element: Node) => LexicalNode

Type declaration

▸ (element): LexicalNode

Parameters
NameType
elementNode
Returns

LexicalNode

Defined in

packages/lexical-utils/src/index.ts:376


DOMNodeToLexicalConversionMap

Ƭ DOMNodeToLexicalConversionMap: Record<string, DOMNodeToLexicalConversion>

Defined in

packages/lexical-utils/src/index.ts:378

Variables

CAN_USE_BEFORE_INPUT

Const CAN_USE_BEFORE_INPUT: boolean = CAN_USE_BEFORE_INPUT_

Defined in

packages/lexical-utils/src/index.ts:57


CAN_USE_DOM

Const CAN_USE_DOM: boolean = CAN_USE_DOM_

Defined in

packages/lexical-utils/src/index.ts:58


IS_ANDROID

Const IS_ANDROID: boolean = IS_ANDROID_

Defined in

packages/lexical-utils/src/index.ts:59


IS_ANDROID_CHROME

Const IS_ANDROID_CHROME: boolean = IS_ANDROID_CHROME_

Defined in

packages/lexical-utils/src/index.ts:60


IS_APPLE

Const IS_APPLE: boolean = IS_APPLE_

Defined in

packages/lexical-utils/src/index.ts:61


IS_APPLE_WEBKIT

Const IS_APPLE_WEBKIT: boolean = IS_APPLE_WEBKIT_

Defined in

packages/lexical-utils/src/index.ts:62


IS_CHROME

Const IS_CHROME: boolean = IS_CHROME_

Defined in

packages/lexical-utils/src/index.ts:63


IS_FIREFOX

Const IS_FIREFOX: boolean = IS_FIREFOX_

Defined in

packages/lexical-utils/src/index.ts:64


IS_IOS

Const IS_IOS: boolean = IS_IOS_

Defined in

packages/lexical-utils/src/index.ts:65


IS_SAFARI

Const IS_SAFARI: boolean = IS_SAFARI_

Defined in

packages/lexical-utils/src/index.ts:66

Functions

$descendantsMatching

$descendantsMatching<T>(children, $predicate): T[]

A depth first traversal of the children array that stops at and collects each node that $predicate matches. This is typically used to discard invalid or unsupported wrapping nodes on a children array in the after of an DOMConversionOutput. For example, a TableNode must only have TableRowNode as children, but an importer might add invalid nodes based on caption, tbody, thead, etc. and this will unwrap and discard those.

This function is read-only and performs no mutation operations, which makes it suitable for import and export purposes but likely not for any in-place mutation. You should use $unwrapAndFilterDescendants for in-place mutations such as node transforms.

Type parameters

NameType
Textends LexicalNode

Parameters

NameTypeDescription
childrenLexicalNode[]The children to traverse
$predicate(node: LexicalNode) => node is TShould return true for nodes that are permitted to be children of root

Returns

T[]

The children or their descendants that match $predicate

Defined in

packages/lexical-utils/src/index.ts:756


$dfs

$dfs(startNode?, endNode?): DFSNode[]

"Depth-First Search" starts at the root/top node of a tree and goes as far as it can down a branch end before backtracking and finding a new path. Consider solving a maze by hugging either wall, moving down a branch until you hit a dead-end (leaf) and backtracking to find the nearest branching path and repeat. It will then return all the nodes found in the search in an array of objects.

Parameters

NameTypeDescription
startNode?LexicalNodeThe node to start the search, if omitted, it will start at the root node.
endNode?LexicalNodeThe node to end the search, if omitted, it will find all descendants of the startingNode.

Returns

DFSNode[]

An array of objects of all the nodes found by the search, including their depth into the tree. {depth: number, node: LexicalNode} It will always return at least 1 node (the start node).

Defined in

packages/lexical-utils/src/index.ts:181


$dfsIterator

$dfsIterator(startNode?, endNode?): DFSIterator

$dfs iterator. Tree traversal is done on the fly as new values are requested with O(1) memory.

Parameters

NameTypeDescription
startNode?LexicalNodeThe node to start the search, if omitted, it will start at the root node.
endNode?LexicalNodeThe node to end the search, if omitted, it will find all descendants of the startingNode.

Returns

DFSIterator

An iterator, each yielded value is a DFSNode. It will always return at least 1 node (the start node).

Defined in

packages/lexical-utils/src/index.ts:207


$filter

$filter<T>(nodes, filterFn): T[]

Filter the nodes

Type parameters

Name
T

Parameters

NameTypeDescription
nodesLexicalNode[]Array of nodes that needs to be filtered
filterFn(node: LexicalNode) => null | TA filter function that returns node if the current node satisfies the condition otherwise null

Returns

T[]

Array of filtered nodes

Defined in

packages/lexical-utils/src/index.ts:625


$findMatchingParent

$findMatchingParent<T>(startingNode, findFn): null | T

Starts with a node and moves up the tree (toward the root node) to find a matching node based on the search parameters of the findFn. (Consider JavaScripts' .find() function where a testing function must be passed as an argument. eg. if( (node) => node.__type === 'div') ) return true; otherwise return false

Type parameters

NameType
Textends LexicalNode

Parameters

NameTypeDescription
startingNodeLexicalNodeThe node where the search starts.
findFn(node: LexicalNode) => node is TA testing function that returns true if the current node satisfies the testing parameters.

Returns

null | T

A parent node that matches the findFn parameters, or null if one wasn't found.

Defined in

packages/lexical-utils/src/index.ts:392

$findMatchingParent(startingNode, findFn): null | LexicalNode

Starts with a node and moves up the tree (toward the root node) to find a matching node based on the search parameters of the findFn. (Consider JavaScripts' .find() function where a testing function must be passed as an argument. eg. if( (node) => node.__type === 'div') ) return true; otherwise return false

Parameters

NameTypeDescription
startingNodeLexicalNodeThe node where the search starts.
findFn(node: LexicalNode) => booleanA testing function that returns true if the current node satisfies the testing parameters.

Returns

null | LexicalNode

A parent node that matches the findFn parameters, or null if one wasn't found.

Defined in

packages/lexical-utils/src/index.ts:396


$firstToLastIterator

$firstToLastIterator(node): Iterable<LexicalNode>

Return an iterator that yields each child of node from first to last, taking care to preserve the next sibling before yielding the value in case the caller removes the yielded node.

Parameters

NameTypeDescription
nodeElementNodeThe node whose children to iterate

Returns

Iterable<LexicalNode>

An iterator of the node's children

Defined in

packages/lexical-utils/src/index.ts:786


$getDepth

$getDepth(node): number

Parameters

NameType
nodeLexicalNode

Returns

number

Defined in

packages/lexical-utils/src/index.ts:288


$getNearestBlockElementAncestorOrThrow

$getNearestBlockElementAncestorOrThrow(startNode): ElementNode

Returns the element node of the nearest ancestor, otherwise throws an error.

Parameters

NameTypeDescription
startNodeLexicalNodeThe starting node of the search

Returns

ElementNode

The ancestor node found

Defined in

packages/lexical-utils/src/index.ts:359


$getNearestNodeOfType

$getNearestNodeOfType<T>(node, klass): T | null

Takes a node and traverses up its ancestors (toward the root node) in order to find a specific type of node.

Type parameters

NameType
Textends ElementNode

Parameters

NameTypeDescription
nodeLexicalNodethe node to begin searching.
klassKlass<T>an instance of the type of node to look for.

Returns

T | null

the node of type klass that was passed, or null if none exist.

Defined in

packages/lexical-utils/src/index.ts:337


$getNextRightPreorderNode

$getNextRightPreorderNode(startingNode): LexicalNode | null

Performs a right-to-left preorder tree traversal. From the starting node it goes to the rightmost child, than backtracks to paret and finds new rightmost path. It will return the next node in traversal sequence after the startingNode. The traversal is similar to $dfs functions above, but the nodes are visited right-to-left, not left-to-right.

Parameters

NameTypeDescription
startingNodeLexicalNodeThe node to start the search.

Returns

LexicalNode | null

The next node in pre-order right to left traversal sequence or null, if the node does not exist

Defined in

packages/lexical-utils/src/index.ts:307


$getNextSiblingOrParentSibling

$getNextSiblingOrParentSibling(node): null | [LexicalNode, number]

Returns the Node sibling when this exists, otherwise the closest parent sibling. For example R -> P -> T1, T2 -> P2 returns T2 for node T1, P2 for node T2, and null for node P2.

Parameters

NameTypeDescription
nodeLexicalNodeLexicalNode.

Returns

null | [LexicalNode, number]

An array (tuple) containing the found Lexical node and the depth difference, or null, if this node doesn't exist.

Defined in

packages/lexical-utils/src/index.ts:263


$insertFirst

$insertFirst(parent, node): void

Appends the node before the first child of the parent node

Parameters

NameTypeDescription
parentElementNodeA parent node
nodeLexicalNodeNode that needs to be appended

Returns

void

Defined in

packages/lexical-utils/src/index.ts:643


$insertNodeToNearestRoot

$insertNodeToNearestRoot<T>(node): T

If the selected insertion area is the root/shadow root node (see $isRootOrShadowRoot), the node will be appended there, otherwise, it will be inserted before the insertion area. If there is no selection where the node is to be inserted, it will be appended after any current nodes within the tree, as a child of the root node. A paragraph node will then be added after the inserted node and selected.

Type parameters

NameType
Textends LexicalNode

Parameters

NameTypeDescription
nodeTThe node to be inserted

Returns

T

The node after its insertion

Defined in

packages/lexical-utils/src/index.ts:536


$isEditorIsNestedEditor

$isEditorIsNestedEditor(editor): boolean

Checks if the editor is a nested editor created by LexicalNestedComposer

Parameters

NameType
editorLexicalEditor

Returns

boolean

Defined in

packages/lexical-utils/src/index.ts:691


$lastToFirstIterator

$lastToFirstIterator(node): Iterable<LexicalNode>

Return an iterator that yields each child of node from last to first, taking care to preserve the previous sibling before yielding the value in case the caller removes the yielded node.

Parameters

NameTypeDescription
nodeElementNodeThe node whose children to iterate

Returns

Iterable<LexicalNode>

An iterator of the node's children

Defined in

packages/lexical-utils/src/index.ts:801


$restoreEditorState

$restoreEditorState(editor, editorState): void

Clones the editor and marks it as dirty to be reconciled. If there was a selection, it would be set back to its previous state, or null otherwise.

Parameters

NameTypeDescription
editorLexicalEditorThe lexical editor
editorStateEditorStateThe editor's state

Returns

void

Defined in

packages/lexical-utils/src/index.ts:507


$unwrapAndFilterDescendants

$unwrapAndFilterDescendants(root, $predicate): boolean

A depth first last-to-first traversal of root that stops at each node that matches $predicate and ensures that its parent is root. This is typically used to discard invalid or unsupported wrapping nodes. For example, a TableNode must only have TableRowNode as children, but an importer might add invalid nodes based on caption, tbody, thead, etc. and this will unwrap and discard those.

Parameters

NameTypeDescription
rootElementNodeThe root to start the traversal
$predicate(node: LexicalNode) => booleanShould return true for nodes that are permitted to be children of root

Returns

boolean

true if this unwrapped or removed any nodes

Defined in

packages/lexical-utils/src/index.ts:706


$unwrapNode

$unwrapNode(node): void

Insert all children before this node, and then remove it.

Parameters

NameTypeDescription
nodeElementNodeThe ElementNode to unwrap and remove

Returns

void

Defined in

packages/lexical-utils/src/index.ts:842


$wrapNodeInElement

$wrapNodeInElement(node, createElementNode): ElementNode

Wraps the node into another node created from a createElementNode function, eg. $createParagraphNode

Parameters

NameTypeDescription
nodeLexicalNodeNode to be wrapped.
createElementNode() => ElementNodeCreates a new lexical element to wrap the to-be-wrapped node and returns it.

Returns

ElementNode

A new lexical element with the previous node appended within (as a child, including its children).

Defined in

packages/lexical-utils/src/index.ts:591


addClassNamesToElement

addClassNamesToElement(element, ...classNames): void

Takes an HTML element and adds the classNames passed within an array, ignoring any non-string types. A space can be used to add multiple classes eg. addClassNamesToElement(element, ['element-inner active', true, null]) will add both 'element-inner' and 'active' as classes to that element.

Parameters

NameTypeDescription
elementHTMLElementThe element in which the classes are added
...classNames(undefined | null | string | boolean)[]An array defining the class names to add to the element

Returns

void

Defined in

packages/lexical-utils/src/index.ts:76


calculateZoomLevel

calculateZoomLevel(element): number

Calculates the zoom level of an element as a result of using css zoom property. For browsers that implement standardized CSS zoom (Firefox, Chrome >= 128), this will always return 1.

Parameters

NameType
elementnull | Element

Returns

number

Defined in

packages/lexical-utils/src/index.ts:677


isMimeType

isMimeType(file, acceptableMimeTypes): boolean

Returns true if the file type matches the types passed within the acceptableMimeTypes array, false otherwise. The types passed must be strings and are CASE-SENSITIVE. eg. if file is of type 'text' and acceptableMimeTypes = ['TEXT', 'IMAGE'] the function will return false.

Parameters

NameTypeDescription
fileFileThe file you want to type check.
acceptableMimeTypesstring[]An array of strings of types which the file is checked against.

Returns

boolean

true if the file is an acceptable mime type, false otherwise.

Defined in

packages/lexical-utils/src/index.ts:112


markSelection

markSelection(editor, onReposition?): () => void

Place one or multiple newly created Nodes at the current selection. Multiple nodes will only be created when the selection spans multiple lines (aka client rects).

This function can come useful when you want to show the selection but the editor has been focused away.

Parameters

NameType
editorLexicalEditor
onReposition?(node: HTMLElement[]) => void

Returns

fn

▸ (): void

Returns

void

Defined in

packages/lexical-utils/src/markSelection.ts:32


mediaFileReader

mediaFileReader(files, acceptableMimeTypes): Promise<{ file: File ; result: string }[]>

Lexical File Reader with:

  1. MIME type support
  2. batched results (HistoryPlugin compatibility)
  3. Order aware (respects the order when multiple Files are passed)

const filesResult = await mediaFileReader(files, ['image/']); filesResult.forEach(file => editor.dispatchCommand('INSERT_IMAGE', { src: file.result, }));

Parameters

NameType
filesFile[]
acceptableMimeTypesstring[]

Returns

Promise<{ file: File ; result: string }[]>

Defined in

packages/lexical-utils/src/index.ts:135


mergeRegister

mergeRegister(...func): () => void

Returns a function that will execute all functions passed when called. It is generally used to register multiple lexical listeners and then tear them down with a single function call, such as React's useEffect hook.

Parameters

NameTypeDescription
...funcFunc[]An array of cleanup functions meant to be executed by the returned function.

Returns

fn

the function which executes all the passed cleanup functions.

▸ (): void

Returns

void

Example

useEffect(() => {
return mergeRegister(
editor.registerCommand(...registerCommand1 logic),
editor.registerCommand(...registerCommand2 logic),
editor.registerCommand(...registerCommand3 logic)
)
}, [editor])

In this case, useEffect is returning the function returned by mergeRegister as a cleanup function to be executed after either the useEffect runs again (due to one of its dependencies updating) or the component it resides in unmounts. Note the functions don't neccesarily need to be in an array as all arguments are considered to be the func argument and spread from there. The order of cleanup is the reverse of the argument order. Generally it is expected that the first "acquire" will be "released" last (LIFO order), because a later step may have some dependency on an earlier one.

Defined in

packages/lexical-utils/src/mergeRegister.ts:36


objectKlassEquals

objectKlassEquals<T>(object, objectClass): boolean

Type parameters

Name
T

Parameters

NameTypeDescription
objectunknown= The instance of the type
objectClassObjectKlass<T>= The class of the type

Returns

boolean

Whether the object is has the same Klass of the objectClass, ignoring the difference across window (e.g. different iframs)

Defined in

packages/lexical-utils/src/index.ts:609


positionNodeOnRange

positionNodeOnRange(editor, range, onReposition): () => void

Place one or multiple newly created Nodes at the passed Range's position. Multiple nodes will only be created when the Range spans multiple lines (aka client rects).

This function can come particularly useful to highlight particular parts of the text without interfering with the EditorState, that will often replicate the state across collab and clipboard.

This function accounts for DOM updates which can modify the passed Range. Hence, the function return to remove the listener.

Parameters

NameType
editorLexicalEditor
rangeRange
onReposition(node: HTMLElement[]) => void

Returns

fn

▸ (): void

Returns

void

Defined in

packages/lexical-utils/src/positionNodeOnRange.ts:38


registerNestedElementResolver

registerNestedElementResolver<N>(editor, targetNode, cloneNode, handleOverlap): () => void

Attempts to resolve nested element nodes of the same type into a single node of that type. It is generally used for marks/commenting

Type parameters

NameType
Nextends ElementNode

Parameters

NameTypeDescription
editorLexicalEditorThe lexical editor
targetNodeKlass<N>The target for the nested element to be extracted from.
cloneNode(from: N) => NSee $createMarkNode
handleOverlap(from: N, to: N) => voidHandles any overlap between the node to extract and the targetNode

Returns

fn

The lexical editor

▸ (): void

Returns

void

Defined in

packages/lexical-utils/src/index.ts:426


removeClassNamesFromElement

removeClassNamesFromElement(element, ...classNames): void

Takes an HTML element and removes the classNames passed within an array, ignoring any non-string types. A space can be used to remove multiple classes eg. removeClassNamesFromElement(element, ['active small', true, null]) will remove both the 'active' and 'small' classes from that element.

Parameters

NameTypeDescription
elementHTMLElementThe element in which the classes are removed
...classNames(undefined | null | string | boolean)[]An array defining the class names to remove from the element

Returns

void

Defined in

packages/lexical-utils/src/index.ts:94


selectionAlwaysOnDisplay

selectionAlwaysOnDisplay(editor): () => void

Parameters

NameType
editorLexicalEditor

Returns

fn

▸ (): void

Returns

void

Defined in

packages/lexical-utils/src/selectionAlwaysOnDisplay.ts:13