@react-fabric/lexical 1.0.0-beta.60 → 1.0.0-beta.61

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 (127) hide show
  1. package/dist/cjs/{packages/lexical/src/components → components}/StickyComponent.js +2 -3
  2. package/dist/cjs/{packages/lexical/src/editor → editor}/LexicalEditor.js +5 -5
  3. package/dist/cjs/{packages/lexical/src/hooks → hooks}/useFormatWatcher.js +101 -95
  4. package/dist/cjs/i18n/ar.json.js +24 -0
  5. package/dist/cjs/i18n/en.json.js +24 -0
  6. package/dist/cjs/i18n/index.js +33 -0
  7. package/dist/cjs/{packages/lexical/src/index.js → index.js} +1 -0
  8. package/dist/cjs/{packages/lexical/src/plugins → plugins}/DraggableBlockPlugin.js +5 -5
  9. package/dist/cjs/{packages/lexical/src/plugins → plugins}/ToolbarPlugin.js +35 -22
  10. package/dist/esm/{packages/lexical/src/components → components}/StickyComponent.js +2 -3
  11. package/dist/esm/{packages/lexical/src/editor → editor}/LexicalEditor.js +4 -4
  12. package/dist/esm/{packages/lexical/src/hooks → hooks}/useFormatWatcher.js +43 -37
  13. package/dist/esm/i18n/ar.json.js +21 -0
  14. package/dist/esm/i18n/en.json.js +21 -0
  15. package/dist/esm/i18n/index.js +33 -0
  16. package/dist/esm/{packages/lexical/src/index.js → index.js} +1 -0
  17. package/dist/esm/{packages/lexical/src/plugins → plugins}/DraggableBlockPlugin.js +2 -2
  18. package/dist/esm/{packages/lexical/src/plugins → plugins}/ToolbarPlugin.js +36 -23
  19. package/dist/types/hooks/useFormatWatcher.d.ts +1 -0
  20. package/dist/types/i18n/index.d.ts +1 -0
  21. package/dist/types/index.d.ts +1 -0
  22. package/package.json +5 -5
  23. package/src/components/StickyComponent.tsx +2 -3
  24. package/src/hooks/useFormatWatcher.ts +3 -0
  25. package/src/i18n/ar.json +16 -0
  26. package/src/i18n/en.json +16 -0
  27. package/src/i18n/index.ts +28 -0
  28. package/src/index.ts +2 -0
  29. package/src/plugins/ToolbarPlugin.tsx +34 -23
  30. package/dist/cjs/_virtual/prism.js +0 -5
  31. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.dev.js +0 -474
  32. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.js +0 -21
  33. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.prod.js +0 -27
  34. package/dist/cjs/node_modules/@lexical/code/LexicalCode.dev.js +0 -1537
  35. package/dist/cjs/node_modules/@lexical/code/LexicalCode.js +0 -25
  36. package/dist/cjs/node_modules/@lexical/code/LexicalCode.prod.js +0 -57
  37. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.dev.js +0 -252
  38. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.js +0 -19
  39. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.prod.js +0 -18
  40. package/dist/cjs/node_modules/@lexical/link/LexicalLink.dev.js +0 -572
  41. package/dist/cjs/node_modules/@lexical/link/LexicalLink.js +0 -17
  42. package/dist/cjs/node_modules/@lexical/link/LexicalLink.prod.js +0 -25
  43. package/dist/cjs/node_modules/@lexical/list/LexicalList.dev.js +0 -1614
  44. package/dist/cjs/node_modules/@lexical/list/LexicalList.js +0 -29
  45. package/dist/cjs/node_modules/@lexical/list/LexicalList.prod.js +0 -36
  46. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.dev.js +0 -838
  47. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.js +0 -29
  48. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.prod.js +0 -26
  49. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.dev.js +0 -1057
  50. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.js +0 -39
  51. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.prod.js +0 -45
  52. package/dist/cjs/node_modules/@lexical/table/LexicalTable.dev.js +0 -4207
  53. package/dist/cjs/node_modules/@lexical/table/LexicalTable.js +0 -23
  54. package/dist/cjs/node_modules/@lexical/table/LexicalTable.prod.js +0 -68
  55. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.dev.js +0 -1166
  56. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.js +0 -47
  57. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.prod.js +0 -81
  58. package/dist/cjs/node_modules/@mdi/js/mdi.js +0 -8
  59. package/dist/cjs/node_modules/prismjs/components/prism-c.js +0 -82
  60. package/dist/cjs/node_modules/prismjs/components/prism-clike.js +0 -33
  61. package/dist/cjs/node_modules/prismjs/components/prism-cpp.js +0 -101
  62. package/dist/cjs/node_modules/prismjs/components/prism-css.js +0 -66
  63. package/dist/cjs/node_modules/prismjs/components/prism-java.js +0 -126
  64. package/dist/cjs/node_modules/prismjs/components/prism-javascript.js +0 -174
  65. package/dist/cjs/node_modules/prismjs/components/prism-markdown.js +0 -417
  66. package/dist/cjs/node_modules/prismjs/components/prism-markup.js +0 -188
  67. package/dist/cjs/node_modules/prismjs/components/prism-objectivec.js +0 -14
  68. package/dist/cjs/node_modules/prismjs/components/prism-powershell.js +0 -60
  69. package/dist/cjs/node_modules/prismjs/components/prism-python.js +0 -67
  70. package/dist/cjs/node_modules/prismjs/components/prism-rust.js +0 -130
  71. package/dist/cjs/node_modules/prismjs/components/prism-sql.js +0 -34
  72. package/dist/cjs/node_modules/prismjs/components/prism-swift.js +0 -150
  73. package/dist/cjs/node_modules/prismjs/components/prism-typescript.js +0 -62
  74. package/dist/cjs/node_modules/prismjs/prism.js +0 -1951
  75. package/dist/esm/_virtual/prism.js +0 -5
  76. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.dev.js +0 -465
  77. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.js +0 -19
  78. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.prod.js +0 -18
  79. package/dist/esm/node_modules/@lexical/code/LexicalCode.dev.js +0 -1512
  80. package/dist/esm/node_modules/@lexical/code/LexicalCode.js +0 -21
  81. package/dist/esm/node_modules/@lexical/code/LexicalCode.prod.js +0 -32
  82. package/dist/esm/node_modules/@lexical/html/LexicalHtml.dev.js +0 -251
  83. package/dist/esm/node_modules/@lexical/html/LexicalHtml.js +0 -18
  84. package/dist/esm/node_modules/@lexical/html/LexicalHtml.prod.js +0 -17
  85. package/dist/esm/node_modules/@lexical/link/LexicalLink.dev.js +0 -563
  86. package/dist/esm/node_modules/@lexical/link/LexicalLink.js +0 -17
  87. package/dist/esm/node_modules/@lexical/link/LexicalLink.prod.js +0 -16
  88. package/dist/esm/node_modules/@lexical/list/LexicalList.dev.js +0 -1595
  89. package/dist/esm/node_modules/@lexical/list/LexicalList.js +0 -23
  90. package/dist/esm/node_modules/@lexical/list/LexicalList.prod.js +0 -17
  91. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.dev.js +0 -830
  92. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.js +0 -23
  93. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.prod.js +0 -18
  94. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.dev.js +0 -1028
  95. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.js +0 -28
  96. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.prod.js +0 -16
  97. package/dist/esm/node_modules/@lexical/table/LexicalTable.dev.js +0 -4156
  98. package/dist/esm/node_modules/@lexical/table/LexicalTable.js +0 -20
  99. package/dist/esm/node_modules/@lexical/table/LexicalTable.prod.js +0 -17
  100. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.dev.js +0 -1102
  101. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.js +0 -32
  102. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.prod.js +0 -17
  103. package/dist/esm/node_modules/@mdi/js/mdi.js +0 -7
  104. package/dist/esm/node_modules/prismjs/components/prism-c.js +0 -82
  105. package/dist/esm/node_modules/prismjs/components/prism-clike.js +0 -33
  106. package/dist/esm/node_modules/prismjs/components/prism-cpp.js +0 -101
  107. package/dist/esm/node_modules/prismjs/components/prism-css.js +0 -66
  108. package/dist/esm/node_modules/prismjs/components/prism-java.js +0 -126
  109. package/dist/esm/node_modules/prismjs/components/prism-javascript.js +0 -174
  110. package/dist/esm/node_modules/prismjs/components/prism-markdown.js +0 -417
  111. package/dist/esm/node_modules/prismjs/components/prism-markup.js +0 -188
  112. package/dist/esm/node_modules/prismjs/components/prism-objectivec.js +0 -14
  113. package/dist/esm/node_modules/prismjs/components/prism-powershell.js +0 -60
  114. package/dist/esm/node_modules/prismjs/components/prism-python.js +0 -67
  115. package/dist/esm/node_modules/prismjs/components/prism-rust.js +0 -130
  116. package/dist/esm/node_modules/prismjs/components/prism-sql.js +0 -34
  117. package/dist/esm/node_modules/prismjs/components/prism-swift.js +0 -150
  118. package/dist/esm/node_modules/prismjs/components/prism-typescript.js +0 -62
  119. package/dist/esm/node_modules/prismjs/prism.js +0 -1951
  120. /package/dist/cjs/{packages/lexical/src/editor → editor}/theme.js +0 -0
  121. /package/dist/cjs/{packages/lexical/src/nodes → nodes}/StickyNode.js +0 -0
  122. /package/dist/cjs/{packages/lexical/src/plugins → plugins}/StickyPlugin.js +0 -0
  123. /package/dist/cjs/{packages/lexical/src/utils → utils}/index.js +0 -0
  124. /package/dist/esm/{packages/lexical/src/editor → editor}/theme.js +0 -0
  125. /package/dist/esm/{packages/lexical/src/nodes → nodes}/StickyNode.js +0 -0
  126. /package/dist/esm/{packages/lexical/src/plugins → plugins}/StickyPlugin.js +0 -0
  127. /package/dist/esm/{packages/lexical/src/utils → utils}/index.js +0 -0
@@ -1,4156 +0,0 @@
1
- 'use client';
2
-
3
- import { addClassNamesToElement, $descendantsMatching, $findMatchingParent, removeClassNamesFromElement, objectKlassEquals, isHTMLElement as isHTMLElement$1, $insertFirst as $insertFirst$1, mergeRegister, $insertNodeToNearestRoot, $unwrapAndFilterDescendants } from '../utils/LexicalUtils.js';
4
- import { ElementNode, isHTMLElement, $isInlineElementOrDecoratorNode, $isTextNode, $isLineBreakNode, $createParagraphNode, $applyNodeReplacement, createCommand, $createTextNode, $getSelection, $isRangeSelection, $isParagraphNode, $createPoint, $getNodeByKey, $getEditor, $setSelection, SELECTION_CHANGE_COMMAND, getDOMSelection, $createRangeSelection, $isRootNode, INSERT_PARAGRAPH_COMMAND, $isElementNode, COMMAND_PRIORITY_HIGH, KEY_ESCAPE_COMMAND, COMMAND_PRIORITY_CRITICAL, CUT_COMMAND, FORMAT_TEXT_COMMAND, FORMAT_ELEMENT_COMMAND, CONTROLLED_TEXT_INSERTION_COMMAND, KEY_TAB_COMMAND, FOCUS_COMMAND, SELECTION_INSERT_CLIPBOARD_NODES_COMMAND, $getPreviousSelection, $getNearestNodeFromDOMNode, $createRangeSelectionFromDom, $isRootOrShadowRoot, setDOMUnmanaged, COMMAND_PRIORITY_EDITOR, CLICK_COMMAND, TEXT_TYPE_TO_FORMAT, $normalizeSelection__EXPERIMENTAL, isCurrentlyReadOnlyMode, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_UP_COMMAND, KEY_ARROW_LEFT_COMMAND, KEY_ARROW_RIGHT_COMMAND, DELETE_WORD_COMMAND, DELETE_LINE_COMMAND, DELETE_CHARACTER_COMMAND, KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, isDOMNode, $caretFromPoint, $isExtendableTextPointCaret, $extendCaretToRange, $isSiblingCaret, $getSiblingCaret, $setPointFromCaret, $normalizeCaret, $getAdjacentChildCaret, $isChildCaret, $getChildCaret } from 'lexical';
5
- import { copyToClipboard, $getClipboardDataFromSelection } from '../clipboard/LexicalClipboard.js';
6
-
7
- /**
8
- * Copyright (c) Meta Platforms, Inc. and affiliates.
9
- *
10
- * This source code is licensed under the MIT license found in the
11
- * LICENSE file in the root directory of this source tree.
12
- *
13
- */
14
-
15
-
16
- /**
17
- * Copyright (c) Meta Platforms, Inc. and affiliates.
18
- *
19
- * This source code is licensed under the MIT license found in the
20
- * LICENSE file in the root directory of this source tree.
21
- *
22
- */
23
-
24
- const PIXEL_VALUE_REG_EXP = /^(\d+(?:\.\d+)?)px$/;
25
-
26
- // .PlaygroundEditorTheme__tableCell width value from
27
- // packages/lexical-playground/src/themes/PlaygroundEditorTheme.css
28
- const COLUMN_WIDTH = 75;
29
-
30
- /**
31
- * Copyright (c) Meta Platforms, Inc. and affiliates.
32
- *
33
- * This source code is licensed under the MIT license found in the
34
- * LICENSE file in the root directory of this source tree.
35
- *
36
- */
37
-
38
- const TableCellHeaderStates = {
39
- BOTH: 3,
40
- COLUMN: 2,
41
- NO_STATUS: 0,
42
- ROW: 1
43
- };
44
- /** @noInheritDoc */
45
- class TableCellNode extends ElementNode {
46
- /** @internal */
47
-
48
- /** @internal */
49
-
50
- /** @internal */
51
-
52
- /** @internal */
53
-
54
- /** @internal */
55
-
56
- /** @internal */
57
-
58
- static getType() {
59
- return 'tablecell';
60
- }
61
- static clone(node) {
62
- return new TableCellNode(node.__headerState, node.__colSpan, node.__width, node.__key);
63
- }
64
- afterCloneFrom(node) {
65
- super.afterCloneFrom(node);
66
- this.__rowSpan = node.__rowSpan;
67
- this.__backgroundColor = node.__backgroundColor;
68
- this.__verticalAlign = node.__verticalAlign;
69
- }
70
- static importDOM() {
71
- return {
72
- td: node => ({
73
- conversion: $convertTableCellNodeElement,
74
- priority: 0
75
- }),
76
- th: node => ({
77
- conversion: $convertTableCellNodeElement,
78
- priority: 0
79
- })
80
- };
81
- }
82
- static importJSON(serializedNode) {
83
- return $createTableCellNode().updateFromJSON(serializedNode);
84
- }
85
- updateFromJSON(serializedNode) {
86
- return super.updateFromJSON(serializedNode).setHeaderStyles(serializedNode.headerState).setColSpan(serializedNode.colSpan || 1).setRowSpan(serializedNode.rowSpan || 1).setWidth(serializedNode.width || undefined).setBackgroundColor(serializedNode.backgroundColor || null).setVerticalAlign(serializedNode.verticalAlign || undefined);
87
- }
88
- constructor(headerState = TableCellHeaderStates.NO_STATUS, colSpan = 1, width, key) {
89
- super(key);
90
- this.__colSpan = colSpan;
91
- this.__rowSpan = 1;
92
- this.__headerState = headerState;
93
- this.__width = width;
94
- this.__backgroundColor = null;
95
- this.__verticalAlign = undefined;
96
- }
97
- createDOM(config) {
98
- const element = document.createElement(this.getTag());
99
- if (this.__width) {
100
- element.style.width = `${this.__width}px`;
101
- }
102
- if (this.__colSpan > 1) {
103
- element.colSpan = this.__colSpan;
104
- }
105
- if (this.__rowSpan > 1) {
106
- element.rowSpan = this.__rowSpan;
107
- }
108
- if (this.__backgroundColor !== null) {
109
- element.style.backgroundColor = this.__backgroundColor;
110
- }
111
- if (isValidVerticalAlign(this.__verticalAlign)) {
112
- element.style.verticalAlign = this.__verticalAlign;
113
- }
114
- addClassNamesToElement(element, config.theme.tableCell, this.hasHeader() && config.theme.tableCellHeader);
115
- return element;
116
- }
117
- exportDOM(editor) {
118
- const output = super.exportDOM(editor);
119
- if (isHTMLElement(output.element)) {
120
- const element = output.element;
121
- element.setAttribute('data-temporary-table-cell-lexical-key', this.getKey());
122
- element.style.border = '1px solid black';
123
- if (this.__colSpan > 1) {
124
- element.colSpan = this.__colSpan;
125
- }
126
- if (this.__rowSpan > 1) {
127
- element.rowSpan = this.__rowSpan;
128
- }
129
- element.style.width = `${this.getWidth() || COLUMN_WIDTH}px`;
130
- element.style.verticalAlign = this.getVerticalAlign() || 'top';
131
- element.style.textAlign = 'start';
132
- if (this.__backgroundColor === null && this.hasHeader()) {
133
- element.style.backgroundColor = '#f2f3f5';
134
- }
135
- }
136
- return output;
137
- }
138
- exportJSON() {
139
- return {
140
- ...super.exportJSON(),
141
- ...(isValidVerticalAlign(this.__verticalAlign) && {
142
- verticalAlign: this.__verticalAlign
143
- }),
144
- backgroundColor: this.getBackgroundColor(),
145
- colSpan: this.__colSpan,
146
- headerState: this.__headerState,
147
- rowSpan: this.__rowSpan,
148
- width: this.getWidth()
149
- };
150
- }
151
- getColSpan() {
152
- return this.getLatest().__colSpan;
153
- }
154
- setColSpan(colSpan) {
155
- const self = this.getWritable();
156
- self.__colSpan = colSpan;
157
- return self;
158
- }
159
- getRowSpan() {
160
- return this.getLatest().__rowSpan;
161
- }
162
- setRowSpan(rowSpan) {
163
- const self = this.getWritable();
164
- self.__rowSpan = rowSpan;
165
- return self;
166
- }
167
- getTag() {
168
- return this.hasHeader() ? 'th' : 'td';
169
- }
170
- setHeaderStyles(headerState, mask = TableCellHeaderStates.BOTH) {
171
- const self = this.getWritable();
172
- self.__headerState = headerState & mask | self.__headerState & ~mask;
173
- return self;
174
- }
175
- getHeaderStyles() {
176
- return this.getLatest().__headerState;
177
- }
178
- setWidth(width) {
179
- const self = this.getWritable();
180
- self.__width = width;
181
- return self;
182
- }
183
- getWidth() {
184
- return this.getLatest().__width;
185
- }
186
- getBackgroundColor() {
187
- return this.getLatest().__backgroundColor;
188
- }
189
- setBackgroundColor(newBackgroundColor) {
190
- const self = this.getWritable();
191
- self.__backgroundColor = newBackgroundColor;
192
- return self;
193
- }
194
- getVerticalAlign() {
195
- return this.getLatest().__verticalAlign;
196
- }
197
- setVerticalAlign(newVerticalAlign) {
198
- const self = this.getWritable();
199
- self.__verticalAlign = newVerticalAlign || undefined;
200
- return self;
201
- }
202
- toggleHeaderStyle(headerStateToToggle) {
203
- const self = this.getWritable();
204
- if ((self.__headerState & headerStateToToggle) === headerStateToToggle) {
205
- self.__headerState -= headerStateToToggle;
206
- } else {
207
- self.__headerState += headerStateToToggle;
208
- }
209
- return self;
210
- }
211
- hasHeaderState(headerState) {
212
- return (this.getHeaderStyles() & headerState) === headerState;
213
- }
214
- hasHeader() {
215
- return this.getLatest().__headerState !== TableCellHeaderStates.NO_STATUS;
216
- }
217
- updateDOM(prevNode) {
218
- return prevNode.__headerState !== this.__headerState || prevNode.__width !== this.__width || prevNode.__colSpan !== this.__colSpan || prevNode.__rowSpan !== this.__rowSpan || prevNode.__backgroundColor !== this.__backgroundColor || prevNode.__verticalAlign !== this.__verticalAlign;
219
- }
220
- isShadowRoot() {
221
- return true;
222
- }
223
- collapseAtStart() {
224
- return true;
225
- }
226
- canBeEmpty() {
227
- return false;
228
- }
229
- canIndent() {
230
- return false;
231
- }
232
- }
233
- function isValidVerticalAlign(verticalAlign) {
234
- return verticalAlign === 'middle' || verticalAlign === 'bottom';
235
- }
236
- function $convertTableCellNodeElement(domNode) {
237
- const domNode_ = domNode;
238
- const nodeName = domNode.nodeName.toLowerCase();
239
- let width = undefined;
240
- if (PIXEL_VALUE_REG_EXP.test(domNode_.style.width)) {
241
- width = parseFloat(domNode_.style.width);
242
- }
243
- const tableCellNode = $createTableCellNode(nodeName === 'th' ? TableCellHeaderStates.ROW : TableCellHeaderStates.NO_STATUS, domNode_.colSpan, width);
244
- tableCellNode.__rowSpan = domNode_.rowSpan;
245
- const backgroundColor = domNode_.style.backgroundColor;
246
- if (backgroundColor !== '') {
247
- tableCellNode.__backgroundColor = backgroundColor;
248
- }
249
- const verticalAlign = domNode_.style.verticalAlign;
250
- if (isValidVerticalAlign(verticalAlign)) {
251
- tableCellNode.__verticalAlign = verticalAlign;
252
- }
253
- const style = domNode_.style;
254
- const textDecoration = (style && style.textDecoration || '').split(' ');
255
- const hasBoldFontWeight = style.fontWeight === '700' || style.fontWeight === 'bold';
256
- const hasLinethroughTextDecoration = textDecoration.includes('line-through');
257
- const hasItalicFontStyle = style.fontStyle === 'italic';
258
- const hasUnderlineTextDecoration = textDecoration.includes('underline');
259
- return {
260
- after: childLexicalNodes => {
261
- const result = [];
262
- let paragraphNode = null;
263
- const removeSingleLineBreakNode = () => {
264
- if (paragraphNode) {
265
- const firstChild = paragraphNode.getFirstChild();
266
- if ($isLineBreakNode(firstChild) && paragraphNode.getChildrenSize() === 1) {
267
- firstChild.remove();
268
- }
269
- }
270
- };
271
- for (const child of childLexicalNodes) {
272
- if ($isInlineElementOrDecoratorNode(child) || $isTextNode(child) || $isLineBreakNode(child)) {
273
- if ($isTextNode(child)) {
274
- if (hasBoldFontWeight) {
275
- child.toggleFormat('bold');
276
- }
277
- if (hasLinethroughTextDecoration) {
278
- child.toggleFormat('strikethrough');
279
- }
280
- if (hasItalicFontStyle) {
281
- child.toggleFormat('italic');
282
- }
283
- if (hasUnderlineTextDecoration) {
284
- child.toggleFormat('underline');
285
- }
286
- }
287
- if (paragraphNode) {
288
- paragraphNode.append(child);
289
- } else {
290
- paragraphNode = $createParagraphNode().append(child);
291
- result.push(paragraphNode);
292
- }
293
- } else {
294
- result.push(child);
295
- removeSingleLineBreakNode();
296
- paragraphNode = null;
297
- }
298
- }
299
- removeSingleLineBreakNode();
300
- if (result.length === 0) {
301
- result.push($createParagraphNode());
302
- }
303
- return result;
304
- },
305
- node: tableCellNode
306
- };
307
- }
308
- function $createTableCellNode(headerState = TableCellHeaderStates.NO_STATUS, colSpan = 1, width) {
309
- return $applyNodeReplacement(new TableCellNode(headerState, colSpan, width));
310
- }
311
- function $isTableCellNode(node) {
312
- return node instanceof TableCellNode;
313
- }
314
-
315
- /**
316
- * Copyright (c) Meta Platforms, Inc. and affiliates.
317
- *
318
- * This source code is licensed under the MIT license found in the
319
- * LICENSE file in the root directory of this source tree.
320
- *
321
- */
322
-
323
- const INSERT_TABLE_COMMAND = createCommand('INSERT_TABLE_COMMAND');
324
-
325
- /**
326
- * Copyright (c) Meta Platforms, Inc. and affiliates.
327
- *
328
- * This source code is licensed under the MIT license found in the
329
- * LICENSE file in the root directory of this source tree.
330
- *
331
- */
332
-
333
- // Do not require this module directly! Use normal `invariant` calls.
334
-
335
- function formatDevErrorMessage(message) {
336
- throw new Error(message);
337
- }
338
-
339
- /**
340
- * Copyright (c) Meta Platforms, Inc. and affiliates.
341
- *
342
- * This source code is licensed under the MIT license found in the
343
- * LICENSE file in the root directory of this source tree.
344
- *
345
- */
346
-
347
- /** @noInheritDoc */
348
- class TableRowNode extends ElementNode {
349
- /** @internal */
350
-
351
- static getType() {
352
- return 'tablerow';
353
- }
354
- static clone(node) {
355
- return new TableRowNode(node.__height, node.__key);
356
- }
357
- static importDOM() {
358
- return {
359
- tr: node => ({
360
- conversion: $convertTableRowElement,
361
- priority: 0
362
- })
363
- };
364
- }
365
- static importJSON(serializedNode) {
366
- return $createTableRowNode().updateFromJSON(serializedNode);
367
- }
368
- updateFromJSON(serializedNode) {
369
- return super.updateFromJSON(serializedNode).setHeight(serializedNode.height);
370
- }
371
- constructor(height, key) {
372
- super(key);
373
- this.__height = height;
374
- }
375
- exportJSON() {
376
- const height = this.getHeight();
377
- return {
378
- ...super.exportJSON(),
379
- ...(height === undefined ? undefined : {
380
- height
381
- })
382
- };
383
- }
384
- createDOM(config) {
385
- const element = document.createElement('tr');
386
- if (this.__height) {
387
- element.style.height = `${this.__height}px`;
388
- }
389
- addClassNamesToElement(element, config.theme.tableRow);
390
- return element;
391
- }
392
- extractWithChild(child, selection, destination) {
393
- return destination === 'html';
394
- }
395
- isShadowRoot() {
396
- return true;
397
- }
398
- setHeight(height) {
399
- const self = this.getWritable();
400
- self.__height = height;
401
- return self;
402
- }
403
- getHeight() {
404
- return this.getLatest().__height;
405
- }
406
- updateDOM(prevNode) {
407
- return prevNode.__height !== this.__height;
408
- }
409
- canBeEmpty() {
410
- return false;
411
- }
412
- canIndent() {
413
- return false;
414
- }
415
- }
416
- function $convertTableRowElement(domNode) {
417
- const domNode_ = domNode;
418
- let height = undefined;
419
- if (PIXEL_VALUE_REG_EXP.test(domNode_.style.height)) {
420
- height = parseFloat(domNode_.style.height);
421
- }
422
- return {
423
- after: children => $descendantsMatching(children, $isTableCellNode),
424
- node: $createTableRowNode(height)
425
- };
426
- }
427
- function $createTableRowNode(height) {
428
- return $applyNodeReplacement(new TableRowNode(height));
429
- }
430
- function $isTableRowNode(node) {
431
- return node instanceof TableRowNode;
432
- }
433
-
434
- /**
435
- * Copyright (c) Meta Platforms, Inc. and affiliates.
436
- *
437
- * This source code is licensed under the MIT license found in the
438
- * LICENSE file in the root directory of this source tree.
439
- *
440
- */
441
-
442
- const CAN_USE_DOM = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined';
443
-
444
- /**
445
- * Copyright (c) Meta Platforms, Inc. and affiliates.
446
- *
447
- * This source code is licensed under the MIT license found in the
448
- * LICENSE file in the root directory of this source tree.
449
- *
450
- */
451
-
452
- const documentMode = CAN_USE_DOM && 'documentMode' in document ? document.documentMode : null;
453
- const IS_FIREFOX = CAN_USE_DOM && /^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent);
454
- CAN_USE_DOM && 'InputEvent' in window && !documentMode ? 'getTargetRanges' in new window.InputEvent('input') : false;
455
-
456
- function $createTableNodeWithDimensions(rowCount, columnCount, includeHeaders = true) {
457
- const tableNode = $createTableNode();
458
- for (let iRow = 0; iRow < rowCount; iRow++) {
459
- const tableRowNode = $createTableRowNode();
460
- for (let iColumn = 0; iColumn < columnCount; iColumn++) {
461
- let headerState = TableCellHeaderStates.NO_STATUS;
462
- if (typeof includeHeaders === 'object') {
463
- if (iRow === 0 && includeHeaders.rows) {
464
- headerState |= TableCellHeaderStates.ROW;
465
- }
466
- if (iColumn === 0 && includeHeaders.columns) {
467
- headerState |= TableCellHeaderStates.COLUMN;
468
- }
469
- } else if (includeHeaders) {
470
- if (iRow === 0) {
471
- headerState |= TableCellHeaderStates.ROW;
472
- }
473
- if (iColumn === 0) {
474
- headerState |= TableCellHeaderStates.COLUMN;
475
- }
476
- }
477
- const tableCellNode = $createTableCellNode(headerState);
478
- const paragraphNode = $createParagraphNode();
479
- paragraphNode.append($createTextNode());
480
- tableCellNode.append(paragraphNode);
481
- tableRowNode.append(tableCellNode);
482
- }
483
- tableNode.append(tableRowNode);
484
- }
485
- return tableNode;
486
- }
487
- function $getTableCellNodeFromLexicalNode(startingNode) {
488
- const node = $findMatchingParent(startingNode, n => $isTableCellNode(n));
489
- if ($isTableCellNode(node)) {
490
- return node;
491
- }
492
- return null;
493
- }
494
- function $getTableRowNodeFromTableCellNodeOrThrow(startingNode) {
495
- const node = $findMatchingParent(startingNode, n => $isTableRowNode(n));
496
- if ($isTableRowNode(node)) {
497
- return node;
498
- }
499
- throw new Error('Expected table cell to be inside of table row.');
500
- }
501
- function $getTableNodeFromLexicalNodeOrThrow(startingNode) {
502
- const node = $findMatchingParent(startingNode, n => $isTableNode(n));
503
- if ($isTableNode(node)) {
504
- return node;
505
- }
506
- throw new Error('Expected table cell to be inside of table.');
507
- }
508
- function $getTableRowIndexFromTableCellNode(tableCellNode) {
509
- const tableRowNode = $getTableRowNodeFromTableCellNodeOrThrow(tableCellNode);
510
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableRowNode);
511
- return tableNode.getChildren().findIndex(n => n.is(tableRowNode));
512
- }
513
- function $getTableColumnIndexFromTableCellNode(tableCellNode) {
514
- const tableRowNode = $getTableRowNodeFromTableCellNodeOrThrow(tableCellNode);
515
- return tableRowNode.getChildren().findIndex(n => n.is(tableCellNode));
516
- }
517
- function $getTableCellSiblingsFromTableCellNode(tableCellNode, table) {
518
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCellNode);
519
- const {
520
- x,
521
- y
522
- } = tableNode.getCordsFromCellNode(tableCellNode, table);
523
- return {
524
- above: tableNode.getCellNodeFromCords(x, y - 1, table),
525
- below: tableNode.getCellNodeFromCords(x, y + 1, table),
526
- left: tableNode.getCellNodeFromCords(x - 1, y, table),
527
- right: tableNode.getCellNodeFromCords(x + 1, y, table)
528
- };
529
- }
530
- function $removeTableRowAtIndex(tableNode, indexToDelete) {
531
- const tableRows = tableNode.getChildren();
532
- if (indexToDelete >= tableRows.length || indexToDelete < 0) {
533
- throw new Error('Expected table cell to be inside of table row.');
534
- }
535
- const targetRowNode = tableRows[indexToDelete];
536
- targetRowNode.remove();
537
- return tableNode;
538
- }
539
-
540
- /**
541
- * @deprecated This function does not support merged cells. Use {@link $insertTableRowAtSelection} or {@link $insertTableRowAtNode} instead.
542
- */
543
- function $insertTableRow(tableNode, targetIndex, shouldInsertAfter = true, rowCount, table) {
544
- const tableRows = tableNode.getChildren();
545
- if (targetIndex >= tableRows.length || targetIndex < 0) {
546
- throw new Error('Table row target index out of range');
547
- }
548
- const targetRowNode = tableRows[targetIndex];
549
- if ($isTableRowNode(targetRowNode)) {
550
- for (let r = 0; r < rowCount; r++) {
551
- const tableRowCells = targetRowNode.getChildren();
552
- const tableColumnCount = tableRowCells.length;
553
- const newTableRowNode = $createTableRowNode();
554
- for (let c = 0; c < tableColumnCount; c++) {
555
- const tableCellFromTargetRow = tableRowCells[c];
556
- if (!$isTableCellNode(tableCellFromTargetRow)) {
557
- formatDevErrorMessage(`Expected table cell`);
558
- }
559
- const {
560
- above,
561
- below
562
- } = $getTableCellSiblingsFromTableCellNode(tableCellFromTargetRow, table);
563
- let headerState = TableCellHeaderStates.NO_STATUS;
564
- const width = above && above.getWidth() || below && below.getWidth() || undefined;
565
- if (above && above.hasHeaderState(TableCellHeaderStates.COLUMN) || below && below.hasHeaderState(TableCellHeaderStates.COLUMN)) {
566
- headerState |= TableCellHeaderStates.COLUMN;
567
- }
568
- const tableCellNode = $createTableCellNode(headerState, 1, width);
569
- tableCellNode.append($createParagraphNode());
570
- newTableRowNode.append(tableCellNode);
571
- }
572
- if (shouldInsertAfter) {
573
- targetRowNode.insertAfter(newTableRowNode);
574
- } else {
575
- targetRowNode.insertBefore(newTableRowNode);
576
- }
577
- }
578
- } else {
579
- throw new Error('Row before insertion index does not exist.');
580
- }
581
- return tableNode;
582
- }
583
- const getHeaderState = (currentState, possibleState) => {
584
- if (currentState === TableCellHeaderStates.BOTH || currentState === possibleState) {
585
- return possibleState;
586
- }
587
- return TableCellHeaderStates.NO_STATUS;
588
- };
589
-
590
- /**
591
- * Inserts a table row before or after the current focus cell node,
592
- * taking into account any spans. If successful, returns the
593
- * inserted table row node.
594
- */
595
- function $insertTableRowAtSelection(insertAfter = true) {
596
- const selection = $getSelection();
597
- if (!($isRangeSelection(selection) || $isTableSelection(selection))) {
598
- formatDevErrorMessage(`Expected a RangeSelection or TableSelection`);
599
- }
600
- const anchor = selection.anchor.getNode();
601
- const focus = selection.focus.getNode();
602
- const [anchorCell] = $getNodeTriplet(anchor);
603
- const [focusCell,, grid] = $getNodeTriplet(focus);
604
- const [, focusCellMap, anchorCellMap] = $computeTableMap(grid, focusCell, anchorCell);
605
- const {
606
- startRow: anchorStartRow
607
- } = anchorCellMap;
608
- const {
609
- startRow: focusStartRow
610
- } = focusCellMap;
611
- if (insertAfter) {
612
- return $insertTableRowAtNode(anchorStartRow + anchorCell.__rowSpan > focusStartRow + focusCell.__rowSpan ? anchorCell : focusCell, true);
613
- } else {
614
- return $insertTableRowAtNode(focusStartRow < anchorStartRow ? focusCell : anchorCell, false);
615
- }
616
- }
617
-
618
- /**
619
- * @deprecated renamed to {@link $insertTableRowAtSelection}
620
- */
621
- const $insertTableRow__EXPERIMENTAL = $insertTableRowAtSelection;
622
-
623
- /**
624
- * Inserts a table row before or after the given cell node,
625
- * taking into account any spans. If successful, returns the
626
- * inserted table row node.
627
- */
628
- function $insertTableRowAtNode(cellNode, insertAfter = true) {
629
- const [,, grid] = $getNodeTriplet(cellNode);
630
- const [gridMap, cellMap] = $computeTableMap(grid, cellNode, cellNode);
631
- const columnCount = gridMap[0].length;
632
- const {
633
- startRow: cellStartRow
634
- } = cellMap;
635
- let insertedRow = null;
636
- if (insertAfter) {
637
- const insertAfterEndRow = cellStartRow + cellNode.__rowSpan - 1;
638
- const insertAfterEndRowMap = gridMap[insertAfterEndRow];
639
- const newRow = $createTableRowNode();
640
- for (let i = 0; i < columnCount; i++) {
641
- const {
642
- cell,
643
- startRow
644
- } = insertAfterEndRowMap[i];
645
- if (startRow + cell.__rowSpan - 1 <= insertAfterEndRow) {
646
- const currentCell = insertAfterEndRowMap[i].cell;
647
- const currentCellHeaderState = currentCell.__headerState;
648
- const headerState = getHeaderState(currentCellHeaderState, TableCellHeaderStates.COLUMN);
649
- newRow.append($createTableCellNode(headerState).append($createParagraphNode()));
650
- } else {
651
- cell.setRowSpan(cell.__rowSpan + 1);
652
- }
653
- }
654
- const insertAfterEndRowNode = grid.getChildAtIndex(insertAfterEndRow);
655
- if (!$isTableRowNode(insertAfterEndRowNode)) {
656
- formatDevErrorMessage(`insertAfterEndRow is not a TableRowNode`);
657
- }
658
- insertAfterEndRowNode.insertAfter(newRow);
659
- insertedRow = newRow;
660
- } else {
661
- const insertBeforeStartRow = cellStartRow;
662
- const insertBeforeStartRowMap = gridMap[insertBeforeStartRow];
663
- const newRow = $createTableRowNode();
664
- for (let i = 0; i < columnCount; i++) {
665
- const {
666
- cell,
667
- startRow
668
- } = insertBeforeStartRowMap[i];
669
- if (startRow === insertBeforeStartRow) {
670
- const currentCell = insertBeforeStartRowMap[i].cell;
671
- const currentCellHeaderState = currentCell.__headerState;
672
- const headerState = getHeaderState(currentCellHeaderState, TableCellHeaderStates.COLUMN);
673
- newRow.append($createTableCellNode(headerState).append($createParagraphNode()));
674
- } else {
675
- cell.setRowSpan(cell.__rowSpan + 1);
676
- }
677
- }
678
- const insertBeforeStartRowNode = grid.getChildAtIndex(insertBeforeStartRow);
679
- if (!$isTableRowNode(insertBeforeStartRowNode)) {
680
- formatDevErrorMessage(`insertBeforeStartRow is not a TableRowNode`);
681
- }
682
- insertBeforeStartRowNode.insertBefore(newRow);
683
- insertedRow = newRow;
684
- }
685
- return insertedRow;
686
- }
687
-
688
- /**
689
- * @deprecated This function does not support merged cells. Use {@link $insertTableColumnAtSelection} or {@link $insertTableColumnAtNode} instead.
690
- */
691
- function $insertTableColumn(tableNode, targetIndex, shouldInsertAfter = true, columnCount, table) {
692
- const tableRows = tableNode.getChildren();
693
- const tableCellsToBeInserted = [];
694
- for (let r = 0; r < tableRows.length; r++) {
695
- const currentTableRowNode = tableRows[r];
696
- if ($isTableRowNode(currentTableRowNode)) {
697
- for (let c = 0; c < columnCount; c++) {
698
- const tableRowChildren = currentTableRowNode.getChildren();
699
- if (targetIndex >= tableRowChildren.length || targetIndex < 0) {
700
- throw new Error('Table column target index out of range');
701
- }
702
- const targetCell = tableRowChildren[targetIndex];
703
- if (!$isTableCellNode(targetCell)) {
704
- formatDevErrorMessage(`Expected table cell`);
705
- }
706
- const {
707
- left,
708
- right
709
- } = $getTableCellSiblingsFromTableCellNode(targetCell, table);
710
- let headerState = TableCellHeaderStates.NO_STATUS;
711
- if (left && left.hasHeaderState(TableCellHeaderStates.ROW) || right && right.hasHeaderState(TableCellHeaderStates.ROW)) {
712
- headerState |= TableCellHeaderStates.ROW;
713
- }
714
- const newTableCell = $createTableCellNode(headerState);
715
- newTableCell.append($createParagraphNode());
716
- tableCellsToBeInserted.push({
717
- newTableCell,
718
- targetCell
719
- });
720
- }
721
- }
722
- }
723
- tableCellsToBeInserted.forEach(({
724
- newTableCell,
725
- targetCell
726
- }) => {
727
- if (shouldInsertAfter) {
728
- targetCell.insertAfter(newTableCell);
729
- } else {
730
- targetCell.insertBefore(newTableCell);
731
- }
732
- });
733
- return tableNode;
734
- }
735
-
736
- /**
737
- * Inserts a column before or after the current focus cell node,
738
- * taking into account any spans. If successful, returns the
739
- * first inserted cell node.
740
- */
741
- function $insertTableColumnAtSelection(insertAfter = true) {
742
- const selection = $getSelection();
743
- if (!($isRangeSelection(selection) || $isTableSelection(selection))) {
744
- formatDevErrorMessage(`Expected a RangeSelection or TableSelection`);
745
- }
746
- const anchor = selection.anchor.getNode();
747
- const focus = selection.focus.getNode();
748
- const [anchorCell] = $getNodeTriplet(anchor);
749
- const [focusCell,, grid] = $getNodeTriplet(focus);
750
- const [, focusCellMap, anchorCellMap] = $computeTableMap(grid, focusCell, anchorCell);
751
- const {
752
- startColumn: anchorStartColumn
753
- } = anchorCellMap;
754
- const {
755
- startColumn: focusStartColumn
756
- } = focusCellMap;
757
- if (insertAfter) {
758
- return $insertTableColumnAtNode(anchorStartColumn + anchorCell.__colSpan > focusStartColumn + focusCell.__colSpan ? anchorCell : focusCell, true);
759
- } else {
760
- return $insertTableColumnAtNode(focusStartColumn < anchorStartColumn ? focusCell : anchorCell, false);
761
- }
762
- }
763
-
764
- /**
765
- * @deprecated renamed to {@link $insertTableColumnAtSelection}
766
- */
767
- const $insertTableColumn__EXPERIMENTAL = $insertTableColumnAtSelection;
768
-
769
- /**
770
- * Inserts a column before or after the given cell node,
771
- * taking into account any spans. If successful, returns the
772
- * first inserted cell node.
773
- */
774
- function $insertTableColumnAtNode(cellNode, insertAfter = true, shouldSetSelection = true) {
775
- const [,, grid] = $getNodeTriplet(cellNode);
776
- const [gridMap, cellMap] = $computeTableMap(grid, cellNode, cellNode);
777
- const rowCount = gridMap.length;
778
- const {
779
- startColumn
780
- } = cellMap;
781
- const insertAfterColumn = insertAfter ? startColumn + cellNode.__colSpan - 1 : startColumn - 1;
782
- const gridFirstChild = grid.getFirstChild();
783
- if (!$isTableRowNode(gridFirstChild)) {
784
- formatDevErrorMessage(`Expected firstTable child to be a row`);
785
- }
786
- let firstInsertedCell = null;
787
- function $createTableCellNodeForInsertTableColumn(headerState = TableCellHeaderStates.NO_STATUS) {
788
- const cell = $createTableCellNode(headerState).append($createParagraphNode());
789
- if (firstInsertedCell === null) {
790
- firstInsertedCell = cell;
791
- }
792
- return cell;
793
- }
794
- let loopRow = gridFirstChild;
795
- rowLoop: for (let i = 0; i < rowCount; i++) {
796
- if (i !== 0) {
797
- const currentRow = loopRow.getNextSibling();
798
- if (!$isTableRowNode(currentRow)) {
799
- formatDevErrorMessage(`Expected row nextSibling to be a row`);
800
- }
801
- loopRow = currentRow;
802
- }
803
- const rowMap = gridMap[i];
804
- const currentCellHeaderState = rowMap[insertAfterColumn < 0 ? 0 : insertAfterColumn].cell.__headerState;
805
- const headerState = getHeaderState(currentCellHeaderState, TableCellHeaderStates.ROW);
806
- if (insertAfterColumn < 0) {
807
- $insertFirst(loopRow, $createTableCellNodeForInsertTableColumn(headerState));
808
- continue;
809
- }
810
- const {
811
- cell: currentCell,
812
- startColumn: currentStartColumn,
813
- startRow: currentStartRow
814
- } = rowMap[insertAfterColumn];
815
- if (currentStartColumn + currentCell.__colSpan - 1 <= insertAfterColumn) {
816
- let insertAfterCell = currentCell;
817
- let insertAfterCellRowStart = currentStartRow;
818
- let prevCellIndex = insertAfterColumn;
819
- while (insertAfterCellRowStart !== i && insertAfterCell.__rowSpan > 1) {
820
- prevCellIndex -= currentCell.__colSpan;
821
- if (prevCellIndex >= 0) {
822
- const {
823
- cell: cell_,
824
- startRow: startRow_
825
- } = rowMap[prevCellIndex];
826
- insertAfterCell = cell_;
827
- insertAfterCellRowStart = startRow_;
828
- } else {
829
- loopRow.append($createTableCellNodeForInsertTableColumn(headerState));
830
- continue rowLoop;
831
- }
832
- }
833
- insertAfterCell.insertAfter($createTableCellNodeForInsertTableColumn(headerState));
834
- } else {
835
- currentCell.setColSpan(currentCell.__colSpan + 1);
836
- }
837
- }
838
- if (firstInsertedCell !== null && shouldSetSelection) {
839
- $moveSelectionToCell(firstInsertedCell);
840
- }
841
- const colWidths = grid.getColWidths();
842
- if (colWidths) {
843
- const newColWidths = [...colWidths];
844
- const columnIndex = insertAfterColumn < 0 ? 0 : insertAfterColumn;
845
- const newWidth = newColWidths[columnIndex];
846
- newColWidths.splice(columnIndex, 0, newWidth);
847
- grid.setColWidths(newColWidths);
848
- }
849
- return firstInsertedCell;
850
- }
851
-
852
- /**
853
- * @deprecated This function does not support merged cells. Use {@link $deleteTableColumnAtSelection} instead.
854
- */
855
- function $deleteTableColumn(tableNode, targetIndex) {
856
- const tableRows = tableNode.getChildren();
857
- for (let i = 0; i < tableRows.length; i++) {
858
- const currentTableRowNode = tableRows[i];
859
- if ($isTableRowNode(currentTableRowNode)) {
860
- const tableRowChildren = currentTableRowNode.getChildren();
861
- if (targetIndex >= tableRowChildren.length || targetIndex < 0) {
862
- throw new Error('Table column target index out of range');
863
- }
864
- tableRowChildren[targetIndex].remove();
865
- }
866
- }
867
- return tableNode;
868
- }
869
- function $deleteTableRowAtSelection() {
870
- const selection = $getSelection();
871
- if (!($isRangeSelection(selection) || $isTableSelection(selection))) {
872
- formatDevErrorMessage(`Expected a RangeSelection or TableSelection`);
873
- }
874
- const [anchor, focus] = selection.isBackward() ? [selection.focus.getNode(), selection.anchor.getNode()] : [selection.anchor.getNode(), selection.focus.getNode()];
875
- const [anchorCell,, grid] = $getNodeTriplet(anchor);
876
- const [focusCell] = $getNodeTriplet(focus);
877
- const [gridMap, anchorCellMap, focusCellMap] = $computeTableMap(grid, anchorCell, focusCell);
878
- const {
879
- startRow: anchorStartRow
880
- } = anchorCellMap;
881
- const {
882
- startRow: focusStartRow
883
- } = focusCellMap;
884
- const focusEndRow = focusStartRow + focusCell.__rowSpan - 1;
885
- if (gridMap.length === focusEndRow - anchorStartRow + 1) {
886
- // Empty grid
887
- grid.remove();
888
- return;
889
- }
890
- const columnCount = gridMap[0].length;
891
- const nextRow = gridMap[focusEndRow + 1];
892
- const nextRowNode = grid.getChildAtIndex(focusEndRow + 1);
893
- for (let row = focusEndRow; row >= anchorStartRow; row--) {
894
- for (let column = columnCount - 1; column >= 0; column--) {
895
- const {
896
- cell,
897
- startRow: cellStartRow,
898
- startColumn: cellStartColumn
899
- } = gridMap[row][column];
900
- if (cellStartColumn !== column) {
901
- // Don't repeat work for the same Cell
902
- continue;
903
- }
904
- // Rows overflowing top or bottom have to be trimmed
905
- if (cellStartRow < anchorStartRow || cellStartRow + cell.__rowSpan - 1 > focusEndRow) {
906
- const intersectionStart = Math.max(cellStartRow, anchorStartRow);
907
- const intersectionEnd = Math.min(cell.__rowSpan + cellStartRow - 1, focusEndRow);
908
- const overflowRowsCount = intersectionStart <= intersectionEnd ? intersectionEnd - intersectionStart + 1 : 0;
909
- cell.setRowSpan(cell.__rowSpan - overflowRowsCount);
910
- }
911
- // Rows overflowing bottom have to be moved to the next row
912
- if (cellStartRow >= anchorStartRow && cellStartRow + cell.__rowSpan - 1 > focusEndRow &&
913
- // Handle overflow only once
914
- row === focusEndRow) {
915
- if (!(nextRowNode !== null)) {
916
- formatDevErrorMessage(`Expected nextRowNode not to be null`);
917
- }
918
- let insertAfterCell = null;
919
- for (let columnIndex = 0; columnIndex < column; columnIndex++) {
920
- const currentCellMap = nextRow[columnIndex];
921
- const currentCell = currentCellMap.cell;
922
- // Checking the cell having startRow as same as nextRow
923
- if (currentCellMap.startRow === row + 1) {
924
- insertAfterCell = currentCell;
925
- }
926
- if (currentCell.__colSpan > 1) {
927
- columnIndex += currentCell.__colSpan - 1;
928
- }
929
- }
930
- if (insertAfterCell === null) {
931
- $insertFirst(nextRowNode, cell);
932
- } else {
933
- insertAfterCell.insertAfter(cell);
934
- }
935
- }
936
- }
937
- const rowNode = grid.getChildAtIndex(row);
938
- if (!$isTableRowNode(rowNode)) {
939
- formatDevErrorMessage(`Expected TableNode childAtIndex(${String(row)}) to be RowNode`);
940
- }
941
- rowNode.remove();
942
- }
943
- if (nextRow !== undefined) {
944
- const {
945
- cell
946
- } = nextRow[0];
947
- $moveSelectionToCell(cell);
948
- } else {
949
- const previousRow = gridMap[anchorStartRow - 1];
950
- const {
951
- cell
952
- } = previousRow[0];
953
- $moveSelectionToCell(cell);
954
- }
955
- }
956
-
957
- /**
958
- * @deprecated renamed to {@link $deleteTableRowAtSelection}
959
- */
960
- const $deleteTableRow__EXPERIMENTAL = $deleteTableRowAtSelection;
961
- function $deleteTableColumnAtSelection() {
962
- const selection = $getSelection();
963
- if (!($isRangeSelection(selection) || $isTableSelection(selection))) {
964
- formatDevErrorMessage(`Expected a RangeSelection or TableSelection`);
965
- }
966
- const anchor = selection.anchor.getNode();
967
- const focus = selection.focus.getNode();
968
- const [anchorCell,, grid] = $getNodeTriplet(anchor);
969
- const [focusCell] = $getNodeTriplet(focus);
970
- const [gridMap, anchorCellMap, focusCellMap] = $computeTableMap(grid, anchorCell, focusCell);
971
- const {
972
- startColumn: anchorStartColumn
973
- } = anchorCellMap;
974
- const {
975
- startRow: focusStartRow,
976
- startColumn: focusStartColumn
977
- } = focusCellMap;
978
- const startColumn = Math.min(anchorStartColumn, focusStartColumn);
979
- const endColumn = Math.max(anchorStartColumn + anchorCell.__colSpan - 1, focusStartColumn + focusCell.__colSpan - 1);
980
- const selectedColumnCount = endColumn - startColumn + 1;
981
- const columnCount = gridMap[0].length;
982
- if (columnCount === endColumn - startColumn + 1) {
983
- // Empty grid
984
- grid.selectPrevious();
985
- grid.remove();
986
- return;
987
- }
988
- const rowCount = gridMap.length;
989
- for (let row = 0; row < rowCount; row++) {
990
- for (let column = startColumn; column <= endColumn; column++) {
991
- const {
992
- cell,
993
- startColumn: cellStartColumn
994
- } = gridMap[row][column];
995
- if (cellStartColumn < startColumn) {
996
- if (column === startColumn) {
997
- const overflowLeft = startColumn - cellStartColumn;
998
- // Overflowing left
999
- cell.setColSpan(cell.__colSpan -
1000
- // Possible overflow right too
1001
- Math.min(selectedColumnCount, cell.__colSpan - overflowLeft));
1002
- }
1003
- } else if (cellStartColumn + cell.__colSpan - 1 > endColumn) {
1004
- if (column === endColumn) {
1005
- // Overflowing right
1006
- const inSelectedArea = endColumn - cellStartColumn + 1;
1007
- cell.setColSpan(cell.__colSpan - inSelectedArea);
1008
- }
1009
- } else {
1010
- cell.remove();
1011
- }
1012
- }
1013
- }
1014
- const focusRowMap = gridMap[focusStartRow];
1015
- const nextColumn = anchorStartColumn > focusStartColumn ? focusRowMap[anchorStartColumn + anchorCell.__colSpan] : focusRowMap[focusStartColumn + focusCell.__colSpan];
1016
- if (nextColumn !== undefined) {
1017
- const {
1018
- cell
1019
- } = nextColumn;
1020
- $moveSelectionToCell(cell);
1021
- } else {
1022
- const previousRow = focusStartColumn < anchorStartColumn ? focusRowMap[focusStartColumn - 1] : focusRowMap[anchorStartColumn - 1];
1023
- const {
1024
- cell
1025
- } = previousRow;
1026
- $moveSelectionToCell(cell);
1027
- }
1028
- const colWidths = grid.getColWidths();
1029
- if (colWidths) {
1030
- const newColWidths = [...colWidths];
1031
- newColWidths.splice(startColumn, selectedColumnCount);
1032
- grid.setColWidths(newColWidths);
1033
- }
1034
- }
1035
-
1036
- /**
1037
- * @deprecated renamed to {@link $deleteTableColumnAtSelection}
1038
- */
1039
- const $deleteTableColumn__EXPERIMENTAL = $deleteTableColumnAtSelection;
1040
- function $moveSelectionToCell(cell) {
1041
- const firstDescendant = cell.getFirstDescendant();
1042
- if (firstDescendant == null) {
1043
- cell.selectStart();
1044
- } else {
1045
- firstDescendant.getParentOrThrow().selectStart();
1046
- }
1047
- }
1048
- function $insertFirst(parent, node) {
1049
- const firstChild = parent.getFirstChild();
1050
- if (firstChild !== null) {
1051
- firstChild.insertBefore(node);
1052
- } else {
1053
- parent.append(node);
1054
- }
1055
- }
1056
- function $mergeCells(cellNodes) {
1057
- if (cellNodes.length === 0) {
1058
- return null;
1059
- }
1060
-
1061
- // Find the table node
1062
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(cellNodes[0]);
1063
- const [gridMap] = $computeTableMapSkipCellCheck(tableNode, null, null);
1064
-
1065
- // Find the boundaries of the selection including merged cells
1066
- let minRow = Infinity;
1067
- let maxRow = -Infinity;
1068
- let minCol = Infinity;
1069
- let maxCol = -Infinity;
1070
-
1071
- // First pass: find the actual boundaries considering merged cells
1072
- const processedCells = new Set();
1073
- for (const row of gridMap) {
1074
- for (const mapCell of row) {
1075
- if (!mapCell || !mapCell.cell) {
1076
- continue;
1077
- }
1078
- const cellKey = mapCell.cell.getKey();
1079
- if (processedCells.has(cellKey)) {
1080
- continue;
1081
- }
1082
- if (cellNodes.some(cell => cell.is(mapCell.cell))) {
1083
- processedCells.add(cellKey);
1084
- // Get the actual position of this cell in the grid
1085
- const cellStartRow = mapCell.startRow;
1086
- const cellStartCol = mapCell.startColumn;
1087
- const cellRowSpan = mapCell.cell.__rowSpan || 1;
1088
- const cellColSpan = mapCell.cell.__colSpan || 1;
1089
-
1090
- // Update boundaries considering the cell's actual position and span
1091
- minRow = Math.min(minRow, cellStartRow);
1092
- maxRow = Math.max(maxRow, cellStartRow + cellRowSpan - 1);
1093
- minCol = Math.min(minCol, cellStartCol);
1094
- maxCol = Math.max(maxCol, cellStartCol + cellColSpan - 1);
1095
- }
1096
- }
1097
- }
1098
-
1099
- // Validate boundaries
1100
- if (minRow === Infinity || minCol === Infinity) {
1101
- return null;
1102
- }
1103
-
1104
- // The total span of the merged cell
1105
- const totalRowSpan = maxRow - minRow + 1;
1106
- const totalColSpan = maxCol - minCol + 1;
1107
-
1108
- // Use the top-left cell as the target cell
1109
- const targetCellMap = gridMap[minRow][minCol];
1110
- if (!targetCellMap.cell) {
1111
- return null;
1112
- }
1113
- const targetCell = targetCellMap.cell;
1114
-
1115
- // Set the spans for the target cell
1116
- targetCell.setColSpan(totalColSpan);
1117
- targetCell.setRowSpan(totalRowSpan);
1118
-
1119
- // Move content from other cells to the target cell
1120
- const seenCells = new Set([targetCell.getKey()]);
1121
-
1122
- // Second pass: merge content and remove other cells
1123
- for (let row = minRow; row <= maxRow; row++) {
1124
- for (let col = minCol; col <= maxCol; col++) {
1125
- const mapCell = gridMap[row][col];
1126
- if (!mapCell.cell) {
1127
- continue;
1128
- }
1129
- const currentCell = mapCell.cell;
1130
- const key = currentCell.getKey();
1131
- if (!seenCells.has(key)) {
1132
- seenCells.add(key);
1133
- const isEmpty = $cellContainsEmptyParagraph(currentCell);
1134
- if (!isEmpty) {
1135
- targetCell.append(...currentCell.getChildren());
1136
- }
1137
- currentCell.remove();
1138
- }
1139
- }
1140
- }
1141
-
1142
- // Ensure target cell has content
1143
- if (targetCell.getChildrenSize() === 0) {
1144
- targetCell.append($createParagraphNode());
1145
- }
1146
- return targetCell;
1147
- }
1148
- function $cellContainsEmptyParagraph(cell) {
1149
- if (cell.getChildrenSize() !== 1) {
1150
- return false;
1151
- }
1152
- const firstChild = cell.getFirstChildOrThrow();
1153
- if (!$isParagraphNode(firstChild) || !firstChild.isEmpty()) {
1154
- return false;
1155
- }
1156
- return true;
1157
- }
1158
- function $unmergeCell() {
1159
- const selection = $getSelection();
1160
- if (!($isRangeSelection(selection) || $isTableSelection(selection))) {
1161
- formatDevErrorMessage(`Expected a RangeSelection or TableSelection`);
1162
- }
1163
- const anchor = selection.anchor.getNode();
1164
- const cellNode = $findMatchingParent(anchor, $isTableCellNode);
1165
- if (!$isTableCellNode(cellNode)) {
1166
- formatDevErrorMessage(`Expected to find a parent TableCellNode`);
1167
- }
1168
- return $unmergeCellNode(cellNode);
1169
- }
1170
- function $unmergeCellNode(cellNode) {
1171
- const [cell, row, grid] = $getNodeTriplet(cellNode);
1172
- const colSpan = cell.__colSpan;
1173
- const rowSpan = cell.__rowSpan;
1174
- if (colSpan === 1 && rowSpan === 1) {
1175
- return;
1176
- }
1177
- const [map, cellMap] = $computeTableMap(grid, cell, cell);
1178
- const {
1179
- startColumn,
1180
- startRow
1181
- } = cellMap;
1182
- // Create a heuristic for what the style of the unmerged cells should be
1183
- // based on whether every row or column already had that state before the
1184
- // unmerge.
1185
- const baseColStyle = cell.__headerState & TableCellHeaderStates.COLUMN;
1186
- const colStyles = Array.from({
1187
- length: colSpan
1188
- }, (_v, i) => {
1189
- let colStyle = baseColStyle;
1190
- for (let rowIdx = 0; colStyle !== 0 && rowIdx < map.length; rowIdx++) {
1191
- colStyle &= map[rowIdx][i + startColumn].cell.__headerState;
1192
- }
1193
- return colStyle;
1194
- });
1195
- const baseRowStyle = cell.__headerState & TableCellHeaderStates.ROW;
1196
- const rowStyles = Array.from({
1197
- length: rowSpan
1198
- }, (_v, i) => {
1199
- let rowStyle = baseRowStyle;
1200
- for (let colIdx = 0; rowStyle !== 0 && colIdx < map[0].length; colIdx++) {
1201
- rowStyle &= map[i + startRow][colIdx].cell.__headerState;
1202
- }
1203
- return rowStyle;
1204
- });
1205
- if (colSpan > 1) {
1206
- for (let i = 1; i < colSpan; i++) {
1207
- cell.insertAfter($createTableCellNode(colStyles[i] | rowStyles[0]).append($createParagraphNode()));
1208
- }
1209
- cell.setColSpan(1);
1210
- }
1211
- if (rowSpan > 1) {
1212
- let currentRowNode;
1213
- for (let i = 1; i < rowSpan; i++) {
1214
- const currentRow = startRow + i;
1215
- const currentRowMap = map[currentRow];
1216
- currentRowNode = (currentRowNode || row).getNextSibling();
1217
- if (!$isTableRowNode(currentRowNode)) {
1218
- formatDevErrorMessage(`Expected row next sibling to be a row`);
1219
- }
1220
- let insertAfterCell = null;
1221
- for (let column = 0; column < startColumn; column++) {
1222
- const currentCellMap = currentRowMap[column];
1223
- const currentCell = currentCellMap.cell;
1224
- if (currentCellMap.startRow === currentRow) {
1225
- insertAfterCell = currentCell;
1226
- }
1227
- if (currentCell.__colSpan > 1) {
1228
- column += currentCell.__colSpan - 1;
1229
- }
1230
- }
1231
- if (insertAfterCell === null) {
1232
- for (let j = colSpan - 1; j >= 0; j--) {
1233
- $insertFirst(currentRowNode, $createTableCellNode(colStyles[j] | rowStyles[i]).append($createParagraphNode()));
1234
- }
1235
- } else {
1236
- for (let j = colSpan - 1; j >= 0; j--) {
1237
- insertAfterCell.insertAfter($createTableCellNode(colStyles[j] | rowStyles[i]).append($createParagraphNode()));
1238
- }
1239
- }
1240
- }
1241
- cell.setRowSpan(1);
1242
- }
1243
- }
1244
- function $computeTableMap(tableNode, cellA, cellB) {
1245
- const [tableMap, cellAValue, cellBValue] = $computeTableMapSkipCellCheck(tableNode, cellA, cellB);
1246
- if (!(cellAValue !== null)) {
1247
- formatDevErrorMessage(`Anchor not found in Table`);
1248
- }
1249
- if (!(cellBValue !== null)) {
1250
- formatDevErrorMessage(`Focus not found in Table`);
1251
- }
1252
- return [tableMap, cellAValue, cellBValue];
1253
- }
1254
- function $computeTableMapSkipCellCheck(tableNode, cellA, cellB) {
1255
- const tableMap = [];
1256
- let cellAValue = null;
1257
- let cellBValue = null;
1258
- function getMapRow(i) {
1259
- let row = tableMap[i];
1260
- if (row === undefined) {
1261
- tableMap[i] = row = [];
1262
- }
1263
- return row;
1264
- }
1265
- const gridChildren = tableNode.getChildren();
1266
- for (let rowIdx = 0; rowIdx < gridChildren.length; rowIdx++) {
1267
- const row = gridChildren[rowIdx];
1268
- if (!$isTableRowNode(row)) {
1269
- formatDevErrorMessage(`Expected TableNode children to be TableRowNode`);
1270
- }
1271
- const startMapRow = getMapRow(rowIdx);
1272
- for (let cell = row.getFirstChild(), colIdx = 0; cell != null; cell = cell.getNextSibling()) {
1273
- if (!$isTableCellNode(cell)) {
1274
- formatDevErrorMessage(`Expected TableRowNode children to be TableCellNode`);
1275
- } // Skip past any columns that were merged from a higher row
1276
- while (startMapRow[colIdx] !== undefined) {
1277
- colIdx++;
1278
- }
1279
- const value = {
1280
- cell,
1281
- startColumn: colIdx,
1282
- startRow: rowIdx
1283
- };
1284
- const {
1285
- __rowSpan: rowSpan,
1286
- __colSpan: colSpan
1287
- } = cell;
1288
- for (let j = 0; j < rowSpan; j++) {
1289
- if (rowIdx + j >= gridChildren.length) {
1290
- // The table is non-rectangular with a rowSpan
1291
- // below the last <tr> in the table.
1292
- // We should probably handle this with a node transform
1293
- // to ensure that tables are always rectangular but this
1294
- // will avoid crashes such as #6584
1295
- // Note that there are probably still latent bugs
1296
- // regarding colSpan or general cell count mismatches.
1297
- break;
1298
- }
1299
- const mapRow = getMapRow(rowIdx + j);
1300
- for (let i = 0; i < colSpan; i++) {
1301
- mapRow[colIdx + i] = value;
1302
- }
1303
- }
1304
- if (cellA !== null && cellAValue === null && cellA.is(cell)) {
1305
- cellAValue = value;
1306
- }
1307
- if (cellB !== null && cellBValue === null && cellB.is(cell)) {
1308
- cellBValue = value;
1309
- }
1310
- }
1311
- }
1312
- return [tableMap, cellAValue, cellBValue];
1313
- }
1314
- function $getNodeTriplet(source) {
1315
- let cell;
1316
- if (source instanceof TableCellNode) {
1317
- cell = source;
1318
- } else if ('__type' in source) {
1319
- const cell_ = $findMatchingParent(source, $isTableCellNode);
1320
- if (!$isTableCellNode(cell_)) {
1321
- formatDevErrorMessage(`Expected to find a parent TableCellNode`);
1322
- }
1323
- cell = cell_;
1324
- } else {
1325
- const cell_ = $findMatchingParent(source.getNode(), $isTableCellNode);
1326
- if (!$isTableCellNode(cell_)) {
1327
- formatDevErrorMessage(`Expected to find a parent TableCellNode`);
1328
- }
1329
- cell = cell_;
1330
- }
1331
- const row = cell.getParent();
1332
- if (!$isTableRowNode(row)) {
1333
- formatDevErrorMessage(`Expected TableCellNode to have a parent TableRowNode`);
1334
- }
1335
- const grid = row.getParent();
1336
- if (!$isTableNode(grid)) {
1337
- formatDevErrorMessage(`Expected TableRowNode to have a parent TableNode`);
1338
- }
1339
- return [cell, row, grid];
1340
- }
1341
- function $computeTableCellRectSpans(map, boundary) {
1342
- const {
1343
- minColumn,
1344
- maxColumn,
1345
- minRow,
1346
- maxRow
1347
- } = boundary;
1348
- let topSpan = 1;
1349
- let leftSpan = 1;
1350
- let rightSpan = 1;
1351
- let bottomSpan = 1;
1352
- const topRow = map[minRow];
1353
- const bottomRow = map[maxRow];
1354
- for (let col = minColumn; col <= maxColumn; col++) {
1355
- topSpan = Math.max(topSpan, topRow[col].cell.__rowSpan);
1356
- bottomSpan = Math.max(bottomSpan, bottomRow[col].cell.__rowSpan);
1357
- }
1358
- for (let row = minRow; row <= maxRow; row++) {
1359
- leftSpan = Math.max(leftSpan, map[row][minColumn].cell.__colSpan);
1360
- rightSpan = Math.max(rightSpan, map[row][maxColumn].cell.__colSpan);
1361
- }
1362
- return {
1363
- bottomSpan,
1364
- leftSpan,
1365
- rightSpan,
1366
- topSpan
1367
- };
1368
- }
1369
- function $computeTableCellRectBoundary(map, cellAMap, cellBMap) {
1370
- // Initial boundaries based on the anchor and focus cells
1371
- let minColumn = Math.min(cellAMap.startColumn, cellBMap.startColumn);
1372
- let minRow = Math.min(cellAMap.startRow, cellBMap.startRow);
1373
- let maxColumn = Math.max(cellAMap.startColumn + cellAMap.cell.__colSpan - 1, cellBMap.startColumn + cellBMap.cell.__colSpan - 1);
1374
- let maxRow = Math.max(cellAMap.startRow + cellAMap.cell.__rowSpan - 1, cellBMap.startRow + cellBMap.cell.__rowSpan - 1);
1375
-
1376
- // Keep expanding until we have a complete rectangle
1377
- let hasChanges;
1378
- do {
1379
- hasChanges = false;
1380
-
1381
- // Check all cells in the table
1382
- for (let row = 0; row < map.length; row++) {
1383
- for (let col = 0; col < map[0].length; col++) {
1384
- const cell = map[row][col];
1385
- if (!cell) {
1386
- continue;
1387
- }
1388
- const cellEndCol = cell.startColumn + cell.cell.__colSpan - 1;
1389
- const cellEndRow = cell.startRow + cell.cell.__rowSpan - 1;
1390
-
1391
- // Check if this cell intersects with our current selection rectangle
1392
- const intersectsHorizontally = cell.startColumn <= maxColumn && cellEndCol >= minColumn;
1393
- const intersectsVertically = cell.startRow <= maxRow && cellEndRow >= minRow;
1394
-
1395
- // If the cell intersects either horizontally or vertically
1396
- if (intersectsHorizontally && intersectsVertically) {
1397
- // Expand boundaries to include this cell completely
1398
- const newMinColumn = Math.min(minColumn, cell.startColumn);
1399
- const newMaxColumn = Math.max(maxColumn, cellEndCol);
1400
- const newMinRow = Math.min(minRow, cell.startRow);
1401
- const newMaxRow = Math.max(maxRow, cellEndRow);
1402
-
1403
- // Check if boundaries changed
1404
- if (newMinColumn !== minColumn || newMaxColumn !== maxColumn || newMinRow !== minRow || newMaxRow !== maxRow) {
1405
- minColumn = newMinColumn;
1406
- maxColumn = newMaxColumn;
1407
- minRow = newMinRow;
1408
- maxRow = newMaxRow;
1409
- hasChanges = true;
1410
- }
1411
- }
1412
- }
1413
- }
1414
- } while (hasChanges);
1415
- return {
1416
- maxColumn,
1417
- maxRow,
1418
- minColumn,
1419
- minRow
1420
- };
1421
- }
1422
- function $getTableCellNodeRect(tableCellNode) {
1423
- const [cellNode,, gridNode] = $getNodeTriplet(tableCellNode);
1424
- const rows = gridNode.getChildren();
1425
- const rowCount = rows.length;
1426
- const columnCount = rows[0].getChildren().length;
1427
-
1428
- // Create a matrix of the same size as the table to track the position of each cell
1429
- const cellMatrix = new Array(rowCount);
1430
- for (let i = 0; i < rowCount; i++) {
1431
- cellMatrix[i] = new Array(columnCount);
1432
- }
1433
- for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
1434
- const row = rows[rowIndex];
1435
- const cells = row.getChildren();
1436
- let columnIndex = 0;
1437
- for (let cellIndex = 0; cellIndex < cells.length; cellIndex++) {
1438
- // Find the next available position in the matrix, skip the position of merged cells
1439
- while (cellMatrix[rowIndex][columnIndex]) {
1440
- columnIndex++;
1441
- }
1442
- const cell = cells[cellIndex];
1443
- const rowSpan = cell.__rowSpan || 1;
1444
- const colSpan = cell.__colSpan || 1;
1445
-
1446
- // Put the cell into the corresponding position in the matrix
1447
- for (let i = 0; i < rowSpan; i++) {
1448
- for (let j = 0; j < colSpan; j++) {
1449
- cellMatrix[rowIndex + i][columnIndex + j] = cell;
1450
- }
1451
- }
1452
-
1453
- // Return to the original index, row span and column span of the cell.
1454
- if (cellNode === cell) {
1455
- return {
1456
- colSpan,
1457
- columnIndex,
1458
- rowIndex,
1459
- rowSpan
1460
- };
1461
- }
1462
- columnIndex += colSpan;
1463
- }
1464
- }
1465
- return null;
1466
- }
1467
-
1468
- function $getCellNodes(tableSelection) {
1469
- const [[anchorNode, anchorCell, anchorRow, anchorTable], [focusNode, focusCell, focusRow, focusTable]] = ['anchor', 'focus'].map(k => {
1470
- const node = tableSelection[k].getNode();
1471
- const cellNode = $findMatchingParent(node, $isTableCellNode);
1472
- if (!$isTableCellNode(cellNode)) {
1473
- formatDevErrorMessage(`Expected TableSelection ${k} to be (or a child of) TableCellNode, got key ${node.getKey()} of type ${node.getType()}`);
1474
- }
1475
- const rowNode = cellNode.getParent();
1476
- if (!$isTableRowNode(rowNode)) {
1477
- formatDevErrorMessage(`Expected TableSelection ${k} cell parent to be a TableRowNode`);
1478
- }
1479
- const tableNode = rowNode.getParent();
1480
- if (!$isTableNode(tableNode)) {
1481
- formatDevErrorMessage(`Expected TableSelection ${k} row parent to be a TableNode`);
1482
- }
1483
- return [node, cellNode, rowNode, tableNode];
1484
- });
1485
- // TODO: nested tables may violate this
1486
- if (!anchorTable.is(focusTable)) {
1487
- formatDevErrorMessage(`Expected TableSelection anchor and focus to be in the same table`);
1488
- }
1489
- return {
1490
- anchorCell,
1491
- anchorNode,
1492
- anchorRow,
1493
- anchorTable,
1494
- focusCell,
1495
- focusNode,
1496
- focusRow,
1497
- focusTable
1498
- };
1499
- }
1500
- class TableSelection {
1501
- constructor(tableKey, anchor, focus) {
1502
- this.anchor = anchor;
1503
- this.focus = focus;
1504
- anchor._selection = this;
1505
- focus._selection = this;
1506
- this._cachedNodes = null;
1507
- this.dirty = false;
1508
- this.tableKey = tableKey;
1509
- }
1510
- getStartEndPoints() {
1511
- return [this.anchor, this.focus];
1512
- }
1513
-
1514
- /**
1515
- * {@link $createTableSelection} unfortunately makes it very easy to create
1516
- * nonsense selections, so we have a method to see if the selection probably
1517
- * makes sense.
1518
- *
1519
- * @returns true if the TableSelection is (probably) valid
1520
- */
1521
- isValid() {
1522
- return this.tableKey !== 'root' && this.anchor.key !== 'root' && this.anchor.type === 'element' && this.focus.key !== 'root' && this.focus.type === 'element';
1523
- }
1524
-
1525
- /**
1526
- * Returns whether the Selection is "backwards", meaning the focus
1527
- * logically precedes the anchor in the EditorState.
1528
- * @returns true if the Selection is backwards, false otherwise.
1529
- */
1530
- isBackward() {
1531
- return this.focus.isBefore(this.anchor);
1532
- }
1533
- getCachedNodes() {
1534
- return this._cachedNodes;
1535
- }
1536
- setCachedNodes(nodes) {
1537
- this._cachedNodes = nodes;
1538
- }
1539
- is(selection) {
1540
- return $isTableSelection(selection) && this.tableKey === selection.tableKey && this.anchor.is(selection.anchor) && this.focus.is(selection.focus);
1541
- }
1542
- set(tableKey, anchorCellKey, focusCellKey) {
1543
- // note: closure compiler's acorn does not support ||=
1544
- this.dirty = this.dirty || tableKey !== this.tableKey || anchorCellKey !== this.anchor.key || focusCellKey !== this.focus.key;
1545
- this.tableKey = tableKey;
1546
- this.anchor.key = anchorCellKey;
1547
- this.focus.key = focusCellKey;
1548
- this._cachedNodes = null;
1549
- }
1550
- clone() {
1551
- return new TableSelection(this.tableKey, $createPoint(this.anchor.key, this.anchor.offset, this.anchor.type), $createPoint(this.focus.key, this.focus.offset, this.focus.type));
1552
- }
1553
- isCollapsed() {
1554
- return false;
1555
- }
1556
- extract() {
1557
- return this.getNodes();
1558
- }
1559
- insertRawText(text) {
1560
- // Do nothing?
1561
- }
1562
- insertText() {
1563
- // Do nothing?
1564
- }
1565
-
1566
- /**
1567
- * Returns whether the provided TextFormatType is present on the Selection.
1568
- * This will be true if any paragraph in table cells has the specified format.
1569
- *
1570
- * @param type the TextFormatType to check for.
1571
- * @returns true if the provided format is currently toggled on on the Selection, false otherwise.
1572
- */
1573
- hasFormat(type) {
1574
- let format = 0;
1575
- const cellNodes = this.getNodes().filter($isTableCellNode);
1576
- cellNodes.forEach(cellNode => {
1577
- const paragraph = cellNode.getFirstChild();
1578
- if ($isParagraphNode(paragraph)) {
1579
- format |= paragraph.getTextFormat();
1580
- }
1581
- });
1582
- const formatFlag = TEXT_TYPE_TO_FORMAT[type];
1583
- return (format & formatFlag) !== 0;
1584
- }
1585
- insertNodes(nodes) {
1586
- const focusNode = this.focus.getNode();
1587
- if (!$isElementNode(focusNode)) {
1588
- formatDevErrorMessage(`Expected TableSelection focus to be an ElementNode`);
1589
- }
1590
- const selection = $normalizeSelection__EXPERIMENTAL(focusNode.select(0, focusNode.getChildrenSize()));
1591
- selection.insertNodes(nodes);
1592
- }
1593
-
1594
- // TODO Deprecate this method. It's confusing when used with colspan|rowspan
1595
- getShape() {
1596
- const {
1597
- anchorCell,
1598
- focusCell
1599
- } = $getCellNodes(this);
1600
- const anchorCellNodeRect = $getTableCellNodeRect(anchorCell);
1601
- if (!(anchorCellNodeRect !== null)) {
1602
- formatDevErrorMessage(`getCellRect: expected to find AnchorNode`);
1603
- }
1604
- const focusCellNodeRect = $getTableCellNodeRect(focusCell);
1605
- if (!(focusCellNodeRect !== null)) {
1606
- formatDevErrorMessage(`getCellRect: expected to find focusCellNode`);
1607
- }
1608
- const startX = Math.min(anchorCellNodeRect.columnIndex, focusCellNodeRect.columnIndex);
1609
- const stopX = Math.max(anchorCellNodeRect.columnIndex + anchorCellNodeRect.colSpan - 1, focusCellNodeRect.columnIndex + focusCellNodeRect.colSpan - 1);
1610
- const startY = Math.min(anchorCellNodeRect.rowIndex, focusCellNodeRect.rowIndex);
1611
- const stopY = Math.max(anchorCellNodeRect.rowIndex + anchorCellNodeRect.rowSpan - 1, focusCellNodeRect.rowIndex + focusCellNodeRect.rowSpan - 1);
1612
- return {
1613
- fromX: Math.min(startX, stopX),
1614
- fromY: Math.min(startY, stopY),
1615
- toX: Math.max(startX, stopX),
1616
- toY: Math.max(startY, stopY)
1617
- };
1618
- }
1619
- getNodes() {
1620
- if (!this.isValid()) {
1621
- return [];
1622
- }
1623
- const cachedNodes = this._cachedNodes;
1624
- if (cachedNodes !== null) {
1625
- return cachedNodes;
1626
- }
1627
- const {
1628
- anchorTable: tableNode,
1629
- anchorCell,
1630
- focusCell
1631
- } = $getCellNodes(this);
1632
- const focusCellGrid = focusCell.getParents()[1];
1633
- if (focusCellGrid !== tableNode) {
1634
- if (!tableNode.isParentOf(focusCell)) {
1635
- // focus is on higher Grid level than anchor
1636
- const gridParent = tableNode.getParent();
1637
- if (!(gridParent != null)) {
1638
- formatDevErrorMessage(`Expected gridParent to have a parent`);
1639
- }
1640
- this.set(this.tableKey, gridParent.getKey(), focusCell.getKey());
1641
- } else {
1642
- // anchor is on higher Grid level than focus
1643
- const focusCellParent = focusCellGrid.getParent();
1644
- if (!(focusCellParent != null)) {
1645
- formatDevErrorMessage(`Expected focusCellParent to have a parent`);
1646
- }
1647
- this.set(this.tableKey, focusCell.getKey(), focusCellParent.getKey());
1648
- }
1649
- return this.getNodes();
1650
- }
1651
-
1652
- // TODO Mapping the whole Grid every time not efficient. We need to compute the entire state only
1653
- // once (on load) and iterate on it as updates occur. However, to do this we need to have the
1654
- // ability to store a state. Killing TableSelection and moving the logic to the plugin would make
1655
- // this possible.
1656
- const [map, cellAMap, cellBMap] = $computeTableMap(tableNode, anchorCell, focusCell);
1657
- const {
1658
- minColumn,
1659
- maxColumn,
1660
- minRow,
1661
- maxRow
1662
- } = $computeTableCellRectBoundary(map, cellAMap, cellBMap);
1663
-
1664
- // We use a Map here because merged cells in the grid would otherwise
1665
- // show up multiple times in the nodes array
1666
- const nodeMap = new Map([[tableNode.getKey(), tableNode]]);
1667
- let lastRow = null;
1668
- for (let i = minRow; i <= maxRow; i++) {
1669
- for (let j = minColumn; j <= maxColumn; j++) {
1670
- const {
1671
- cell
1672
- } = map[i][j];
1673
- const currentRow = cell.getParent();
1674
- if (!$isTableRowNode(currentRow)) {
1675
- formatDevErrorMessage(`Expected TableCellNode parent to be a TableRowNode`);
1676
- }
1677
- if (currentRow !== lastRow) {
1678
- nodeMap.set(currentRow.getKey(), currentRow);
1679
- lastRow = currentRow;
1680
- }
1681
- if (!nodeMap.has(cell.getKey())) {
1682
- $visitRecursively(cell, childNode => {
1683
- nodeMap.set(childNode.getKey(), childNode);
1684
- });
1685
- }
1686
- }
1687
- }
1688
- const nodes = Array.from(nodeMap.values());
1689
- if (!isCurrentlyReadOnlyMode()) {
1690
- this._cachedNodes = nodes;
1691
- }
1692
- return nodes;
1693
- }
1694
- getTextContent() {
1695
- const nodes = this.getNodes().filter(node => $isTableCellNode(node));
1696
- let textContent = '';
1697
- for (let i = 0; i < nodes.length; i++) {
1698
- const node = nodes[i];
1699
- const row = node.__parent;
1700
- const nextRow = (nodes[i + 1] || {}).__parent;
1701
- textContent += node.getTextContent() + (nextRow !== row ? '\n' : '\t');
1702
- }
1703
- return textContent;
1704
- }
1705
- }
1706
- function $isTableSelection(x) {
1707
- return x instanceof TableSelection;
1708
- }
1709
- function $createTableSelection() {
1710
- // TODO this is a suboptimal design, it doesn't make sense to have
1711
- // a table selection that isn't associated with a table. This
1712
- // constructor should have required arguments and in true we
1713
- // should check that they point to a table and are element points to
1714
- // cell nodes of that table.
1715
- const anchor = $createPoint('root', 0, 'element');
1716
- const focus = $createPoint('root', 0, 'element');
1717
- return new TableSelection('root', anchor, focus);
1718
- }
1719
- function $createTableSelectionFrom(tableNode, anchorCell, focusCell) {
1720
- const tableNodeKey = tableNode.getKey();
1721
- const anchorCellKey = anchorCell.getKey();
1722
- const focusCellKey = focusCell.getKey();
1723
- {
1724
- if (!tableNode.isAttached()) {
1725
- formatDevErrorMessage(`$createTableSelectionFrom: tableNode ${tableNodeKey} is not attached`);
1726
- }
1727
- if (!tableNode.is($findTableNode(anchorCell))) {
1728
- formatDevErrorMessage(`$createTableSelectionFrom: anchorCell ${anchorCellKey} is not in table ${tableNodeKey}`);
1729
- }
1730
- if (!tableNode.is($findTableNode(focusCell))) {
1731
- formatDevErrorMessage(`$createTableSelectionFrom: focusCell ${focusCellKey} is not in table ${tableNodeKey}`);
1732
- } // TODO: Check for rectangular grid
1733
- }
1734
- const prevSelection = $getSelection();
1735
- const nextSelection = $isTableSelection(prevSelection) ? prevSelection.clone() : $createTableSelection();
1736
- nextSelection.set(tableNode.getKey(), anchorCell.getKey(), focusCell.getKey());
1737
- return nextSelection;
1738
- }
1739
-
1740
- /**
1741
- * Depth first visitor
1742
- * @param node The starting node
1743
- * @param $visit The function to call for each node. If the function returns false, then children of this node will not be explored
1744
- */
1745
- function $visitRecursively(node, $visit) {
1746
- const stack = [[node]];
1747
- for (let currentArray = stack.at(-1); currentArray !== undefined && stack.length > 0; currentArray = stack.at(-1)) {
1748
- const currentNode = currentArray.pop();
1749
- if (currentNode === undefined) {
1750
- stack.pop();
1751
- } else if ($visit(currentNode) !== false && $isElementNode(currentNode)) {
1752
- stack.push(currentNode.getChildren());
1753
- }
1754
- }
1755
- }
1756
-
1757
- function $getTableAndElementByKey(tableNodeKey, editor = $getEditor()) {
1758
- const tableNode = $getNodeByKey(tableNodeKey);
1759
- if (!$isTableNode(tableNode)) {
1760
- formatDevErrorMessage(`TableObserver: Expected tableNodeKey ${tableNodeKey} to be a TableNode`);
1761
- }
1762
- const tableElement = getTableElement(tableNode, editor.getElementByKey(tableNodeKey));
1763
- if (!(tableElement !== null)) {
1764
- formatDevErrorMessage(`TableObserver: Expected to find TableElement in DOM for key ${tableNodeKey}`);
1765
- }
1766
- return {
1767
- tableElement,
1768
- tableNode
1769
- };
1770
- }
1771
- class TableObserver {
1772
- constructor(editor, tableNodeKey) {
1773
- this.isHighlightingCells = false;
1774
- this.anchorX = -1;
1775
- this.anchorY = -1;
1776
- this.focusX = -1;
1777
- this.focusY = -1;
1778
- this.listenersToRemove = new Set();
1779
- this.tableNodeKey = tableNodeKey;
1780
- this.editor = editor;
1781
- this.table = {
1782
- columns: 0,
1783
- domRows: [],
1784
- rows: 0
1785
- };
1786
- this.tableSelection = null;
1787
- this.anchorCellNodeKey = null;
1788
- this.focusCellNodeKey = null;
1789
- this.anchorCell = null;
1790
- this.focusCell = null;
1791
- this.hasHijackedSelectionStyles = false;
1792
- this.isSelecting = false;
1793
- this.pointerType = null;
1794
- this.shouldCheckSelection = false;
1795
- this.abortController = new AbortController();
1796
- this.listenerOptions = {
1797
- signal: this.abortController.signal
1798
- };
1799
- this.nextFocus = null;
1800
- this.trackTable();
1801
- }
1802
- getTable() {
1803
- return this.table;
1804
- }
1805
- removeListeners() {
1806
- this.abortController.abort('removeListeners');
1807
- Array.from(this.listenersToRemove).forEach(removeListener => removeListener());
1808
- this.listenersToRemove.clear();
1809
- }
1810
- $lookup() {
1811
- return $getTableAndElementByKey(this.tableNodeKey, this.editor);
1812
- }
1813
- trackTable() {
1814
- const observer = new MutationObserver(records => {
1815
- this.editor.getEditorState().read(() => {
1816
- let gridNeedsRedraw = false;
1817
- for (let i = 0; i < records.length; i++) {
1818
- const record = records[i];
1819
- const target = record.target;
1820
- const nodeName = target.nodeName;
1821
- if (nodeName === 'TABLE' || nodeName === 'TBODY' || nodeName === 'THEAD' || nodeName === 'TR') {
1822
- gridNeedsRedraw = true;
1823
- break;
1824
- }
1825
- }
1826
- if (!gridNeedsRedraw) {
1827
- return;
1828
- }
1829
- const {
1830
- tableNode,
1831
- tableElement
1832
- } = this.$lookup();
1833
- this.table = getTable(tableNode, tableElement);
1834
- }, {
1835
- editor: this.editor
1836
- });
1837
- });
1838
- this.editor.getEditorState().read(() => {
1839
- const {
1840
- tableNode,
1841
- tableElement
1842
- } = this.$lookup();
1843
- this.table = getTable(tableNode, tableElement);
1844
- observer.observe(tableElement, {
1845
- attributes: true,
1846
- childList: true,
1847
- subtree: true
1848
- });
1849
- }, {
1850
- editor: this.editor
1851
- });
1852
- }
1853
- $clearHighlight() {
1854
- const editor = this.editor;
1855
- this.isHighlightingCells = false;
1856
- this.anchorX = -1;
1857
- this.anchorY = -1;
1858
- this.focusX = -1;
1859
- this.focusY = -1;
1860
- this.tableSelection = null;
1861
- this.anchorCellNodeKey = null;
1862
- this.focusCellNodeKey = null;
1863
- this.anchorCell = null;
1864
- this.focusCell = null;
1865
- this.hasHijackedSelectionStyles = false;
1866
- this.$enableHighlightStyle();
1867
- const {
1868
- tableNode,
1869
- tableElement
1870
- } = this.$lookup();
1871
- const grid = getTable(tableNode, tableElement);
1872
- $updateDOMForSelection(editor, grid, null);
1873
- if ($getSelection() !== null) {
1874
- $setSelection(null);
1875
- editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);
1876
- }
1877
- }
1878
- $enableHighlightStyle() {
1879
- const editor = this.editor;
1880
- const {
1881
- tableElement
1882
- } = this.$lookup();
1883
- removeClassNamesFromElement(tableElement, editor._config.theme.tableSelection);
1884
- tableElement.classList.remove('disable-selection');
1885
- this.hasHijackedSelectionStyles = false;
1886
- }
1887
- $disableHighlightStyle() {
1888
- const {
1889
- tableElement
1890
- } = this.$lookup();
1891
- addClassNamesToElement(tableElement, this.editor._config.theme.tableSelection);
1892
- this.hasHijackedSelectionStyles = true;
1893
- }
1894
- $updateTableTableSelection(selection) {
1895
- if (selection !== null) {
1896
- if (!(selection.tableKey === this.tableNodeKey)) {
1897
- formatDevErrorMessage(`TableObserver.$updateTableTableSelection: selection.tableKey !== this.tableNodeKey ('${selection.tableKey}' !== '${this.tableNodeKey}')`);
1898
- }
1899
- const editor = this.editor;
1900
- this.tableSelection = selection;
1901
- this.isHighlightingCells = true;
1902
- this.$disableHighlightStyle();
1903
- this.updateDOMSelection();
1904
- $updateDOMForSelection(editor, this.table, this.tableSelection);
1905
- } else {
1906
- this.$clearHighlight();
1907
- }
1908
- }
1909
-
1910
- /**
1911
- * @internal
1912
- * Firefox has a strange behavior where pressing the down arrow key from
1913
- * above the table will move the caret after the table and then lexical
1914
- * will select the last cell instead of the first.
1915
- * We do still want to let the browser handle caret movement but we will
1916
- * use this property to "tag" the update so that we can recheck the
1917
- * selection after the event is processed.
1918
- */
1919
- setShouldCheckSelection() {
1920
- this.shouldCheckSelection = true;
1921
- }
1922
- /**
1923
- * @internal
1924
- */
1925
- getAndClearShouldCheckSelection() {
1926
- if (this.shouldCheckSelection) {
1927
- this.shouldCheckSelection = false;
1928
- return true;
1929
- }
1930
- return false;
1931
- }
1932
-
1933
- /**
1934
- * @internal
1935
- * When handling mousemove events we track what the focus cell should be, but
1936
- * the DOM selection may end up somewhere else entirely. We don't have an elegant
1937
- * way to handle this after the DOM selection has been resolved in a
1938
- * SELECTION_CHANGE_COMMAND callback.
1939
- */
1940
- setNextFocus(nextFocus) {
1941
- this.nextFocus = nextFocus;
1942
- }
1943
-
1944
- /** @internal */
1945
- getAndClearNextFocus() {
1946
- const {
1947
- nextFocus
1948
- } = this;
1949
- if (nextFocus !== null) {
1950
- this.nextFocus = null;
1951
- }
1952
- return nextFocus;
1953
- }
1954
-
1955
- /** @internal */
1956
- updateDOMSelection() {
1957
- if (this.anchorCell !== null && this.focusCell !== null) {
1958
- const domSelection = getDOMSelection(this.editor._window);
1959
- // We are not using a native selection for tables, and if we
1960
- // set one then the reconciler will undo it.
1961
- // TODO - it would make sense to have one so that native
1962
- // copy/paste worked. Right now we have to emulate with
1963
- // keyboard events but it won't fire if triggered from the menu
1964
- if (domSelection && domSelection.rangeCount > 0) {
1965
- domSelection.removeAllRanges();
1966
- }
1967
- }
1968
- }
1969
- $setFocusCellForSelection(cell, ignoreStart = false) {
1970
- const editor = this.editor;
1971
- const {
1972
- tableNode
1973
- } = this.$lookup();
1974
- const cellX = cell.x;
1975
- const cellY = cell.y;
1976
- this.focusCell = cell;
1977
- if (!this.isHighlightingCells && (this.anchorX !== cellX || this.anchorY !== cellY || ignoreStart)) {
1978
- this.isHighlightingCells = true;
1979
- this.$disableHighlightStyle();
1980
- } else if (cellX === this.focusX && cellY === this.focusY) {
1981
- return false;
1982
- }
1983
- this.focusX = cellX;
1984
- this.focusY = cellY;
1985
- if (this.isHighlightingCells) {
1986
- const focusTableCellNode = $getNearestTableCellInTableFromDOMNode(tableNode, cell.elem);
1987
- if (this.tableSelection != null && this.anchorCellNodeKey != null && focusTableCellNode !== null) {
1988
- this.focusCellNodeKey = focusTableCellNode.getKey();
1989
- this.tableSelection = $createTableSelectionFrom(tableNode, this.$getAnchorTableCellOrThrow(), focusTableCellNode);
1990
- $setSelection(this.tableSelection);
1991
- editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);
1992
- $updateDOMForSelection(editor, this.table, this.tableSelection);
1993
- return true;
1994
- }
1995
- }
1996
- return false;
1997
- }
1998
- $getAnchorTableCell() {
1999
- return this.anchorCellNodeKey ? $getNodeByKey(this.anchorCellNodeKey) : null;
2000
- }
2001
- $getAnchorTableCellOrThrow() {
2002
- const anchorTableCell = this.$getAnchorTableCell();
2003
- if (!(anchorTableCell !== null)) {
2004
- formatDevErrorMessage(`TableObserver anchorTableCell is null`);
2005
- }
2006
- return anchorTableCell;
2007
- }
2008
- $getFocusTableCell() {
2009
- return this.focusCellNodeKey ? $getNodeByKey(this.focusCellNodeKey) : null;
2010
- }
2011
- $getFocusTableCellOrThrow() {
2012
- const focusTableCell = this.$getFocusTableCell();
2013
- if (!(focusTableCell !== null)) {
2014
- formatDevErrorMessage(`TableObserver focusTableCell is null`);
2015
- }
2016
- return focusTableCell;
2017
- }
2018
- $setAnchorCellForSelection(cell) {
2019
- this.isHighlightingCells = false;
2020
- this.anchorCell = cell;
2021
- this.anchorX = cell.x;
2022
- this.anchorY = cell.y;
2023
- const {
2024
- tableNode
2025
- } = this.$lookup();
2026
- const anchorTableCellNode = $getNearestTableCellInTableFromDOMNode(tableNode, cell.elem);
2027
- if (anchorTableCellNode !== null) {
2028
- const anchorNodeKey = anchorTableCellNode.getKey();
2029
- this.tableSelection = this.tableSelection != null ? this.tableSelection.clone() : $createTableSelection();
2030
- this.anchorCellNodeKey = anchorNodeKey;
2031
- }
2032
- }
2033
- $formatCells(type) {
2034
- const selection = $getSelection();
2035
- if (!$isTableSelection(selection)) {
2036
- formatDevErrorMessage(`Expected Table selection`);
2037
- }
2038
- const formatSelection = $createRangeSelection();
2039
- const anchor = formatSelection.anchor;
2040
- const focus = formatSelection.focus;
2041
- const cellNodes = selection.getNodes().filter($isTableCellNode);
2042
- if (!(cellNodes.length > 0)) {
2043
- formatDevErrorMessage(`No table cells present`);
2044
- }
2045
- const paragraph = cellNodes[0].getFirstChild();
2046
- const alignFormatWith = $isParagraphNode(paragraph) ? paragraph.getFormatFlags(type, null) : null;
2047
- cellNodes.forEach(cellNode => {
2048
- anchor.set(cellNode.getKey(), 0, 'element');
2049
- focus.set(cellNode.getKey(), cellNode.getChildrenSize(), 'element');
2050
- formatSelection.formatText(type, alignFormatWith);
2051
- });
2052
- $setSelection(selection);
2053
- this.editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);
2054
- }
2055
- $clearText() {
2056
- const {
2057
- editor
2058
- } = this;
2059
- const tableNode = $getNodeByKey(this.tableNodeKey);
2060
- if (!$isTableNode(tableNode)) {
2061
- throw new Error('Expected TableNode.');
2062
- }
2063
- const selection = $getSelection();
2064
- if (!$isTableSelection(selection)) {
2065
- formatDevErrorMessage(`Expected TableSelection`);
2066
- }
2067
- const selectedNodes = selection.getNodes().filter($isTableCellNode);
2068
-
2069
- // Check if the entire table is selected by verifying first and last cells
2070
- const firstRow = tableNode.getFirstChild();
2071
- const lastRow = tableNode.getLastChild();
2072
- const isEntireTableSelected = selectedNodes.length > 0 && firstRow !== null && lastRow !== null && $isTableRowNode(firstRow) && $isTableRowNode(lastRow) && selectedNodes[0] === firstRow.getFirstChild() && selectedNodes[selectedNodes.length - 1] === lastRow.getLastChild();
2073
- if (isEntireTableSelected) {
2074
- tableNode.selectPrevious();
2075
- const parent = tableNode.getParent();
2076
- // Delete entire table
2077
- tableNode.remove();
2078
- // Handle case when table was the only node
2079
- if ($isRootNode(parent) && parent.isEmpty()) {
2080
- editor.dispatchCommand(INSERT_PARAGRAPH_COMMAND, undefined);
2081
- }
2082
- return;
2083
- }
2084
- selectedNodes.forEach(cellNode => {
2085
- if ($isElementNode(cellNode)) {
2086
- const paragraphNode = $createParagraphNode();
2087
- const textNode = $createTextNode();
2088
- paragraphNode.append(textNode);
2089
- cellNode.append(paragraphNode);
2090
- cellNode.getChildren().forEach(child => {
2091
- if (child !== paragraphNode) {
2092
- child.remove();
2093
- }
2094
- });
2095
- }
2096
- });
2097
- $updateDOMForSelection(editor, this.table, null);
2098
- $setSelection(null);
2099
- editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);
2100
- }
2101
- }
2102
-
2103
- const LEXICAL_ELEMENT_KEY = '__lexicalTableSelection';
2104
- const isPointerDownOnEvent = event => {
2105
- return (event.buttons & 1) === 1;
2106
- };
2107
- function isHTMLTableElement(el) {
2108
- return isHTMLElement(el) && el.nodeName === 'TABLE';
2109
- }
2110
- function getTableElement(tableNode, dom) {
2111
- if (!dom) {
2112
- return dom;
2113
- }
2114
- const element = isHTMLTableElement(dom) ? dom : tableNode.getDOMSlot(dom).element;
2115
- if (!(element.nodeName === 'TABLE')) {
2116
- formatDevErrorMessage(`getTableElement: Expecting table in as DOM node for TableNode, not ${dom.nodeName}`);
2117
- }
2118
- return element;
2119
- }
2120
- function getEditorWindow(editor) {
2121
- return editor._window;
2122
- }
2123
- function $findParentTableCellNodeInTable(tableNode, node) {
2124
- for (let currentNode = node, lastTableCellNode = null; currentNode !== null; currentNode = currentNode.getParent()) {
2125
- if (tableNode.is(currentNode)) {
2126
- return lastTableCellNode;
2127
- } else if ($isTableCellNode(currentNode)) {
2128
- lastTableCellNode = currentNode;
2129
- }
2130
- }
2131
- return null;
2132
- }
2133
- const ARROW_KEY_COMMANDS_WITH_DIRECTION = [[KEY_ARROW_DOWN_COMMAND, 'down'], [KEY_ARROW_UP_COMMAND, 'up'], [KEY_ARROW_LEFT_COMMAND, 'backward'], [KEY_ARROW_RIGHT_COMMAND, 'forward']];
2134
- const DELETE_TEXT_COMMANDS = [DELETE_WORD_COMMAND, DELETE_LINE_COMMAND, DELETE_CHARACTER_COMMAND];
2135
- const DELETE_KEY_COMMANDS = [KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND];
2136
- function applyTableHandlers(tableNode, element, editor, hasTabHandler) {
2137
- const rootElement = editor.getRootElement();
2138
- const editorWindow = getEditorWindow(editor);
2139
- if (!(rootElement !== null && editorWindow !== null)) {
2140
- formatDevErrorMessage(`applyTableHandlers: editor has no root element set`);
2141
- }
2142
- const tableObserver = new TableObserver(editor, tableNode.getKey());
2143
- const tableElement = getTableElement(tableNode, element);
2144
- attachTableObserverToTableElement(tableElement, tableObserver);
2145
- tableObserver.listenersToRemove.add(() => detachTableObserverFromTableElement(tableElement, tableObserver));
2146
- const createPointerHandlers = () => {
2147
- if (tableObserver.isSelecting) {
2148
- return;
2149
- }
2150
- const onPointerUp = () => {
2151
- tableObserver.isSelecting = false;
2152
- editorWindow.removeEventListener('pointerup', onPointerUp);
2153
- editorWindow.removeEventListener('pointermove', onPointerMove);
2154
- };
2155
- const onPointerMove = moveEvent => {
2156
- if (!isPointerDownOnEvent(moveEvent) && tableObserver.isSelecting) {
2157
- tableObserver.isSelecting = false;
2158
- editorWindow.removeEventListener('pointerup', onPointerUp);
2159
- editorWindow.removeEventListener('pointermove', onPointerMove);
2160
- return;
2161
- }
2162
- if (!isDOMNode(moveEvent.target)) {
2163
- return;
2164
- }
2165
- let focusCell = null;
2166
- // In firefox the moveEvent.target may be captured so we must always
2167
- // consult the coordinates #7245
2168
- const override = !(IS_FIREFOX || tableElement.contains(moveEvent.target));
2169
- if (override) {
2170
- focusCell = getDOMCellInTableFromTarget(tableElement, moveEvent.target);
2171
- } else {
2172
- for (const el of document.elementsFromPoint(moveEvent.clientX, moveEvent.clientY)) {
2173
- focusCell = getDOMCellInTableFromTarget(tableElement, el);
2174
- if (focusCell) {
2175
- break;
2176
- }
2177
- }
2178
- }
2179
- if (focusCell && (tableObserver.focusCell === null || focusCell.elem !== tableObserver.focusCell.elem)) {
2180
- tableObserver.setNextFocus({
2181
- focusCell,
2182
- override
2183
- });
2184
- editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);
2185
- }
2186
- };
2187
- tableObserver.isSelecting = true;
2188
- editorWindow.addEventListener('pointerup', onPointerUp, tableObserver.listenerOptions);
2189
- editorWindow.addEventListener('pointermove', onPointerMove, tableObserver.listenerOptions);
2190
- };
2191
- const onPointerDown = event => {
2192
- tableObserver.pointerType = event.pointerType;
2193
- if (event.button !== 0 || !isDOMNode(event.target) || !editorWindow) {
2194
- return;
2195
- }
2196
- const targetCell = getDOMCellFromTarget(event.target);
2197
- if (targetCell !== null) {
2198
- editor.update(() => {
2199
- const prevSelection = $getPreviousSelection();
2200
- // We can't trust Firefox to do the right thing with the selection and
2201
- // we don't have a proper state machine to do this "correctly" but
2202
- // if we go ahead and make the table selection now it will work
2203
- if (IS_FIREFOX && event.shiftKey && $isSelectionInTable(prevSelection, tableNode) && ($isRangeSelection(prevSelection) || $isTableSelection(prevSelection))) {
2204
- const prevAnchorNode = prevSelection.anchor.getNode();
2205
- const prevAnchorCell = $findParentTableCellNodeInTable(tableNode, prevSelection.anchor.getNode());
2206
- if (prevAnchorCell) {
2207
- tableObserver.$setAnchorCellForSelection($getObserverCellFromCellNodeOrThrow(tableObserver, prevAnchorCell));
2208
- tableObserver.$setFocusCellForSelection(targetCell);
2209
- stopEvent(event);
2210
- } else {
2211
- const newSelection = tableNode.isBefore(prevAnchorNode) ? tableNode.selectStart() : tableNode.selectEnd();
2212
- newSelection.anchor.set(prevSelection.anchor.key, prevSelection.anchor.offset, prevSelection.anchor.type);
2213
- }
2214
- } else {
2215
- // Only set anchor cell for selection if this is not a simple touch tap
2216
- // Touch taps should not initiate table selection mode
2217
- if (event.pointerType !== 'touch') {
2218
- tableObserver.$setAnchorCellForSelection(targetCell);
2219
- }
2220
- }
2221
- });
2222
- }
2223
- createPointerHandlers();
2224
- };
2225
- tableElement.addEventListener('pointerdown', onPointerDown, tableObserver.listenerOptions);
2226
- tableObserver.listenersToRemove.add(() => {
2227
- tableElement.removeEventListener('pointerdown', onPointerDown);
2228
- });
2229
- const onTripleClick = event => {
2230
- if (event.detail >= 3 && isDOMNode(event.target)) {
2231
- const targetCell = getDOMCellFromTarget(event.target);
2232
- if (targetCell !== null) {
2233
- event.preventDefault();
2234
- }
2235
- }
2236
- };
2237
- tableElement.addEventListener('mousedown', onTripleClick, tableObserver.listenerOptions);
2238
- tableObserver.listenersToRemove.add(() => {
2239
- tableElement.removeEventListener('mousedown', onTripleClick);
2240
- });
2241
-
2242
- // Clear selection when clicking outside of dom.
2243
- const pointerDownCallback = event => {
2244
- const target = event.target;
2245
- if (event.button !== 0 || !isDOMNode(target)) {
2246
- return;
2247
- }
2248
- editor.update(() => {
2249
- const selection = $getSelection();
2250
- if ($isTableSelection(selection) && selection.tableKey === tableObserver.tableNodeKey && rootElement.contains(target)) {
2251
- tableObserver.$clearHighlight();
2252
- }
2253
- });
2254
- };
2255
- editorWindow.addEventListener('pointerdown', pointerDownCallback, tableObserver.listenerOptions);
2256
- tableObserver.listenersToRemove.add(() => {
2257
- editorWindow.removeEventListener('pointerdown', pointerDownCallback);
2258
- });
2259
- for (const [command, direction] of ARROW_KEY_COMMANDS_WITH_DIRECTION) {
2260
- tableObserver.listenersToRemove.add(editor.registerCommand(command, event => $handleArrowKey(editor, event, direction, tableNode, tableObserver), COMMAND_PRIORITY_HIGH));
2261
- }
2262
- tableObserver.listenersToRemove.add(editor.registerCommand(KEY_ESCAPE_COMMAND, event => {
2263
- const selection = $getSelection();
2264
- if ($isTableSelection(selection)) {
2265
- const focusCellNode = $findParentTableCellNodeInTable(tableNode, selection.focus.getNode());
2266
- if (focusCellNode !== null) {
2267
- stopEvent(event);
2268
- focusCellNode.selectEnd();
2269
- return true;
2270
- }
2271
- }
2272
- return false;
2273
- }, COMMAND_PRIORITY_HIGH));
2274
- const deleteTextHandler = command => () => {
2275
- const selection = $getSelection();
2276
- if (!$isSelectionInTable(selection, tableNode)) {
2277
- return false;
2278
- }
2279
- if ($isTableSelection(selection)) {
2280
- tableObserver.$clearText();
2281
- return true;
2282
- } else if ($isRangeSelection(selection)) {
2283
- const tableCellNode = $findParentTableCellNodeInTable(tableNode, selection.anchor.getNode());
2284
- if (!$isTableCellNode(tableCellNode)) {
2285
- return false;
2286
- }
2287
- const anchorNode = selection.anchor.getNode();
2288
- const focusNode = selection.focus.getNode();
2289
- const isAnchorInside = tableNode.isParentOf(anchorNode);
2290
- const isFocusInside = tableNode.isParentOf(focusNode);
2291
- const selectionContainsPartialTable = isAnchorInside && !isFocusInside || isFocusInside && !isAnchorInside;
2292
- if (selectionContainsPartialTable) {
2293
- tableObserver.$clearText();
2294
- return true;
2295
- }
2296
- const nearestElementNode = $findMatchingParent(selection.anchor.getNode(), n => $isElementNode(n));
2297
- const topLevelCellElementNode = nearestElementNode && $findMatchingParent(nearestElementNode, n => $isElementNode(n) && $isTableCellNode(n.getParent()));
2298
- if (!$isElementNode(topLevelCellElementNode) || !$isElementNode(nearestElementNode)) {
2299
- return false;
2300
- }
2301
- if (command === DELETE_LINE_COMMAND && topLevelCellElementNode.getPreviousSibling() === null) {
2302
- // TODO: Fix Delete Line in Table Cells.
2303
- return true;
2304
- }
2305
- }
2306
- return false;
2307
- };
2308
- for (const command of DELETE_TEXT_COMMANDS) {
2309
- tableObserver.listenersToRemove.add(editor.registerCommand(command, deleteTextHandler(command), COMMAND_PRIORITY_CRITICAL));
2310
- }
2311
- const $deleteCellHandler = event => {
2312
- const selection = $getSelection();
2313
- if (!($isTableSelection(selection) || $isRangeSelection(selection))) {
2314
- return false;
2315
- }
2316
-
2317
- // If the selection is inside the table but should remove the whole table
2318
- // we expand the selection so that both the anchor and focus are outside
2319
- // the table and the editor's command listener will handle the delete
2320
- const isAnchorInside = tableNode.isParentOf(selection.anchor.getNode());
2321
- const isFocusInside = tableNode.isParentOf(selection.focus.getNode());
2322
- if (isAnchorInside !== isFocusInside) {
2323
- const tablePoint = isAnchorInside ? 'anchor' : 'focus';
2324
- const outerPoint = isAnchorInside ? 'focus' : 'anchor';
2325
- // Preserve the outer point
2326
- const {
2327
- key,
2328
- offset,
2329
- type
2330
- } = selection[outerPoint];
2331
- // Expand the selection around the table
2332
- const newSelection = tableNode[selection[tablePoint].isBefore(selection[outerPoint]) ? 'selectPrevious' : 'selectNext']();
2333
- // Restore the outer point of the selection
2334
- newSelection[outerPoint].set(key, offset, type);
2335
- // Let the base implementation handle the rest
2336
- return false;
2337
- }
2338
- if (!$isSelectionInTable(selection, tableNode)) {
2339
- return false;
2340
- }
2341
- if ($isTableSelection(selection)) {
2342
- if (event) {
2343
- event.preventDefault();
2344
- event.stopPropagation();
2345
- }
2346
- tableObserver.$clearText();
2347
- return true;
2348
- }
2349
- return false;
2350
- };
2351
- for (const command of DELETE_KEY_COMMANDS) {
2352
- tableObserver.listenersToRemove.add(editor.registerCommand(command, $deleteCellHandler, COMMAND_PRIORITY_CRITICAL));
2353
- }
2354
- tableObserver.listenersToRemove.add(editor.registerCommand(CUT_COMMAND, event => {
2355
- const selection = $getSelection();
2356
- if (selection) {
2357
- if (!($isTableSelection(selection) || $isRangeSelection(selection))) {
2358
- return false;
2359
- }
2360
- // Copying to the clipboard is async so we must capture the data
2361
- // before we delete it
2362
- void copyToClipboard(editor, objectKlassEquals(event, ClipboardEvent) ? event : null, $getClipboardDataFromSelection(selection));
2363
- const intercepted = $deleteCellHandler(event);
2364
- if ($isRangeSelection(selection)) {
2365
- selection.removeText();
2366
- return true;
2367
- }
2368
- return intercepted;
2369
- }
2370
- return false;
2371
- }, COMMAND_PRIORITY_CRITICAL));
2372
- tableObserver.listenersToRemove.add(editor.registerCommand(FORMAT_TEXT_COMMAND, payload => {
2373
- const selection = $getSelection();
2374
- if (!$isSelectionInTable(selection, tableNode)) {
2375
- return false;
2376
- }
2377
- if ($isTableSelection(selection)) {
2378
- tableObserver.$formatCells(payload);
2379
- return true;
2380
- } else if ($isRangeSelection(selection)) {
2381
- const tableCellNode = $findMatchingParent(selection.anchor.getNode(), n => $isTableCellNode(n));
2382
- if (!$isTableCellNode(tableCellNode)) {
2383
- return false;
2384
- }
2385
- }
2386
- return false;
2387
- }, COMMAND_PRIORITY_CRITICAL));
2388
- tableObserver.listenersToRemove.add(editor.registerCommand(FORMAT_ELEMENT_COMMAND, formatType => {
2389
- const selection = $getSelection();
2390
- if (!$isTableSelection(selection) || !$isSelectionInTable(selection, tableNode)) {
2391
- return false;
2392
- }
2393
- const anchorNode = selection.anchor.getNode();
2394
- const focusNode = selection.focus.getNode();
2395
- if (!$isTableCellNode(anchorNode) || !$isTableCellNode(focusNode)) {
2396
- return false;
2397
- }
2398
-
2399
- // Align the table if the entire table is selected
2400
- if ($isFullTableSelection(selection, tableNode)) {
2401
- tableNode.setFormat(formatType);
2402
- return true;
2403
- }
2404
- const [tableMap, anchorCell, focusCell] = $computeTableMap(tableNode, anchorNode, focusNode);
2405
- const maxRow = Math.max(anchorCell.startRow + anchorCell.cell.__rowSpan - 1, focusCell.startRow + focusCell.cell.__rowSpan - 1);
2406
- const maxColumn = Math.max(anchorCell.startColumn + anchorCell.cell.__colSpan - 1, focusCell.startColumn + focusCell.cell.__colSpan - 1);
2407
- const minRow = Math.min(anchorCell.startRow, focusCell.startRow);
2408
- const minColumn = Math.min(anchorCell.startColumn, focusCell.startColumn);
2409
- const visited = new Set();
2410
- for (let i = minRow; i <= maxRow; i++) {
2411
- for (let j = minColumn; j <= maxColumn; j++) {
2412
- const cell = tableMap[i][j].cell;
2413
- if (visited.has(cell)) {
2414
- continue;
2415
- }
2416
- visited.add(cell);
2417
- cell.setFormat(formatType);
2418
- const cellChildren = cell.getChildren();
2419
- for (let k = 0; k < cellChildren.length; k++) {
2420
- const child = cellChildren[k];
2421
- if ($isElementNode(child) && !child.isInline()) {
2422
- child.setFormat(formatType);
2423
- }
2424
- }
2425
- }
2426
- }
2427
- return true;
2428
- }, COMMAND_PRIORITY_CRITICAL));
2429
- tableObserver.listenersToRemove.add(editor.registerCommand(CONTROLLED_TEXT_INSERTION_COMMAND, payload => {
2430
- const selection = $getSelection();
2431
- if (!$isSelectionInTable(selection, tableNode)) {
2432
- return false;
2433
- }
2434
- if ($isTableSelection(selection)) {
2435
- tableObserver.$clearHighlight();
2436
- return false;
2437
- } else if ($isRangeSelection(selection)) {
2438
- const tableCellNode = $findMatchingParent(selection.anchor.getNode(), n => $isTableCellNode(n));
2439
- if (!$isTableCellNode(tableCellNode)) {
2440
- return false;
2441
- }
2442
- if (typeof payload === 'string') {
2443
- const edgePosition = $getTableEdgeCursorPosition(editor, selection, tableNode);
2444
- if (edgePosition) {
2445
- $insertParagraphAtTableEdge(edgePosition, tableNode, [$createTextNode(payload)]);
2446
- return true;
2447
- }
2448
- }
2449
- }
2450
- return false;
2451
- }, COMMAND_PRIORITY_CRITICAL));
2452
- if (hasTabHandler) {
2453
- tableObserver.listenersToRemove.add(editor.registerCommand(KEY_TAB_COMMAND, event => {
2454
- const selection = $getSelection();
2455
- if (!$isRangeSelection(selection) || !selection.isCollapsed() || !$isSelectionInTable(selection, tableNode)) {
2456
- return false;
2457
- }
2458
- const tableCellNode = $findCellNode(selection.anchor.getNode());
2459
- if (tableCellNode === null || !tableNode.is($findTableNode(tableCellNode))) {
2460
- return false;
2461
- }
2462
- stopEvent(event);
2463
- $selectAdjacentCell(tableCellNode, event.shiftKey ? 'previous' : 'next');
2464
- return true;
2465
- }, COMMAND_PRIORITY_CRITICAL));
2466
- }
2467
- tableObserver.listenersToRemove.add(editor.registerCommand(FOCUS_COMMAND, payload => {
2468
- return tableNode.isSelected();
2469
- }, COMMAND_PRIORITY_HIGH));
2470
- tableObserver.listenersToRemove.add(editor.registerCommand(SELECTION_INSERT_CLIPBOARD_NODES_COMMAND, (selectionPayload, dispatchEditor) => {
2471
- if (editor !== dispatchEditor) {
2472
- return false;
2473
- }
2474
- const {
2475
- nodes,
2476
- selection
2477
- } = selectionPayload;
2478
- const anchorAndFocus = selection.getStartEndPoints();
2479
- const isTableSelection = $isTableSelection(selection);
2480
- const isRangeSelection = $isRangeSelection(selection);
2481
- const isSelectionInsideOfGrid = isRangeSelection && $findMatchingParent(selection.anchor.getNode(), n => $isTableCellNode(n)) !== null && $findMatchingParent(selection.focus.getNode(), n => $isTableCellNode(n)) !== null || isTableSelection;
2482
- if (nodes.length !== 1 || !$isTableNode(nodes[0]) || !isSelectionInsideOfGrid || anchorAndFocus === null) {
2483
- return false;
2484
- }
2485
- const [anchor, focus] = anchorAndFocus;
2486
- const [anchorCellNode, anchorRowNode, gridNode] = $getNodeTriplet(anchor);
2487
- const focusCellNode = $findMatchingParent(focus.getNode(), n => $isTableCellNode(n));
2488
- if (!$isTableCellNode(anchorCellNode) || !$isTableCellNode(focusCellNode) || !$isTableRowNode(anchorRowNode) || !$isTableNode(gridNode)) {
2489
- return false;
2490
- }
2491
- const templateGrid = nodes[0];
2492
- const [initialGridMap, anchorCellMap, focusCellMap] = $computeTableMap(gridNode, anchorCellNode, focusCellNode);
2493
- const [templateGridMap] = $computeTableMapSkipCellCheck(templateGrid, null, null);
2494
- const initialRowCount = initialGridMap.length;
2495
- const initialColCount = initialRowCount > 0 ? initialGridMap[0].length : 0;
2496
-
2497
- // If we have a range selection, we'll fit the template grid into the
2498
- // table, growing the table if necessary.
2499
- let startRow = anchorCellMap.startRow;
2500
- let startCol = anchorCellMap.startColumn;
2501
- let affectedRowCount = templateGridMap.length;
2502
- let affectedColCount = affectedRowCount > 0 ? templateGridMap[0].length : 0;
2503
- if (isTableSelection) {
2504
- // If we have a table selection, we'll only modify the cells within
2505
- // the selection boundary.
2506
- const selectionBoundary = $computeTableCellRectBoundary(initialGridMap, anchorCellMap, focusCellMap);
2507
- const selectionRowCount = selectionBoundary.maxRow - selectionBoundary.minRow + 1;
2508
- const selectionColCount = selectionBoundary.maxColumn - selectionBoundary.minColumn + 1;
2509
- startRow = selectionBoundary.minRow;
2510
- startCol = selectionBoundary.minColumn;
2511
- affectedRowCount = Math.min(affectedRowCount, selectionRowCount);
2512
- affectedColCount = Math.min(affectedColCount, selectionColCount);
2513
- }
2514
-
2515
- // Step 1: Unmerge all merged cells within the affected area
2516
- let didPerformMergeOperations = false;
2517
- const lastRowForUnmerge = Math.min(initialRowCount, startRow + affectedRowCount) - 1;
2518
- const lastColForUnmerge = Math.min(initialColCount, startCol + affectedColCount) - 1;
2519
- const unmergedKeys = new Set();
2520
- for (let row = startRow; row <= lastRowForUnmerge; row++) {
2521
- for (let col = startCol; col <= lastColForUnmerge; col++) {
2522
- const cellMap = initialGridMap[row][col];
2523
- if (unmergedKeys.has(cellMap.cell.getKey())) {
2524
- continue; // cell was a merged cell that was already handled
2525
- }
2526
- if (cellMap.cell.__rowSpan === 1 && cellMap.cell.__colSpan === 1) {
2527
- continue; // cell is not a merged cell
2528
- }
2529
- $unmergeCellNode(cellMap.cell);
2530
- unmergedKeys.add(cellMap.cell.getKey());
2531
- didPerformMergeOperations = true;
2532
- }
2533
- }
2534
- let [interimGridMap] = $computeTableMapSkipCellCheck(gridNode.getWritable(), null, null);
2535
-
2536
- // Step 2: Expand current table (if needed)
2537
- const rowsToInsert = affectedRowCount - initialRowCount + startRow;
2538
- for (let i = 0; i < rowsToInsert; i++) {
2539
- const cellMap = interimGridMap[initialRowCount - 1][0];
2540
- $insertTableRowAtNode(cellMap.cell);
2541
- }
2542
- const colsToInsert = affectedColCount - initialColCount + startCol;
2543
- for (let i = 0; i < colsToInsert; i++) {
2544
- const cellMap = interimGridMap[0][initialColCount - 1];
2545
- $insertTableColumnAtNode(cellMap.cell, true, false);
2546
- }
2547
- [interimGridMap] = $computeTableMapSkipCellCheck(gridNode.getWritable(), null, null);
2548
-
2549
- // Step 3: Merge cells and set cell content, to match template grid
2550
- for (let row = startRow; row < startRow + affectedRowCount; row++) {
2551
- for (let col = startCol; col < startCol + affectedColCount; col++) {
2552
- const templateRow = row - startRow;
2553
- const templateCol = col - startCol;
2554
- const templateCellMap = templateGridMap[templateRow][templateCol];
2555
- if (templateCellMap.startRow !== templateRow || templateCellMap.startColumn !== templateCol) {
2556
- continue; // cell is a merged cell that was already handled
2557
- }
2558
- const templateCell = templateCellMap.cell;
2559
- if (templateCell.__rowSpan !== 1 || templateCell.__colSpan !== 1) {
2560
- const cellsToMerge = [];
2561
- const lastRowForMerge = Math.min(row + templateCell.__rowSpan, startRow + affectedRowCount) - 1;
2562
- const lastColForMerge = Math.min(col + templateCell.__colSpan, startCol + affectedColCount) - 1;
2563
- for (let r = row; r <= lastRowForMerge; r++) {
2564
- for (let c = col; c <= lastColForMerge; c++) {
2565
- const cellMap = interimGridMap[r][c];
2566
- cellsToMerge.push(cellMap.cell);
2567
- }
2568
- }
2569
- $mergeCells(cellsToMerge);
2570
- didPerformMergeOperations = true;
2571
- }
2572
- const {
2573
- cell
2574
- } = interimGridMap[row][col];
2575
- const originalChildren = cell.getChildren();
2576
- templateCell.getChildren().forEach(child => {
2577
- if ($isTextNode(child)) {
2578
- const paragraphNode = $createParagraphNode();
2579
- paragraphNode.append(child);
2580
- cell.append(child);
2581
- } else {
2582
- cell.append(child);
2583
- }
2584
- });
2585
- originalChildren.forEach(n => n.remove());
2586
- }
2587
- }
2588
- if (isTableSelection && didPerformMergeOperations) {
2589
- // reset the table selection in case the anchor or focus cell was
2590
- // removed via merge operations
2591
- const [finalGridMap] = $computeTableMapSkipCellCheck(gridNode.getWritable(), null, null);
2592
- const newAnchorCellMap = finalGridMap[anchorCellMap.startRow][anchorCellMap.startColumn];
2593
- newAnchorCellMap.cell.selectEnd();
2594
- }
2595
- return true;
2596
- }, COMMAND_PRIORITY_CRITICAL));
2597
- tableObserver.listenersToRemove.add(editor.registerCommand(SELECTION_CHANGE_COMMAND, () => {
2598
- const selection = $getSelection();
2599
- const prevSelection = $getPreviousSelection();
2600
- const nextFocus = tableObserver.getAndClearNextFocus();
2601
- if (nextFocus !== null) {
2602
- const {
2603
- focusCell
2604
- } = nextFocus;
2605
- if ($isTableSelection(selection) && selection.tableKey === tableObserver.tableNodeKey) {
2606
- if (focusCell.x === tableObserver.focusX && focusCell.y === tableObserver.focusY) {
2607
- // The selection is already the correct table selection
2608
- return false;
2609
- } else {
2610
- tableObserver.$setFocusCellForSelection(focusCell);
2611
- return true;
2612
- }
2613
- } else if (focusCell !== tableObserver.anchorCell && $isSelectionInTable(selection, tableNode)) {
2614
- // The selection has crossed cells
2615
- tableObserver.$setFocusCellForSelection(focusCell);
2616
- return true;
2617
- }
2618
- }
2619
- const shouldCheckSelection = tableObserver.getAndClearShouldCheckSelection();
2620
- // If they pressed the down arrow with the selection outside of the
2621
- // table, and then the selection ends up in the table but not in the
2622
- // first cell, then move the selection to the first cell.
2623
- if (shouldCheckSelection && $isRangeSelection(prevSelection) && $isRangeSelection(selection) && selection.isCollapsed()) {
2624
- const anchor = selection.anchor.getNode();
2625
- const firstRow = tableNode.getFirstChild();
2626
- const anchorCell = $findCellNode(anchor);
2627
- if (anchorCell !== null && $isTableRowNode(firstRow)) {
2628
- const firstCell = firstRow.getFirstChild();
2629
- if ($isTableCellNode(firstCell) && tableNode.is($findMatchingParent(anchorCell, node => node.is(tableNode) || node.is(firstCell)))) {
2630
- // The selection moved to the table, but not in the first cell
2631
- firstCell.selectStart();
2632
- return true;
2633
- }
2634
- }
2635
- }
2636
- if ($isRangeSelection(selection)) {
2637
- const {
2638
- anchor,
2639
- focus
2640
- } = selection;
2641
- const anchorNode = anchor.getNode();
2642
- const focusNode = focus.getNode();
2643
- // Using explicit comparison with table node to ensure it's not a nested table
2644
- // as in that case we'll leave selection resolving to that table
2645
- const anchorCellNode = $findCellNode(anchorNode);
2646
- const focusCellNode = $findCellNode(focusNode);
2647
- const isAnchorInside = !!(anchorCellNode && tableNode.is($findTableNode(anchorCellNode)));
2648
- const isFocusInside = !!(focusCellNode && tableNode.is($findTableNode(focusCellNode)));
2649
- const isPartiallyWithinTable = isAnchorInside !== isFocusInside;
2650
- const isWithinTable = isAnchorInside && isFocusInside;
2651
- const isBackward = selection.isBackward();
2652
- if (isPartiallyWithinTable) {
2653
- const newSelection = selection.clone();
2654
- if (isFocusInside) {
2655
- const [tableMap] = $computeTableMap(tableNode, focusCellNode, focusCellNode);
2656
- const firstCell = tableMap[0][0].cell;
2657
- const lastCell = tableMap[tableMap.length - 1].at(-1).cell;
2658
- newSelection.focus.set(isBackward ? firstCell.getKey() : lastCell.getKey(), isBackward ? firstCell.getChildrenSize() : lastCell.getChildrenSize(), 'element');
2659
- } else if (isAnchorInside) {
2660
- const [tableMap] = $computeTableMap(tableNode, anchorCellNode, anchorCellNode);
2661
- const firstCell = tableMap[0][0].cell;
2662
- const lastCell = tableMap[tableMap.length - 1].at(-1).cell;
2663
- /**
2664
- * If isBackward, set the anchor to be at the end of the table so that when the cursor moves outside of
2665
- * the table in the backward direction, the entire table will be selected from its end.
2666
- * Otherwise, if forward, set the anchor to be at the start of the table so that when the focus is dragged
2667
- * outside th end of the table, it will start from the beginning of the table.
2668
- */
2669
- newSelection.anchor.set(isBackward ? lastCell.getKey() : firstCell.getKey(), isBackward ? lastCell.getChildrenSize() : 0, 'element');
2670
- }
2671
- $setSelection(newSelection);
2672
- $addHighlightStyleToTable(editor, tableObserver);
2673
- } else if (isWithinTable) {
2674
- // Handle case when selection spans across multiple cells but still
2675
- // has range selection, then we convert it into table selection
2676
- if (!anchorCellNode.is(focusCellNode)) {
2677
- tableObserver.$setAnchorCellForSelection($getObserverCellFromCellNodeOrThrow(tableObserver, anchorCellNode));
2678
- tableObserver.$setFocusCellForSelection($getObserverCellFromCellNodeOrThrow(tableObserver, focusCellNode), true);
2679
- }
2680
-
2681
- // Handle case when the pointer type is touch and the current and
2682
- // previous selection are collapsed, and the previous anchor and current
2683
- // focus cell nodes are different, then we convert it into table selection
2684
- // However, only do this if the table observer is actively selecting (user dragging)
2685
- // to prevent unwanted selections when simply tapping between cells on mobile
2686
- if (tableObserver.pointerType === 'touch' && tableObserver.isSelecting && selection.isCollapsed() && $isRangeSelection(prevSelection) && prevSelection.isCollapsed()) {
2687
- const prevAnchorCellNode = $findCellNode(prevSelection.anchor.getNode());
2688
- if (prevAnchorCellNode && !prevAnchorCellNode.is(focusCellNode)) {
2689
- tableObserver.$setAnchorCellForSelection($getObserverCellFromCellNodeOrThrow(tableObserver, prevAnchorCellNode));
2690
- tableObserver.$setFocusCellForSelection($getObserverCellFromCellNodeOrThrow(tableObserver, focusCellNode), true);
2691
- tableObserver.pointerType = null;
2692
- }
2693
- }
2694
- }
2695
- } else if (selection && $isTableSelection(selection) && selection.is(prevSelection) && selection.tableKey === tableNode.getKey()) {
2696
- // if selection goes outside of the table we need to change it to Range selection
2697
- const domSelection = getDOMSelection(editorWindow);
2698
- if (domSelection && domSelection.anchorNode && domSelection.focusNode) {
2699
- const focusNode = $getNearestNodeFromDOMNode(domSelection.focusNode);
2700
- const isFocusOutside = focusNode && !tableNode.isParentOf(focusNode);
2701
- const anchorNode = $getNearestNodeFromDOMNode(domSelection.anchorNode);
2702
- const isAnchorInside = anchorNode && tableNode.isParentOf(anchorNode);
2703
- if (isFocusOutside && isAnchorInside && domSelection.rangeCount > 0) {
2704
- const newSelection = $createRangeSelectionFromDom(domSelection, editor);
2705
- if (newSelection) {
2706
- newSelection.anchor.set(tableNode.getKey(), selection.isBackward() ? tableNode.getChildrenSize() : 0, 'element');
2707
- domSelection.removeAllRanges();
2708
- $setSelection(newSelection);
2709
- }
2710
- }
2711
- }
2712
- }
2713
- if (selection && !selection.is(prevSelection) && ($isTableSelection(selection) || $isTableSelection(prevSelection)) && tableObserver.tableSelection && !tableObserver.tableSelection.is(prevSelection)) {
2714
- if ($isTableSelection(selection) && selection.tableKey === tableObserver.tableNodeKey) {
2715
- tableObserver.$updateTableTableSelection(selection);
2716
- } else if (!$isTableSelection(selection) && $isTableSelection(prevSelection) && prevSelection.tableKey === tableObserver.tableNodeKey) {
2717
- tableObserver.$updateTableTableSelection(null);
2718
- }
2719
- return false;
2720
- }
2721
- if (tableObserver.hasHijackedSelectionStyles && !tableNode.isSelected()) {
2722
- $removeHighlightStyleToTable(editor, tableObserver);
2723
- } else if (!tableObserver.hasHijackedSelectionStyles && tableNode.isSelected()) {
2724
- $addHighlightStyleToTable(editor, tableObserver);
2725
- }
2726
- return false;
2727
- }, COMMAND_PRIORITY_CRITICAL));
2728
- tableObserver.listenersToRemove.add(editor.registerCommand(INSERT_PARAGRAPH_COMMAND, () => {
2729
- const selection = $getSelection();
2730
- if (!$isRangeSelection(selection) || !selection.isCollapsed() || !$isSelectionInTable(selection, tableNode)) {
2731
- return false;
2732
- }
2733
- const edgePosition = $getTableEdgeCursorPosition(editor, selection, tableNode);
2734
- if (edgePosition) {
2735
- $insertParagraphAtTableEdge(edgePosition, tableNode);
2736
- return true;
2737
- }
2738
- return false;
2739
- }, COMMAND_PRIORITY_CRITICAL));
2740
- return tableObserver;
2741
- }
2742
- function detachTableObserverFromTableElement(tableElement, tableObserver) {
2743
- if (getTableObserverFromTableElement(tableElement) === tableObserver) {
2744
- delete tableElement[LEXICAL_ELEMENT_KEY];
2745
- }
2746
- }
2747
- function attachTableObserverToTableElement(tableElement, tableObserver) {
2748
- if (!(getTableObserverFromTableElement(tableElement) === null)) {
2749
- formatDevErrorMessage(`tableElement already has an attached TableObserver`);
2750
- }
2751
- tableElement[LEXICAL_ELEMENT_KEY] = tableObserver;
2752
- }
2753
- function getTableObserverFromTableElement(tableElement) {
2754
- return tableElement[LEXICAL_ELEMENT_KEY] || null;
2755
- }
2756
- function getDOMCellFromTarget(node) {
2757
- let currentNode = node;
2758
- while (currentNode != null) {
2759
- const nodeName = currentNode.nodeName;
2760
- if (nodeName === 'TD' || nodeName === 'TH') {
2761
- // @ts-expect-error: internal field
2762
- const cell = currentNode._cell;
2763
- if (cell === undefined) {
2764
- return null;
2765
- }
2766
- return cell;
2767
- }
2768
- currentNode = currentNode.parentNode;
2769
- }
2770
- return null;
2771
- }
2772
- function getDOMCellInTableFromTarget(table, node) {
2773
- if (!table.contains(node)) {
2774
- return null;
2775
- }
2776
- let cell = null;
2777
- for (let currentNode = node; currentNode != null; currentNode = currentNode.parentNode) {
2778
- if (currentNode === table) {
2779
- return cell;
2780
- }
2781
- const nodeName = currentNode.nodeName;
2782
- if (nodeName === 'TD' || nodeName === 'TH') {
2783
- // @ts-expect-error: internal field
2784
- cell = currentNode._cell || null;
2785
- }
2786
- }
2787
- return null;
2788
- }
2789
- function getTable(tableNode, dom) {
2790
- const tableElement = getTableElement(tableNode, dom);
2791
- const domRows = [];
2792
- const grid = {
2793
- columns: 0,
2794
- domRows,
2795
- rows: 0
2796
- };
2797
- let currentNode = tableElement.querySelector('tr');
2798
- let x = 0;
2799
- let y = 0;
2800
- domRows.length = 0;
2801
- while (currentNode != null) {
2802
- const nodeMame = currentNode.nodeName;
2803
- if (nodeMame === 'TD' || nodeMame === 'TH') {
2804
- const elem = currentNode;
2805
- const cell = {
2806
- elem,
2807
- hasBackgroundColor: elem.style.backgroundColor !== '',
2808
- highlighted: false,
2809
- x,
2810
- y
2811
- };
2812
-
2813
- // @ts-expect-error: internal field
2814
- currentNode._cell = cell;
2815
- let row = domRows[y];
2816
- if (row === undefined) {
2817
- row = domRows[y] = [];
2818
- }
2819
- row[x] = cell;
2820
- } else {
2821
- const child = currentNode.firstChild;
2822
- if (child != null) {
2823
- currentNode = child;
2824
- continue;
2825
- }
2826
- }
2827
- const sibling = currentNode.nextSibling;
2828
- if (sibling != null) {
2829
- x++;
2830
- currentNode = sibling;
2831
- continue;
2832
- }
2833
- const parent = currentNode.parentNode;
2834
- if (parent != null) {
2835
- const parentSibling = parent.nextSibling;
2836
- if (parentSibling == null) {
2837
- break;
2838
- }
2839
- y++;
2840
- x = 0;
2841
- currentNode = parentSibling;
2842
- }
2843
- }
2844
- grid.columns = x + 1;
2845
- grid.rows = y + 1;
2846
- return grid;
2847
- }
2848
- function $updateDOMForSelection(editor, table, selection) {
2849
- const selectedCellNodes = new Set(selection ? selection.getNodes() : []);
2850
- $forEachTableCell(table, (cell, lexicalNode) => {
2851
- const elem = cell.elem;
2852
- if (selectedCellNodes.has(lexicalNode)) {
2853
- cell.highlighted = true;
2854
- $addHighlightToDOM(editor, cell);
2855
- } else {
2856
- cell.highlighted = false;
2857
- $removeHighlightFromDOM(editor, cell);
2858
- if (!elem.getAttribute('style')) {
2859
- elem.removeAttribute('style');
2860
- }
2861
- }
2862
- });
2863
- }
2864
- function $forEachTableCell(grid, cb) {
2865
- const {
2866
- domRows
2867
- } = grid;
2868
- for (let y = 0; y < domRows.length; y++) {
2869
- const row = domRows[y];
2870
- if (!row) {
2871
- continue;
2872
- }
2873
- for (let x = 0; x < row.length; x++) {
2874
- const cell = row[x];
2875
- if (!cell) {
2876
- continue;
2877
- }
2878
- const lexicalNode = $getNearestNodeFromDOMNode(cell.elem);
2879
- if (lexicalNode !== null) {
2880
- cb(cell, lexicalNode, {
2881
- x,
2882
- y
2883
- });
2884
- }
2885
- }
2886
- }
2887
- }
2888
- function $addHighlightStyleToTable(editor, tableSelection) {
2889
- tableSelection.$disableHighlightStyle();
2890
- $forEachTableCell(tableSelection.table, cell => {
2891
- cell.highlighted = true;
2892
- $addHighlightToDOM(editor, cell);
2893
- });
2894
- }
2895
- function $removeHighlightStyleToTable(editor, tableObserver) {
2896
- tableObserver.$enableHighlightStyle();
2897
- $forEachTableCell(tableObserver.table, cell => {
2898
- const elem = cell.elem;
2899
- cell.highlighted = false;
2900
- $removeHighlightFromDOM(editor, cell);
2901
- if (!elem.getAttribute('style')) {
2902
- elem.removeAttribute('style');
2903
- }
2904
- });
2905
- }
2906
- function $selectAdjacentCell(tableCellNode, direction) {
2907
- const siblingMethod = direction === 'next' ? 'getNextSibling' : 'getPreviousSibling';
2908
- const childMethod = direction === 'next' ? 'getFirstChild' : 'getLastChild';
2909
- const sibling = tableCellNode[siblingMethod]();
2910
- if ($isElementNode(sibling)) {
2911
- return sibling.selectEnd();
2912
- }
2913
- const parentRow = $findMatchingParent(tableCellNode, $isTableRowNode);
2914
- if (!(parentRow !== null)) {
2915
- formatDevErrorMessage(`selectAdjacentCell: Cell not in table row`);
2916
- }
2917
- for (let nextRow = parentRow[siblingMethod](); $isTableRowNode(nextRow); nextRow = nextRow[siblingMethod]()) {
2918
- const child = nextRow[childMethod]();
2919
- if ($isElementNode(child)) {
2920
- return child.selectEnd();
2921
- }
2922
- }
2923
- const parentTable = $findMatchingParent(parentRow, $isTableNode);
2924
- if (!(parentTable !== null)) {
2925
- formatDevErrorMessage(`selectAdjacentCell: Row not in table`);
2926
- }
2927
- return direction === 'next' ? parentTable.selectNext() : parentTable.selectPrevious();
2928
- }
2929
- const selectTableNodeInDirection = (tableObserver, tableNode, x, y, direction) => {
2930
- const isForward = direction === 'forward';
2931
- switch (direction) {
2932
- case 'backward':
2933
- case 'forward':
2934
- if (x !== (isForward ? tableObserver.table.columns - 1 : 0)) {
2935
- selectTableCellNode(tableNode.getCellNodeFromCordsOrThrow(x + (isForward ? 1 : -1), y, tableObserver.table), isForward);
2936
- } else {
2937
- if (y !== (isForward ? tableObserver.table.rows - 1 : 0)) {
2938
- selectTableCellNode(tableNode.getCellNodeFromCordsOrThrow(isForward ? 0 : tableObserver.table.columns - 1, y + (isForward ? 1 : -1), tableObserver.table), isForward);
2939
- } else if (!isForward) {
2940
- tableNode.selectPrevious();
2941
- } else {
2942
- tableNode.selectNext();
2943
- }
2944
- }
2945
- return true;
2946
- case 'up':
2947
- if (y !== 0) {
2948
- selectTableCellNode(tableNode.getCellNodeFromCordsOrThrow(x, y - 1, tableObserver.table), false);
2949
- } else {
2950
- tableNode.selectPrevious();
2951
- }
2952
- return true;
2953
- case 'down':
2954
- if (y !== tableObserver.table.rows - 1) {
2955
- selectTableCellNode(tableNode.getCellNodeFromCordsOrThrow(x, y + 1, tableObserver.table), true);
2956
- } else {
2957
- tableNode.selectNext();
2958
- }
2959
- return true;
2960
- default:
2961
- return false;
2962
- }
2963
- };
2964
- function getCorner(rect, cellValue) {
2965
- let colName;
2966
- let rowName;
2967
- if (cellValue.startColumn === rect.minColumn) {
2968
- colName = 'minColumn';
2969
- } else if (cellValue.startColumn + cellValue.cell.__colSpan - 1 === rect.maxColumn) {
2970
- colName = 'maxColumn';
2971
- } else {
2972
- return null;
2973
- }
2974
- if (cellValue.startRow === rect.minRow) {
2975
- rowName = 'minRow';
2976
- } else if (cellValue.startRow + cellValue.cell.__rowSpan - 1 === rect.maxRow) {
2977
- rowName = 'maxRow';
2978
- } else {
2979
- return null;
2980
- }
2981
- return [colName, rowName];
2982
- }
2983
- function getCornerOrThrow(rect, cellValue) {
2984
- const corner = getCorner(rect, cellValue);
2985
- if (!(corner !== null)) {
2986
- formatDevErrorMessage(`getCornerOrThrow: cell ${cellValue.cell.getKey()} is not at a corner of rect`);
2987
- }
2988
- return corner;
2989
- }
2990
- function oppositeCorner([colName, rowName]) {
2991
- return [colName === 'minColumn' ? 'maxColumn' : 'minColumn', rowName === 'minRow' ? 'maxRow' : 'minRow'];
2992
- }
2993
- function cellAtCornerOrThrow(tableMap, rect, [colName, rowName]) {
2994
- const rowNum = rect[rowName];
2995
- const rowMap = tableMap[rowNum];
2996
- if (!(rowMap !== undefined)) {
2997
- formatDevErrorMessage(`cellAtCornerOrThrow: ${rowName} = ${String(rowNum)} missing in tableMap`);
2998
- }
2999
- const colNum = rect[colName];
3000
- const cell = rowMap[colNum];
3001
- if (!(cell !== undefined)) {
3002
- formatDevErrorMessage(`cellAtCornerOrThrow: ${colName} = ${String(colNum)} missing in tableMap`);
3003
- }
3004
- return cell;
3005
- }
3006
- function $extractRectCorners(tableMap, anchorCellValue, newFocusCellValue) {
3007
- // We are sure that the focus now either contracts or expands the rect
3008
- // but both the anchor and focus might be moved to ensure a rectangle
3009
- // given a potentially ragged merge shape
3010
- const rect = $computeTableCellRectBoundary(tableMap, anchorCellValue, newFocusCellValue);
3011
- const anchorCorner = getCorner(rect, anchorCellValue);
3012
- if (anchorCorner) {
3013
- return [cellAtCornerOrThrow(tableMap, rect, anchorCorner), cellAtCornerOrThrow(tableMap, rect, oppositeCorner(anchorCorner))];
3014
- }
3015
- const newFocusCorner = getCorner(rect, newFocusCellValue);
3016
- if (newFocusCorner) {
3017
- return [cellAtCornerOrThrow(tableMap, rect, oppositeCorner(newFocusCorner)), cellAtCornerOrThrow(tableMap, rect, newFocusCorner)];
3018
- }
3019
- // TODO this doesn't have to be arbitrary, use the closest corner instead
3020
- const newAnchorCorner = ['minColumn', 'minRow'];
3021
- return [cellAtCornerOrThrow(tableMap, rect, newAnchorCorner), cellAtCornerOrThrow(tableMap, rect, oppositeCorner(newAnchorCorner))];
3022
- }
3023
- function $adjustFocusInDirection(tableObserver, tableMap, anchorCellValue, focusCellValue, direction) {
3024
- const rect = $computeTableCellRectBoundary(tableMap, anchorCellValue, focusCellValue);
3025
- const spans = $computeTableCellRectSpans(tableMap, rect);
3026
- const {
3027
- topSpan,
3028
- leftSpan,
3029
- bottomSpan,
3030
- rightSpan
3031
- } = spans;
3032
- const anchorCorner = getCornerOrThrow(rect, anchorCellValue);
3033
- const [focusColumn, focusRow] = oppositeCorner(anchorCorner);
3034
- let fCol = rect[focusColumn];
3035
- let fRow = rect[focusRow];
3036
- if (direction === 'forward') {
3037
- fCol += focusColumn === 'maxColumn' ? 1 : leftSpan;
3038
- } else if (direction === 'backward') {
3039
- fCol -= focusColumn === 'minColumn' ? 1 : rightSpan;
3040
- } else if (direction === 'down') {
3041
- fRow += focusRow === 'maxRow' ? 1 : topSpan;
3042
- } else if (direction === 'up') {
3043
- fRow -= focusRow === 'minRow' ? 1 : bottomSpan;
3044
- }
3045
- const targetRowMap = tableMap[fRow];
3046
- if (targetRowMap === undefined) {
3047
- return false;
3048
- }
3049
- const newFocusCellValue = targetRowMap[fCol];
3050
- if (newFocusCellValue === undefined) {
3051
- return false;
3052
- }
3053
- // We can be certain that anchorCellValue and newFocusCellValue are
3054
- // contained within the desired selection, but we are not certain if
3055
- // they need to be expanded or not to maintain a rectangular shape
3056
- const [finalAnchorCell, finalFocusCell] = $extractRectCorners(tableMap, anchorCellValue, newFocusCellValue);
3057
- const anchorDOM = $getObserverCellFromCellNodeOrThrow(tableObserver, finalAnchorCell.cell);
3058
- const focusDOM = $getObserverCellFromCellNodeOrThrow(tableObserver, finalFocusCell.cell);
3059
- tableObserver.$setAnchorCellForSelection(anchorDOM);
3060
- tableObserver.$setFocusCellForSelection(focusDOM, true);
3061
- return true;
3062
- }
3063
- function $isSelectionInTable(selection, tableNode) {
3064
- if ($isRangeSelection(selection) || $isTableSelection(selection)) {
3065
- // TODO this should probably return false if there's an unrelated
3066
- // shadow root between the node and the table (e.g. another table,
3067
- // collapsible, etc.)
3068
- const isAnchorInside = tableNode.isParentOf(selection.anchor.getNode());
3069
- const isFocusInside = tableNode.isParentOf(selection.focus.getNode());
3070
- return isAnchorInside && isFocusInside;
3071
- }
3072
- return false;
3073
- }
3074
- function $isFullTableSelection(selection, tableNode) {
3075
- if ($isTableSelection(selection)) {
3076
- const anchorNode = selection.anchor.getNode();
3077
- const focusNode = selection.focus.getNode();
3078
- if (tableNode && anchorNode && focusNode) {
3079
- const [map] = $computeTableMap(tableNode, anchorNode, focusNode);
3080
- return anchorNode.getKey() === map[0][0].cell.getKey() && focusNode.getKey() === map[map.length - 1].at(-1).cell.getKey();
3081
- }
3082
- }
3083
- return false;
3084
- }
3085
- function selectTableCellNode(tableCell, fromStart) {
3086
- if (fromStart) {
3087
- tableCell.selectStart();
3088
- } else {
3089
- tableCell.selectEnd();
3090
- }
3091
- }
3092
- function $addHighlightToDOM(editor, cell) {
3093
- const element = cell.elem;
3094
- const editorThemeClasses = editor._config.theme;
3095
- const node = $getNearestNodeFromDOMNode(element);
3096
- if (!$isTableCellNode(node)) {
3097
- formatDevErrorMessage(`Expected to find LexicalNode from Table Cell DOMNode`);
3098
- }
3099
- addClassNamesToElement(element, editorThemeClasses.tableCellSelected);
3100
- }
3101
- function $removeHighlightFromDOM(editor, cell) {
3102
- const element = cell.elem;
3103
- const node = $getNearestNodeFromDOMNode(element);
3104
- if (!$isTableCellNode(node)) {
3105
- formatDevErrorMessage(`Expected to find LexicalNode from Table Cell DOMNode`);
3106
- }
3107
- const editorThemeClasses = editor._config.theme;
3108
- removeClassNamesFromElement(element, editorThemeClasses.tableCellSelected);
3109
- }
3110
- function $findCellNode(node) {
3111
- const cellNode = $findMatchingParent(node, $isTableCellNode);
3112
- return $isTableCellNode(cellNode) ? cellNode : null;
3113
- }
3114
- function $findTableNode(node) {
3115
- const tableNode = $findMatchingParent(node, $isTableNode);
3116
- return $isTableNode(tableNode) ? tableNode : null;
3117
- }
3118
- function $getBlockParentIfFirstNode(node) {
3119
- for (let prevNode = node, currentNode = node; currentNode !== null; prevNode = currentNode, currentNode = currentNode.getParent()) {
3120
- if ($isElementNode(currentNode)) {
3121
- if (currentNode !== prevNode && currentNode.getFirstChild() !== prevNode) {
3122
- // Not the first child or the initial node
3123
- return null;
3124
- } else if (!currentNode.isInline()) {
3125
- return currentNode;
3126
- }
3127
- }
3128
- }
3129
- return null;
3130
- }
3131
- function $handleHorizontalArrowKeyRangeSelection(editor, event, selection, alter, isBackward, tableNode, tableObserver) {
3132
- const initialFocus = $caretFromPoint(selection.focus, isBackward ? 'previous' : 'next');
3133
- if ($isExtendableTextPointCaret(initialFocus)) {
3134
- return false;
3135
- }
3136
- let lastCaret = initialFocus;
3137
- // TableCellNode is the only shadow root we are interested in piercing so
3138
- // we find the last internal caret and then check its parent
3139
- for (const nextCaret of $extendCaretToRange(initialFocus).iterNodeCarets('shadowRoot')) {
3140
- if (!($isSiblingCaret(nextCaret) && $isElementNode(nextCaret.origin))) {
3141
- return false;
3142
- }
3143
- lastCaret = nextCaret;
3144
- }
3145
- const lastCaretParent = lastCaret.getParentAtCaret();
3146
- if (!$isTableCellNode(lastCaretParent)) {
3147
- return false;
3148
- }
3149
- const anchorCell = lastCaretParent;
3150
- const focusCaret = $findNextTableCell($getSiblingCaret(anchorCell, lastCaret.direction));
3151
- const anchorCellTable = $findMatchingParent(anchorCell, $isTableNode);
3152
- if (!(anchorCellTable && anchorCellTable.is(tableNode))) {
3153
- return false;
3154
- }
3155
- const anchorCellDOM = editor.getElementByKey(anchorCell.getKey());
3156
- const anchorDOMCell = getDOMCellFromTarget(anchorCellDOM);
3157
- if (!anchorCellDOM || !anchorDOMCell) {
3158
- return false;
3159
- }
3160
- const anchorCellTableElement = $getElementForTableNode(editor, anchorCellTable);
3161
- tableObserver.table = anchorCellTableElement;
3162
- if (!focusCaret) {
3163
- if (alter === 'extend') {
3164
- // extend the selection from a range inside the cell to a table selection of the cell
3165
- tableObserver.$setAnchorCellForSelection(anchorDOMCell);
3166
- tableObserver.$setFocusCellForSelection(anchorDOMCell, true);
3167
- } else {
3168
- // exit the table
3169
- const outerFocusCaret = $getTableExitCaret($getSiblingCaret(anchorCellTable, initialFocus.direction));
3170
- $setPointFromCaret(selection.anchor, outerFocusCaret);
3171
- $setPointFromCaret(selection.focus, outerFocusCaret);
3172
- }
3173
- } else if (alter === 'extend') {
3174
- const focusDOMCell = getDOMCellFromTarget(editor.getElementByKey(focusCaret.origin.getKey()));
3175
- if (!focusDOMCell) {
3176
- return false;
3177
- }
3178
- tableObserver.$setAnchorCellForSelection(anchorDOMCell);
3179
- tableObserver.$setFocusCellForSelection(focusDOMCell, true);
3180
- } else {
3181
- // alter === 'move'
3182
- const innerFocusCaret = $normalizeCaret(focusCaret);
3183
- $setPointFromCaret(selection.anchor, innerFocusCaret);
3184
- $setPointFromCaret(selection.focus, innerFocusCaret);
3185
- }
3186
- stopEvent(event);
3187
- return true;
3188
- }
3189
- function $getTableExitCaret(initialCaret) {
3190
- const adjacent = $getAdjacentChildCaret(initialCaret);
3191
- return $isChildCaret(adjacent) ? $normalizeCaret(adjacent) : initialCaret;
3192
- }
3193
- function $findNextTableCell(initialCaret) {
3194
- for (const nextCaret of $extendCaretToRange(initialCaret).iterNodeCarets('root')) {
3195
- const {
3196
- origin
3197
- } = nextCaret;
3198
- if ($isTableCellNode(origin)) {
3199
- // not sure why ts isn't narrowing here (even if the guard is on nextCaret.origin)
3200
- // but returning a new caret is fine
3201
- if ($isChildCaret(nextCaret)) {
3202
- return $getChildCaret(origin, initialCaret.direction);
3203
- }
3204
- } else if (!$isTableRowNode(origin)) {
3205
- break;
3206
- }
3207
- }
3208
- return null;
3209
- }
3210
- function $handleArrowKey(editor, event, direction, tableNode, tableObserver) {
3211
- if ((direction === 'up' || direction === 'down') && isTypeaheadMenuInView(editor)) {
3212
- return false;
3213
- }
3214
- const selection = $getSelection();
3215
- if (!$isSelectionInTable(selection, tableNode)) {
3216
- if ($isRangeSelection(selection)) {
3217
- if (direction === 'backward') {
3218
- if (selection.focus.offset > 0) {
3219
- return false;
3220
- }
3221
- const parentNode = $getBlockParentIfFirstNode(selection.focus.getNode());
3222
- if (!parentNode) {
3223
- return false;
3224
- }
3225
- const siblingNode = parentNode.getPreviousSibling();
3226
- if (!$isTableNode(siblingNode)) {
3227
- return false;
3228
- }
3229
- stopEvent(event);
3230
- if (event.shiftKey) {
3231
- selection.focus.set(siblingNode.getParentOrThrow().getKey(), siblingNode.getIndexWithinParent(), 'element');
3232
- } else {
3233
- siblingNode.selectEnd();
3234
- }
3235
- return true;
3236
- } else if (event.shiftKey && (direction === 'up' || direction === 'down')) {
3237
- const focusNode = selection.focus.getNode();
3238
- const isTableUnselect = !selection.isCollapsed() && (direction === 'up' && !selection.isBackward() || direction === 'down' && selection.isBackward());
3239
- if (isTableUnselect) {
3240
- let focusParentNode = $findMatchingParent(focusNode, n => $isTableNode(n));
3241
- if ($isTableCellNode(focusParentNode)) {
3242
- focusParentNode = $findMatchingParent(focusParentNode, $isTableNode);
3243
- }
3244
- if (focusParentNode !== tableNode) {
3245
- return false;
3246
- }
3247
- if (!focusParentNode) {
3248
- return false;
3249
- }
3250
- const sibling = direction === 'down' ? focusParentNode.getNextSibling() : focusParentNode.getPreviousSibling();
3251
- if (!sibling) {
3252
- return false;
3253
- }
3254
- let newOffset = 0;
3255
- if (direction === 'up') {
3256
- if ($isElementNode(sibling)) {
3257
- newOffset = sibling.getChildrenSize();
3258
- }
3259
- }
3260
- let newFocusNode = sibling;
3261
- if (direction === 'up') {
3262
- if ($isElementNode(sibling)) {
3263
- const lastCell = sibling.getLastChild();
3264
- newFocusNode = lastCell ? lastCell : sibling;
3265
- newOffset = $isTextNode(newFocusNode) ? newFocusNode.getTextContentSize() : 0;
3266
- }
3267
- }
3268
- const newSelection = selection.clone();
3269
- newSelection.focus.set(newFocusNode.getKey(), newOffset, $isTextNode(newFocusNode) ? 'text' : 'element');
3270
- $setSelection(newSelection);
3271
- stopEvent(event);
3272
- return true;
3273
- } else if ($isRootOrShadowRoot(focusNode)) {
3274
- const selectedNode = direction === 'up' ? selection.getNodes()[selection.getNodes().length - 1] : selection.getNodes()[0];
3275
- if (selectedNode) {
3276
- const tableCellNode = $findParentTableCellNodeInTable(tableNode, selectedNode);
3277
- if (tableCellNode !== null) {
3278
- const firstDescendant = tableNode.getFirstDescendant();
3279
- const lastDescendant = tableNode.getLastDescendant();
3280
- if (!firstDescendant || !lastDescendant) {
3281
- return false;
3282
- }
3283
- const [firstCellNode] = $getNodeTriplet(firstDescendant);
3284
- const [lastCellNode] = $getNodeTriplet(lastDescendant);
3285
- const firstCellCoords = tableNode.getCordsFromCellNode(firstCellNode, tableObserver.table);
3286
- const lastCellCoords = tableNode.getCordsFromCellNode(lastCellNode, tableObserver.table);
3287
- const firstCellDOM = tableNode.getDOMCellFromCordsOrThrow(firstCellCoords.x, firstCellCoords.y, tableObserver.table);
3288
- const lastCellDOM = tableNode.getDOMCellFromCordsOrThrow(lastCellCoords.x, lastCellCoords.y, tableObserver.table);
3289
- tableObserver.$setAnchorCellForSelection(firstCellDOM);
3290
- tableObserver.$setFocusCellForSelection(lastCellDOM, true);
3291
- return true;
3292
- }
3293
- }
3294
- return false;
3295
- } else {
3296
- let focusParentNode = $findMatchingParent(focusNode, n => $isElementNode(n) && !n.isInline());
3297
- if ($isTableCellNode(focusParentNode)) {
3298
- focusParentNode = $findMatchingParent(focusParentNode, $isTableNode);
3299
- }
3300
- if (!focusParentNode) {
3301
- return false;
3302
- }
3303
- const sibling = direction === 'down' ? focusParentNode.getNextSibling() : focusParentNode.getPreviousSibling();
3304
- if ($isTableNode(sibling) && tableObserver.tableNodeKey === sibling.getKey()) {
3305
- const firstDescendant = sibling.getFirstDescendant();
3306
- const lastDescendant = sibling.getLastDescendant();
3307
- if (!firstDescendant || !lastDescendant) {
3308
- return false;
3309
- }
3310
- const [firstCellNode] = $getNodeTriplet(firstDescendant);
3311
- const [lastCellNode] = $getNodeTriplet(lastDescendant);
3312
- const newSelection = selection.clone();
3313
- newSelection.focus.set((direction === 'up' ? firstCellNode : lastCellNode).getKey(), direction === 'up' ? 0 : lastCellNode.getChildrenSize(), 'element');
3314
- stopEvent(event);
3315
- $setSelection(newSelection);
3316
- return true;
3317
- }
3318
- }
3319
- }
3320
- }
3321
- if (direction === 'down' && $isScrollableTablesActive(editor)) {
3322
- // Enable Firefox workaround
3323
- tableObserver.setShouldCheckSelection();
3324
- }
3325
- return false;
3326
- }
3327
- if ($isRangeSelection(selection)) {
3328
- if (direction === 'backward' || direction === 'forward') {
3329
- const alter = event.shiftKey ? 'extend' : 'move';
3330
- return $handleHorizontalArrowKeyRangeSelection(editor, event, selection, alter, direction === 'backward', tableNode, tableObserver);
3331
- }
3332
- if (selection.isCollapsed()) {
3333
- const {
3334
- anchor,
3335
- focus
3336
- } = selection;
3337
- const anchorCellNode = $findMatchingParent(anchor.getNode(), $isTableCellNode);
3338
- const focusCellNode = $findMatchingParent(focus.getNode(), $isTableCellNode);
3339
- if (!$isTableCellNode(anchorCellNode) || !anchorCellNode.is(focusCellNode)) {
3340
- return false;
3341
- }
3342
- const anchorCellTable = $findTableNode(anchorCellNode);
3343
- if (anchorCellTable !== tableNode && anchorCellTable != null) {
3344
- const anchorCellTableElement = getTableElement(anchorCellTable, editor.getElementByKey(anchorCellTable.getKey()));
3345
- if (anchorCellTableElement != null) {
3346
- tableObserver.table = getTable(anchorCellTable, anchorCellTableElement);
3347
- return $handleArrowKey(editor, event, direction, anchorCellTable, tableObserver);
3348
- }
3349
- }
3350
- const anchorCellDom = editor.getElementByKey(anchorCellNode.__key);
3351
- const anchorDOM = editor.getElementByKey(anchor.key);
3352
- if (anchorDOM == null || anchorCellDom == null) {
3353
- return false;
3354
- }
3355
- let edgeSelectionRect;
3356
- if (anchor.type === 'element') {
3357
- edgeSelectionRect = anchorDOM.getBoundingClientRect();
3358
- } else {
3359
- const domSelection = getDOMSelection(getEditorWindow(editor));
3360
- if (domSelection === null || domSelection.rangeCount === 0) {
3361
- return false;
3362
- }
3363
- const range = domSelection.getRangeAt(0);
3364
- edgeSelectionRect = range.getBoundingClientRect();
3365
- }
3366
- const edgeChild = direction === 'up' ? anchorCellNode.getFirstChild() : anchorCellNode.getLastChild();
3367
- if (edgeChild == null) {
3368
- return false;
3369
- }
3370
- const edgeChildDOM = editor.getElementByKey(edgeChild.__key);
3371
- if (edgeChildDOM == null) {
3372
- return false;
3373
- }
3374
- const edgeRect = edgeChildDOM.getBoundingClientRect();
3375
- const isExiting = direction === 'up' ? edgeRect.top > edgeSelectionRect.top - edgeSelectionRect.height : edgeSelectionRect.bottom + edgeSelectionRect.height > edgeRect.bottom;
3376
- if (isExiting) {
3377
- stopEvent(event);
3378
- const cords = tableNode.getCordsFromCellNode(anchorCellNode, tableObserver.table);
3379
- if (event.shiftKey) {
3380
- const cell = tableNode.getDOMCellFromCordsOrThrow(cords.x, cords.y, tableObserver.table);
3381
- tableObserver.$setAnchorCellForSelection(cell);
3382
- tableObserver.$setFocusCellForSelection(cell, true);
3383
- } else {
3384
- return selectTableNodeInDirection(tableObserver, tableNode, cords.x, cords.y, direction);
3385
- }
3386
- return true;
3387
- }
3388
- }
3389
- } else if ($isTableSelection(selection)) {
3390
- const {
3391
- anchor,
3392
- focus
3393
- } = selection;
3394
- const anchorCellNode = $findMatchingParent(anchor.getNode(), $isTableCellNode);
3395
- const focusCellNode = $findMatchingParent(focus.getNode(), $isTableCellNode);
3396
- const [tableNodeFromSelection] = selection.getNodes();
3397
- if (!$isTableNode(tableNodeFromSelection)) {
3398
- formatDevErrorMessage(`$handleArrowKey: TableSelection.getNodes()[0] expected to be TableNode`);
3399
- }
3400
- const tableElement = getTableElement(tableNodeFromSelection, editor.getElementByKey(tableNodeFromSelection.getKey()));
3401
- if (!$isTableCellNode(anchorCellNode) || !$isTableCellNode(focusCellNode) || !$isTableNode(tableNodeFromSelection) || tableElement == null) {
3402
- return false;
3403
- }
3404
- tableObserver.$updateTableTableSelection(selection);
3405
- const grid = getTable(tableNodeFromSelection, tableElement);
3406
- const cordsAnchor = tableNode.getCordsFromCellNode(anchorCellNode, grid);
3407
- const anchorCell = tableNode.getDOMCellFromCordsOrThrow(cordsAnchor.x, cordsAnchor.y, grid);
3408
- tableObserver.$setAnchorCellForSelection(anchorCell);
3409
- stopEvent(event);
3410
- if (event.shiftKey) {
3411
- const [tableMap, anchorValue, focusValue] = $computeTableMap(tableNode, anchorCellNode, focusCellNode);
3412
- return $adjustFocusInDirection(tableObserver, tableMap, anchorValue, focusValue, direction);
3413
- } else {
3414
- focusCellNode.selectEnd();
3415
- }
3416
- return true;
3417
- }
3418
- return false;
3419
- }
3420
- function stopEvent(event) {
3421
- event.preventDefault();
3422
- event.stopImmediatePropagation();
3423
- event.stopPropagation();
3424
- }
3425
- function isTypeaheadMenuInView(editor) {
3426
- // There is no inbuilt way to check if the component picker is in view
3427
- // but we can check if the root DOM element has the aria-controls attribute "typeahead-menu".
3428
- const root = editor.getRootElement();
3429
- if (!root) {
3430
- return false;
3431
- }
3432
- return root.hasAttribute('aria-controls') && root.getAttribute('aria-controls') === 'typeahead-menu';
3433
- }
3434
- function $insertParagraphAtTableEdge(edgePosition, tableNode, children) {
3435
- const paragraphNode = $createParagraphNode();
3436
- if (edgePosition === 'first') {
3437
- tableNode.insertBefore(paragraphNode);
3438
- } else {
3439
- tableNode.insertAfter(paragraphNode);
3440
- }
3441
- paragraphNode.append(...(children || []));
3442
- paragraphNode.selectEnd();
3443
- }
3444
- function $getTableEdgeCursorPosition(editor, selection, tableNode) {
3445
- const tableNodeParent = tableNode.getParent();
3446
- if (!tableNodeParent) {
3447
- return undefined;
3448
- }
3449
-
3450
- // TODO: Add support for nested tables
3451
- const domSelection = getDOMSelection(getEditorWindow(editor));
3452
- if (!domSelection) {
3453
- return undefined;
3454
- }
3455
- const domAnchorNode = domSelection.anchorNode;
3456
- const tableNodeParentDOM = editor.getElementByKey(tableNodeParent.getKey());
3457
- const tableElement = getTableElement(tableNode, editor.getElementByKey(tableNode.getKey()));
3458
- // We are only interested in the scenario where the
3459
- // native selection anchor is:
3460
- // - at or inside the table's parent DOM
3461
- // - and NOT at or inside the table DOM
3462
- // It may be adjacent to the table DOM (e.g. in a wrapper)
3463
- if (!domAnchorNode || !tableNodeParentDOM || !tableElement || !tableNodeParentDOM.contains(domAnchorNode) || tableElement.contains(domAnchorNode)) {
3464
- return undefined;
3465
- }
3466
- const anchorCellNode = $findMatchingParent(selection.anchor.getNode(), n => $isTableCellNode(n));
3467
- if (!anchorCellNode) {
3468
- return undefined;
3469
- }
3470
- const parentTable = $findMatchingParent(anchorCellNode, n => $isTableNode(n));
3471
- if (!$isTableNode(parentTable) || !parentTable.is(tableNode)) {
3472
- return undefined;
3473
- }
3474
- const [tableMap, cellValue] = $computeTableMap(tableNode, anchorCellNode, anchorCellNode);
3475
- const firstCell = tableMap[0][0];
3476
- const lastCell = tableMap[tableMap.length - 1][tableMap[0].length - 1];
3477
- const {
3478
- startRow,
3479
- startColumn
3480
- } = cellValue;
3481
- const isAtFirstCell = startRow === firstCell.startRow && startColumn === firstCell.startColumn;
3482
- const isAtLastCell = startRow === lastCell.startRow && startColumn === lastCell.startColumn;
3483
- if (isAtFirstCell) {
3484
- return 'first';
3485
- } else if (isAtLastCell) {
3486
- return 'last';
3487
- } else {
3488
- return undefined;
3489
- }
3490
- }
3491
- function $getObserverCellFromCellNodeOrThrow(tableObserver, tableCellNode) {
3492
- const {
3493
- tableNode
3494
- } = tableObserver.$lookup();
3495
- const currentCords = tableNode.getCordsFromCellNode(tableCellNode, tableObserver.table);
3496
- return tableNode.getDOMCellFromCordsOrThrow(currentCords.x, currentCords.y, tableObserver.table);
3497
- }
3498
- function $getNearestTableCellInTableFromDOMNode(tableNode, startingDOM, editorState) {
3499
- return $findParentTableCellNodeInTable(tableNode, $getNearestNodeFromDOMNode(startingDOM, editorState));
3500
- }
3501
-
3502
- function isHTMLDivElement(element) {
3503
- return isHTMLElement$1(element) && element.nodeName === 'DIV';
3504
- }
3505
- function updateColgroup(dom, config, colCount, colWidths) {
3506
- const colGroup = dom.querySelector('colgroup');
3507
- if (!colGroup) {
3508
- return;
3509
- }
3510
- const cols = [];
3511
- for (let i = 0; i < colCount; i++) {
3512
- const col = document.createElement('col');
3513
- const width = colWidths && colWidths[i];
3514
- if (width) {
3515
- col.style.width = `${width}px`;
3516
- }
3517
- cols.push(col);
3518
- }
3519
- colGroup.replaceChildren(...cols);
3520
- }
3521
- function setRowStriping(dom, config, rowStriping) {
3522
- if (rowStriping) {
3523
- addClassNamesToElement(dom, config.theme.tableRowStriping);
3524
- dom.setAttribute('data-lexical-row-striping', 'true');
3525
- } else {
3526
- removeClassNamesFromElement(dom, config.theme.tableRowStriping);
3527
- dom.removeAttribute('data-lexical-row-striping');
3528
- }
3529
- }
3530
- function setFrozenColumns(dom, tableElement, config, frozenColumnCount) {
3531
- if (frozenColumnCount > 0) {
3532
- addClassNamesToElement(dom, config.theme.tableFrozenColumn);
3533
- tableElement.setAttribute('data-lexical-frozen-column', 'true');
3534
- } else {
3535
- removeClassNamesFromElement(dom, config.theme.tableFrozenColumn);
3536
- tableElement.removeAttribute('data-lexical-frozen-column');
3537
- }
3538
- }
3539
- function setFrozenRows(dom, tableElement, config, frozenRowCount) {
3540
- if (frozenRowCount > 0) {
3541
- addClassNamesToElement(dom, config.theme.tableFrozenRow);
3542
- tableElement.setAttribute('data-lexical-frozen-row', 'true');
3543
- } else {
3544
- removeClassNamesFromElement(dom, config.theme.tableFrozenRow);
3545
- tableElement.removeAttribute('data-lexical-frozen-row');
3546
- }
3547
- }
3548
- function alignTableElement(dom, config, formatType) {
3549
- if (!config.theme.tableAlignment) {
3550
- return;
3551
- }
3552
- const removeClasses = [];
3553
- const addClasses = [];
3554
- for (const format of ['center', 'right']) {
3555
- const classes = config.theme.tableAlignment[format];
3556
- if (!classes) {
3557
- continue;
3558
- }
3559
- (format === formatType ? addClasses : removeClasses).push(classes);
3560
- }
3561
- removeClassNamesFromElement(dom, ...removeClasses);
3562
- addClassNamesToElement(dom, ...addClasses);
3563
- }
3564
- const scrollableEditors = new WeakSet();
3565
- function $isScrollableTablesActive(editor = $getEditor()) {
3566
- return scrollableEditors.has(editor);
3567
- }
3568
- function setScrollableTablesActive(editor, active) {
3569
- if (active) {
3570
- if (!editor._config.theme.tableScrollableWrapper) {
3571
- console.warn('TableNode: hasHorizontalScroll is active but theme.tableScrollableWrapper is not defined.');
3572
- }
3573
- scrollableEditors.add(editor);
3574
- } else {
3575
- scrollableEditors.delete(editor);
3576
- }
3577
- }
3578
-
3579
- /** @noInheritDoc */
3580
- class TableNode extends ElementNode {
3581
- /** @internal */
3582
-
3583
- static getType() {
3584
- return 'table';
3585
- }
3586
- getColWidths() {
3587
- const self = this.getLatest();
3588
- return self.__colWidths;
3589
- }
3590
- setColWidths(colWidths) {
3591
- const self = this.getWritable();
3592
- // NOTE: Node properties should be immutable. Freeze to prevent accidental mutation.
3593
- self.__colWidths = colWidths !== undefined && true ? Object.freeze(colWidths) : colWidths;
3594
- return self;
3595
- }
3596
- static clone(node) {
3597
- return new TableNode(node.__key);
3598
- }
3599
- afterCloneFrom(prevNode) {
3600
- super.afterCloneFrom(prevNode);
3601
- this.__colWidths = prevNode.__colWidths;
3602
- this.__rowStriping = prevNode.__rowStriping;
3603
- this.__frozenColumnCount = prevNode.__frozenColumnCount;
3604
- this.__frozenRowCount = prevNode.__frozenRowCount;
3605
- }
3606
- static importDOM() {
3607
- return {
3608
- table: _node => ({
3609
- conversion: $convertTableElement,
3610
- priority: 1
3611
- })
3612
- };
3613
- }
3614
- static importJSON(serializedNode) {
3615
- return $createTableNode().updateFromJSON(serializedNode);
3616
- }
3617
- updateFromJSON(serializedNode) {
3618
- return super.updateFromJSON(serializedNode).setRowStriping(serializedNode.rowStriping || false).setFrozenColumns(serializedNode.frozenColumnCount || 0).setFrozenRows(serializedNode.frozenRowCount || 0).setColWidths(serializedNode.colWidths);
3619
- }
3620
- constructor(key) {
3621
- super(key);
3622
- this.__rowStriping = false;
3623
- this.__frozenColumnCount = 0;
3624
- this.__frozenRowCount = 0;
3625
- }
3626
- exportJSON() {
3627
- return {
3628
- ...super.exportJSON(),
3629
- colWidths: this.getColWidths(),
3630
- frozenColumnCount: this.__frozenColumnCount ? this.__frozenColumnCount : undefined,
3631
- frozenRowCount: this.__frozenRowCount ? this.__frozenRowCount : undefined,
3632
- rowStriping: this.__rowStriping ? this.__rowStriping : undefined
3633
- };
3634
- }
3635
- extractWithChild(child, selection, destination) {
3636
- return destination === 'html';
3637
- }
3638
- getDOMSlot(element) {
3639
- const tableElement = !isHTMLTableElement(element) ? element.querySelector('table') : element;
3640
- if (!isHTMLTableElement(tableElement)) {
3641
- formatDevErrorMessage(`TableNode.getDOMSlot: createDOM() did not return a table`);
3642
- }
3643
- return super.getDOMSlot(element).withElement(tableElement).withAfter(tableElement.querySelector('colgroup'));
3644
- }
3645
- createDOM(config, editor) {
3646
- const tableElement = document.createElement('table');
3647
- if (this.__style) {
3648
- tableElement.style.cssText = this.__style;
3649
- }
3650
- const colGroup = document.createElement('colgroup');
3651
- tableElement.appendChild(colGroup);
3652
- setDOMUnmanaged(colGroup);
3653
- addClassNamesToElement(tableElement, config.theme.table);
3654
- this.updateTableElement(null, tableElement, config);
3655
- if ($isScrollableTablesActive(editor)) {
3656
- const wrapperElement = document.createElement('div');
3657
- const classes = config.theme.tableScrollableWrapper;
3658
- if (classes) {
3659
- addClassNamesToElement(wrapperElement, classes);
3660
- } else {
3661
- wrapperElement.style.cssText = 'overflow-x: auto;';
3662
- }
3663
- wrapperElement.appendChild(tableElement);
3664
- this.updateTableWrapper(null, wrapperElement, tableElement, config);
3665
- return wrapperElement;
3666
- }
3667
- return tableElement;
3668
- }
3669
- updateTableWrapper(prevNode, tableWrapper, tableElement, config) {
3670
- if (this.__frozenColumnCount !== (prevNode ? prevNode.__frozenColumnCount : 0)) {
3671
- setFrozenColumns(tableWrapper, tableElement, config, this.__frozenColumnCount);
3672
- }
3673
- if (this.__frozenRowCount !== (prevNode ? prevNode.__frozenRowCount : 0)) {
3674
- setFrozenRows(tableWrapper, tableElement, config, this.__frozenRowCount);
3675
- }
3676
- }
3677
- updateTableElement(prevNode, tableElement, config) {
3678
- if (this.__style !== (prevNode ? prevNode.__style : '')) {
3679
- tableElement.style.cssText = this.__style;
3680
- }
3681
- if (this.__rowStriping !== (prevNode ? prevNode.__rowStriping : false)) {
3682
- setRowStriping(tableElement, config, this.__rowStriping);
3683
- }
3684
- updateColgroup(tableElement, config, this.getColumnCount(), this.getColWidths());
3685
- alignTableElement(tableElement, config, this.getFormatType());
3686
- }
3687
- updateDOM(prevNode, dom, config) {
3688
- const slot = this.getDOMSlot(dom);
3689
- const tableElement = slot.element;
3690
- if (dom === tableElement === $isScrollableTablesActive()) {
3691
- return true;
3692
- }
3693
- if (isHTMLDivElement(dom)) {
3694
- this.updateTableWrapper(prevNode, dom, tableElement, config);
3695
- }
3696
- this.updateTableElement(prevNode, tableElement, config);
3697
- return false;
3698
- }
3699
- exportDOM(editor) {
3700
- const superExport = super.exportDOM(editor);
3701
- const {
3702
- element
3703
- } = superExport;
3704
- return {
3705
- after: tableElement => {
3706
- if (superExport.after) {
3707
- tableElement = superExport.after(tableElement);
3708
- }
3709
- if (!isHTMLTableElement(tableElement) && isHTMLElement$1(tableElement)) {
3710
- tableElement = tableElement.querySelector('table');
3711
- }
3712
- if (!isHTMLTableElement(tableElement)) {
3713
- return null;
3714
- }
3715
- alignTableElement(tableElement, editor._config, this.getFormatType());
3716
-
3717
- // Scan the table map to build a map of table cell key to the columns it needs
3718
- const [tableMap] = $computeTableMapSkipCellCheck(this, null, null);
3719
- const cellValues = new Map();
3720
- for (const mapRow of tableMap) {
3721
- for (const mapValue of mapRow) {
3722
- const key = mapValue.cell.getKey();
3723
- if (!cellValues.has(key)) {
3724
- cellValues.set(key, {
3725
- colSpan: mapValue.cell.getColSpan(),
3726
- startColumn: mapValue.startColumn
3727
- });
3728
- }
3729
- }
3730
- }
3731
-
3732
- // scan the DOM to find the table cell keys that were used and mark those columns
3733
- const knownColumns = new Set();
3734
- for (const cellDOM of tableElement.querySelectorAll(':scope > tr > [data-temporary-table-cell-lexical-key]')) {
3735
- const key = cellDOM.getAttribute('data-temporary-table-cell-lexical-key');
3736
- if (key) {
3737
- const cellSpan = cellValues.get(key);
3738
- cellDOM.removeAttribute('data-temporary-table-cell-lexical-key');
3739
- if (cellSpan) {
3740
- cellValues.delete(key);
3741
- for (let i = 0; i < cellSpan.colSpan; i++) {
3742
- knownColumns.add(i + cellSpan.startColumn);
3743
- }
3744
- }
3745
- }
3746
- }
3747
-
3748
- // Compute the colgroup and columns in the export
3749
- const colGroup = tableElement.querySelector(':scope > colgroup');
3750
- if (colGroup) {
3751
- // Only include the <col /> for rows that are in the output
3752
- const cols = Array.from(tableElement.querySelectorAll(':scope > colgroup > col')).filter((dom, i) => knownColumns.has(i));
3753
- colGroup.replaceChildren(...cols);
3754
- }
3755
-
3756
- // Wrap direct descendant rows in a tbody for export
3757
- const rows = tableElement.querySelectorAll(':scope > tr');
3758
- if (rows.length > 0) {
3759
- const tBody = document.createElement('tbody');
3760
- for (const row of rows) {
3761
- tBody.appendChild(row);
3762
- }
3763
- tableElement.append(tBody);
3764
- }
3765
- return tableElement;
3766
- },
3767
- element: !isHTMLTableElement(element) && isHTMLElement$1(element) ? element.querySelector('table') : element
3768
- };
3769
- }
3770
- canBeEmpty() {
3771
- return false;
3772
- }
3773
- isShadowRoot() {
3774
- return true;
3775
- }
3776
- getCordsFromCellNode(tableCellNode, table) {
3777
- const {
3778
- rows,
3779
- domRows
3780
- } = table;
3781
- for (let y = 0; y < rows; y++) {
3782
- const row = domRows[y];
3783
- if (row == null) {
3784
- continue;
3785
- }
3786
- for (let x = 0; x < row.length; x++) {
3787
- const cell = row[x];
3788
- if (cell == null) {
3789
- continue;
3790
- }
3791
- const {
3792
- elem
3793
- } = cell;
3794
- const cellNode = $getNearestTableCellInTableFromDOMNode(this, elem);
3795
- if (cellNode !== null && tableCellNode.is(cellNode)) {
3796
- return {
3797
- x,
3798
- y
3799
- };
3800
- }
3801
- }
3802
- }
3803
- throw new Error('Cell not found in table.');
3804
- }
3805
- getDOMCellFromCords(x, y, table) {
3806
- const {
3807
- domRows
3808
- } = table;
3809
- const row = domRows[y];
3810
- if (row == null) {
3811
- return null;
3812
- }
3813
- const index = x < row.length ? x : row.length - 1;
3814
- const cell = row[index];
3815
- if (cell == null) {
3816
- return null;
3817
- }
3818
- return cell;
3819
- }
3820
- getDOMCellFromCordsOrThrow(x, y, table) {
3821
- const cell = this.getDOMCellFromCords(x, y, table);
3822
- if (!cell) {
3823
- throw new Error('Cell not found at cords.');
3824
- }
3825
- return cell;
3826
- }
3827
- getCellNodeFromCords(x, y, table) {
3828
- const cell = this.getDOMCellFromCords(x, y, table);
3829
- if (cell == null) {
3830
- return null;
3831
- }
3832
- const node = $getNearestNodeFromDOMNode(cell.elem);
3833
- if ($isTableCellNode(node)) {
3834
- return node;
3835
- }
3836
- return null;
3837
- }
3838
- getCellNodeFromCordsOrThrow(x, y, table) {
3839
- const node = this.getCellNodeFromCords(x, y, table);
3840
- if (!node) {
3841
- throw new Error('Node at cords not TableCellNode.');
3842
- }
3843
- return node;
3844
- }
3845
- getRowStriping() {
3846
- return Boolean(this.getLatest().__rowStriping);
3847
- }
3848
- setRowStriping(newRowStriping) {
3849
- const self = this.getWritable();
3850
- self.__rowStriping = newRowStriping;
3851
- return self;
3852
- }
3853
- setFrozenColumns(columnCount) {
3854
- const self = this.getWritable();
3855
- self.__frozenColumnCount = columnCount;
3856
- return self;
3857
- }
3858
- getFrozenColumns() {
3859
- return this.getLatest().__frozenColumnCount;
3860
- }
3861
- setFrozenRows(rowCount) {
3862
- const self = this.getWritable();
3863
- self.__frozenRowCount = rowCount;
3864
- return self;
3865
- }
3866
- getFrozenRows() {
3867
- return this.getLatest().__frozenRowCount;
3868
- }
3869
- canSelectBefore() {
3870
- return true;
3871
- }
3872
- canIndent() {
3873
- return false;
3874
- }
3875
- getColumnCount() {
3876
- const firstRow = this.getFirstChild();
3877
- if (!firstRow) {
3878
- return 0;
3879
- }
3880
- let columnCount = 0;
3881
- firstRow.getChildren().forEach(cell => {
3882
- if ($isTableCellNode(cell)) {
3883
- columnCount += cell.getColSpan();
3884
- }
3885
- });
3886
- return columnCount;
3887
- }
3888
- }
3889
- function $getElementForTableNode(editor, tableNode) {
3890
- const tableElement = editor.getElementByKey(tableNode.getKey());
3891
- if (!(tableElement !== null)) {
3892
- formatDevErrorMessage(`$getElementForTableNode: Table Element Not Found`);
3893
- }
3894
- return getTable(tableNode, tableElement);
3895
- }
3896
- function $convertTableElement(domNode) {
3897
- const tableNode = $createTableNode();
3898
- if (domNode.hasAttribute('data-lexical-row-striping')) {
3899
- tableNode.setRowStriping(true);
3900
- }
3901
- if (domNode.hasAttribute('data-lexical-frozen-column')) {
3902
- tableNode.setFrozenColumns(1);
3903
- }
3904
- if (domNode.hasAttribute('data-lexical-frozen-row')) {
3905
- tableNode.setFrozenRows(1);
3906
- }
3907
- const colGroup = domNode.querySelector(':scope > colgroup');
3908
- if (colGroup) {
3909
- let columns = [];
3910
- for (const col of colGroup.querySelectorAll(':scope > col')) {
3911
- let width = col.style.width || '';
3912
- if (!PIXEL_VALUE_REG_EXP.test(width)) {
3913
- // Also support deprecated width attribute for google docs
3914
- width = col.getAttribute('width') || '';
3915
- if (!/^\d+$/.test(width)) {
3916
- columns = undefined;
3917
- break;
3918
- }
3919
- }
3920
- columns.push(parseFloat(width));
3921
- }
3922
- if (columns) {
3923
- tableNode.setColWidths(columns);
3924
- }
3925
- }
3926
- return {
3927
- after: children => $descendantsMatching(children, $isTableRowNode),
3928
- node: tableNode
3929
- };
3930
- }
3931
- function $createTableNode() {
3932
- return $applyNodeReplacement(new TableNode());
3933
- }
3934
- function $isTableNode(node) {
3935
- return node instanceof TableNode;
3936
- }
3937
-
3938
- function $insertTableCommandListener({
3939
- rows,
3940
- columns,
3941
- includeHeaders
3942
- }) {
3943
- const selection = $getSelection() || $getPreviousSelection();
3944
- if (!selection || !$isRangeSelection(selection)) {
3945
- return false;
3946
- }
3947
-
3948
- // Prevent nested tables by checking if we're already inside a table
3949
- if ($findTableNode(selection.anchor.getNode())) {
3950
- return false;
3951
- }
3952
- const tableNode = $createTableNodeWithDimensions(Number(rows), Number(columns), includeHeaders);
3953
- $insertNodeToNearestRoot(tableNode);
3954
- const firstDescendant = tableNode.getFirstDescendant();
3955
- if ($isTextNode(firstDescendant)) {
3956
- firstDescendant.select();
3957
- }
3958
- return true;
3959
- }
3960
- function $tableCellTransform(node) {
3961
- if (!$isTableRowNode(node.getParent())) {
3962
- // TableCellNode must be a child of TableRowNode.
3963
- node.remove();
3964
- } else if (node.isEmpty()) {
3965
- // TableCellNode should never be empty
3966
- node.append($createParagraphNode());
3967
- }
3968
- }
3969
- function $tableRowTransform(node) {
3970
- if (!$isTableNode(node.getParent())) {
3971
- // TableRowNode must be a child of TableNode.
3972
- // TODO: Future support of tbody/thead/tfoot may change this
3973
- node.remove();
3974
- } else {
3975
- $unwrapAndFilterDescendants(node, $isTableCellNode);
3976
- }
3977
- }
3978
- function $tableTransform(node) {
3979
- // TableRowNode is the only valid child for TableNode
3980
- // TODO: Future support of tbody/thead/tfoot/caption may change this
3981
- $unwrapAndFilterDescendants(node, $isTableRowNode);
3982
- const [gridMap] = $computeTableMapSkipCellCheck(node, null, null);
3983
- const maxRowLength = gridMap.reduce((curLength, row) => {
3984
- return Math.max(curLength, row.length);
3985
- }, 0);
3986
- const rowNodes = node.getChildren();
3987
- for (let i = 0; i < gridMap.length; ++i) {
3988
- const rowNode = rowNodes[i];
3989
- if (!rowNode) {
3990
- continue;
3991
- }
3992
- if (!$isTableRowNode(rowNode)) {
3993
- formatDevErrorMessage(`TablePlugin: Expecting all children of TableNode to be TableRowNode, found ${rowNode.constructor.name} (type ${rowNode.getType()})`);
3994
- }
3995
- const rowLength = gridMap[i].reduce((acc, cell) => cell ? 1 + acc : acc, 0);
3996
- if (rowLength === maxRowLength) {
3997
- continue;
3998
- }
3999
- for (let j = rowLength; j < maxRowLength; ++j) {
4000
- // TODO: inherit header state from another header or body
4001
- const newCell = $createTableCellNode();
4002
- newCell.append($createParagraphNode());
4003
- rowNode.append(newCell);
4004
- }
4005
- }
4006
- }
4007
- function $tableClickCommand(event) {
4008
- if (event.detail < 3 || !isDOMNode(event.target)) {
4009
- return false;
4010
- }
4011
- const startNode = $getNearestNodeFromDOMNode(event.target);
4012
- if (startNode === null) {
4013
- return false;
4014
- }
4015
- const blockNode = $findMatchingParent(startNode, node => $isElementNode(node) && !node.isInline());
4016
- if (blockNode === null) {
4017
- return false;
4018
- }
4019
- const rootNode = blockNode.getParent();
4020
- if (!$isTableCellNode(rootNode)) {
4021
- return false;
4022
- }
4023
- blockNode.select(0);
4024
- return true;
4025
- }
4026
-
4027
- /**
4028
- * Register a transform to ensure that all TableCellNode have a colSpan and rowSpan of 1.
4029
- * This should only be registered when you do not want to support merged cells.
4030
- *
4031
- * @param editor The editor
4032
- * @returns An unregister callback
4033
- */
4034
- function registerTableCellUnmergeTransform(editor) {
4035
- return editor.registerNodeTransform(TableCellNode, node => {
4036
- if (node.getColSpan() > 1 || node.getRowSpan() > 1) {
4037
- // When we have rowSpan we have to map the entire Table to understand where the new Cells
4038
- // fit best; let's analyze all Cells at once to save us from further transform iterations
4039
- const [,, gridNode] = $getNodeTriplet(node);
4040
- const [gridMap] = $computeTableMap(gridNode, node, node);
4041
- // TODO this function expects Tables to be normalized. Look into this once it exists
4042
- const rowsCount = gridMap.length;
4043
- const columnsCount = gridMap[0].length;
4044
- let row = gridNode.getFirstChild();
4045
- if (!$isTableRowNode(row)) {
4046
- formatDevErrorMessage(`Expected TableNode first child to be a RowNode`);
4047
- }
4048
- const unmerged = [];
4049
- for (let i = 0; i < rowsCount; i++) {
4050
- if (i !== 0) {
4051
- row = row.getNextSibling();
4052
- if (!$isTableRowNode(row)) {
4053
- formatDevErrorMessage(`Expected TableNode first child to be a RowNode`);
4054
- }
4055
- }
4056
- let lastRowCell = null;
4057
- for (let j = 0; j < columnsCount; j++) {
4058
- const cellMap = gridMap[i][j];
4059
- const cell = cellMap.cell;
4060
- if (cellMap.startRow === i && cellMap.startColumn === j) {
4061
- lastRowCell = cell;
4062
- unmerged.push(cell);
4063
- } else if (cell.getColSpan() > 1 || cell.getRowSpan() > 1) {
4064
- if (!$isTableCellNode(cell)) {
4065
- formatDevErrorMessage(`Expected TableNode cell to be a TableCellNode`);
4066
- }
4067
- const newCell = $createTableCellNode(cell.__headerState);
4068
- if (lastRowCell !== null) {
4069
- lastRowCell.insertAfter(newCell);
4070
- } else {
4071
- $insertFirst$1(row, newCell);
4072
- }
4073
- }
4074
- }
4075
- }
4076
- for (const cell of unmerged) {
4077
- cell.setColSpan(1);
4078
- cell.setRowSpan(1);
4079
- }
4080
- }
4081
- });
4082
- }
4083
- function registerTableSelectionObserver(editor, hasTabHandler = true) {
4084
- const tableSelections = new Map();
4085
- const initializeTableNode = (tableNode, nodeKey, dom) => {
4086
- const tableElement = getTableElement(tableNode, dom);
4087
- const tableSelection = applyTableHandlers(tableNode, tableElement, editor, hasTabHandler);
4088
- tableSelections.set(nodeKey, [tableSelection, tableElement]);
4089
- };
4090
- const unregisterMutationListener = editor.registerMutationListener(TableNode, nodeMutations => {
4091
- editor.getEditorState().read(() => {
4092
- for (const [nodeKey, mutation] of nodeMutations) {
4093
- const tableSelection = tableSelections.get(nodeKey);
4094
- if (mutation === 'created' || mutation === 'updated') {
4095
- const {
4096
- tableNode,
4097
- tableElement
4098
- } = $getTableAndElementByKey(nodeKey);
4099
- if (tableSelection === undefined) {
4100
- initializeTableNode(tableNode, nodeKey, tableElement);
4101
- } else if (tableElement !== tableSelection[1]) {
4102
- // The update created a new DOM node, destroy the existing TableObserver
4103
- tableSelection[0].removeListeners();
4104
- tableSelections.delete(nodeKey);
4105
- initializeTableNode(tableNode, nodeKey, tableElement);
4106
- }
4107
- } else if (mutation === 'destroyed') {
4108
- if (tableSelection !== undefined) {
4109
- tableSelection[0].removeListeners();
4110
- tableSelections.delete(nodeKey);
4111
- }
4112
- }
4113
- }
4114
- }, {
4115
- editor
4116
- });
4117
- }, {
4118
- skipInitialization: false
4119
- });
4120
- return () => {
4121
- unregisterMutationListener();
4122
- // Hook might be called multiple times so cleaning up tables listeners as well,
4123
- // as it'll be reinitialized during recurring call
4124
- for (const [, [tableSelection]] of tableSelections) {
4125
- tableSelection.removeListeners();
4126
- }
4127
- };
4128
- }
4129
-
4130
- /**
4131
- * Register the INSERT_TABLE_COMMAND listener and the table integrity transforms. The
4132
- * table selection observer should be registered separately after this with
4133
- * {@link registerTableSelectionObserver}.
4134
- *
4135
- * @param editor The editor
4136
- * @returns An unregister callback
4137
- */
4138
- function registerTablePlugin(editor) {
4139
- if (!editor.hasNodes([TableNode])) {
4140
- {
4141
- formatDevErrorMessage(`TablePlugin: TableNode is not registered on editor`);
4142
- }
4143
- }
4144
- return mergeRegister(editor.registerCommand(INSERT_TABLE_COMMAND, $insertTableCommandListener, COMMAND_PRIORITY_EDITOR), editor.registerCommand(SELECTION_INSERT_CLIPBOARD_NODES_COMMAND, ({
4145
- nodes,
4146
- selection
4147
- }, dispatchEditor) => {
4148
- if (editor !== dispatchEditor || !$isRangeSelection(selection)) {
4149
- return false;
4150
- }
4151
- const isInsideTableCell = $findTableNode(selection.anchor.getNode()) !== null;
4152
- return isInsideTableCell && nodes.some($isTableNode);
4153
- }, COMMAND_PRIORITY_EDITOR), editor.registerCommand(CLICK_COMMAND, $tableClickCommand, COMMAND_PRIORITY_EDITOR), editor.registerNodeTransform(TableNode, $tableTransform), editor.registerNodeTransform(TableRowNode, $tableRowTransform), editor.registerNodeTransform(TableCellNode, $tableCellTransform));
4154
- }
4155
-
4156
- export { $computeTableMap, $computeTableMapSkipCellCheck, $createTableCellNode, $createTableNode, $createTableNodeWithDimensions, $createTableRowNode, $createTableSelection, $createTableSelectionFrom, $deleteTableColumn, $deleteTableColumnAtSelection, $deleteTableColumn__EXPERIMENTAL, $deleteTableRowAtSelection, $deleteTableRow__EXPERIMENTAL, $findCellNode, $findTableNode, $getElementForTableNode, $getNodeTriplet, $getTableAndElementByKey, $getTableCellNodeFromLexicalNode, $getTableCellNodeRect, $getTableColumnIndexFromTableCellNode, $getTableNodeFromLexicalNodeOrThrow, $getTableRowIndexFromTableCellNode, $getTableRowNodeFromTableCellNodeOrThrow, $insertTableColumn, $insertTableColumnAtSelection, $insertTableColumn__EXPERIMENTAL, $insertTableRow, $insertTableRowAtSelection, $insertTableRow__EXPERIMENTAL, $isScrollableTablesActive, $isTableCellNode, $isTableNode, $isTableRowNode, $isTableSelection, $mergeCells, $removeTableRowAtIndex, $unmergeCell, INSERT_TABLE_COMMAND, TableCellHeaderStates, TableCellNode, TableNode, TableObserver, TableRowNode, applyTableHandlers, getDOMCellFromTarget, getTableElement, getTableObserverFromTableElement, registerTableCellUnmergeTransform, registerTablePlugin, registerTableSelectionObserver, setScrollableTablesActive };