@react-fabric/lexical 1.0.0-beta.47 → 1.0.0-beta.49

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.
Files changed (62) hide show
  1. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.dev.js +29 -19
  2. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.js +1 -1
  3. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.prod.js +9 -9
  4. package/dist/cjs/node_modules/@lexical/code/LexicalCode.dev.js +142 -75
  5. package/dist/cjs/node_modules/@lexical/code/LexicalCode.js +1 -1
  6. package/dist/cjs/node_modules/@lexical/code/LexicalCode.prod.js +25 -21
  7. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.dev.js +10 -3
  8. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.js +1 -1
  9. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.prod.js +3 -3
  10. package/dist/cjs/node_modules/@lexical/link/LexicalLink.dev.js +147 -103
  11. package/dist/cjs/node_modules/@lexical/link/LexicalLink.js +1 -1
  12. package/dist/cjs/node_modules/@lexical/link/LexicalLink.prod.js +10 -10
  13. package/dist/cjs/node_modules/@lexical/list/LexicalList.dev.js +254 -178
  14. package/dist/cjs/node_modules/@lexical/list/LexicalList.js +1 -1
  15. package/dist/cjs/node_modules/@lexical/list/LexicalList.prod.js +19 -16
  16. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.dev.js +53 -29
  17. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.js +1 -1
  18. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.prod.js +10 -10
  19. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.dev.js +176 -194
  20. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.js +1 -1
  21. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.prod.js +25 -18
  22. package/dist/cjs/node_modules/@lexical/table/LexicalTable.dev.js +1925 -793
  23. package/dist/cjs/node_modules/@lexical/table/LexicalTable.js +1 -1
  24. package/dist/cjs/node_modules/@lexical/table/LexicalTable.prod.js +48 -40
  25. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.dev.js +426 -144
  26. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.js +11 -1
  27. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.prod.js +46 -32
  28. package/dist/cjs/node_modules/prismjs/prism.js +1 -1
  29. package/dist/cjs/packages/lexical/src/editor/LexicalEditor.js +1 -1
  30. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.dev.js +29 -19
  31. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.js +1 -1
  32. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.prod.js +3 -3
  33. package/dist/esm/node_modules/@lexical/code/LexicalCode.dev.js +139 -76
  34. package/dist/esm/node_modules/@lexical/code/LexicalCode.js +1 -1
  35. package/dist/esm/node_modules/@lexical/code/LexicalCode.prod.js +4 -4
  36. package/dist/esm/node_modules/@lexical/html/LexicalHtml.dev.js +11 -4
  37. package/dist/esm/node_modules/@lexical/html/LexicalHtml.js +1 -1
  38. package/dist/esm/node_modules/@lexical/html/LexicalHtml.prod.js +3 -3
  39. package/dist/esm/node_modules/@lexical/link/LexicalLink.dev.js +149 -105
  40. package/dist/esm/node_modules/@lexical/link/LexicalLink.js +1 -1
  41. package/dist/esm/node_modules/@lexical/link/LexicalLink.prod.js +4 -4
  42. package/dist/esm/node_modules/@lexical/list/LexicalList.dev.js +253 -180
  43. package/dist/esm/node_modules/@lexical/list/LexicalList.js +1 -1
  44. package/dist/esm/node_modules/@lexical/list/LexicalList.prod.js +4 -4
  45. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.dev.js +54 -30
  46. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.js +1 -1
  47. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.prod.js +3 -3
  48. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.dev.js +171 -196
  49. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.js +1 -1
  50. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.prod.js +4 -4
  51. package/dist/esm/node_modules/@lexical/table/LexicalTable.dev.js +1920 -796
  52. package/dist/esm/node_modules/@lexical/table/LexicalTable.js +1 -1
  53. package/dist/esm/node_modules/@lexical/table/LexicalTable.prod.js +4 -4
  54. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.dev.js +413 -145
  55. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.js +7 -2
  56. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.prod.js +3 -3
  57. package/dist/esm/node_modules/prismjs/prism.js +1 -1
  58. package/dist/esm/packages/lexical/src/editor/LexicalEditor.js +1 -1
  59. package/package.json +7 -8
  60. package/src/components/StickyComponent.tsx +1 -1
  61. package/src/editor/LexicalEditor.tsx +25 -21
  62. package/src/plugins/ToolbarPlugin.tsx +20 -4
@@ -12,6 +12,20 @@ var LexicalSelection = require('../selection/LexicalSelection.js');
12
12
  */
13
13
 
14
14
 
15
+ /**
16
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
17
+ *
18
+ * This source code is licensed under the MIT license found in the
19
+ * LICENSE file in the root directory of this source tree.
20
+ *
21
+ */
22
+
23
+ // Do not require this module directly! Use normal `invariant` calls.
24
+
25
+ function formatDevErrorMessage(message) {
26
+ throw new Error(message);
27
+ }
28
+
15
29
  /**
16
30
  * Copyright (c) Meta Platforms, Inc. and affiliates.
17
31
  *
@@ -121,41 +135,49 @@ function px(value) {
121
135
  return `${value}px`;
122
136
  }
123
137
 
124
- /**
125
- * Copyright (c) Meta Platforms, Inc. and affiliates.
126
- *
127
- * This source code is licensed under the MIT license found in the
128
- * LICENSE file in the root directory of this source tree.
129
- *
130
- */
131
-
132
138
  const mutationObserverConfig = {
133
139
  attributes: true,
134
140
  characterData: true,
135
141
  childList: true,
136
142
  subtree: true
137
143
  };
138
- function positionNodeOnRange(editor, range, onReposition) {
144
+ function prependDOMNode(parent, node) {
145
+ parent.insertBefore(node, parent.firstChild);
146
+ }
147
+
148
+ /**
149
+ * Place one or multiple newly created Nodes at the passed Range's position.
150
+ * Multiple nodes will only be created when the Range spans multiple lines (aka
151
+ * client rects).
152
+ *
153
+ * This function can come particularly useful to highlight particular parts of
154
+ * the text without interfering with the EditorState, that will often replicate
155
+ * the state across collab and clipboard.
156
+ *
157
+ * This function accounts for DOM updates which can modify the passed Range.
158
+ * Hence, the function return to remove the listener.
159
+ */
160
+ function mlcPositionNodeOnRange(editor, range, onReposition) {
139
161
  let rootDOMNode = null;
140
162
  let parentDOMNode = null;
141
163
  let observer = null;
142
164
  let lastNodes = [];
143
165
  const wrapperNode = document.createElement('div');
166
+ wrapperNode.style.position = 'relative';
144
167
  function position() {
145
168
  if (!(rootDOMNode !== null)) {
146
- throw Error(`Unexpected null rootDOMNode`);
169
+ formatDevErrorMessage(`Unexpected null rootDOMNode`);
147
170
  }
148
171
  if (!(parentDOMNode !== null)) {
149
- throw Error(`Unexpected null parentDOMNode`);
172
+ formatDevErrorMessage(`Unexpected null parentDOMNode`);
150
173
  }
151
174
  const {
152
- left: rootLeft,
153
- top: rootTop
154
- } = rootDOMNode.getBoundingClientRect();
155
- const parentDOMNode_ = parentDOMNode;
175
+ left: parentLeft,
176
+ top: parentTop
177
+ } = parentDOMNode.getBoundingClientRect();
156
178
  const rects = LexicalSelection.createRectsFromDOMRange(editor, range);
157
179
  if (!wrapperNode.isConnected) {
158
- parentDOMNode_.append(wrapperNode);
180
+ prependDOMNode(parentDOMNode, wrapperNode);
159
181
  }
160
182
  let hasRepositioned = false;
161
183
  for (let i = 0; i < rects.length; i++) {
@@ -168,12 +190,12 @@ function positionNodeOnRange(editor, range, onReposition) {
168
190
  rectNodeStyle.position = 'absolute';
169
191
  hasRepositioned = true;
170
192
  }
171
- const left = px(rect.left - rootLeft);
193
+ const left = px(rect.left - parentLeft);
172
194
  if (rectNodeStyle.left !== left) {
173
195
  rectNodeStyle.left = left;
174
196
  hasRepositioned = true;
175
197
  }
176
- const top = px(rect.top - rootTop);
198
+ const top = px(rect.top - parentTop);
177
199
  if (rectNodeStyle.top !== top) {
178
200
  rectNode.style.top = top;
179
201
  hasRepositioned = true;
@@ -220,7 +242,7 @@ function positionNodeOnRange(editor, range, onReposition) {
220
242
  return stop();
221
243
  }
222
244
  const currentParentDOMNode = currentRootDOMNode.parentElement;
223
- if (!(currentParentDOMNode instanceof HTMLElement)) {
245
+ if (!lexical.isHTMLElement(currentParentDOMNode)) {
224
246
  return stop();
225
247
  }
226
248
  stop();
@@ -257,10 +279,41 @@ function positionNodeOnRange(editor, range, onReposition) {
257
279
  *
258
280
  */
259
281
 
282
+ function rangeTargetFromPoint(point, node, dom) {
283
+ if (point.type === 'text' || !lexical.$isElementNode(node)) {
284
+ const textDOM = lexical.getDOMTextNode(dom) || dom;
285
+ return [textDOM, point.offset];
286
+ } else {
287
+ const slot = node.getDOMSlot(dom);
288
+ return [slot.element, slot.getFirstChildOffset() + point.offset];
289
+ }
290
+ }
291
+ function rangeFromPoints(editor, anchor, anchorNode, anchorDOM, focus, focusNode, focusDOM) {
292
+ const editorDocument = editor._window ? editor._window.document : document;
293
+ const range = editorDocument.createRange();
294
+ if (focusNode.isBefore(anchorNode)) {
295
+ range.setStart(...rangeTargetFromPoint(focus, focusNode, focusDOM));
296
+ range.setEnd(...rangeTargetFromPoint(anchor, anchorNode, anchorDOM));
297
+ } else {
298
+ range.setStart(...rangeTargetFromPoint(anchor, anchorNode, anchorDOM));
299
+ range.setEnd(...rangeTargetFromPoint(focus, focusNode, focusDOM));
300
+ }
301
+ return range;
302
+ }
303
+ /**
304
+ * Place one or multiple newly created Nodes at the current selection. Multiple
305
+ * nodes will only be created when the selection spans multiple lines (aka
306
+ * client rects).
307
+ *
308
+ * This function can come useful when you want to show the selection but the
309
+ * editor has been focused away.
310
+ */
260
311
  function markSelection(editor, onReposition) {
261
312
  let previousAnchorNode = null;
313
+ let previousAnchorNodeDOM = null;
262
314
  let previousAnchorOffset = null;
263
315
  let previousFocusNode = null;
316
+ let previousFocusNodeDOM = null;
264
317
  let previousFocusOffset = null;
265
318
  let removeRangeListener = () => {};
266
319
  function compute(editorState) {
@@ -288,41 +341,13 @@ function markSelection(editor, onReposition) {
288
341
  const currentFocusOffset = focus.offset;
289
342
  const currentAnchorNodeDOM = editor.getElementByKey(currentAnchorNodeKey);
290
343
  const currentFocusNodeDOM = editor.getElementByKey(currentFocusNodeKey);
291
- const differentAnchorDOM = previousAnchorNode === null || currentAnchorNodeDOM === null || currentAnchorOffset !== previousAnchorOffset || currentAnchorNodeKey !== previousAnchorNode.getKey() || currentAnchorNode !== previousAnchorNode && (!(previousAnchorNode instanceof lexical.TextNode) || currentAnchorNode.updateDOM(previousAnchorNode, currentAnchorNodeDOM, editor._config));
292
- const differentFocusDOM = previousFocusNode === null || currentFocusNodeDOM === null || currentFocusOffset !== previousFocusOffset || currentFocusNodeKey !== previousFocusNode.getKey() || currentFocusNode !== previousFocusNode && (!(previousFocusNode instanceof lexical.TextNode) || currentFocusNode.updateDOM(previousFocusNode, currentFocusNodeDOM, editor._config));
293
- if (differentAnchorDOM || differentFocusDOM) {
294
- const anchorHTMLElement = editor.getElementByKey(anchor.getNode().getKey());
295
- const focusHTMLElement = editor.getElementByKey(focus.getNode().getKey());
296
- // TODO handle selection beyond the common TextNode
297
- if (anchorHTMLElement !== null && focusHTMLElement !== null && anchorHTMLElement.tagName === 'SPAN' && focusHTMLElement.tagName === 'SPAN') {
298
- const range = document.createRange();
299
- let firstHTMLElement;
300
- let firstOffset;
301
- let lastHTMLElement;
302
- let lastOffset;
303
- if (focus.isBefore(anchor)) {
304
- firstHTMLElement = focusHTMLElement;
305
- firstOffset = focus.offset;
306
- lastHTMLElement = anchorHTMLElement;
307
- lastOffset = anchor.offset;
308
- } else {
309
- firstHTMLElement = anchorHTMLElement;
310
- firstOffset = anchor.offset;
311
- lastHTMLElement = focusHTMLElement;
312
- lastOffset = focus.offset;
313
- }
314
- const firstTextNode = firstHTMLElement.firstChild;
315
- if (!(firstTextNode !== null)) {
316
- throw Error(`Expected text node to be first child of span`);
317
- }
318
- const lastTextNode = lastHTMLElement.firstChild;
319
- if (!(lastTextNode !== null)) {
320
- throw Error(`Expected text node to be first child of span`);
321
- }
322
- range.setStart(firstTextNode, firstOffset);
323
- range.setEnd(lastTextNode, lastOffset);
324
- removeRangeListener();
325
- removeRangeListener = positionNodeOnRange(editor, range, domNodes => {
344
+ const differentAnchorDOM = previousAnchorNode === null || currentAnchorNodeDOM !== previousAnchorNodeDOM || currentAnchorOffset !== previousAnchorOffset || currentAnchorNodeKey !== previousAnchorNode.getKey();
345
+ const differentFocusDOM = previousFocusNode === null || currentFocusNodeDOM !== previousFocusNodeDOM || currentFocusOffset !== previousFocusOffset || currentFocusNodeKey !== previousFocusNode.getKey();
346
+ if ((differentAnchorDOM || differentFocusDOM) && currentAnchorNodeDOM !== null && currentFocusNodeDOM !== null) {
347
+ const range = rangeFromPoints(editor, anchor, currentAnchorNode, currentAnchorNodeDOM, focus, currentFocusNode, currentFocusNodeDOM);
348
+ removeRangeListener();
349
+ removeRangeListener = mlcPositionNodeOnRange(editor, range, domNodes => {
350
+ if (onReposition === undefined) {
326
351
  for (const domNode of domNodes) {
327
352
  const domNodeStyle = domNode.style;
328
353
  if (domNodeStyle.background !== 'Highlight') {
@@ -331,12 +356,6 @@ function markSelection(editor, onReposition) {
331
356
  if (domNodeStyle.color !== 'HighlightText') {
332
357
  domNodeStyle.color = 'HighlightText';
333
358
  }
334
- if (domNodeStyle.zIndex !== '-1') {
335
- domNodeStyle.zIndex = '-1';
336
- }
337
- if (domNodeStyle.pointerEvents !== 'none') {
338
- domNodeStyle.pointerEvents = 'none';
339
- }
340
359
  if (domNodeStyle.marginTop !== px(-1.5)) {
341
360
  domNodeStyle.marginTop = px(-1.5);
342
361
  }
@@ -347,22 +366,23 @@ function markSelection(editor, onReposition) {
347
366
  domNodeStyle.paddingBottom = px(0);
348
367
  }
349
368
  }
350
- if (onReposition !== undefined) {
351
- onReposition(domNodes);
352
- }
353
- });
354
- }
369
+ } else {
370
+ onReposition(domNodes);
371
+ }
372
+ });
355
373
  }
356
374
  previousAnchorNode = currentAnchorNode;
375
+ previousAnchorNodeDOM = currentAnchorNodeDOM;
357
376
  previousAnchorOffset = currentAnchorOffset;
358
377
  previousFocusNode = currentFocusNode;
378
+ previousFocusNodeDOM = currentFocusNodeDOM;
359
379
  previousFocusOffset = currentFocusOffset;
360
380
  });
361
381
  }
362
382
  compute(editor.getEditorState());
363
383
  return mergeRegister(editor.registerUpdateListener(({
364
384
  editorState
365
- }) => compute(editorState)), removeRangeListener, () => {
385
+ }) => compute(editorState)), () => {
366
386
  removeRangeListener();
367
387
  });
368
388
  }
@@ -375,6 +395,33 @@ function markSelection(editor, onReposition) {
375
395
  *
376
396
  */
377
397
 
398
+ function selectionAlwaysOnDisplay(editor) {
399
+ let removeSelectionMark = null;
400
+ const onSelectionChange = () => {
401
+ const domSelection = getSelection();
402
+ const domAnchorNode = domSelection && domSelection.anchorNode;
403
+ const editorRootElement = editor.getRootElement();
404
+ const isSelectionInsideEditor = domAnchorNode !== null && editorRootElement !== null && editorRootElement.contains(domAnchorNode);
405
+ if (isSelectionInsideEditor) {
406
+ if (removeSelectionMark !== null) {
407
+ removeSelectionMark();
408
+ removeSelectionMark = null;
409
+ }
410
+ } else {
411
+ if (removeSelectionMark === null) {
412
+ removeSelectionMark = markSelection(editor);
413
+ }
414
+ }
415
+ };
416
+ document.addEventListener('selectionchange', onSelectionChange);
417
+ return () => {
418
+ if (removeSelectionMark !== null) {
419
+ removeSelectionMark();
420
+ }
421
+ document.removeEventListener('selectionchange', onSelectionChange);
422
+ };
423
+ }
424
+
378
425
  // Hotfix to export these with inlined types #5918
379
426
  const CAN_USE_BEFORE_INPUT = CAN_USE_BEFORE_INPUT$1;
380
427
  const CAN_USE_DOM = CAN_USE_DOM$1;
@@ -386,6 +433,7 @@ const IS_CHROME = IS_CHROME$1;
386
433
  const IS_FIREFOX = IS_FIREFOX$1;
387
434
  const IS_IOS = IS_IOS$1;
388
435
  const IS_SAFARI = IS_SAFARI$1;
436
+
389
437
  /**
390
438
  * Takes an HTML element and adds the classNames passed within an array,
391
439
  * ignoring any non-string types. A space can be used to add multiple classes
@@ -477,57 +525,99 @@ function mediaFileReader(files, acceptableMimeTypes) {
477
525
  handleNextFile();
478
526
  });
479
527
  }
480
-
481
528
  /**
482
529
  * "Depth-First Search" starts at the root/top node of a tree and goes as far as it can down a branch end
483
530
  * before backtracking and finding a new path. Consider solving a maze by hugging either wall, moving down a
484
531
  * branch until you hit a dead-end (leaf) and backtracking to find the nearest branching path and repeat.
485
532
  * It will then return all the nodes found in the search in an array of objects.
486
- * @param startingNode - The node to start the search, if ommitted, it will start at the root node.
487
- * @param endingNode - The node to end the search, if ommitted, it will find all descendants of the startingNode.
533
+ * @param startNode - The node to start the search, if omitted, it will start at the root node.
534
+ * @param endNode - The node to end the search, if omitted, it will find all descendants of the startingNode.
488
535
  * @returns An array of objects of all the nodes found by the search, including their depth into the tree.
489
- * \\{depth: number, node: LexicalNode\\} It will always return at least 1 node (the ending node) so long as it exists
490
- */
491
- function $dfs(startingNode, endingNode) {
492
- const nodes = [];
493
- const start = (startingNode || lexical.$getRoot()).getLatest();
494
- const end = endingNode || (lexical.$isElementNode(start) ? start.getLastDescendant() || start : start);
495
- let node = start;
496
- let depth = $getDepth(node);
497
- while (node !== null && !node.is(end)) {
498
- nodes.push({
536
+ * \\{depth: number, node: LexicalNode\\} It will always return at least 1 node (the start node).
537
+ */
538
+ function $dfs(startNode, endNode) {
539
+ return Array.from($dfsIterator(startNode, endNode));
540
+ }
541
+
542
+ /**
543
+ * Get the adjacent caret in the same direction
544
+ *
545
+ * @param caret A caret or null
546
+ * @returns `caret.getAdjacentCaret()` or `null`
547
+ */
548
+ function $getAdjacentCaret(caret) {
549
+ return caret ? caret.getAdjacentCaret() : null;
550
+ }
551
+
552
+ /**
553
+ * $dfs iterator (right to left). Tree traversal is done on the fly as new values are requested with O(1) memory.
554
+ * @param startNode - The node to start the search, if omitted, it will start at the root node.
555
+ * @param endNode - The node to end the search, if omitted, it will find all descendants of the startingNode.
556
+ * @returns An iterator, each yielded value is a DFSNode. It will always return at least 1 node (the start node).
557
+ */
558
+ function $reverseDfs(startNode, endNode) {
559
+ return Array.from($reverseDfsIterator(startNode, endNode));
560
+ }
561
+
562
+ /**
563
+ * $dfs iterator (left to right). Tree traversal is done on the fly as new values are requested with O(1) memory.
564
+ * @param startNode - The node to start the search, if omitted, it will start at the root node.
565
+ * @param endNode - The node to end the search, if omitted, it will find all descendants of the startingNode.
566
+ * @returns An iterator, each yielded value is a DFSNode. It will always return at least 1 node (the start node).
567
+ */
568
+ function $dfsIterator(startNode, endNode) {
569
+ return $dfsCaretIterator('next', startNode, endNode);
570
+ }
571
+ function $getEndCaret(startNode, direction) {
572
+ const rval = $getAdjacentSiblingOrParentSiblingCaret(lexical.$getSiblingCaret(startNode, direction));
573
+ return rval && rval[0];
574
+ }
575
+ function $dfsCaretIterator(direction, startNode, endNode) {
576
+ const root = lexical.$getRoot();
577
+ const start = startNode || root;
578
+ const startCaret = lexical.$isElementNode(start) ? lexical.$getChildCaret(start, direction) : lexical.$getSiblingCaret(start, direction);
579
+ const startDepth = $getDepth(start);
580
+ const endCaret = endNode ? lexical.$getAdjacentChildCaret(lexical.$getChildCaretOrSelf(lexical.$getSiblingCaret(endNode, direction))) : $getEndCaret(start, direction);
581
+ let depth = startDepth;
582
+ return lexical.makeStepwiseIterator({
583
+ hasNext: state => state !== null,
584
+ initial: startCaret,
585
+ map: state => ({
499
586
  depth,
500
- node
501
- });
502
- if (lexical.$isElementNode(node) && node.getChildrenSize() > 0) {
503
- node = node.getFirstChild();
504
- depth++;
505
- } else {
506
- // Find immediate sibling or nearest parent sibling
507
- let sibling = null;
508
- while (sibling === null && node !== null) {
509
- sibling = node.getNextSibling();
510
- if (sibling === null) {
511
- node = node.getParent();
512
- depth--;
513
- } else {
514
- node = sibling;
515
- }
587
+ node: state.origin
588
+ }),
589
+ step: state => {
590
+ if (state.isSameNodeCaret(endCaret)) {
591
+ return null;
592
+ }
593
+ if (lexical.$isChildCaret(state)) {
594
+ depth++;
595
+ }
596
+ const rval = $getAdjacentSiblingOrParentSiblingCaret(state);
597
+ if (!rval || rval[0].isSameNodeCaret(endCaret)) {
598
+ return null;
516
599
  }
600
+ depth += rval[1];
601
+ return rval[0];
517
602
  }
518
- }
519
- if (node !== null && node.is(end)) {
520
- nodes.push({
521
- depth,
522
- node
523
- });
524
- }
525
- return nodes;
603
+ });
604
+ }
605
+
606
+ /**
607
+ * Returns the Node sibling when this exists, otherwise the closest parent sibling. For example
608
+ * R -> P -> T1, T2
609
+ * -> P2
610
+ * returns T2 for node T1, P2 for node T2, and null for node P2.
611
+ * @param node LexicalNode.
612
+ * @returns An array (tuple) containing the found Lexical node and the depth difference, or null, if this node doesn't exist.
613
+ */
614
+ function $getNextSiblingOrParentSibling(node) {
615
+ const rval = $getAdjacentSiblingOrParentSiblingCaret(lexical.$getSiblingCaret(node, 'next'));
616
+ return rval && [rval[0].origin, rval[1]];
526
617
  }
527
618
  function $getDepth(node) {
528
- let innerNode = node;
529
- let depth = 0;
530
- while ((innerNode = innerNode.getParent()) !== null) {
619
+ let depth = -1;
620
+ for (let innerNode = node; innerNode !== null; innerNode = innerNode.getParent()) {
531
621
  depth++;
532
622
  }
533
623
  return depth;
@@ -535,28 +625,26 @@ function $getDepth(node) {
535
625
 
536
626
  /**
537
627
  * Performs a right-to-left preorder tree traversal.
538
- * From the starting node it goes to the rightmost child, than backtracks to paret and finds new rightmost path.
628
+ * From the starting node it goes to the rightmost child, than backtracks to parent and finds new rightmost path.
539
629
  * It will return the next node in traversal sequence after the startingNode.
540
630
  * The traversal is similar to $dfs functions above, but the nodes are visited right-to-left, not left-to-right.
541
631
  * @param startingNode - The node to start the search.
542
632
  * @returns The next node in pre-order right to left traversal sequence or `null`, if the node does not exist
543
633
  */
544
634
  function $getNextRightPreorderNode(startingNode) {
545
- let node = startingNode;
546
- if (lexical.$isElementNode(node) && node.getChildrenSize() > 0) {
547
- node = node.getLastChild();
548
- } else {
549
- let sibling = null;
550
- while (sibling === null && node !== null) {
551
- sibling = node.getPreviousSibling();
552
- if (sibling === null) {
553
- node = node.getParent();
554
- } else {
555
- node = sibling;
556
- }
557
- }
558
- }
559
- return node;
635
+ const startCaret = lexical.$getChildCaretOrSelf(lexical.$getSiblingCaret(startingNode, 'previous'));
636
+ const next = $getAdjacentSiblingOrParentSiblingCaret(startCaret, 'root');
637
+ return next && next[0].origin;
638
+ }
639
+
640
+ /**
641
+ * $dfs iterator (right to left). Tree traversal is done on the fly as new values are requested with O(1) memory.
642
+ * @param startNode - The node to start the search, if omitted, it will start at the root node.
643
+ * @param endNode - The node to end the search, if omitted, it will find all descendants of the startingNode.
644
+ * @returns An iterator, each yielded value is a DFSNode. It will always return at least 1 node (the start node).
645
+ */
646
+ function $reverseDfsIterator(startNode, endNode) {
647
+ return $dfsCaretIterator('previous', startNode, endNode);
560
648
  }
561
649
 
562
650
  /**
@@ -586,7 +674,7 @@ function $getNearestBlockElementAncestorOrThrow(startNode) {
586
674
  const blockNode = $findMatchingParent(startNode, node => lexical.$isElementNode(node) && !node.isInline());
587
675
  if (!lexical.$isElementNode(blockNode)) {
588
676
  {
589
- throw Error(`Expected node ${startNode.__key} to have closest block element node.`);
677
+ formatDevErrorMessage(`Expected node ${startNode.__key} to have closest block element node.`);
590
678
  }
591
679
  }
592
680
  return blockNode;
@@ -716,12 +804,7 @@ function $insertNodeToNearestRoot(node) {
716
804
  const focusNode = focus.getNode();
717
805
  const focusOffset = focus.offset;
718
806
  if (lexical.$isRootOrShadowRoot(focusNode)) {
719
- const focusChild = focusNode.getChildAtIndex(focusOffset);
720
- if (focusChild == null) {
721
- focusNode.append(node);
722
- } else {
723
- focusChild.insertBefore(node);
724
- }
807
+ lexical.$getChildCaretAtIndex(focusNode, focusOffset, 'next').insert(node);
725
808
  node.selectNext();
726
809
  } else {
727
810
  let splitNode;
@@ -746,8 +829,7 @@ function $insertNodeToNearestRoot(node) {
746
829
  const nodes = selection.getNodes();
747
830
  nodes[nodes.length - 1].getTopLevelElementOrThrow().insertAfter(node);
748
831
  } else {
749
- const root = lexical.$getRoot();
750
- root.append(node);
832
+ lexical.$getRoot().append(node);
751
833
  }
752
834
  const paragraphNode = lexical.$createParagraphNode();
753
835
  node.insertAfter(paragraphNode);
@@ -803,27 +885,39 @@ function $filter(nodes, filterFn) {
803
885
  * @param node Node that needs to be appended
804
886
  */
805
887
  function $insertFirst(parent, node) {
806
- const firstChild = parent.getFirstChild();
807
- if (firstChild !== null) {
808
- firstChild.insertBefore(node);
809
- } else {
810
- parent.append(node);
888
+ lexical.$getChildCaret(parent, 'next').insert(node);
889
+ }
890
+ let NEEDS_MANUAL_ZOOM = IS_FIREFOX || !CAN_USE_DOM ? false : undefined;
891
+ function needsManualZoom() {
892
+ if (NEEDS_MANUAL_ZOOM === undefined) {
893
+ // If the browser implements standardized CSS zoom, then the client rect
894
+ // will be wider after zoom is applied
895
+ // https://chromestatus.com/feature/5198254868529152
896
+ // https://github.com/facebook/lexical/issues/6863
897
+ const div = document.createElement('div');
898
+ div.style.cssText = 'position: absolute; opacity: 0; width: 100px; left: -1000px;';
899
+ document.body.appendChild(div);
900
+ const noZoom = div.getBoundingClientRect();
901
+ div.style.setProperty('zoom', '2');
902
+ NEEDS_MANUAL_ZOOM = div.getBoundingClientRect().width === noZoom.width;
903
+ document.body.removeChild(div);
811
904
  }
905
+ return NEEDS_MANUAL_ZOOM;
812
906
  }
813
907
 
814
908
  /**
815
909
  * Calculates the zoom level of an element as a result of using
816
- * css zoom property.
910
+ * css zoom property. For browsers that implement standardized CSS
911
+ * zoom (Firefox, Chrome >= 128), this will always return 1.
817
912
  * @param element
818
913
  */
819
914
  function calculateZoomLevel(element) {
820
- if (IS_FIREFOX) {
821
- return 1;
822
- }
823
915
  let zoom = 1;
824
- while (element) {
825
- zoom *= Number(window.getComputedStyle(element).getPropertyValue('zoom'));
826
- element = element.parentElement;
916
+ if (needsManualZoom()) {
917
+ while (element) {
918
+ zoom *= Number(window.getComputedStyle(element).getPropertyValue('zoom'));
919
+ element = element.parentElement;
920
+ }
827
921
  }
828
922
  return zoom;
829
923
  }
@@ -835,6 +929,180 @@ function $isEditorIsNestedEditor(editor) {
835
929
  return editor._parentEditor !== null;
836
930
  }
837
931
 
932
+ /**
933
+ * A depth first last-to-first traversal of root that stops at each node that matches
934
+ * $predicate and ensures that its parent is root. This is typically used to discard
935
+ * invalid or unsupported wrapping nodes. For example, a TableNode must only have
936
+ * TableRowNode as children, but an importer might add invalid nodes based on
937
+ * caption, tbody, thead, etc. and this will unwrap and discard those.
938
+ *
939
+ * @param root The root to start the traversal
940
+ * @param $predicate Should return true for nodes that are permitted to be children of root
941
+ * @returns true if this unwrapped or removed any nodes
942
+ */
943
+ function $unwrapAndFilterDescendants(root, $predicate) {
944
+ return $unwrapAndFilterDescendantsImpl(root, $predicate, null);
945
+ }
946
+ function $unwrapAndFilterDescendantsImpl(root, $predicate, $onSuccess) {
947
+ let didMutate = false;
948
+ for (const node of $lastToFirstIterator(root)) {
949
+ if ($predicate(node)) {
950
+ if ($onSuccess !== null) {
951
+ $onSuccess(node);
952
+ }
953
+ continue;
954
+ }
955
+ didMutate = true;
956
+ if (lexical.$isElementNode(node)) {
957
+ $unwrapAndFilterDescendantsImpl(node, $predicate, $onSuccess || (child => node.insertAfter(child)));
958
+ }
959
+ node.remove();
960
+ }
961
+ return didMutate;
962
+ }
963
+
964
+ /**
965
+ * A depth first traversal of the children array that stops at and collects
966
+ * each node that `$predicate` matches. This is typically used to discard
967
+ * invalid or unsupported wrapping nodes on a children array in the `after`
968
+ * of an {@link lexical!DOMConversionOutput}. For example, a TableNode must only have
969
+ * TableRowNode as children, but an importer might add invalid nodes based on
970
+ * caption, tbody, thead, etc. and this will unwrap and discard those.
971
+ *
972
+ * This function is read-only and performs no mutation operations, which makes
973
+ * it suitable for import and export purposes but likely not for any in-place
974
+ * mutation. You should use {@link $unwrapAndFilterDescendants} for in-place
975
+ * mutations such as node transforms.
976
+ *
977
+ * @param children The children to traverse
978
+ * @param $predicate Should return true for nodes that are permitted to be children of root
979
+ * @returns The children or their descendants that match $predicate
980
+ */
981
+
982
+ function $descendantsMatching(children, $predicate) {
983
+ const result = [];
984
+ const stack = Array.from(children).reverse();
985
+ for (let child = stack.pop(); child !== undefined; child = stack.pop()) {
986
+ if ($predicate(child)) {
987
+ result.push(child);
988
+ } else if (lexical.$isElementNode(child)) {
989
+ for (const grandchild of $lastToFirstIterator(child)) {
990
+ stack.push(grandchild);
991
+ }
992
+ }
993
+ }
994
+ return result;
995
+ }
996
+
997
+ /**
998
+ * Return an iterator that yields each child of node from first to last, taking
999
+ * care to preserve the next sibling before yielding the value in case the caller
1000
+ * removes the yielded node.
1001
+ *
1002
+ * @param node The node whose children to iterate
1003
+ * @returns An iterator of the node's children
1004
+ */
1005
+ function $firstToLastIterator(node) {
1006
+ return $childIterator(lexical.$getChildCaret(node, 'next'));
1007
+ }
1008
+
1009
+ /**
1010
+ * Return an iterator that yields each child of node from last to first, taking
1011
+ * care to preserve the previous sibling before yielding the value in case the caller
1012
+ * removes the yielded node.
1013
+ *
1014
+ * @param node The node whose children to iterate
1015
+ * @returns An iterator of the node's children
1016
+ */
1017
+ function $lastToFirstIterator(node) {
1018
+ return $childIterator(lexical.$getChildCaret(node, 'previous'));
1019
+ }
1020
+ function $childIterator(startCaret) {
1021
+ const seen = new Set() ;
1022
+ return lexical.makeStepwiseIterator({
1023
+ hasNext: lexical.$isSiblingCaret,
1024
+ initial: startCaret.getAdjacentCaret(),
1025
+ map: caret => {
1026
+ const origin = caret.origin.getLatest();
1027
+ if (seen !== null) {
1028
+ const key = origin.getKey();
1029
+ if (!!seen.has(key)) {
1030
+ formatDevErrorMessage(`$childIterator: Cycle detected, node with key ${String(key)} has already been traversed`);
1031
+ }
1032
+ seen.add(key);
1033
+ }
1034
+ return origin;
1035
+ },
1036
+ step: caret => caret.getAdjacentCaret()
1037
+ });
1038
+ }
1039
+
1040
+ /**
1041
+ * Replace this node with its children
1042
+ *
1043
+ * @param node The ElementNode to unwrap and remove
1044
+ */
1045
+ function $unwrapNode(node) {
1046
+ lexical.$rewindSiblingCaret(lexical.$getSiblingCaret(node, 'next')).splice(1, node.getChildren());
1047
+ }
1048
+
1049
+ /**
1050
+ * Returns the Node sibling when this exists, otherwise the closest parent sibling. For example
1051
+ * R -> P -> T1, T2
1052
+ * -> P2
1053
+ * returns T2 for node T1, P2 for node T2, and null for node P2.
1054
+ * @param node LexicalNode.
1055
+ * @returns An array (tuple) containing the found Lexical node and the depth difference, or null, if this node doesn't exist.
1056
+ */
1057
+ function $getAdjacentSiblingOrParentSiblingCaret(startCaret, rootMode = 'root') {
1058
+ let depthDiff = 0;
1059
+ let caret = startCaret;
1060
+ let nextCaret = lexical.$getAdjacentChildCaret(caret);
1061
+ while (nextCaret === null) {
1062
+ depthDiff--;
1063
+ nextCaret = caret.getParentCaret(rootMode);
1064
+ if (!nextCaret) {
1065
+ return null;
1066
+ }
1067
+ caret = nextCaret;
1068
+ nextCaret = lexical.$getAdjacentChildCaret(caret);
1069
+ }
1070
+ return nextCaret && [nextCaret, depthDiff];
1071
+ }
1072
+
1073
+ /**
1074
+ * A wrapper that creates bound functions and methods for the
1075
+ * StateConfig to save some boilerplate when defining methods
1076
+ * or exporting only the accessors from your modules rather
1077
+ * than exposing the StateConfig directly.
1078
+ */
1079
+
1080
+ /**
1081
+ * EXPERIMENTAL
1082
+ *
1083
+ * A convenience interface for working with {@link $getState} and
1084
+ * {@link $setState}.
1085
+ *
1086
+ * @param stateConfig The stateConfig to wrap with convenience functionality
1087
+ * @returns a StateWrapper
1088
+ */
1089
+ function makeStateWrapper(stateConfig) {
1090
+ const $get = node => lexical.$getState(node, stateConfig);
1091
+ const $set = (node, valueOrUpdater) => lexical.$setState(node, stateConfig, valueOrUpdater);
1092
+ return {
1093
+ $get,
1094
+ $set,
1095
+ accessors: [$get, $set],
1096
+ makeGetterMethod: () => function $getter() {
1097
+ return $get(this);
1098
+ },
1099
+ makeSetterMethod: () => function $setter(valueOrUpdater) {
1100
+ return $set(this, valueOrUpdater);
1101
+ },
1102
+ stateConfig
1103
+ };
1104
+ }
1105
+
838
1106
  Object.defineProperty(exports, "$splitNode", {
839
1107
  enumerable: true,
840
1108
  get: function () { return lexical.$splitNode; }
@@ -855,16 +1123,28 @@ Object.defineProperty(exports, "isInlineDomNode", {
855
1123
  enumerable: true,
856
1124
  get: function () { return lexical.isInlineDomNode; }
857
1125
  });
1126
+ exports.$descendantsMatching = $descendantsMatching;
858
1127
  exports.$dfs = $dfs;
1128
+ exports.$dfsIterator = $dfsIterator;
859
1129
  exports.$filter = $filter;
860
1130
  exports.$findMatchingParent = $findMatchingParent;
1131
+ exports.$firstToLastIterator = $firstToLastIterator;
1132
+ exports.$getAdjacentCaret = $getAdjacentCaret;
1133
+ exports.$getAdjacentSiblingOrParentSiblingCaret = $getAdjacentSiblingOrParentSiblingCaret;
1134
+ exports.$getDepth = $getDepth;
861
1135
  exports.$getNearestBlockElementAncestorOrThrow = $getNearestBlockElementAncestorOrThrow;
862
1136
  exports.$getNearestNodeOfType = $getNearestNodeOfType;
863
1137
  exports.$getNextRightPreorderNode = $getNextRightPreorderNode;
1138
+ exports.$getNextSiblingOrParentSibling = $getNextSiblingOrParentSibling;
864
1139
  exports.$insertFirst = $insertFirst;
865
1140
  exports.$insertNodeToNearestRoot = $insertNodeToNearestRoot;
866
1141
  exports.$isEditorIsNestedEditor = $isEditorIsNestedEditor;
1142
+ exports.$lastToFirstIterator = $lastToFirstIterator;
867
1143
  exports.$restoreEditorState = $restoreEditorState;
1144
+ exports.$reverseDfs = $reverseDfs;
1145
+ exports.$reverseDfsIterator = $reverseDfsIterator;
1146
+ exports.$unwrapAndFilterDescendants = $unwrapAndFilterDescendants;
1147
+ exports.$unwrapNode = $unwrapNode;
868
1148
  exports.$wrapNodeInElement = $wrapNodeInElement;
869
1149
  exports.CAN_USE_BEFORE_INPUT = CAN_USE_BEFORE_INPUT;
870
1150
  exports.CAN_USE_DOM = CAN_USE_DOM;
@@ -879,10 +1159,12 @@ exports.IS_SAFARI = IS_SAFARI;
879
1159
  exports.addClassNamesToElement = addClassNamesToElement;
880
1160
  exports.calculateZoomLevel = calculateZoomLevel;
881
1161
  exports.isMimeType = isMimeType;
1162
+ exports.makeStateWrapper = makeStateWrapper;
882
1163
  exports.markSelection = markSelection;
883
1164
  exports.mediaFileReader = mediaFileReader;
884
1165
  exports.mergeRegister = mergeRegister;
885
1166
  exports.objectKlassEquals = objectKlassEquals;
886
- exports.positionNodeOnRange = positionNodeOnRange;
1167
+ exports.positionNodeOnRange = mlcPositionNodeOnRange;
887
1168
  exports.registerNestedElementResolver = registerNestedElementResolver;
888
1169
  exports.removeClassNamesFromElement = removeClassNamesFromElement;
1170
+ exports.selectionAlwaysOnDisplay = selectionAlwaysOnDisplay;