@lexical/utils 0.44.1-nightly.20260519.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,1004 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ */
8
+
9
+ import invariant from '@lexical/internal/invariant';
10
+ import {
11
+ CAN_USE_BEFORE_INPUT,
12
+ CAN_USE_DOM,
13
+ IS_ANDROID,
14
+ IS_ANDROID_CHROME,
15
+ IS_APPLE,
16
+ IS_APPLE_WEBKIT,
17
+ IS_CHROME,
18
+ IS_FIREFOX,
19
+ IS_IOS,
20
+ IS_SAFARI,
21
+ } from 'lexical';
22
+ import {
23
+ $caretFromPoint,
24
+ $caretRangeFromSelection,
25
+ $cloneWithProperties,
26
+ $createParagraphNode,
27
+ $findMatchingParent,
28
+ $fullReconcile,
29
+ $getAdjacentChildCaret,
30
+ $getAdjacentSiblingOrParentSiblingCaret,
31
+ $getCaretInDirection,
32
+ $getCaretRange,
33
+ $getCaretRangeInDirection,
34
+ $getChildCaret,
35
+ $getChildCaretOrSelf,
36
+ $getCollapsedCaretRange,
37
+ $getPreviousSelection,
38
+ $getRoot,
39
+ $getSelection,
40
+ $getSiblingCaret,
41
+ $getState,
42
+ $isChildCaret,
43
+ $isElementNode,
44
+ $isRangeSelection,
45
+ $isSiblingCaret,
46
+ $isTextPointCaret,
47
+ $normalizeCaret,
48
+ $removeTextFromCaretRange,
49
+ $rewindSiblingCaret,
50
+ $setSelection,
51
+ $setSelectionFromCaretRange,
52
+ $setState,
53
+ $splitAtPointCaretNext,
54
+ type CaretDirection,
55
+ type EditorState,
56
+ ElementNode,
57
+ type Klass,
58
+ type LexicalEditor,
59
+ type LexicalNode,
60
+ makeStepwiseIterator,
61
+ type NodeCaret,
62
+ type NodeKey,
63
+ PointCaret,
64
+ type SiblingCaret,
65
+ SplitAtPointCaretNextOptions,
66
+ StateConfig,
67
+ ValueOrUpdater,
68
+ } from 'lexical';
69
+
70
+ export {default as markSelection} from './markSelection';
71
+ export {default as positionNodeOnRange} from './positionNodeOnRange';
72
+ export {default as selectionAlwaysOnDisplay} from './selectionAlwaysOnDisplay';
73
+ export {
74
+ $findMatchingParent,
75
+ $getAdjacentSiblingOrParentSiblingCaret,
76
+ $splitNode,
77
+ addClassNamesToElement,
78
+ isBlockDomNode,
79
+ isHTMLAnchorElement,
80
+ isHTMLElement,
81
+ isInlineDomNode,
82
+ mergeRegister,
83
+ removeClassNamesFromElement,
84
+ } from 'lexical';
85
+
86
+ const __DEV__ = process.env.NODE_ENV !== 'production';
87
+ export {
88
+ CAN_USE_BEFORE_INPUT,
89
+ CAN_USE_DOM,
90
+ IS_ANDROID,
91
+ IS_ANDROID_CHROME,
92
+ IS_APPLE,
93
+ IS_APPLE_WEBKIT,
94
+ IS_CHROME,
95
+ IS_FIREFOX,
96
+ IS_IOS,
97
+ IS_SAFARI,
98
+ };
99
+
100
+ /**
101
+ * Returns true if the file type matches the types passed within the acceptableMimeTypes array, false otherwise.
102
+ * The types passed must be strings and are CASE-SENSITIVE.
103
+ * eg. if file is of type 'text' and acceptableMimeTypes = ['TEXT', 'IMAGE'] the function will return false.
104
+ * @param file - The file you want to type check.
105
+ * @param acceptableMimeTypes - An array of strings of types which the file is checked against.
106
+ * @returns true if the file is an acceptable mime type, false otherwise.
107
+ */
108
+ export function isMimeType(
109
+ file: File,
110
+ acceptableMimeTypes: Array<string>,
111
+ ): boolean {
112
+ for (const acceptableType of acceptableMimeTypes) {
113
+ if (file.type.startsWith(acceptableType)) {
114
+ return true;
115
+ }
116
+ }
117
+ return false;
118
+ }
119
+
120
+ /**
121
+ * Lexical File Reader with:
122
+ * 1. MIME type support
123
+ * 2. batched results (HistoryPlugin compatibility)
124
+ * 3. Order aware (respects the order when multiple Files are passed)
125
+ *
126
+ * const filesResult = await mediaFileReader(files, ['image/']);
127
+ * filesResult.forEach(file => editor.dispatchCommand('INSERT_IMAGE', \\{
128
+ * src: file.result,
129
+ * \\}));
130
+ */
131
+ export function mediaFileReader(
132
+ files: Array<File>,
133
+ acceptableMimeTypes: Array<string>,
134
+ ): Promise<Array<{file: File; result: string}>> {
135
+ const filesIterator = files[Symbol.iterator]();
136
+ return new Promise((resolve, reject) => {
137
+ const processed: Array<{file: File; result: string}> = [];
138
+ const handleNextFile = () => {
139
+ const {done, value: file} = filesIterator.next();
140
+ if (done) {
141
+ return resolve(processed);
142
+ }
143
+ const fileReader = new FileReader();
144
+ fileReader.addEventListener('error', reject);
145
+ fileReader.addEventListener('load', () => {
146
+ const result = fileReader.result;
147
+ if (typeof result === 'string') {
148
+ processed.push({file, result});
149
+ }
150
+ handleNextFile();
151
+ });
152
+ if (isMimeType(file, acceptableMimeTypes)) {
153
+ fileReader.readAsDataURL(file);
154
+ } else {
155
+ handleNextFile();
156
+ }
157
+ };
158
+ handleNextFile();
159
+ });
160
+ }
161
+
162
+ export interface DFSNode {
163
+ readonly depth: number;
164
+ readonly node: LexicalNode;
165
+ }
166
+
167
+ /**
168
+ * "Depth-First Search" starts at the root/top node of a tree and goes as far as it can down a branch end
169
+ * before backtracking and finding a new path. Consider solving a maze by hugging either wall, moving down a
170
+ * branch until you hit a dead-end (leaf) and backtracking to find the nearest branching path and repeat.
171
+ * It will then return all the nodes found in the search in an array of objects.
172
+ * Preorder traversal is used, meaning that nodes are listed in the order of when they are FIRST encountered.
173
+ * @param startNode - The node to start the search (inclusive), if omitted, it will start at the root node.
174
+ * @param endNode - The node to end the search (inclusive), if omitted, it will find all descendants of the startingNode. If endNode
175
+ * is an ElementNode, it will stop before visiting any of its children.
176
+ * @returns An array of objects of all the nodes found by the search, including their depth into the tree.
177
+ * \\{depth: number, node: LexicalNode\\} It will always return at least 1 node (the start node).
178
+ */
179
+ export function $dfs(
180
+ startNode?: LexicalNode,
181
+ endNode?: LexicalNode,
182
+ ): Array<DFSNode> {
183
+ return Array.from($dfsIterator(startNode, endNode));
184
+ }
185
+
186
+ /**
187
+ * Get the adjacent caret in the same direction
188
+ *
189
+ * @param caret A caret or null
190
+ * @returns `caret.getAdjacentCaret()` or `null`
191
+ */
192
+ export function $getAdjacentCaret<D extends CaretDirection>(
193
+ caret: null | NodeCaret<D>,
194
+ ): null | SiblingCaret<LexicalNode, D> {
195
+ return caret ? caret.getAdjacentCaret() : null;
196
+ }
197
+
198
+ /**
199
+ * $dfs iterator (right to left). Tree traversal is done on the fly as new values are requested with O(1) memory.
200
+ * @param startNode - The node to start the search, if omitted, it will start at the root node.
201
+ * @param endNode - The node to end the search, if omitted, it will find all descendants of the startingNode.
202
+ * @returns An iterator, each yielded value is a DFSNode. It will always return at least 1 node (the start node).
203
+ */
204
+ export function $reverseDfs(
205
+ startNode?: LexicalNode,
206
+ endNode?: LexicalNode,
207
+ ): Array<DFSNode> {
208
+ return Array.from($reverseDfsIterator(startNode, endNode));
209
+ }
210
+
211
+ /**
212
+ * $dfs iterator (left to right). Tree traversal is done on the fly as new values are requested with O(1) memory.
213
+ * Preorder traversal is used, meaning that nodes are iterated over in the order of when they are FIRST encountered.
214
+ * @param startNode - The node to start the search (inclusive), if omitted, it will start at the root node.
215
+ * @param endNode - The node to end the search (inclusive), if omitted, it will find all descendants of the startingNode.
216
+ * If endNode is an ElementNode, the iterator will end as soon as it reaches the endNode (no children will be visited).
217
+ * @returns An iterator, each yielded value is a DFSNode. It will always return at least 1 node (the start node).
218
+ */
219
+ export function $dfsIterator(
220
+ startNode?: LexicalNode,
221
+ endNode?: LexicalNode,
222
+ ): IterableIterator<DFSNode> {
223
+ return $dfsCaretIterator('next', startNode, endNode);
224
+ }
225
+
226
+ function $getEndCaret<D extends CaretDirection>(
227
+ startNode: LexicalNode,
228
+ direction: D,
229
+ ): null | NodeCaret<D> {
230
+ const rval = $getAdjacentSiblingOrParentSiblingCaret(
231
+ $getSiblingCaret(startNode, direction),
232
+ );
233
+ return rval && rval[0];
234
+ }
235
+
236
+ function $dfsCaretIterator<D extends CaretDirection>(
237
+ direction: D,
238
+ startNode?: LexicalNode,
239
+ endNode?: LexicalNode,
240
+ ): IterableIterator<DFSNode> {
241
+ const root = $getRoot();
242
+ const start = startNode || root;
243
+ const startCaret = $isElementNode(start)
244
+ ? $getChildCaret(start, direction)
245
+ : $getSiblingCaret(start, direction);
246
+ const startDepth = $getDepth(start);
247
+ const endCaret = endNode
248
+ ? $getAdjacentChildCaret(
249
+ $getChildCaretOrSelf($getSiblingCaret(endNode, direction)),
250
+ ) || $getEndCaret(endNode, direction)
251
+ : $getEndCaret(start, direction);
252
+ let depth = startDepth;
253
+ return makeStepwiseIterator({
254
+ hasNext: (state): state is NodeCaret<'next'> => state !== null,
255
+ initial: startCaret,
256
+ map: state => ({depth, node: state.origin}),
257
+ step: (state: NodeCaret<'next'>) => {
258
+ if (state.isSameNodeCaret(endCaret)) {
259
+ return null;
260
+ }
261
+ if ($isChildCaret(state)) {
262
+ depth++;
263
+ }
264
+ const rval = $getAdjacentSiblingOrParentSiblingCaret(state);
265
+ if (!rval || rval[0].isSameNodeCaret(endCaret)) {
266
+ return null;
267
+ }
268
+ depth += rval[1];
269
+ return rval[0];
270
+ },
271
+ });
272
+ }
273
+
274
+ /**
275
+ * Returns the Node sibling when this exists, otherwise the closest parent sibling. For example
276
+ * R -> P -> T1, T2
277
+ * -> P2
278
+ * returns T2 for node T1, P2 for node T2, and null for node P2.
279
+ * @param node LexicalNode.
280
+ * @returns An array (tuple) containing the found Lexical node and the depth difference, or null, if this node doesn't exist.
281
+ */
282
+ export function $getNextSiblingOrParentSibling(
283
+ node: LexicalNode,
284
+ ): null | [LexicalNode, number] {
285
+ const rval = $getAdjacentSiblingOrParentSiblingCaret(
286
+ $getSiblingCaret(node, 'next'),
287
+ );
288
+ return rval && [rval[0].origin, rval[1]];
289
+ }
290
+
291
+ export function $getDepth(node: null | LexicalNode): number {
292
+ let depth = -1;
293
+ for (
294
+ let innerNode = node;
295
+ innerNode !== null;
296
+ innerNode = innerNode.getParent()
297
+ ) {
298
+ depth++;
299
+ }
300
+ return depth;
301
+ }
302
+
303
+ /**
304
+ * Performs a right-to-left preorder tree traversal.
305
+ * From the starting node it goes to the rightmost child, than backtracks to parent and finds new rightmost path.
306
+ * It will return the next node in traversal sequence after the startingNode.
307
+ * The traversal is similar to $dfs functions above, but the nodes are visited right-to-left, not left-to-right.
308
+ * @param startingNode - The node to start the search.
309
+ * @returns The next node in pre-order right to left traversal sequence or `null`, if the node does not exist
310
+ */
311
+ export function $getNextRightPreorderNode(
312
+ startingNode: LexicalNode,
313
+ ): LexicalNode | null {
314
+ const startCaret = $getChildCaretOrSelf(
315
+ $getSiblingCaret(startingNode, 'previous'),
316
+ );
317
+ const next = $getAdjacentSiblingOrParentSiblingCaret(startCaret, 'root');
318
+ return next && next[0].origin;
319
+ }
320
+
321
+ /**
322
+ * $dfs iterator (right to left). Tree traversal is done on the fly as new values are requested with O(1) memory.
323
+ * @param startNode - The node to start the search, if omitted, it will start at the root node.
324
+ * @param endNode - The node to end the search, if omitted, it will find all descendants of the startingNode.
325
+ * @returns An iterator, each yielded value is a DFSNode. It will always return at least 1 node (the start node).
326
+ */
327
+ export function $reverseDfsIterator(
328
+ startNode?: LexicalNode,
329
+ endNode?: LexicalNode,
330
+ ): IterableIterator<DFSNode> {
331
+ return $dfsCaretIterator('previous', startNode, endNode);
332
+ }
333
+
334
+ /**
335
+ * Takes a node and traverses up its ancestors (toward the root node)
336
+ * in order to find a specific type of node.
337
+ * @param node - the node to begin searching.
338
+ * @param klass - an instance of the type of node to look for.
339
+ * @returns the node of type klass that was passed, or null if none exist.
340
+ */
341
+ export function $getNearestNodeOfType<T extends ElementNode>(
342
+ node: LexicalNode,
343
+ klass: Klass<T>,
344
+ ): T | null {
345
+ let parent: ElementNode | LexicalNode | null = node;
346
+
347
+ while (parent != null) {
348
+ if (parent instanceof klass) {
349
+ return parent as T;
350
+ }
351
+
352
+ parent = parent.getParent();
353
+ }
354
+
355
+ return null;
356
+ }
357
+
358
+ /**
359
+ * Returns the element node of the nearest ancestor, otherwise throws an error.
360
+ * @param startNode - The starting node of the search
361
+ * @returns The ancestor node found
362
+ */
363
+ export function $getNearestBlockElementAncestorOrThrow(
364
+ startNode: LexicalNode,
365
+ ): ElementNode {
366
+ const blockNode = $findMatchingParent(
367
+ startNode,
368
+ node => $isElementNode(node) && !node.isInline(),
369
+ );
370
+ if (!$isElementNode(blockNode)) {
371
+ invariant(
372
+ false,
373
+ 'Expected node %s to have closest block element node.',
374
+ startNode.__key,
375
+ );
376
+ }
377
+ return blockNode;
378
+ }
379
+
380
+ export type DOMNodeToLexicalConversion = (element: Node) => LexicalNode;
381
+
382
+ export type DOMNodeToLexicalConversionMap = Record<
383
+ string,
384
+ DOMNodeToLexicalConversion
385
+ >;
386
+
387
+ /**
388
+ * Attempts to resolve nested element nodes of the same type into a single node of that type.
389
+ * It is generally used for marks/commenting
390
+ * @param editor - The lexical editor
391
+ * @param targetNode - The target for the nested element to be extracted from.
392
+ * @param cloneNode - See {@link $createMarkNode}
393
+ * @param handleOverlap - Handles any overlap between the node to extract and the targetNode
394
+ * @returns The lexical editor
395
+ */
396
+ export function registerNestedElementResolver<N extends ElementNode>(
397
+ editor: LexicalEditor,
398
+ targetNode: Klass<N>,
399
+ cloneNode: (from: N) => N,
400
+ handleOverlap: (from: N, to: N) => void,
401
+ ): () => void {
402
+ const $isTargetNode = (node: LexicalNode | null | undefined): node is N => {
403
+ return node instanceof targetNode;
404
+ };
405
+
406
+ const $findMatch = (node: N): {child: ElementNode; parent: N} | null => {
407
+ // First validate we don't have any children that are of the target,
408
+ // as we need to handle them first.
409
+ const children = node.getChildren();
410
+
411
+ for (let i = 0; i < children.length; i++) {
412
+ const child = children[i];
413
+
414
+ if ($isTargetNode(child)) {
415
+ return null;
416
+ }
417
+ }
418
+
419
+ let parentNode: N | null = node;
420
+ let childNode = node;
421
+
422
+ while (parentNode !== null) {
423
+ childNode = parentNode;
424
+ parentNode = parentNode.getParent();
425
+
426
+ if ($isTargetNode(parentNode)) {
427
+ return {child: childNode, parent: parentNode};
428
+ }
429
+ }
430
+
431
+ return null;
432
+ };
433
+
434
+ const $elementNodeTransform = (node: N) => {
435
+ const match = $findMatch(node);
436
+
437
+ if (match !== null) {
438
+ const {child, parent} = match;
439
+
440
+ // Simple path, we can move child out and siblings into a new parent.
441
+
442
+ if (child.is(node)) {
443
+ handleOverlap(parent, node);
444
+ const nextSiblings = child.getNextSiblings();
445
+ const nextSiblingsLength = nextSiblings.length;
446
+ parent.insertAfter(child);
447
+
448
+ if (nextSiblingsLength !== 0) {
449
+ const newParent = cloneNode(parent);
450
+ child.insertAfter(newParent);
451
+
452
+ for (let i = 0; i < nextSiblingsLength; i++) {
453
+ newParent.append(nextSiblings[i]);
454
+ }
455
+ }
456
+
457
+ if (!parent.canBeEmpty() && parent.getChildrenSize() === 0) {
458
+ parent.remove();
459
+ }
460
+ } else {
461
+ // Complex path, we have a deep node that isn't a child of the
462
+ // target parent.
463
+ // TODO: implement this functionality
464
+ }
465
+ }
466
+ };
467
+
468
+ return editor.registerNodeTransform(targetNode, $elementNodeTransform);
469
+ }
470
+
471
+ /**
472
+ * Clones the editor and marks it as dirty to be reconciled. If there was a selection,
473
+ * it would be set back to its previous state, or null otherwise.
474
+ * @param editor - The lexical editor
475
+ * @param editorState - The editor's state
476
+ */
477
+ export function $restoreEditorState(
478
+ editor: LexicalEditor,
479
+ editorState: EditorState,
480
+ ): void {
481
+ const nodeMap = new Map();
482
+ const activeEditorState = editor._pendingEditorState;
483
+
484
+ for (const [key, node] of editorState._nodeMap) {
485
+ nodeMap.set(key, $cloneWithProperties(node));
486
+ }
487
+
488
+ if (activeEditorState) {
489
+ activeEditorState._nodeMap = nodeMap;
490
+ }
491
+
492
+ $fullReconcile();
493
+ const selection = editorState._selection;
494
+ $setSelection(selection === null ? null : selection.clone());
495
+ }
496
+
497
+ /**
498
+ * If the selected insertion area is the root/shadow root node (see {@link lexical!$isRootOrShadowRoot}),
499
+ * the node will be appended there, otherwise, it will be inserted before the insertion area.
500
+ * If there is no selection where the node is to be inserted, it will be appended after any current nodes
501
+ * within the tree, as a child of the root node. A paragraph will then be added after the inserted node and selected.
502
+ * @param node - The node to be inserted
503
+ * @returns The node after its insertion
504
+ */
505
+ export function $insertNodeToNearestRoot<T extends LexicalNode>(node: T): T {
506
+ const selection = $getSelection() || $getPreviousSelection();
507
+ let initialCaret: undefined | PointCaret<'next'>;
508
+ if ($isRangeSelection(selection)) {
509
+ initialCaret = $caretFromPoint(selection.focus, 'next');
510
+ } else {
511
+ if (selection != null) {
512
+ const nodes = selection.getNodes();
513
+ const lastNode = nodes[nodes.length - 1];
514
+ if (lastNode) {
515
+ initialCaret = $getSiblingCaret(lastNode, 'next');
516
+ }
517
+ }
518
+ initialCaret =
519
+ initialCaret ||
520
+ $getChildCaret($getRoot(), 'previous')
521
+ .getFlipped()
522
+ .insert($createParagraphNode());
523
+ }
524
+ const insertCaret = $insertNodeToNearestRootAtCaret(node, initialCaret);
525
+ const adjacent = $getAdjacentChildCaret(insertCaret);
526
+ const selectionCaret = $isChildCaret(adjacent)
527
+ ? $normalizeCaret(adjacent)
528
+ : insertCaret;
529
+ $setSelectionFromCaretRange($getCollapsedCaretRange(selectionCaret));
530
+ return node.getLatest();
531
+ }
532
+
533
+ /**
534
+ * If the insertion caret is the root/shadow root node (see {@link lexical!$isRootOrShadowRoot}),
535
+ * the node will be inserted there, otherwise the parent nodes will be split according to the
536
+ * given options.
537
+ * @param node - The node to be inserted
538
+ * @param caret - The location to insert or split from
539
+ * @returns The node after its insertion
540
+ */
541
+ export function $insertNodeToNearestRootAtCaret<
542
+ T extends LexicalNode,
543
+ D extends CaretDirection,
544
+ >(
545
+ node: T,
546
+ caret: PointCaret<D>,
547
+ options?: SplitAtPointCaretNextOptions,
548
+ ): NodeCaret<D> {
549
+ let insertCaret: PointCaret<'next'> = $getCaretInDirection(caret, 'next');
550
+ // Normalize boundary cases for TextPointCaret
551
+ if ($isTextPointCaret(insertCaret)) {
552
+ if (insertCaret.offset === 0) {
553
+ insertCaret = $getSiblingCaret(
554
+ insertCaret.origin,
555
+ 'previous',
556
+ ).getFlipped();
557
+ } else if (insertCaret.offset === insertCaret.origin.getTextContentSize()) {
558
+ insertCaret = $getSiblingCaret(insertCaret.origin, 'next');
559
+ }
560
+ }
561
+ // Make sure we have a distinct node as the origin
562
+ if (insertCaret.origin.is(node)) {
563
+ invariant(
564
+ $isSiblingCaret(insertCaret),
565
+ '$insertNodeToNearestRootAtCaret node %s of type %s can not be inserted into itself',
566
+ node.getKey(),
567
+ node.getType(),
568
+ );
569
+ insertCaret = $rewindSiblingCaret(insertCaret);
570
+ }
571
+ // Handle split boundary conditions where node is being inserted adjacent to itself
572
+ if (
573
+ node.is(insertCaret.getNodeAtCaret()) ||
574
+ node.is(insertCaret.getFlipped().getNodeAtCaret())
575
+ ) {
576
+ node.remove(true);
577
+ }
578
+ for (
579
+ let nextCaret: null | PointCaret<'next'> = insertCaret;
580
+ nextCaret;
581
+ nextCaret = $splitAtPointCaretNext(nextCaret, options)
582
+ ) {
583
+ insertCaret = nextCaret;
584
+ }
585
+ invariant(
586
+ !$isTextPointCaret(insertCaret),
587
+ '$insertNodeToNearestRootAtCaret: An unattached TextNode can not be split',
588
+ );
589
+ insertCaret.insert(
590
+ node.isInline() ? $createParagraphNode().append(node) : node,
591
+ );
592
+ return $getCaretInDirection(
593
+ $getSiblingCaret(node.getLatest(), 'next'),
594
+ caret.direction,
595
+ );
596
+ }
597
+
598
+ /**
599
+ * Inserts a node into leaf — the deepest accessible node at the carriage position
600
+ * @param node - The node to be inserted
601
+ */
602
+ export function $insertNodeIntoLeaf(node: LexicalNode): void {
603
+ const selection = $getSelection();
604
+ if (!$isRangeSelection(selection)) {
605
+ if (selection) {
606
+ selection.insertNodes([node]);
607
+ }
608
+ return;
609
+ }
610
+ const caretRange = $caretRangeFromSelection(selection);
611
+ let insertCaret = $getCaretRangeInDirection(
612
+ $removeTextFromCaretRange(caretRange),
613
+ 'next',
614
+ ).anchor;
615
+ if ($isTextPointCaret(insertCaret)) {
616
+ const nextAnchor = $splitAtPointCaretNext(insertCaret);
617
+ if (!nextAnchor) {
618
+ return;
619
+ }
620
+ insertCaret = nextAnchor;
621
+ }
622
+ const focus = insertCaret.getFlipped();
623
+ focus.insert(node);
624
+ $setSelectionFromCaretRange($getCaretRange(focus, focus));
625
+ }
626
+
627
+ /**
628
+ * Wraps the node into another node created from a createElementNode function, eg. $createParagraphNode
629
+ * @param node - Node to be wrapped.
630
+ * @param createElementNode - Creates a new lexical element to wrap the to-be-wrapped node and returns it.
631
+ * @returns A new lexical element with the previous node appended within (as a child, including its children).
632
+ */
633
+ export function $wrapNodeInElement(
634
+ node: LexicalNode,
635
+ createElementNode: () => ElementNode,
636
+ ): ElementNode {
637
+ const elementNode = createElementNode();
638
+ node.replace(elementNode);
639
+ elementNode.append(node);
640
+ return elementNode;
641
+ }
642
+
643
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
644
+ export type ObjectKlass<T> = new (...args: any[]) => T;
645
+
646
+ /**
647
+ * @param object = The instance of the type
648
+ * @param objectClass = The class of the type
649
+ * @returns Whether the object is has the same Klass of the objectClass, ignoring the difference across window (e.g. different iframes)
650
+ */
651
+ export function objectKlassEquals<T>(
652
+ object: unknown,
653
+ objectClass: ObjectKlass<T>,
654
+ ): object is T {
655
+ return object !== null
656
+ ? Object.getPrototypeOf(object).constructor.name === objectClass.name
657
+ : false;
658
+ }
659
+
660
+ /**
661
+ * @deprecated Use Array filter or flatMap
662
+ *
663
+ * Filter the nodes
664
+ * @param nodes Array of nodes that needs to be filtered
665
+ * @param filterFn A filter function that returns node if the current node satisfies the condition otherwise null
666
+ * @returns Array of filtered nodes
667
+ */
668
+
669
+ export function $filter<T>(
670
+ nodes: Array<LexicalNode>,
671
+ filterFn: (node: LexicalNode) => null | T,
672
+ ): Array<T> {
673
+ const result: T[] = [];
674
+ for (let i = 0; i < nodes.length; i++) {
675
+ const node = filterFn(nodes[i]);
676
+ if (node !== null) {
677
+ result.push(node);
678
+ }
679
+ }
680
+ return result;
681
+ }
682
+
683
+ /**
684
+ * Applies the provided callback to each indentable block element in the Selection
685
+ *
686
+ * @param indentOrOutdent callback for performing the indent or outdent action
687
+ * on a given block element.
688
+ * @returns true if at least one block was handled, false otherwise.
689
+ */
690
+ export function $handleIndentAndOutdent(
691
+ indentOrOutdent: (block: ElementNode) => void,
692
+ ): boolean {
693
+ const selection = $getSelection();
694
+ if (!$isRangeSelection(selection)) {
695
+ return false;
696
+ }
697
+ const alreadyHandled = new Set();
698
+ const nodes = selection.getNodes();
699
+ for (let i = 0; i < nodes.length; i++) {
700
+ const node = nodes[i];
701
+ const key = node.getKey();
702
+ if (alreadyHandled.has(key)) {
703
+ continue;
704
+ }
705
+ const parentBlock = $findMatchingParent(
706
+ node,
707
+ (parentNode): parentNode is ElementNode =>
708
+ $isElementNode(parentNode) && !parentNode.isInline(),
709
+ );
710
+ if (parentBlock === null) {
711
+ continue;
712
+ }
713
+ const parentKey = parentBlock.getKey();
714
+ if (parentBlock.canIndent() && !alreadyHandled.has(parentKey)) {
715
+ alreadyHandled.add(parentKey);
716
+ indentOrOutdent(parentBlock);
717
+ }
718
+ }
719
+ return alreadyHandled.size > 0;
720
+ }
721
+
722
+ /**
723
+ * Appends the node before the first child of the parent node
724
+ * @param parent A parent node
725
+ * @param node Node that needs to be appended
726
+ */
727
+ export function $insertFirst(parent: ElementNode, node: LexicalNode): void {
728
+ $getChildCaret(parent, 'next').insert(node);
729
+ }
730
+
731
+ let NEEDS_MANUAL_ZOOM = IS_FIREFOX || !CAN_USE_DOM ? false : undefined;
732
+ function needsManualZoom(): boolean {
733
+ if (NEEDS_MANUAL_ZOOM === undefined) {
734
+ // If the browser implements standardized CSS zoom, then the client rect
735
+ // will be wider after zoom is applied
736
+ // https://chromestatus.com/feature/5198254868529152
737
+ // https://github.com/facebook/lexical/issues/6863
738
+ const div = document.createElement('div');
739
+ div.style.position = 'absolute';
740
+ div.style.opacity = '0';
741
+ div.style.width = '100px';
742
+ div.style.left = '-1000px';
743
+ document.body.appendChild(div);
744
+ const noZoom = div.getBoundingClientRect();
745
+ div.style.setProperty('zoom', '2');
746
+ NEEDS_MANUAL_ZOOM = div.getBoundingClientRect().width === noZoom.width;
747
+ document.body.removeChild(div);
748
+ }
749
+ return NEEDS_MANUAL_ZOOM;
750
+ }
751
+
752
+ /**
753
+ * Calculates the zoom level of an element as a result of using
754
+ * css zoom property. For browsers that implement standardized CSS
755
+ * zoom (Firefox, Chrome >= 128), this will always return 1.
756
+ * @param element
757
+ * @param useManualZoom - If true, always use zoom level will be calculated manually, otherwise it will be calculated on as needed basis.
758
+ */
759
+ export function calculateZoomLevel(
760
+ element: Element | null,
761
+ useManualZoom: boolean = false,
762
+ ): number {
763
+ let zoom = 1;
764
+ if (needsManualZoom() || useManualZoom) {
765
+ while (element) {
766
+ zoom *= Number(window.getComputedStyle(element).getPropertyValue('zoom'));
767
+ element = element.parentElement;
768
+ }
769
+ }
770
+ return zoom;
771
+ }
772
+
773
+ /**
774
+ * Checks if the editor is a nested editor created by LexicalNestedComposer
775
+ */
776
+ export function $isEditorIsNestedEditor(editor: LexicalEditor): boolean {
777
+ return editor._parentEditor !== null;
778
+ }
779
+
780
+ /**
781
+ * A depth first last-to-first traversal of root that stops at each node that matches
782
+ * $predicate and ensures that its parent is root. This is typically used to discard
783
+ * invalid or unsupported wrapping nodes. For example, a TableNode must only have
784
+ * TableRowNode as children, but an importer might add invalid nodes based on
785
+ * caption, tbody, thead, etc. and this will unwrap and discard those.
786
+ *
787
+ * @param root The root to start the traversal
788
+ * @param $predicate Should return true for nodes that are permitted to be children of root
789
+ * @returns true if this unwrapped or removed any nodes
790
+ */
791
+ export function $unwrapAndFilterDescendants(
792
+ root: ElementNode,
793
+ $predicate: (node: LexicalNode) => boolean,
794
+ ): boolean {
795
+ return $unwrapAndFilterDescendantsImpl(root, $predicate, null);
796
+ }
797
+
798
+ function $unwrapAndFilterDescendantsImpl(
799
+ root: ElementNode,
800
+ $predicate: (node: LexicalNode) => boolean,
801
+ $onSuccess: null | ((node: LexicalNode) => void),
802
+ ): boolean {
803
+ let didMutate = false;
804
+ for (const node of $lastToFirstIterator(root)) {
805
+ if ($predicate(node)) {
806
+ if ($onSuccess !== null) {
807
+ $onSuccess(node);
808
+ }
809
+ continue;
810
+ }
811
+ didMutate = true;
812
+ if ($isElementNode(node)) {
813
+ $unwrapAndFilterDescendantsImpl(
814
+ node,
815
+ $predicate,
816
+ $onSuccess || (child => node.insertAfter(child)),
817
+ );
818
+ }
819
+ node.remove();
820
+ }
821
+ return didMutate;
822
+ }
823
+
824
+ /**
825
+ * A depth first traversal of the children array that stops at and collects
826
+ * each node that `$predicate` matches. This is typically used to discard
827
+ * invalid or unsupported wrapping nodes on a children array in the `after`
828
+ * of an {@link lexical!DOMConversionOutput}. For example, a TableNode must only have
829
+ * TableRowNode as children, but an importer might add invalid nodes based on
830
+ * caption, tbody, thead, etc. and this will unwrap and discard those.
831
+ *
832
+ * This function is read-only and performs no mutation operations, which makes
833
+ * it suitable for import and export purposes but likely not for any in-place
834
+ * mutation. You should use {@link $unwrapAndFilterDescendants} for in-place
835
+ * mutations such as node transforms.
836
+ *
837
+ * @param children The children to traverse
838
+ * @param $predicate Should return true for nodes that are permitted to be children of root
839
+ * @returns The children or their descendants that match $predicate
840
+ */
841
+ export function $descendantsMatching<T extends LexicalNode>(
842
+ children: LexicalNode[],
843
+ $predicate: (node: LexicalNode) => node is T,
844
+ ): T[];
845
+ export function $descendantsMatching(
846
+ children: LexicalNode[],
847
+ $predicate: (node: LexicalNode) => boolean,
848
+ ): LexicalNode[] {
849
+ const result: LexicalNode[] = [];
850
+ const stack = Array.from(children).reverse();
851
+ for (let child = stack.pop(); child !== undefined; child = stack.pop()) {
852
+ if ($predicate(child)) {
853
+ result.push(child);
854
+ } else if ($isElementNode(child)) {
855
+ for (const grandchild of $lastToFirstIterator(child)) {
856
+ stack.push(grandchild);
857
+ }
858
+ }
859
+ }
860
+ return result;
861
+ }
862
+
863
+ /**
864
+ * Return an iterator that yields each child of node from first to last, taking
865
+ * care to preserve the next sibling before yielding the value in case the caller
866
+ * removes the yielded node.
867
+ *
868
+ * @param node The node whose children to iterate
869
+ * @returns An iterator of the node's children
870
+ */
871
+ export function $firstToLastIterator(node: ElementNode): Iterable<LexicalNode> {
872
+ return $childIterator($getChildCaret(node, 'next'));
873
+ }
874
+
875
+ /**
876
+ * Return an iterator that yields each child of node from last to first, taking
877
+ * care to preserve the previous sibling before yielding the value in case the caller
878
+ * removes the yielded node.
879
+ *
880
+ * @param node The node whose children to iterate
881
+ * @returns An iterator of the node's children
882
+ */
883
+ export function $lastToFirstIterator(node: ElementNode): Iterable<LexicalNode> {
884
+ return $childIterator($getChildCaret(node, 'previous'));
885
+ }
886
+
887
+ function $childIterator<D extends CaretDirection>(
888
+ startCaret: NodeCaret<D>,
889
+ ): IterableIterator<LexicalNode> {
890
+ const seen = __DEV__ ? new Set<NodeKey>() : null;
891
+ return makeStepwiseIterator({
892
+ hasNext: $isSiblingCaret,
893
+ initial: startCaret.getAdjacentCaret(),
894
+ map: caret => {
895
+ const origin = caret.origin.getLatest();
896
+ if (__DEV__ && seen !== null) {
897
+ const key = origin.getKey();
898
+ invariant(
899
+ !seen.has(key),
900
+ '$childIterator: Cycle detected, node with key %s has already been traversed',
901
+ String(key),
902
+ );
903
+ seen.add(key);
904
+ }
905
+ return origin;
906
+ },
907
+ step: (caret: SiblingCaret<LexicalNode, D>) => caret.getAdjacentCaret(),
908
+ });
909
+ }
910
+
911
+ /**
912
+ * Replace this node with its children
913
+ *
914
+ * @param node The ElementNode to unwrap and remove
915
+ */
916
+ export function $unwrapNode(node: ElementNode): void {
917
+ $rewindSiblingCaret($getSiblingCaret(node, 'next')).splice(
918
+ 1,
919
+ node.getChildren(),
920
+ );
921
+ }
922
+
923
+ /**
924
+ * A wrapper that creates bound functions and methods for the
925
+ * StateConfig to save some boilerplate when defining methods
926
+ * or exporting only the accessors from your modules rather
927
+ * than exposing the StateConfig directly.
928
+ */
929
+ export interface StateConfigWrapper<K extends string, V> {
930
+ /** A reference to the stateConfig */
931
+ readonly stateConfig: StateConfig<K, V>;
932
+ /** `(node) => $getState(node, stateConfig)` */
933
+ readonly $get: <T extends LexicalNode>(node: T) => V;
934
+ /** `(node, valueOrUpdater) => $setState(node, stateConfig, valueOrUpdater)` */
935
+ readonly $set: <T extends LexicalNode>(
936
+ node: T,
937
+ valueOrUpdater: ValueOrUpdater<V>,
938
+ ) => T;
939
+ /** `[$get, $set]` */
940
+ readonly accessors: readonly [$get: this['$get'], $set: this['$set']];
941
+ /**
942
+ * `() => function () { return $get(this) }`
943
+ *
944
+ * Should be called with an explicit `this` type parameter.
945
+ *
946
+ * @example
947
+ * ```ts
948
+ * class MyNode {
949
+ * // …
950
+ * myGetter = myWrapper.makeGetterMethod<this>();
951
+ * }
952
+ * ```
953
+ */
954
+ makeGetterMethod<T extends LexicalNode>(): (this: T) => V;
955
+ /**
956
+ * `() => function (valueOrUpdater) { return $set(this, valueOrUpdater) }`
957
+ *
958
+ * Must be called with an explicit `this` type parameter.
959
+ *
960
+ * @example
961
+ * ```ts
962
+ * class MyNode {
963
+ * // …
964
+ * mySetter = myWrapper.makeSetterMethod<this>();
965
+ * }
966
+ * ```
967
+ */
968
+ makeSetterMethod<T extends LexicalNode>(): (
969
+ this: T,
970
+ valueOrUpdater: ValueOrUpdater<V>,
971
+ ) => T;
972
+ }
973
+
974
+ /**
975
+ * EXPERIMENTAL
976
+ *
977
+ * A convenience interface for working with {@link $getState} and
978
+ * {@link $setState}.
979
+ *
980
+ * @param stateConfig The stateConfig to wrap with convenience functionality
981
+ * @returns a StateWrapper
982
+ */
983
+ export function makeStateWrapper<K extends string, V>(
984
+ stateConfig: StateConfig<K, V>,
985
+ ): StateConfigWrapper<K, V> {
986
+ const $get: StateConfigWrapper<K, V>['$get'] = node =>
987
+ $getState(node, stateConfig);
988
+ const $set: StateConfigWrapper<K, V>['$set'] = (node, valueOrUpdater) =>
989
+ $setState(node, stateConfig, valueOrUpdater);
990
+ return {
991
+ $get,
992
+ $set,
993
+ accessors: [$get, $set],
994
+ makeGetterMethod: () =>
995
+ function $getter() {
996
+ return $get(this);
997
+ },
998
+ makeSetterMethod: () =>
999
+ function $setter(valueOrUpdater) {
1000
+ return $set(this, valueOrUpdater);
1001
+ },
1002
+ stateConfig,
1003
+ };
1004
+ }