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