@lexical/table 0.1.10 → 0.1.13

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.
@@ -98,6 +98,17 @@ function $findMatchingParent(startingNode, findFn) {
98
98
  return null;
99
99
  }
100
100
 
101
+ /**
102
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
103
+ *
104
+ * This source code is licensed under the MIT license found in the
105
+ * LICENSE file in the root directory of this source tree.
106
+ *
107
+ *
108
+ */
109
+ const getSelection = window.getSelection;
110
+ var getDOMSelection = getSelection;
111
+
101
112
  /**
102
113
  * Copyright (c) Meta Platforms, Inc. and affiliates.
103
114
  *
@@ -110,7 +121,6 @@ const LowPriority = 1;
110
121
  const CriticalPriority = 4;
111
122
  const removeHighlightStyle = document.createElement('style');
112
123
  removeHighlightStyle.appendChild(document.createTextNode('::selection{background-color: transparent}'));
113
-
114
124
  function getCellFromTarget(node) {
115
125
  let currentNode = node;
116
126
 
@@ -133,7 +143,6 @@ function getCellFromTarget(node) {
133
143
 
134
144
  return null;
135
145
  }
136
-
137
146
  function trackTableGrid(tableNode, tableElement, editor) {
138
147
  const cells = [];
139
148
  const grid = {
@@ -141,95 +150,99 @@ function trackTableGrid(tableNode, tableElement, editor) {
141
150
  columns: 0,
142
151
  rows: 0
143
152
  };
144
- const observer = new MutationObserver(records => {
145
- editor.update(() => {
146
- let currentNode = tableElement.firstChild;
147
- let x = 0;
148
- let y = 0;
149
- let gridNeedsRedraw = false;
150
153
 
151
- for (let i = 0; i < records.length; i++) {
152
- const record = records[i];
153
- const target = record.target;
154
- const nodeName = target.nodeName;
154
+ const calcSize = () => {
155
+ let currentNode = tableElement.firstChild;
156
+ let x = 0;
157
+ let y = 0;
158
+ cells.length = 0;
159
+
160
+ while (currentNode != null) {
161
+ const nodeMame = currentNode.nodeName;
162
+
163
+ if (nodeMame === 'TD' || nodeMame === 'TH') {
164
+ // $FlowFixMe: TD is always an HTMLElement
165
+ const elem = currentNode;
166
+ const cell = {
167
+ elem,
168
+ highlighted: false,
169
+ x,
170
+ y
171
+ }; // $FlowFixMe: internal field
155
172
 
156
- if (nodeName === 'TABLE' || nodeName === 'TR') {
157
- gridNeedsRedraw = true;
158
- break;
159
- }
160
- }
173
+ currentNode._cell = cell;
161
174
 
162
- if (!gridNeedsRedraw) {
163
- return;
164
- }
175
+ if (cells[y] === undefined) {
176
+ cells[y] = [];
177
+ }
165
178
 
166
- cells.length = 0;
179
+ cells[y][x] = cell;
180
+ } else {
181
+ const child = currentNode.firstChild;
167
182
 
168
- while (currentNode != null) {
169
- const nodeMame = currentNode.nodeName;
183
+ if (child != null) {
184
+ currentNode = child;
185
+ continue;
186
+ }
187
+ }
170
188
 
171
- if (nodeMame === 'TD' || nodeMame === 'TH') {
172
- // $FlowFixMe: TD is always an HTMLElement
173
- const elem = currentNode;
174
- const cell = {
175
- elem,
176
- highlighted: false,
177
- x,
178
- y
179
- }; // $FlowFixMe: internal field
189
+ const sibling = currentNode.nextSibling;
180
190
 
181
- currentNode._cell = cell;
191
+ if (sibling != null) {
192
+ x++;
193
+ currentNode = sibling;
194
+ continue;
195
+ }
182
196
 
183
- if (cells[y] === undefined) {
184
- cells[y] = [];
185
- }
197
+ const parent = currentNode.parentNode;
186
198
 
187
- cells[y][x] = cell;
188
- } else {
189
- const child = currentNode.firstChild;
199
+ if (parent != null) {
200
+ const parentSibling = parent.nextSibling;
190
201
 
191
- if (child != null) {
192
- currentNode = child;
193
- continue;
194
- }
202
+ if (parentSibling == null) {
203
+ break;
195
204
  }
196
205
 
197
- const sibling = currentNode.nextSibling;
198
-
199
- if (sibling != null) {
200
- x++;
201
- currentNode = sibling;
202
- continue;
203
- }
206
+ y++;
207
+ x = 0;
208
+ currentNode = parentSibling;
209
+ }
210
+ }
204
211
 
205
- const parent = currentNode.parentNode;
212
+ grid.columns = x + 1;
213
+ grid.rows = y + 1;
214
+ tableNode.setGrid(grid);
215
+ };
206
216
 
207
- if (parent != null) {
208
- const parentSibling = parent.nextSibling;
217
+ const observer = new MutationObserver(records => {
218
+ editor.update(() => {
219
+ let gridNeedsRedraw = false;
209
220
 
210
- if (parentSibling == null) {
211
- break;
212
- }
221
+ for (let i = 0; i < records.length; i++) {
222
+ const record = records[i];
223
+ const target = record.target;
224
+ const nodeName = target.nodeName;
213
225
 
214
- y++;
215
- x = 0;
216
- currentNode = parentSibling;
226
+ if (nodeName === 'TABLE' || nodeName === 'TR') {
227
+ gridNeedsRedraw = true;
228
+ break;
217
229
  }
218
230
  }
219
231
 
220
- grid.columns = x + 1;
221
- grid.rows = y + 1;
222
- tableNode.setGrid(grid);
232
+ if (!gridNeedsRedraw) {
233
+ return;
234
+ }
235
+
236
+ calcSize();
223
237
  });
224
238
  });
225
239
  observer.observe(tableElement, {
226
240
  childList: true,
227
241
  subtree: true
228
242
  });
229
- tableNode.setGrid(grid);
243
+ calcSize();
230
244
  return grid;
231
245
  }
232
-
233
246
  function updateCells(fromX, toX, fromY, toY, cells) {
234
247
  const highlighted = [];
235
248
 
@@ -252,18 +265,21 @@ function updateCells(fromX, toX, fromY, toY, cells) {
252
265
  cell.highlighted = false;
253
266
  elemStyle.removeProperty('background-color');
254
267
  elemStyle.removeProperty('caret-color');
268
+
269
+ if (!cell.elem.getAttribute('style')) {
270
+ cell.elem.removeAttribute('style');
271
+ }
255
272
  }
256
273
  }
257
274
  }
258
275
 
259
276
  return highlighted;
260
277
  }
261
-
262
- function applyCustomTableHandlers(tableNode, tableElement, editor) {
278
+ function $applyCustomTableHandlers(tableNode, tableElement, editor) {
263
279
  const rootElement = editor.getRootElement();
264
280
 
265
281
  if (rootElement === null) {
266
- return;
282
+ throw new Error('No root element.');
267
283
  }
268
284
 
269
285
  trackTableGrid(tableNode, tableElement, editor);
@@ -275,6 +291,8 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
275
291
  let currentX = -1;
276
292
  let currentY = -1;
277
293
  let highlightedCells = [];
294
+ const editorListeners = new Set();
295
+ let deleteCharacterListener = null;
278
296
 
279
297
  if (grid == null) {
280
298
  throw new Error('Table grid not found.');
@@ -291,9 +309,14 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
291
309
 
292
310
  if (!isHighlightingCells && (startX !== cellX || startY !== cellY)) {
293
311
  event.preventDefault();
294
- const windowSelection = window.getSelection(); // Collapse the selection
312
+ const domSelection = getDOMSelection();
313
+ const anchorNode = domSelection.anchorNode;
314
+
315
+ if (anchorNode !== null) {
316
+ // Collapse the selection
317
+ domSelection.setBaseAndExtent(anchorNode, 0, anchorNode, 0);
318
+ }
295
319
 
296
- windowSelection.setBaseAndExtent(windowSelection.anchorNode, 0, windowSelection.anchorNode, 0);
297
320
  isHighlightingCells = true;
298
321
 
299
322
  if (document.body) {
@@ -317,11 +340,15 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
317
340
  const cellNode = lexical.$getNearestNodeFromDOMNode(elem);
318
341
 
319
342
  if (lexical.$isElementNode(cellNode)) {
320
- cellNode.clear();
321
343
  const paragraphNode = lexical.$createParagraphNode();
322
344
  const textNode = lexical.$createTextNode();
323
345
  paragraphNode.append(textNode);
324
346
  cellNode.append(paragraphNode);
347
+ cellNode.getChildren().forEach(child => {
348
+ if (child !== paragraphNode) {
349
+ child.remove();
350
+ }
351
+ });
325
352
  }
326
353
  });
327
354
  tableNode.setSelectionState(null);
@@ -337,6 +364,7 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
337
364
 
338
365
  return false;
339
366
  }, LowPriority);
367
+ editorListeners.add(deleteCharacterListener);
340
368
  }
341
369
  } else if (cellX === currentX && cellY === currentY) {
342
370
  return;
@@ -379,6 +407,7 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
379
407
  if (deleteCharacterListener !== null) {
380
408
  deleteCharacterListener();
381
409
  deleteCharacterListener = null;
410
+ editorListeners.delete(deleteCharacterListener);
382
411
  }
383
412
 
384
413
  const parent = removeHighlightStyle.parentNode;
@@ -409,7 +438,7 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
409
438
  highlightedCells.forEach(highlightedCell => {
410
439
  const cellNode = lexical.$getNearestNodeFromDOMNode(highlightedCell.elem);
411
440
 
412
- if (lexical.$isElementNode(cellNode)) {
441
+ if (lexical.$isElementNode(cellNode) && cellNode.getTextContentSize() !== 0) {
413
442
  anchor.set(cellNode.getKey(), 0, 'element');
414
443
  focus.set(cellNode.getKey(), cellNode.getChildrenSize(), 'element');
415
444
  formatSelection.formatText(type);
@@ -421,7 +450,6 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
421
450
  lexical.$setSelection(selection);
422
451
  };
423
452
 
424
- let deleteCharacterListener = null;
425
453
  tableElement.addEventListener('mousedown', event => {
426
454
  if (isSelected) {
427
455
  if (isHighlightingCells) {
@@ -453,7 +481,7 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
453
481
  }, 0);
454
482
  });
455
483
  window.addEventListener('click', e => {
456
- if (highlightedCells.length > 0 && !tableElement.contains(e.target)) {
484
+ if (highlightedCells.length > 0 && !tableElement.contains(e.target) && rootElement.contains(e.target)) {
457
485
  editor.update(() => {
458
486
  tableNode.setSelectionState(null);
459
487
  });
@@ -467,11 +495,11 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
467
495
  {
468
496
  const isForward = direction === 'forward';
469
497
 
470
- if (y !== (isForward ? grid.columns - 1 : 0)) {
471
- tableNode.getCellNodeFromCords(x, y + (isForward ? 1 : -1)).select();
498
+ if (x !== (isForward ? grid.columns - 1 : 0)) {
499
+ tableNode.getCellNodeFromCords(x + (isForward ? 1 : -1), y).select();
472
500
  } else {
473
- if (x !== (isForward ? grid.rows - 1 : 0)) {
474
- tableNode.getCellNodeFromCords(x + (isForward ? 1 : -1), isForward ? 0 : grid.columns - 1).select();
501
+ if (y !== (isForward ? grid.rows - 1 : 0)) {
502
+ tableNode.getCellNodeFromCords(isForward ? 0 : grid.columns - 1, y + (isForward ? 1 : -1)).select();
475
503
  } else if (!isForward) {
476
504
  tableNode.selectPrevious();
477
505
  } else {
@@ -484,8 +512,8 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
484
512
 
485
513
  case 'up':
486
514
  {
487
- if (x !== 0) {
488
- tableNode.getCellNodeFromCords(x - 1, y).select();
515
+ if (y !== 0) {
516
+ tableNode.getCellNodeFromCords(x, y - 1).select();
489
517
  } else {
490
518
  tableNode.selectPrevious();
491
519
  }
@@ -495,8 +523,8 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
495
523
 
496
524
  case 'down':
497
525
  {
498
- if (x !== grid.rows - 1) {
499
- tableNode.getCellNodeFromCords(x + 1, y).select();
526
+ if (y !== grid.rows - 1) {
527
+ tableNode.getCellNodeFromCords(x, y + 1).select();
500
528
  } else {
501
529
  tableNode.selectNext();
502
530
  }
@@ -508,7 +536,7 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
508
536
  return false;
509
537
  };
510
538
 
511
- editor.addListener('command', (type, payload) => {
539
+ const genericCommandListener = editor.addListener('command', (type, payload) => {
512
540
  const selection = lexical.$getSelection();
513
541
 
514
542
  if (!lexical.$isRangeSelection(selection)) {
@@ -522,15 +550,18 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
522
550
  }
523
551
 
524
552
  if (type === 'deleteCharacter') {
525
- if (highlightedCells.length === 0 && selection.isCollapsed() && selection.anchor.offset === 0) {
553
+ if (highlightedCells.length === 0 && selection.isCollapsed() && selection.anchor.offset === 0 && selection.anchor.getNode().getPreviousSiblings().length === 0) {
526
554
  return true;
527
555
  }
528
556
  }
529
557
 
530
- if (type === 'indentContent' || type === 'outdentContent') {
558
+ if (type === 'keyTab') {
559
+ const event = payload;
560
+
531
561
  if (selection.isCollapsed() && highlightedCells.length === 0) {
532
562
  const currentCords = tableNode.getCordsFromCellNode(tableCellNode);
533
- selectGridNodeInDirection(currentCords.x, currentCords.y, type === 'indentContent' ? 'forward' : 'backward');
563
+ event.preventDefault();
564
+ selectGridNodeInDirection(currentCords.x, currentCords.y, !event.shiftKey && type === 'keyTab' ? 'forward' : 'backward');
534
565
  return true;
535
566
  }
536
567
  }
@@ -553,8 +584,18 @@ function applyCustomTableHandlers(tableNode, tableElement, editor) {
553
584
 
554
585
  return false;
555
586
  }, CriticalPriority);
587
+ editorListeners.add(genericCommandListener);
588
+ return () => Array.from(editorListeners).forEach(removeListener => removeListener ? removeListener() : null);
556
589
  }
557
590
 
591
+ /**
592
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
593
+ *
594
+ * This source code is licensed under the MIT license found in the
595
+ * LICENSE file in the root directory of this source tree.
596
+ *
597
+ *
598
+ */
558
599
  class TableNode extends lexical.GridNode {
559
600
  static getType() {
560
601
  return 'table';
@@ -575,7 +616,6 @@ class TableNode extends lexical.GridNode {
575
616
  createDOM(config, editor) {
576
617
  const element = document.createElement('table');
577
618
  addClassNamesToElement(element, config.theme.table);
578
- applyCustomTableHandlers(this, element, editor);
579
619
  return element;
580
620
  }
581
621
 
@@ -594,44 +634,47 @@ class TableNode extends lexical.GridNode {
594
634
  setSelectionState(selectionShape) {
595
635
  const self = this.getWritable();
596
636
  self.__selectionShape = selectionShape;
597
- if (this.__grid == null) return [];
637
+ const grid = this.getGrid();
638
+ if (grid == null) return [];
598
639
 
599
640
  if (!selectionShape) {
600
- return updateCells(-1, -1, -1, -1, this.__grid.cells);
641
+ return updateCells(-1, -1, -1, -1, grid.cells);
601
642
  }
602
643
 
603
- return updateCells(selectionShape.fromX, selectionShape.toX, selectionShape.fromY, selectionShape.toY, this.__grid.cells);
644
+ return updateCells(selectionShape.fromX, selectionShape.toX, selectionShape.fromY, selectionShape.toY, grid.cells);
604
645
  }
605
646
 
606
647
  getSelectionState() {
607
- return this.__selectionShape;
648
+ return this.getLatest().__selectionShape;
608
649
  }
609
650
 
610
651
  getCordsFromCellNode(tableCellNode) {
611
- if (!this.__grid) {
652
+ const grid = this.getGrid();
653
+
654
+ if (!grid) {
612
655
  throw Error(`Grid not found.`);
613
656
  }
614
657
 
615
658
  const {
616
659
  rows,
617
660
  cells
618
- } = this.__grid;
661
+ } = grid;
619
662
 
620
- for (let x = 0; x < rows; x++) {
621
- const row = cells[x];
663
+ for (let y = 0; y < rows; y++) {
664
+ const row = cells[y];
622
665
 
623
666
  if (row == null) {
624
- throw new Error(`Row not found at x:${x}`);
667
+ throw new Error(`Row not found at y:${y}`);
625
668
  }
626
669
 
627
- const y = row.findIndex(({
670
+ const x = row.findIndex(({
628
671
  elem
629
672
  }) => {
630
673
  const cellNode = lexical.$getNearestNodeFromDOMNode(elem);
631
674
  return cellNode === tableCellNode;
632
675
  });
633
676
 
634
- if (y !== -1) {
677
+ if (x !== -1) {
635
678
  return {
636
679
  x,
637
680
  y
@@ -643,23 +686,25 @@ class TableNode extends lexical.GridNode {
643
686
  }
644
687
 
645
688
  getCellNodeFromCords(x, y) {
646
- if (!this.__grid) {
689
+ const grid = this.getGrid();
690
+
691
+ if (!grid) {
647
692
  throw Error(`Grid not found.`);
648
693
  }
649
694
 
650
695
  const {
651
696
  cells
652
- } = this.__grid;
653
- const row = cells[x];
697
+ } = grid;
698
+ const row = cells[y];
654
699
 
655
700
  if (row == null) {
656
- throw new Error(`Table row x:"${x}" not found.`);
701
+ throw new Error(`Table row x:"${y}" not found.`);
657
702
  }
658
703
 
659
- const cell = row[y];
704
+ const cell = row[x];
660
705
 
661
706
  if (cell == null) {
662
- throw new Error(`Table cell y:"${y}" in row x:"${x}" not found.`);
707
+ throw new Error(`Table cell y:"${x}" in row x:"${y}" not found.`);
663
708
  }
664
709
 
665
710
  const node = lexical.$getNearestNodeFromDOMNode(cell.elem);
@@ -674,10 +719,11 @@ class TableNode extends lexical.GridNode {
674
719
  setGrid(grid) {
675
720
  const self = this.getWritable();
676
721
  self.__grid = grid;
722
+ return self;
677
723
  }
678
724
 
679
725
  getGrid() {
680
- return this.__grid;
726
+ return this.getLatest().__grid;
681
727
  }
682
728
 
683
729
  canSelectBefore() {
@@ -825,7 +871,7 @@ function $insertTableRow(tableNode, targetIndex, shouldInsertAfter = true, rowCo
825
871
 
826
872
  for (let j = 0; j < tableColumnCount; j++) {
827
873
  const tableCellNode = $createTableCellNode(false);
828
- tableCellNode.append(lexical.$createTextNode());
874
+ tableCellNode.append(lexical.$createParagraphNode());
829
875
  newTableRowNode.append(tableCellNode);
830
876
  }
831
877
 
@@ -850,7 +896,7 @@ function $insertTableColumn(tableNode, targetIndex, shouldInsertAfter = true, co
850
896
  if ($isTableRowNode(currentTableRowNode)) {
851
897
  for (let j = 0; j < columnCount; j++) {
852
898
  const newTableCell = $createTableCellNode(i === 0);
853
- newTableCell.append(lexical.$createTextNode());
899
+ newTableCell.append(lexical.$createParagraphNode());
854
900
  const tableRowChildren = currentTableRowNode.getChildren();
855
901
 
856
902
  if (targetIndex >= tableRowChildren.length || targetIndex < 0) {
@@ -890,6 +936,7 @@ function $deleteTableColumn(tableNode, targetIndex) {
890
936
  return tableNode;
891
937
  }
892
938
 
939
+ exports.$applyCustomTableHandlers = $applyCustomTableHandlers;
893
940
  exports.$createTableCellNode = $createTableCellNode;
894
941
  exports.$createTableNode = $createTableNode;
895
942
  exports.$createTableNodeWithDimensions = $createTableNodeWithDimensions;
@@ -4,26 +4,27 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- var p=require("lexical");function x(a,...b){b.forEach(c=>{null!=c&&"string"===typeof c&&a.classList.add(...c.split(" "))})}
8
- class y extends p.GridCellNode{static getType(){return"tablecell"}static clone(a){return new y(!1,a.__colSpan,a.__key)}constructor(a=!1,b=1,c){super(b,c);this.__isHeader=a}getTag(){return this.__isHeader?"th":"td"}createDOM(a){const b=document.createElement(this.getTag());x(b,a.theme.tableCell,!0===this.__isHeader&&a.theme.tableCellHeader);return b}updateDOM(){return!1}collapseAtStart(){return!0}canBeEmpty(){return!1}}function z(a){return new y(a)}function B(a){return a instanceof y}
9
- function C(a){throw Error(`Minified Lexical error #${a}; see codes.json for the full message or `+"use the non-minified dev environment for full errors and additional helpful warnings.");}function D(a,b){for(;a!==p.$getRoot()&&null!=a;){if(b(a))return a;a=a.getParent()}return null}const F=document.createElement("style");F.appendChild(document.createTextNode("::selection{background-color: transparent}"));
10
- function G(a){for(;null!=a;){const b=a.nodeName;if("TD"===b||"TH"===b){a=a._cell;if(void 0===a)break;return a}a=a.parentNode}return null}
11
- function H(a,b,c){const g=[],d={cells:g,columns:0,rows:0};(new MutationObserver(n=>{c.update(()=>{var e=b.firstChild;let q=0,m=0;var h=!1;for(let r=0;r<n.length;r++){const w=n[r].target.nodeName;if("TABLE"===w||"TR"===w){h=!0;break}}if(h){for(g.length=0;null!=e;){h=e.nodeName;if("TD"===h||"TH"===h)h={elem:e,highlighted:!1,x:q,y:m},e._cell=h,void 0===g[m]&&(g[m]=[]),g[m][q]=h;else if(h=e.firstChild,null!=h){e=h;continue}h=e.nextSibling;if(null!=h)q++,e=h;else if(h=e.parentNode,null!=h){e=h.nextSibling;
12
- if(null==e)break;m++;q=0}}d.columns=q+1;d.rows=m+1;a.setGrid(d)}})})).observe(b,{childList:!0,subtree:!0});a.setGrid(d);return d}
13
- function I(a,b,c,g,d){const n=[];for(let e=0;e<d.length;e++){const q=d[e];for(let m=0;m<q.length;m++){const h=q[m],r=h.elem.style;m>=a&&m<=b&&e>=c&&e<=g?(h.highlighted||(h.highlighted=!0,r.setProperty("background-color","rgb(163, 187, 255)"),r.setProperty("caret-color","transparent")),n.push(h)):h.highlighted&&(h.highlighted=!1,r.removeProperty("background-color"),r.removeProperty("caret-color"))}}return n}
14
- function J(a,b,c){if(null!==c.getRootElement()){H(a,b,c);var g=a.getGrid(),d=!1,n=!1,e=-1,q=-1,m=-1,h=-1,r=[];if(null==g)throw Error("Table grid not found.");b.addEventListener("mousemove",k=>{if(d){var f=G(k.target);if(null!==f){const l=f.x;f=f.y;if(!n&&(e!==l||q!==f))k.preventDefault(),k=window.getSelection(),k.setBaseAndExtent(k.anchorNode,0,k.anchorNode,0),n=!0,document.body&&document.body.appendChild(F),null===A&&(A=c.addListener("command",(u,v)=>{if("deleteCharacter"===u){if(r.length===g.columns*
15
- g.rows)return a.selectPrevious(),a.remove(),w(),!0;r.forEach(({elem:t})=>{t=p.$getNearestNodeFromDOMNode(t);if(p.$isElementNode(t)){t.clear();const E=p.$createParagraphNode(),T=p.$createTextNode();E.append(T);t.append(E)}});a.setSelectionState(null);p.$setSelection(null);return!0}if("formatText"===u)return U(v),!0;"insertText"===u&&w();return!1},1));else if(l===m&&f===h)return;m=l;h=f;if(n){const u=Math.min(e,m),v=Math.max(e,m),t=Math.min(q,h),E=Math.max(q,h);c.update(()=>{r=a.setSelectionState({fromX:u,
16
- fromY:t,toX:v,toY:E})})}}}});var w=()=>{c.update(()=>{d=n=!1;h=m=q=e=-1;c.update(()=>{a.setSelectionState(null)});r=[];null!==A&&(A(),A=null);const k=F.parentNode;null!=k&&k.removeChild(F)})};b.addEventListener("mouseleave",()=>{});var U=k=>{let f=p.$getSelection();p.$isRangeSelection(f)||(f=p.$createRangeSelection());const l=f,u=l.anchor,v=l.focus;r.forEach(t=>{t=p.$getNearestNodeFromDOMNode(t.elem);p.$isElementNode(t)&&(u.set(t.getKey(),0,"element"),v.set(t.getKey(),t.getChildrenSize(),"element"),
17
- l.formatText(k))});f.anchor.set(f.anchor.key,f.anchor.offset,f.anchor.type);f.focus.set(f.anchor.key,f.anchor.offset,f.anchor.type);p.$setSelection(f)},A=null;b.addEventListener("mousedown",k=>{d?n&&w():setTimeout(()=>{n&&w();const f=G(k.target);null!==f&&(d=!0,e=f.x,q=f.y,document.addEventListener("mouseup",()=>{d=!1},{capture:!0,once:!0}))},0)});window.addEventListener("click",k=>{0<r.length&&!b.contains(k.target)&&c.update(()=>{a.setSelectionState(null)})});var O=(k,f,l)=>{switch(l){case "backward":case "forward":return l=
18
- "forward"===l,f!==(l?g.columns-1:0)?a.getCellNodeFromCords(k,f+(l?1:-1)).select():k!==(l?g.rows-1:0)?a.getCellNodeFromCords(k+(l?1:-1),l?0:g.columns-1).select():l?a.selectNext():a.selectPrevious(),!0;case "up":return 0!==k?a.getCellNodeFromCords(k-1,f).select():a.selectPrevious(),!0;case "down":return k!==g.rows-1?a.getCellNodeFromCords(k+1,f).select():a.selectNext(),!0}return!1};c.addListener("command",(k,f)=>{var l=p.$getSelection();if(!p.$isRangeSelection(l))return!1;const u=D(l.anchor.getNode(),
19
- v=>B(v));if(!B(u))return!1;if("deleteCharacter"===k&&0===r.length&&l.isCollapsed()&&0===l.anchor.offset)return!0;if(("indentContent"===k||"outdentContent"===k)&&l.isCollapsed()&&0===r.length)return f=a.getCordsFromCellNode(u),O(f.x,f.y,"indentContent"===k?"forward":"backward"),!0;if(("keyArrowDown"===k||"keyArrowUp"===k)&&l.isCollapsed()&&0===r.length){const v=a.getCordsFromCellNode(u);l=D(l.anchor.getNode(),t=>p.$isElementNode(t));if("keyArrowUp"===k&&l===u.getFirstChild()||"keyArrowDown"===k&&l===
20
- u.getLastChild())return f.preventDefault(),f.stopImmediatePropagation(),O(v.x,v.y,"keyArrowUp"===k?"up":"down"),!0}return!1},4)}}
21
- class K extends p.GridNode{static getType(){return"table"}static clone(a){return new K(a.__key,a.__selectionShape,a.__grid)}constructor(a,b,c){super(a);this.__selectionShape=b;this.__grid=c}createDOM(a,b){const c=document.createElement("table");x(c,a.theme.table);J(this,c,b);return c}updateDOM(){return!1}canExtractContents(){return!1}canBeEmpty(){return!1}setSelectionState(a){this.getWritable().__selectionShape=a;return null==this.__grid?[]:a?I(a.fromX,a.toX,a.fromY,a.toY,this.__grid.cells):I(-1,
22
- -1,-1,-1,this.__grid.cells)}getSelectionState(){return this.__selectionShape}getCordsFromCellNode(a){this.__grid||C(55);const {rows:b,cells:c}=this.__grid;for(let d=0;d<b;d++){var g=c[d];if(null==g)throw Error(`Row not found at x:${d}`);g=g.findIndex(({elem:n})=>p.$getNearestNodeFromDOMNode(n)===a);if(-1!==g)return{x:d,y:g}}throw Error("Cell not found in table.");}getCellNodeFromCords(a,b){this.__grid||C(55);var {cells:c}=this.__grid;c=c[a];if(null==c)throw Error(`Table row x:"${a}" not found.`);
23
- c=c[b];if(null==c)throw Error(`Table cell y:"${b}" in row x:"${a}" not found.`);a=p.$getNearestNodeFromDOMNode(c.elem);if(B(a))return a;throw Error("Node at cords not TableCellNode.");}setGrid(a){this.getWritable().__grid=a}getGrid(){return this.__grid}canSelectBefore(){return!0}}function L(){return new K}function M(a){return a instanceof K}
24
- class N extends p.GridRowNode{static getType(){return"tablerow"}static clone(a){return new N(a.__key)}constructor(a){super(a)}createDOM(a){const b=document.createElement("tr");x(b,a.theme.tableRow);return b}updateDOM(){return!1}canBeEmpty(){return!1}}function P(){return new N}function Q(a){return a instanceof N}function R(a){a=D(a,b=>Q(b));if(Q(a))return a;throw Error("Expected table cell to be inside of table row.");}
25
- function S(a){a=D(a,b=>M(b));if(M(a))return a;throw Error("Expected table cell to be inside of table.");}exports.$createTableCellNode=z;exports.$createTableNode=L;exports.$createTableNodeWithDimensions=function(a,b,c=!0){const g=L();for(let d=0;d<a;d++){const n=P();for(let e=0;e<b;e++){const q=z(0===d&&c),m=p.$createParagraphNode();m.append(p.$createTextNode());q.append(m);n.append(q)}g.append(n)}return g};exports.$createTableRowNode=P;
26
- exports.$deleteTableColumn=function(a,b){const c=a.getChildren();for(let d=0;d<c.length;d++){var g=c[d];if(Q(g)){g=g.getChildren();if(b>=g.length||0>b)throw Error("Table column target index out of range");g[b].remove()}}return a};exports.$getTableCellNodeFromLexicalNode=function(a){a=D(a,b=>B(b));return B(a)?a:null};exports.$getTableColumnIndexFromTableCellNode=function(a){return R(a).getChildren().findIndex(b=>b.is(a))};exports.$getTableNodeFromLexicalNodeOrThrow=S;
27
- exports.$getTableRowIndexFromTableCellNode=function(a){const b=R(a);return S(b).getChildren().findIndex(c=>c.is(b))};exports.$getTableRowNodeFromTableCellNodeOrThrow=R;exports.$insertTableColumn=function(a,b,c=!0,g){const d=a.getChildren();for(let e=0;e<d.length;e++){const q=d[e];if(Q(q))for(let m=0;m<g;m++){const h=z(0===e);h.append(p.$createTextNode());var n=q.getChildren();if(b>=n.length||0>b)throw Error("Table column target index out of range");n=n[b];c?n.insertAfter(h):n.insertBefore(h)}}return a};
28
- exports.$insertTableRow=function(a,b,c=!0,g){var d=a.getChildren();if(b>=d.length||0>b)throw Error("Table row target index out of range");b=d[b];if(Q(b))for(d=0;d<g;d++){const n=b.getChildren().length,e=P();for(let q=0;q<n;q++){const m=z(!1);m.append(p.$createTextNode());e.append(m)}c?b.insertAfter(e):b.insertBefore(e)}else throw Error("Row before insertion index does not exist.");return a};exports.$isTableCellNode=B;exports.$isTableNode=M;exports.$isTableRowNode=Q;
29
- exports.$removeTableRowAtIndex=function(a,b){const c=a.getChildren();if(b>=c.length||0>b)throw Error("Expected table cell to be inside of table row.");c[b].remove();return a};exports.TableCellNode=y;exports.TableNode=K;exports.TableRowNode=N;
7
+ var p=require("lexical");function z(a,...b){b.forEach(c=>{null!=c&&"string"===typeof c&&a.classList.add(...c.split(" "))})}
8
+ class A extends p.GridCellNode{static getType(){return"tablecell"}static clone(a){return new A(!1,a.__colSpan,a.__key)}constructor(a=!1,b=1,c){super(b,c);this.__isHeader=a}getTag(){return this.__isHeader?"th":"td"}createDOM(a){const b=document.createElement(this.getTag());z(b,a.theme.tableCell,!0===this.__isHeader&&a.theme.tableCellHeader);return b}updateDOM(){return!1}collapseAtStart(){return!0}canBeEmpty(){return!1}}function B(a){return new A(a)}function C(a){return a instanceof A}
9
+ function D(a,b){for(;a!==p.$getRoot()&&null!=a;){if(b(a))return a;a=a.getParent()}return null}var E=window.getSelection;const F=document.createElement("style");F.appendChild(document.createTextNode("::selection{background-color: transparent}"));function G(a){for(;null!=a;){const b=a.nodeName;if("TD"===b||"TH"===b){a=a._cell;if(void 0===a)break;return a}a=a.parentNode}return null}
10
+ function J(a,b,c){const n=[],e={cells:n,columns:0,rows:0},q=()=>{var d=b.firstChild;let m=0,k=0;for(n.length=0;null!=d;){var g=d.nodeName;if("TD"===g||"TH"===g)g={elem:d,highlighted:!1,x:m,y:k},d._cell=g,void 0===n[k]&&(n[k]=[]),n[k][m]=g;else if(g=d.firstChild,null!=g){d=g;continue}g=d.nextSibling;if(null!=g)m++,d=g;else if(g=d.parentNode,null!=g){d=g.nextSibling;if(null==d)break;k++;m=0}}e.columns=m+1;e.rows=k+1;a.setGrid(e)};(new MutationObserver(d=>{c.update(()=>{let m=!1;for(let k=0;k<d.length;k++){const g=
11
+ d[k].target.nodeName;if("TABLE"===g||"TR"===g){m=!0;break}}m&&q()})})).observe(b,{childList:!0,subtree:!0});q();return e}
12
+ function K(a,b,c,n,e){const q=[];for(let d=0;d<e.length;d++){const m=e[d];for(let k=0;k<m.length;k++){const g=m[k],v=g.elem.style;k>=a&&k<=b&&d>=c&&d<=n?(g.highlighted||(g.highlighted=!0,v.setProperty("background-color","rgb(163, 187, 255)"),v.setProperty("caret-color","transparent")),q.push(g)):g.highlighted&&(g.highlighted=!1,v.removeProperty("background-color"),v.removeProperty("caret-color"),g.elem.getAttribute("style")||g.elem.removeAttribute("style"))}}return q}
13
+ function L(a){throw Error(`Minified Lexical error #${a}; see codes.json for the full message or `+"use the non-minified dev environment for full errors and additional helpful warnings.");}
14
+ class M extends p.GridNode{static getType(){return"table"}static clone(a){return new M(a.__key,a.__selectionShape,a.__grid)}constructor(a,b,c){super(a);this.__selectionShape=b;this.__grid=c}createDOM(a){const b=document.createElement("table");z(b,a.theme.table);return b}updateDOM(){return!1}canExtractContents(){return!1}canBeEmpty(){return!1}setSelectionState(a){this.getWritable().__selectionShape=a;const b=this.getGrid();return null==b?[]:a?K(a.fromX,a.toX,a.fromY,a.toY,b.cells):K(-1,-1,-1,-1,b.cells)}getSelectionState(){return this.getLatest().__selectionShape}getCordsFromCellNode(a){var b=
15
+ this.getGrid();b||L(55);const {rows:c,cells:n}=b;for(b=0;b<c;b++){var e=n[b];if(null==e)throw Error(`Row not found at y:${b}`);e=e.findIndex(({elem:q})=>p.$getNearestNodeFromDOMNode(q)===a);if(-1!==e)return{x:e,y:b}}throw Error("Cell not found in table.");}getCellNodeFromCords(a,b){var c=this.getGrid();c||L(55);({cells:c}=c);c=c[b];if(null==c)throw Error(`Table row x:"${b}" not found.`);c=c[a];if(null==c)throw Error(`Table cell y:"${a}" in row x:"${b}" not found.`);a=p.$getNearestNodeFromDOMNode(c.elem);
16
+ if(C(a))return a;throw Error("Node at cords not TableCellNode.");}setGrid(a){const b=this.getWritable();b.__grid=a;return b}getGrid(){return this.getLatest().__grid}canSelectBefore(){return!0}}function O(){return new M}function P(a){return a instanceof M}
17
+ class Q extends p.GridRowNode{static getType(){return"tablerow"}static clone(a){return new Q(a.__key)}constructor(a){super(a)}createDOM(a){const b=document.createElement("tr");z(b,a.theme.tableRow);return b}updateDOM(){return!1}canBeEmpty(){return!1}}function R(){return new Q}function S(a){return a instanceof Q}function V(a){a=D(a,b=>S(b));if(S(a))return a;throw Error("Expected table cell to be inside of table row.");}
18
+ function W(a){a=D(a,b=>P(b));if(P(a))return a;throw Error("Expected table cell to be inside of table.");}
19
+ exports.$applyCustomTableHandlers=function(a,b,c){const n=c.getRootElement();if(null===n)throw Error("No root element.");J(a,b,c);const e=a.getGrid();let q=!1,d=!1,m=-1,k=-1,g=-1,v=-1,w=[];const H=new Set;let x=null;if(null==e)throw Error("Table grid not found.");b.addEventListener("mousemove",h=>{if(q){var f=G(h.target);if(null!==f){const l=f.x;f=f.y;if(!d&&(m!==l||k!==f)){h.preventDefault();h=E();const r=h.anchorNode;null!==r&&h.setBaseAndExtent(r,0,r,0);d=!0;document.body&&document.body.appendChild(F);
20
+ null===x&&(x=c.addListener("command",(u,t)=>{if("deleteCharacter"===u){if(w.length===e.columns*e.rows)return a.selectPrevious(),a.remove(),I(),!0;w.forEach(({elem:y})=>{y=p.$getNearestNodeFromDOMNode(y);if(p.$isElementNode(y)){const N=p.$createParagraphNode(),X=p.$createTextNode();N.append(X);y.append(N);y.getChildren().forEach(T=>{T!==N&&T.remove()})}});a.setSelectionState(null);p.$setSelection(null);return!0}if("formatText"===u)return Y(t),!0;"insertText"===u&&I();return!1},1),H.add(x))}else if(l===
21
+ g&&f===v)return;g=l;v=f;if(d){const r=Math.min(m,g),u=Math.max(m,g),t=Math.min(k,v),y=Math.max(k,v);c.update(()=>{w=a.setSelectionState({fromX:r,fromY:t,toX:u,toY:y})})}}}});const I=()=>{c.update(()=>{q=d=!1;v=g=k=m=-1;c.update(()=>{a.setSelectionState(null)});w=[];null!==x&&(x(),x=null,H.delete(x));const h=F.parentNode;null!=h&&h.removeChild(F)})};b.addEventListener("mouseleave",()=>{});const Y=h=>{let f=p.$getSelection();p.$isRangeSelection(f)||(f=p.$createRangeSelection());const l=f,r=l.anchor,
22
+ u=l.focus;w.forEach(t=>{t=p.$getNearestNodeFromDOMNode(t.elem);p.$isElementNode(t)&&0!==t.getTextContentSize()&&(r.set(t.getKey(),0,"element"),u.set(t.getKey(),t.getChildrenSize(),"element"),l.formatText(h))});f.anchor.set(f.anchor.key,f.anchor.offset,f.anchor.type);f.focus.set(f.anchor.key,f.anchor.offset,f.anchor.type);p.$setSelection(f)};b.addEventListener("mousedown",h=>{q?d&&I():setTimeout(()=>{d&&I();const f=G(h.target);null!==f&&(q=!0,m=f.x,k=f.y,document.addEventListener("mouseup",()=>{q=
23
+ !1},{capture:!0,once:!0}))},0)});window.addEventListener("click",h=>{0<w.length&&!b.contains(h.target)&&n.contains(h.target)&&c.update(()=>{a.setSelectionState(null)})});const U=(h,f,l)=>{switch(l){case "backward":case "forward":return l="forward"===l,h!==(l?e.columns-1:0)?a.getCellNodeFromCords(h+(l?1:-1),f).select():f!==(l?e.rows-1:0)?a.getCellNodeFromCords(l?0:e.columns-1,f+(l?1:-1)).select():l?a.selectNext():a.selectPrevious(),!0;case "up":return 0!==f?a.getCellNodeFromCords(h,f-1).select():a.selectPrevious(),
24
+ !0;case "down":return f!==e.rows-1?a.getCellNodeFromCords(h,f+1).select():a.selectNext(),!0}return!1},Z=c.addListener("command",(h,f)=>{var l=p.$getSelection();if(!p.$isRangeSelection(l))return!1;var r=D(l.anchor.getNode(),u=>C(u));if(!C(r))return!1;if("deleteCharacter"===h&&0===w.length&&l.isCollapsed()&&0===l.anchor.offset&&0===l.anchor.getNode().getPreviousSiblings().length)return!0;if("keyTab"===h&&l.isCollapsed()&&0===w.length)return r=a.getCordsFromCellNode(r),f.preventDefault(),U(r.x,r.y,f.shiftKey||
25
+ "keyTab"!==h?"backward":"forward"),!0;if(("keyArrowDown"===h||"keyArrowUp"===h)&&l.isCollapsed()&&0===w.length){const u=a.getCordsFromCellNode(r);l=D(l.anchor.getNode(),t=>p.$isElementNode(t));if("keyArrowUp"===h&&l===r.getFirstChild()||"keyArrowDown"===h&&l===r.getLastChild())return f.preventDefault(),f.stopImmediatePropagation(),U(u.x,u.y,"keyArrowUp"===h?"up":"down"),!0}return!1},4);H.add(Z);return()=>Array.from(H).forEach(h=>h?h():null)};exports.$createTableCellNode=B;
26
+ exports.$createTableNode=O;exports.$createTableNodeWithDimensions=function(a,b,c=!0){const n=O();for(let e=0;e<a;e++){const q=R();for(let d=0;d<b;d++){const m=B(0===e&&c),k=p.$createParagraphNode();k.append(p.$createTextNode());m.append(k);q.append(m)}n.append(q)}return n};exports.$createTableRowNode=R;
27
+ exports.$deleteTableColumn=function(a,b){const c=a.getChildren();for(let e=0;e<c.length;e++){var n=c[e];if(S(n)){n=n.getChildren();if(b>=n.length||0>b)throw Error("Table column target index out of range");n[b].remove()}}return a};exports.$getTableCellNodeFromLexicalNode=function(a){a=D(a,b=>C(b));return C(a)?a:null};exports.$getTableColumnIndexFromTableCellNode=function(a){return V(a).getChildren().findIndex(b=>b.is(a))};exports.$getTableNodeFromLexicalNodeOrThrow=W;
28
+ exports.$getTableRowIndexFromTableCellNode=function(a){const b=V(a);return W(b).getChildren().findIndex(c=>c.is(b))};exports.$getTableRowNodeFromTableCellNodeOrThrow=V;exports.$insertTableColumn=function(a,b,c=!0,n){const e=a.getChildren();for(let d=0;d<e.length;d++){const m=e[d];if(S(m))for(let k=0;k<n;k++){const g=B(0===d);g.append(p.$createParagraphNode());var q=m.getChildren();if(b>=q.length||0>b)throw Error("Table column target index out of range");q=q[b];c?q.insertAfter(g):q.insertBefore(g)}}return a};
29
+ exports.$insertTableRow=function(a,b,c=!0,n){var e=a.getChildren();if(b>=e.length||0>b)throw Error("Table row target index out of range");b=e[b];if(S(b))for(e=0;e<n;e++){const q=b.getChildren().length,d=R();for(let m=0;m<q;m++){const k=B(!1);k.append(p.$createParagraphNode());d.append(k)}c?b.insertAfter(d):b.insertBefore(d)}else throw Error("Row before insertion index does not exist.");return a};exports.$isTableCellNode=C;exports.$isTableNode=P;exports.$isTableRowNode=S;
30
+ exports.$removeTableRowAtIndex=function(a,b){const c=a.getChildren();if(b>=c.length||0>b)throw Error("Expected table cell to be inside of table row.");c[b].remove();return a};exports.TableCellNode=A;exports.TableNode=M;exports.TableRowNode=Q;
package/package.json CHANGED
@@ -12,10 +12,10 @@
12
12
  "table"
13
13
  ],
14
14
  "license": "MIT",
15
- "version": "0.1.10",
15
+ "version": "0.1.13",
16
16
  "main": "LexicalTable.js",
17
17
  "peerDependencies": {
18
- "lexical": "0.1.10"
18
+ "lexical": "0.1.13"
19
19
  },
20
20
  "repository": {
21
21
  "type": "git",