0
# Lexical Utils
1
2
Lexical Utils is a comprehensive TypeScript utility library providing essential functions for the Lexical rich text editor framework. It offers DOM manipulation helpers, tree traversal algorithms, file handling utilities, and editor state management tools designed to support complex editor operations while maintaining high performance and cross-browser compatibility.
3
4
## Package Information
5
6
- **Package Name**: @lexical/utils
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @lexical/utils`
10
- **Dependencies**: Requires `lexical` (core package) for types and base functionality
11
12
## Core Imports
13
14
```typescript
15
import {
16
addClassNamesToElement,
17
removeClassNamesFromElement,
18
$dfs,
19
$insertNodeToNearestRoot,
20
mergeRegister,
21
markSelection
22
} from "@lexical/utils";
23
```
24
25
For CommonJS:
26
27
```javascript
28
const {
29
addClassNamesToElement,
30
removeClassNamesFromElement,
31
$dfs,
32
$insertNodeToNearestRoot,
33
mergeRegister,
34
markSelection
35
} = require("@lexical/utils");
36
```
37
38
## Basic Usage
39
40
```typescript
41
import {
42
addClassNamesToElement,
43
$dfs,
44
$insertNodeToNearestRoot,
45
$createParagraphNode,
46
mergeRegister
47
} from "@lexical/utils";
48
import { $getRoot } from "lexical";
49
50
// DOM manipulation
51
const element = document.createElement('div');
52
addClassNamesToElement(element, 'editor-content', 'active');
53
54
// Tree traversal
55
const nodes = $dfs($getRoot());
56
nodes.forEach(({ node, depth }) => {
57
console.log(`Node at depth ${depth}:`, node);
58
});
59
60
// Node insertion
61
const paragraph = $createParagraphNode();
62
$insertNodeToNearestRoot(paragraph);
63
64
// Register cleanup functions
65
const cleanup = mergeRegister(
66
editor.registerCommand(...),
67
editor.registerUpdateListener(...),
68
editor.registerNodeTransform(...)
69
);
70
```
71
72
## Architecture
73
74
Lexical Utils is organized around several key functional areas:
75
76
- **DOM Manipulation**: CSS class management and HTML element utilities
77
- **Tree Traversal**: Depth-first search algorithms and node navigation functions
78
- **File Handling**: MIME type validation and asynchronous file reading with batching
79
- **Editor State Management**: State restoration, nested element resolution, and editor utilities
80
- **Specialized Utilities**: Focused modules for selection marking, node positioning, and function merging
81
- **Environment Detection**: Cross-platform browser and environment constants
82
83
## Capabilities
84
85
### DOM Manipulation
86
87
CSS class manipulation and HTML element utilities for managing editor presentation and styling.
88
89
```typescript { .api }
90
function addClassNamesToElement(
91
element: HTMLElement,
92
...classNames: Array<undefined | boolean | null | string>
93
): void;
94
95
function removeClassNamesFromElement(
96
element: HTMLElement,
97
...classNames: Array<undefined | boolean | null | string>
98
): void;
99
```
100
101
[DOM Manipulation](./dom-manipulation.md)
102
103
### Tree Traversal
104
105
Comprehensive tree traversal algorithms and node navigation utilities for exploring the Lexical node tree structure.
106
107
```typescript { .api }
108
function $dfs(
109
startNode?: LexicalNode,
110
endNode?: LexicalNode
111
): Array<DFSNode>;
112
113
function $dfsIterator(
114
startNode?: LexicalNode,
115
endNode?: LexicalNode
116
): IterableIterator<DFSNode>;
117
118
interface DFSNode {
119
readonly depth: number;
120
readonly node: LexicalNode;
121
}
122
```
123
124
[Tree Traversal](./tree-traversal.md)
125
126
### File Handling
127
128
MIME type validation and asynchronous file reading utilities with support for batching and order preservation.
129
130
```typescript { .api }
131
function isMimeType(
132
file: File,
133
acceptableMimeTypes: Array<string>
134
): boolean;
135
136
function mediaFileReader(
137
files: Array<File>,
138
acceptableMimeTypes: Array<string>
139
): Promise<Array<{file: File; result: string}>>;
140
```
141
142
[File Handling](./file-handling.md)
143
144
### Editor State Management
145
146
Advanced editor state manipulation, node insertion, and state restoration utilities for complex editor operations.
147
148
```typescript { .api }
149
function $insertNodeToNearestRoot<T extends LexicalNode>(node: T): T;
150
151
function $restoreEditorState(
152
editor: LexicalEditor,
153
editorState: EditorState
154
): void;
155
156
function registerNestedElementResolver<N extends ElementNode>(
157
editor: LexicalEditor,
158
targetNode: Klass<N>,
159
cloneNode: (from: N) => N,
160
handleOverlap: (from: N, to: N) => void
161
): () => void;
162
```
163
164
[Editor State Management](./editor-state.md)
165
166
### Specialized Utilities
167
168
Focused utility modules providing selection marking, DOM node positioning, function merging, and CSS utilities.
169
170
```typescript { .api }
171
function mergeRegister(...func: Array<() => void>): () => void;
172
173
function markSelection(
174
editor: LexicalEditor,
175
onReposition?: (node: Array<HTMLElement>) => void
176
): () => void;
177
178
function positionNodeOnRange(
179
editor: LexicalEditor,
180
range: Range,
181
onReposition: (node: Array<HTMLElement>) => void
182
): () => void;
183
```
184
185
[Specialized Utilities](./specialized-utilities.md)
186
187
## Environment Constants
188
189
Cross-platform browser and environment detection constants for conditional functionality.
190
191
```typescript { .api }
192
const CAN_USE_BEFORE_INPUT: boolean;
193
const CAN_USE_DOM: boolean;
194
const IS_ANDROID: boolean;
195
const IS_ANDROID_CHROME: boolean;
196
const IS_APPLE: boolean;
197
const IS_APPLE_WEBKIT: boolean;
198
const IS_CHROME: boolean;
199
const IS_FIREFOX: boolean;
200
const IS_IOS: boolean;
201
const IS_SAFARI: boolean;
202
```
203
204
## Core Types
205
206
### Package-Specific Types
207
208
```typescript { .api }
209
interface DFSNode {
210
readonly depth: number;
211
readonly node: LexicalNode;
212
}
213
214
interface StateConfigWrapper<K extends string, V> {
215
readonly stateConfig: StateConfig<K, V>;
216
readonly $get: <T extends LexicalNode>(node: T) => V;
217
readonly $set: <T extends LexicalNode>(
218
node: T,
219
valueOrUpdater: ValueOrUpdater<V>
220
) => T;
221
readonly accessors: readonly [$get: this['$get'], $set: this['$set']];
222
makeGetterMethod<T extends LexicalNode>(): (this: T) => V;
223
makeSetterMethod<T extends LexicalNode>(): (
224
this: T,
225
valueOrUpdater: ValueOrUpdater<V>
226
) => T;
227
}
228
229
type DOMNodeToLexicalConversion = (element: Node) => LexicalNode;
230
type DOMNodeToLexicalConversionMap = Record<string, DOMNodeToLexicalConversion>;
231
type ObjectKlass<T> = new (...args: any[]) => T;
232
```
233
234
## Re-exported Functions from Lexical Core
235
236
The following utility functions are re-exported from the core `lexical` package for convenience:
237
238
```typescript { .api }
239
/**
240
* Splits a node at the current selection point
241
*/
242
function $splitNode(node: ElementNode): ElementNode;
243
244
/**
245
* Checks if a DOM node is a block-level element
246
*/
247
function isBlockDomNode(node: Node): boolean;
248
249
/**
250
* Type guard to check if element is an HTML anchor element
251
*/
252
function isHTMLAnchorElement(x: Node | EventTarget | null): x is HTMLAnchorElement;
253
254
/**
255
* Type guard to check if element is an HTML element
256
*/
257
function isHTMLElement(x: Node | EventTarget | null): x is HTMLElement;
258
259
/**
260
* Checks if a DOM node is an inline element
261
*/
262
function isInlineDomNode(node: Node): boolean;
263
```
264
265
### External Types from `lexical` Core
266
267
The following types are imported from the core `lexical` package and used throughout the API:
268
269
- **LexicalNode**: Base class for all nodes in the editor tree
270
- **ElementNode**: Base class for container nodes that can have children
271
- **LexicalEditor**: The main editor instance
272
- **EditorState**: Immutable state snapshot of the editor
273
- **CaretDirection**: `'next' | 'previous'` for tree traversal direction
274
- **NodeCaret**, **SiblingCaret**, **PointCaret**: Caret positioning types for precise node navigation
275
- **Klass**: Constructor type `new (...args: any[]) => T`
276
- **ValueOrUpdater**: `V | ((prev: V) => V)` for state updates
277
- **StateConfig**: Configuration for custom node state management