Skip to main content

@lexical/utils

Interfaces

DFSNode

Defined in: packages/lexical-utils/src/index.ts:189

Properties

depth

readonly depth: number

Defined in: packages/lexical-utils/src/index.ts:190

node

readonly node: LexicalNode

Defined in: packages/lexical-utils/src/index.ts:191


StateConfigWrapper<K, V>

Defined in: packages/lexical-utils/src/index.ts:882

A wrapper that creates bound functions and methods for the StateConfig to save some boilerplate when defining methods or exporting only the accessors from your modules rather than exposing the StateConfig directly.

Type Parameters

K

K extends string

V

V

Properties

$get()

readonly $get: <T>(node) => V

Defined in: packages/lexical-utils/src/index.ts:886

(node) => $getState(node, stateConfig)

Type Parameters
T

T extends LexicalNode

Parameters
node

T

Returns

V

$set()

readonly $set: <T>(node, valueOrUpdater) => T

Defined in: packages/lexical-utils/src/index.ts:888

(node, valueOrUpdater) => $setState(node, stateConfig, valueOrUpdater)

Type Parameters
T

T extends LexicalNode

Parameters
node

T

valueOrUpdater

ValueOrUpdater<V>

Returns

T

accessors

readonly accessors: readonly [<T>(node) => V, <T>(node, valueOrUpdater) => T]

Defined in: packages/lexical-utils/src/index.ts:893

[$get, $set]

stateConfig

readonly stateConfig: StateConfig<K, V>

Defined in: packages/lexical-utils/src/index.ts:884

A reference to the stateConfig

Methods

makeGetterMethod()

makeGetterMethod<T>(): (this) => V

Defined in: packages/lexical-utils/src/index.ts:907

() => function () { return $get(this) }

Should be called with an explicit this type parameter.

Type Parameters
T

T extends LexicalNode

Returns

(this): V

Parameters
this

T

Returns

V

Example
class MyNode {
// …
myGetter = myWrapper.makeGetterMethod<this>();
}
makeSetterMethod()

makeSetterMethod<T>(): (this, valueOrUpdater) => T

Defined in: packages/lexical-utils/src/index.ts:921

() => function (valueOrUpdater) { return $set(this, valueOrUpdater) }

Must be called with an explicit this type parameter.

Type Parameters
T

T extends LexicalNode

Returns

(this, valueOrUpdater): T

Parameters
this

T

valueOrUpdater

ValueOrUpdater<V>

Returns

T

Example
class MyNode {
// …
mySetter = myWrapper.makeSetterMethod<this>();
}

Type Aliases

DOMNodeToLexicalConversion()

DOMNodeToLexicalConversion = (element) => LexicalNode

Defined in: packages/lexical-utils/src/index.ts:403

Parameters

element

Node

Returns

LexicalNode


DOMNodeToLexicalConversionMap

DOMNodeToLexicalConversionMap = Record<string, DOMNodeToLexicalConversion>

Defined in: packages/lexical-utils/src/index.ts:405


ObjectKlass()<T>

ObjectKlass<T> = (...args) => T

Defined in: packages/lexical-utils/src/index.ts:645

Type Parameters

T

T

Parameters

args

...any[]

Returns

T

Variables

$findMatchingParent()

const $findMatchingParent: {<T>(startingNode, findFn): null | T; (startingNode, findFn): null | LexicalNode; }

Defined in: packages/lexical-utils/src/index.ts:418

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

Call Signature

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

Type Parameters
T

T extends LexicalNode

Parameters
startingNode

LexicalNode

findFn

(node) => node is T

Returns

null | T

Call Signature

(startingNode, findFn): null | LexicalNode

Parameters
startingNode

LexicalNode

findFn

(node) => boolean

Returns

null | LexicalNode

Param

The node where the search starts.

Param

A testing function that returns true if the current node satisfies the testing parameters.

Returns

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


CAN_USE_BEFORE_INPUT

const CAN_USE_BEFORE_INPUT: boolean = CAN_USE_BEFORE_INPUT_

Defined in: packages/lexical-utils/src/index.ts:80


CAN_USE_DOM

const CAN_USE_DOM: boolean = CAN_USE_DOM_

Defined in: packages/lexical-utils/src/index.ts:81


IS_ANDROID

const IS_ANDROID: boolean = IS_ANDROID_

Defined in: packages/lexical-utils/src/index.ts:82


IS_ANDROID_CHROME

const IS_ANDROID_CHROME: boolean = IS_ANDROID_CHROME_

Defined in: packages/lexical-utils/src/index.ts:83


IS_APPLE

const IS_APPLE: boolean = IS_APPLE_

Defined in: packages/lexical-utils/src/index.ts:84


IS_APPLE_WEBKIT

const IS_APPLE_WEBKIT: boolean = IS_APPLE_WEBKIT_

Defined in: packages/lexical-utils/src/index.ts:85


IS_CHROME

const IS_CHROME: boolean = IS_CHROME_

Defined in: packages/lexical-utils/src/index.ts:86


IS_FIREFOX

const IS_FIREFOX: boolean = IS_FIREFOX_

Defined in: packages/lexical-utils/src/index.ts:87


IS_IOS

const IS_IOS: boolean = IS_IOS_

Defined in: packages/lexical-utils/src/index.ts:88


IS_SAFARI

const IS_SAFARI: boolean = IS_SAFARI_

Defined in: packages/lexical-utils/src/index.ts:89

Functions

$descendantsMatching()

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

Defined in: packages/lexical-utils/src/index.ts:794

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

T

T extends LexicalNode

Parameters

children

LexicalNode[]

The children to traverse

$predicate

(node) => node is T

Should return true for nodes that are permitted to be children of root

Returns

T[]

The children or their descendants that match $predicate


$dfs()

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

Defined in: packages/lexical-utils/src/index.ts:204

"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

startNode?

LexicalNode

The node to start the search, if omitted, it will start at the root node.

endNode?

LexicalNode

The 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).


$dfsIterator()

$dfsIterator(startNode?, endNode?): IterableIterator<DFSNode>

Defined in: packages/lexical-utils/src/index.ts:242

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

Parameters

startNode?

LexicalNode

The node to start the search, if omitted, it will start at the root node.

endNode?

LexicalNode

The node to end the search, if omitted, it will find all descendants of the startingNode.

Returns

IterableIterator<DFSNode>

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


$filter()

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

Defined in: packages/lexical-utils/src/index.ts:668

Filter the nodes

Type Parameters

T

T

Parameters

nodes

LexicalNode[]

Array of nodes that needs to be filtered

filterFn

(node) => null | T

A filter function that returns node if the current node satisfies the condition otherwise null

Returns

T[]

Array of filtered nodes


$firstToLastIterator()

$firstToLastIterator(node): Iterable<LexicalNode>

Defined in: packages/lexical-utils/src/index.ts:824

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

node

ElementNode

The node whose children to iterate

Returns

Iterable<LexicalNode>

An iterator of the node's children


$getAdjacentCaret()

$getAdjacentCaret<D>(caret): null | SiblingCaret<LexicalNode, D>

Defined in: packages/lexical-utils/src/index.ts:217

Get the adjacent caret in the same direction

Type Parameters

D

D extends CaretDirection

Parameters

caret

A caret or null

null | NodeCaret<D>

Returns

null | SiblingCaret<LexicalNode, D>

caret.getAdjacentCaret() or null


$getDepth()

$getDepth(node): number

Defined in: packages/lexical-utils/src/index.ts:314

Parameters

node

null | LexicalNode

Returns

number


$getNearestBlockElementAncestorOrThrow()

$getNearestBlockElementAncestorOrThrow(startNode): ElementNode

Defined in: packages/lexical-utils/src/index.ts:386

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

Parameters

startNode

LexicalNode

The starting node of the search

Returns

ElementNode

The ancestor node found


$getNearestNodeOfType()

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

Defined in: packages/lexical-utils/src/index.ts:364

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

Type Parameters

T

T extends ElementNode

Parameters

node

LexicalNode

the node to begin searching.

klass

Klass<T>

an instance of the type of node to look for.

Returns

null | T

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


$getNextRightPreorderNode()

$getNextRightPreorderNode(startingNode): null | LexicalNode

Defined in: packages/lexical-utils/src/index.ts:334

Performs a right-to-left preorder tree traversal. From the starting node it goes to the rightmost child, than backtracks to parent 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

startingNode

LexicalNode

The node to start the search.

Returns

null | LexicalNode

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


$getNextSiblingOrParentSibling()

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

Defined in: packages/lexical-utils/src/index.ts:305

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

node

LexicalNode

LexicalNode.

Returns

null | [LexicalNode, number]

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


$insertFirst()

$insertFirst(parent, node): void

Defined in: packages/lexical-utils/src/index.ts:686

Appends the node before the first child of the parent node

Parameters

parent

ElementNode

A parent node

node

LexicalNode

Node that needs to be appended

Returns

void


$insertNodeToNearestRoot()

$insertNodeToNearestRoot<T>(node): T

Defined in: packages/lexical-utils/src/index.ts:563

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 will then be added after the inserted node and selected.

Type Parameters

T

T extends LexicalNode

Parameters

node

T

The node to be inserted

Returns

T

The node after its insertion


$insertNodeToNearestRootAtCaret()

$insertNodeToNearestRootAtCaret<T, D>(node, caret, options?): NodeCaret<D>

Defined in: packages/lexical-utils/src/index.ts:599

If the insertion caret is the root/shadow root node (see $isRootOrShadowRoot), the node will be inserted there, otherwise the parent nodes will be split according to the given options.

Type Parameters

T

T extends LexicalNode

D

D extends CaretDirection

Parameters

node

T

The node to be inserted

caret

PointCaret<D>

The location to insert or split from

options?

SplitAtPointCaretNextOptions

Returns

NodeCaret<D>

The node after its insertion


$isEditorIsNestedEditor()

$isEditorIsNestedEditor(editor): boolean

Defined in: packages/lexical-utils/src/index.ts:729

Checks if the editor is a nested editor created by LexicalNestedComposer

Parameters

editor

LexicalEditor

Returns

boolean


$lastToFirstIterator()

$lastToFirstIterator(node): Iterable<LexicalNode>

Defined in: packages/lexical-utils/src/index.ts:836

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

node

ElementNode

The node whose children to iterate

Returns

Iterable<LexicalNode>

An iterator of the node's children


$restoreEditorState()

$restoreEditorState(editor, editorState): void

Defined in: packages/lexical-utils/src/index.ts:534

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

editor

LexicalEditor

The lexical editor

editorState

EditorState

The editor's state

Returns

void


$reverseDfs()

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

Defined in: packages/lexical-utils/src/index.ts:229

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

Parameters

startNode?

LexicalNode

The node to start the search, if omitted, it will start at the root node.

endNode?

LexicalNode

The node to end the search, if omitted, it will find all descendants of the startingNode.

Returns

DFSNode[]

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


$reverseDfsIterator()

$reverseDfsIterator(startNode?, endNode?): IterableIterator<DFSNode>

Defined in: packages/lexical-utils/src/index.ts:350

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

Parameters

startNode?

LexicalNode

The node to start the search, if omitted, it will start at the root node.

endNode?

LexicalNode

The node to end the search, if omitted, it will find all descendants of the startingNode.

Returns

IterableIterator<DFSNode>

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


$unwrapAndFilterDescendants()

$unwrapAndFilterDescendants(root, $predicate): boolean

Defined in: packages/lexical-utils/src/index.ts:744

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

root

ElementNode

The root to start the traversal

$predicate

(node) => boolean

Should return true for nodes that are permitted to be children of root

Returns

boolean

true if this unwrapped or removed any nodes


$unwrapNode()

$unwrapNode(node): void

Defined in: packages/lexical-utils/src/index.ts:869

Replace this node with its children

Parameters

node

ElementNode

The ElementNode to unwrap and remove

Returns

void


$wrapNodeInElement()

$wrapNodeInElement(node, createElementNode): ElementNode

Defined in: packages/lexical-utils/src/index.ts:634

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

Parameters

node

LexicalNode

Node to be wrapped.

createElementNode

() => ElementNode

Creates 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).


addClassNamesToElement()

addClassNamesToElement(element, ...classNames): void

Defined in: packages/lexical-utils/src/index.ts:99

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

element

HTMLElement

The 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


calculateZoomLevel()

calculateZoomLevel(element): number

Defined in: packages/lexical-utils/src/index.ts:715

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

element

null | Element

Returns

number


isMimeType()

isMimeType(file, acceptableMimeTypes): boolean

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

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

file

File

The file you want to type check.

acceptableMimeTypes

string[]

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.


makeStateWrapper()

makeStateWrapper<K, V>(stateConfig): StateConfigWrapper<K, V>

Defined in: packages/lexical-utils/src/index.ts:936

EXPERIMENTAL

A convenience interface for working with $getState and $setState.

Type Parameters

K

K extends string

V

V

Parameters

stateConfig

StateConfig<K, V>

The stateConfig to wrap with convenience functionality

Returns

StateConfigWrapper<K, V>

a StateWrapper


markSelection()

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

Defined in: packages/lexical-utils/src/markSelection.ts:68

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

editor

LexicalEditor

onReposition?

(node) => void

Returns

(): void

Returns

void


mediaFileReader()

mediaFileReader(files, acceptableMimeTypes): Promise<object[]>

Defined in: packages/lexical-utils/src/index.ts:158

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

files

File[]

acceptableMimeTypes

string[]

Returns

Promise<object[]>


mergeRegister()

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

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

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

func

...Func[]

An array of cleanup functions meant to be executed by the returned function.

Returns

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 necessarily 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.


objectKlassEquals()

objectKlassEquals<T>(object, objectClass): object is T

Defined in: packages/lexical-utils/src/index.ts:652

Type Parameters

T

T

Parameters

object

unknown

= The instance of the type

objectClass

ObjectKlass<T>

= The class of the type

Returns

object is T

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


positionNodeOnRange()

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

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

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

editor

LexicalEditor

range

Range

onReposition

(node) => void

Returns

(): void

Returns

void


registerNestedElementResolver()

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

Defined in: packages/lexical-utils/src/index.ts:453

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

N

N extends ElementNode

Parameters

editor

LexicalEditor

The lexical editor

targetNode

Klass<N>

The target for the nested element to be extracted from.

cloneNode

(from) => N

See $createMarkNode

handleOverlap

(from, to) => void

Handles any overlap between the node to extract and the targetNode

Returns

The lexical editor

(): void

Returns

void


removeClassNamesFromElement()

removeClassNamesFromElement(element, ...classNames): void

Defined in: packages/lexical-utils/src/index.ts:117

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

element

HTMLElement

The 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


selectionAlwaysOnDisplay()

selectionAlwaysOnDisplay(editor): () => void

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

Parameters

editor

LexicalEditor

Returns

(): void

Returns

void

References

$getAdjacentSiblingOrParentSiblingCaret

Re-exports $getAdjacentSiblingOrParentSiblingCaret


$splitNode

Re-exports $splitNode


isBlockDomNode

Re-exports isBlockDomNode


isHTMLAnchorElement

Re-exports isHTMLAnchorElement


isHTMLElement

Re-exports isHTMLElement


isInlineDomNode

Re-exports isInlineDomNode