@react-fabric/lexical 1.0.0-beta.6 → 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 (134) hide show
  1. package/{src/editor/Lexical.module.css → css/_lexical.css} +8 -4
  2. package/css/styles.css +24 -0
  3. package/dist/cjs/{packages/lexical/src/components → components}/StickyComponent.js +3 -4
  4. package/dist/cjs/{packages/lexical/src/editor → editor}/LexicalEditor.js +35 -10
  5. package/dist/cjs/{packages/lexical/src/hooks → hooks}/useFormatWatcher.js +154 -145
  6. package/dist/cjs/i18n/ar.json.js +24 -0
  7. package/dist/cjs/i18n/en.json.js +24 -0
  8. package/dist/cjs/i18n/index.js +33 -0
  9. package/dist/cjs/{packages/lexical/src/index.js → index.js} +1 -0
  10. package/dist/cjs/{packages/lexical/src/plugins → plugins}/DraggableBlockPlugin.js +5 -5
  11. package/dist/cjs/{packages/lexical/src/plugins → plugins}/ToolbarPlugin.js +55 -34
  12. package/dist/esm/{packages/lexical/src/components → components}/StickyComponent.js +3 -4
  13. package/dist/esm/{packages/lexical/src/editor → editor}/LexicalEditor.js +34 -9
  14. package/dist/esm/{packages/lexical/src/hooks → hooks}/useFormatWatcher.js +102 -93
  15. package/dist/esm/i18n/ar.json.js +21 -0
  16. package/dist/esm/i18n/en.json.js +21 -0
  17. package/dist/esm/i18n/index.js +33 -0
  18. package/dist/esm/{packages/lexical/src/index.js → index.js} +1 -0
  19. package/dist/esm/{packages/lexical/src/plugins → plugins}/DraggableBlockPlugin.js +2 -2
  20. package/dist/esm/{packages/lexical/src/plugins → plugins}/ToolbarPlugin.js +56 -35
  21. package/dist/types/editor/LexicalEditor.d.ts +25 -0
  22. package/dist/types/hooks/useFormatWatcher.d.ts +3 -2
  23. package/dist/types/i18n/index.d.ts +1 -0
  24. package/dist/types/index.d.ts +1 -0
  25. package/dist/types/nodes/StickyNode.d.ts +0 -1
  26. package/package.json +14 -13
  27. package/src/components/StickyComponent.tsx +4 -5
  28. package/src/editor/LexicalEditor.tsx +57 -26
  29. package/src/hooks/useFormatWatcher.ts +38 -31
  30. package/src/i18n/ar.json +16 -0
  31. package/src/i18n/en.json +16 -0
  32. package/src/i18n/index.ts +28 -0
  33. package/src/index.ts +2 -0
  34. package/src/plugins/ToolbarPlugin.tsx +56 -35
  35. package/dist/cjs/_virtual/prism.js +0 -5
  36. package/dist/cjs/editor/Lexical.module.css +0 -1
  37. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.dev.js +0 -432
  38. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.js +0 -21
  39. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.prod.js +0 -27
  40. package/dist/cjs/node_modules/@lexical/code/LexicalCode.dev.js +0 -1139
  41. package/dist/cjs/node_modules/@lexical/code/LexicalCode.js +0 -25
  42. package/dist/cjs/node_modules/@lexical/code/LexicalCode.prod.js +0 -50
  43. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.dev.js +0 -245
  44. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.js +0 -19
  45. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.prod.js +0 -18
  46. package/dist/cjs/node_modules/@lexical/link/LexicalLink.dev.js +0 -471
  47. package/dist/cjs/node_modules/@lexical/link/LexicalLink.js +0 -17
  48. package/dist/cjs/node_modules/@lexical/link/LexicalLink.prod.js +0 -24
  49. package/dist/cjs/node_modules/@lexical/list/LexicalList.dev.js +0 -1275
  50. package/dist/cjs/node_modules/@lexical/list/LexicalList.js +0 -29
  51. package/dist/cjs/node_modules/@lexical/list/LexicalList.prod.js +0 -29
  52. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.dev.js +0 -789
  53. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.js +0 -29
  54. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.prod.js +0 -26
  55. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.dev.js +0 -976
  56. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.js +0 -35
  57. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.prod.js +0 -35
  58. package/dist/cjs/node_modules/@lexical/table/LexicalTable.dev.js +0 -2792
  59. package/dist/cjs/node_modules/@lexical/table/LexicalTable.js +0 -23
  60. package/dist/cjs/node_modules/@lexical/table/LexicalTable.prod.js +0 -55
  61. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.dev.js +0 -888
  62. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.js +0 -35
  63. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.prod.js +0 -66
  64. package/dist/cjs/node_modules/@mdi/js/mdi.js +0 -8
  65. package/dist/cjs/node_modules/prismjs/components/prism-c.js +0 -82
  66. package/dist/cjs/node_modules/prismjs/components/prism-clike.js +0 -33
  67. package/dist/cjs/node_modules/prismjs/components/prism-cpp.js +0 -101
  68. package/dist/cjs/node_modules/prismjs/components/prism-css.js +0 -66
  69. package/dist/cjs/node_modules/prismjs/components/prism-java.js +0 -126
  70. package/dist/cjs/node_modules/prismjs/components/prism-javascript.js +0 -174
  71. package/dist/cjs/node_modules/prismjs/components/prism-markdown.js +0 -417
  72. package/dist/cjs/node_modules/prismjs/components/prism-markup.js +0 -188
  73. package/dist/cjs/node_modules/prismjs/components/prism-objectivec.js +0 -14
  74. package/dist/cjs/node_modules/prismjs/components/prism-powershell.js +0 -60
  75. package/dist/cjs/node_modules/prismjs/components/prism-python.js +0 -67
  76. package/dist/cjs/node_modules/prismjs/components/prism-rust.js +0 -130
  77. package/dist/cjs/node_modules/prismjs/components/prism-sql.js +0 -34
  78. package/dist/cjs/node_modules/prismjs/components/prism-swift.js +0 -150
  79. package/dist/cjs/node_modules/prismjs/components/prism-typescript.js +0 -62
  80. package/dist/cjs/node_modules/prismjs/prism.js +0 -1951
  81. package/dist/esm/_virtual/prism.js +0 -5
  82. package/dist/esm/editor/Lexical.module.css +0 -1
  83. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.dev.js +0 -423
  84. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.js +0 -19
  85. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.prod.js +0 -18
  86. package/dist/esm/node_modules/@lexical/code/LexicalCode.dev.js +0 -1121
  87. package/dist/esm/node_modules/@lexical/code/LexicalCode.js +0 -21
  88. package/dist/esm/node_modules/@lexical/code/LexicalCode.prod.js +0 -32
  89. package/dist/esm/node_modules/@lexical/html/LexicalHtml.dev.js +0 -244
  90. package/dist/esm/node_modules/@lexical/html/LexicalHtml.js +0 -18
  91. package/dist/esm/node_modules/@lexical/html/LexicalHtml.prod.js +0 -17
  92. package/dist/esm/node_modules/@lexical/link/LexicalLink.dev.js +0 -463
  93. package/dist/esm/node_modules/@lexical/link/LexicalLink.js +0 -17
  94. package/dist/esm/node_modules/@lexical/link/LexicalLink.prod.js +0 -16
  95. package/dist/esm/node_modules/@lexical/list/LexicalList.dev.js +0 -1262
  96. package/dist/esm/node_modules/@lexical/list/LexicalList.js +0 -23
  97. package/dist/esm/node_modules/@lexical/list/LexicalList.prod.js +0 -16
  98. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.dev.js +0 -781
  99. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.js +0 -23
  100. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.prod.js +0 -18
  101. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.dev.js +0 -957
  102. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.js +0 -26
  103. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.prod.js +0 -16
  104. package/dist/esm/node_modules/@lexical/table/LexicalTable.dev.js +0 -2754
  105. package/dist/esm/node_modules/@lexical/table/LexicalTable.js +0 -20
  106. package/dist/esm/node_modules/@lexical/table/LexicalTable.prod.js +0 -17
  107. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.dev.js +0 -839
  108. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.js +0 -26
  109. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.prod.js +0 -17
  110. package/dist/esm/node_modules/@mdi/js/mdi.js +0 -7
  111. package/dist/esm/node_modules/prismjs/components/prism-c.js +0 -82
  112. package/dist/esm/node_modules/prismjs/components/prism-clike.js +0 -33
  113. package/dist/esm/node_modules/prismjs/components/prism-cpp.js +0 -101
  114. package/dist/esm/node_modules/prismjs/components/prism-css.js +0 -66
  115. package/dist/esm/node_modules/prismjs/components/prism-java.js +0 -126
  116. package/dist/esm/node_modules/prismjs/components/prism-javascript.js +0 -174
  117. package/dist/esm/node_modules/prismjs/components/prism-markdown.js +0 -417
  118. package/dist/esm/node_modules/prismjs/components/prism-markup.js +0 -188
  119. package/dist/esm/node_modules/prismjs/components/prism-objectivec.js +0 -14
  120. package/dist/esm/node_modules/prismjs/components/prism-powershell.js +0 -60
  121. package/dist/esm/node_modules/prismjs/components/prism-python.js +0 -67
  122. package/dist/esm/node_modules/prismjs/components/prism-rust.js +0 -130
  123. package/dist/esm/node_modules/prismjs/components/prism-sql.js +0 -34
  124. package/dist/esm/node_modules/prismjs/components/prism-swift.js +0 -150
  125. package/dist/esm/node_modules/prismjs/components/prism-typescript.js +0 -62
  126. package/dist/esm/node_modules/prismjs/prism.js +0 -1951
  127. /package/dist/cjs/{packages/lexical/src/editor → editor}/theme.js +0 -0
  128. /package/dist/cjs/{packages/lexical/src/nodes → nodes}/StickyNode.js +0 -0
  129. /package/dist/cjs/{packages/lexical/src/plugins → plugins}/StickyPlugin.js +0 -0
  130. /package/dist/cjs/{packages/lexical/src/utils → utils}/index.js +0 -0
  131. /package/dist/esm/{packages/lexical/src/editor → editor}/theme.js +0 -0
  132. /package/dist/esm/{packages/lexical/src/nodes → nodes}/StickyNode.js +0 -0
  133. /package/dist/esm/{packages/lexical/src/plugins → plugins}/StickyPlugin.js +0 -0
  134. /package/dist/esm/{packages/lexical/src/utils → utils}/index.js +0 -0
@@ -1,2754 +0,0 @@
1
- 'use client';
2
-
3
- import { addClassNamesToElement, $findMatchingParent, removeClassNamesFromElement, objectKlassEquals, isHTMLElement } from '../utils/LexicalUtils.js';
4
- import { ElementNode, $createParagraphNode, $isElementNode, $isLineBreakNode, $isTextNode, $applyNodeReplacement, createCommand, $createTextNode, $getSelection, $isRangeSelection, $createPoint, $getNodeByKey, $setSelection, SELECTION_CHANGE_COMMAND, $getNearestNodeFromDOMNode, $createRangeSelection, $getRoot, KEY_ARROW_DOWN_COMMAND, COMMAND_PRIORITY_HIGH, KEY_ARROW_UP_COMMAND, KEY_ARROW_LEFT_COMMAND, KEY_ARROW_RIGHT_COMMAND, KEY_ESCAPE_COMMAND, DELETE_WORD_COMMAND, DELETE_LINE_COMMAND, DELETE_CHARACTER_COMMAND, COMMAND_PRIORITY_CRITICAL, KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, CUT_COMMAND, FORMAT_TEXT_COMMAND, FORMAT_ELEMENT_COMMAND, CONTROLLED_TEXT_INSERTION_COMMAND, KEY_TAB_COMMAND, FOCUS_COMMAND, SELECTION_INSERT_CLIPBOARD_NODES_COMMAND, $getPreviousSelection, $createRangeSelectionFromDom, INSERT_PARAGRAPH_COMMAND, $isRootOrShadowRoot, $isDecoratorNode, $normalizeSelection__EXPERIMENTAL, isCurrentlyReadOnlyMode } 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
- static getType() {
57
- return 'tablecell';
58
- }
59
- static clone(node) {
60
- const cellNode = new TableCellNode(node.__headerState, node.__colSpan, node.__width, node.__key);
61
- cellNode.__rowSpan = node.__rowSpan;
62
- cellNode.__backgroundColor = node.__backgroundColor;
63
- return cellNode;
64
- }
65
- static importDOM() {
66
- return {
67
- td: node => ({
68
- conversion: $convertTableCellNodeElement,
69
- priority: 0
70
- }),
71
- th: node => ({
72
- conversion: $convertTableCellNodeElement,
73
- priority: 0
74
- })
75
- };
76
- }
77
- static importJSON(serializedNode) {
78
- const colSpan = serializedNode.colSpan || 1;
79
- const rowSpan = serializedNode.rowSpan || 1;
80
- const cellNode = $createTableCellNode(serializedNode.headerState, colSpan, serializedNode.width || undefined);
81
- cellNode.__rowSpan = rowSpan;
82
- cellNode.__backgroundColor = serializedNode.backgroundColor || null;
83
- return cellNode;
84
- }
85
- constructor(headerState = TableCellHeaderStates.NO_STATUS, colSpan = 1, width, key) {
86
- super(key);
87
- this.__colSpan = colSpan;
88
- this.__rowSpan = 1;
89
- this.__headerState = headerState;
90
- this.__width = width;
91
- this.__backgroundColor = null;
92
- }
93
- createDOM(config) {
94
- const element = document.createElement(this.getTag());
95
- if (this.__width) {
96
- element.style.width = `${this.__width}px`;
97
- }
98
- if (this.__colSpan > 1) {
99
- element.colSpan = this.__colSpan;
100
- }
101
- if (this.__rowSpan > 1) {
102
- element.rowSpan = this.__rowSpan;
103
- }
104
- if (this.__backgroundColor !== null) {
105
- element.style.backgroundColor = this.__backgroundColor;
106
- }
107
- addClassNamesToElement(element, config.theme.tableCell, this.hasHeader() && config.theme.tableCellHeader);
108
- return element;
109
- }
110
- exportDOM(editor) {
111
- const {
112
- element
113
- } = super.exportDOM(editor);
114
- if (element) {
115
- const element_ = element;
116
- element_.style.border = '1px solid black';
117
- if (this.__colSpan > 1) {
118
- element_.colSpan = this.__colSpan;
119
- }
120
- if (this.__rowSpan > 1) {
121
- element_.rowSpan = this.__rowSpan;
122
- }
123
- element_.style.width = `${this.getWidth() || COLUMN_WIDTH}px`;
124
- element_.style.verticalAlign = 'top';
125
- element_.style.textAlign = 'start';
126
- const backgroundColor = this.getBackgroundColor();
127
- if (backgroundColor !== null) {
128
- element_.style.backgroundColor = backgroundColor;
129
- } else if (this.hasHeader()) {
130
- element_.style.backgroundColor = '#f2f3f5';
131
- }
132
- }
133
- return {
134
- element
135
- };
136
- }
137
- exportJSON() {
138
- return {
139
- ...super.exportJSON(),
140
- backgroundColor: this.getBackgroundColor(),
141
- colSpan: this.__colSpan,
142
- headerState: this.__headerState,
143
- rowSpan: this.__rowSpan,
144
- type: 'tablecell',
145
- width: this.getWidth()
146
- };
147
- }
148
- getColSpan() {
149
- return this.__colSpan;
150
- }
151
- setColSpan(colSpan) {
152
- this.getWritable().__colSpan = colSpan;
153
- return this;
154
- }
155
- getRowSpan() {
156
- return this.__rowSpan;
157
- }
158
- setRowSpan(rowSpan) {
159
- this.getWritable().__rowSpan = rowSpan;
160
- return this;
161
- }
162
- getTag() {
163
- return this.hasHeader() ? 'th' : 'td';
164
- }
165
- setHeaderStyles(headerState) {
166
- const self = this.getWritable();
167
- self.__headerState = headerState;
168
- return this.__headerState;
169
- }
170
- getHeaderStyles() {
171
- return this.getLatest().__headerState;
172
- }
173
- setWidth(width) {
174
- const self = this.getWritable();
175
- self.__width = width;
176
- return this.__width;
177
- }
178
- getWidth() {
179
- return this.getLatest().__width;
180
- }
181
- getBackgroundColor() {
182
- return this.getLatest().__backgroundColor;
183
- }
184
- setBackgroundColor(newBackgroundColor) {
185
- this.getWritable().__backgroundColor = newBackgroundColor;
186
- }
187
- toggleHeaderStyle(headerStateToToggle) {
188
- const self = this.getWritable();
189
- if ((self.__headerState & headerStateToToggle) === headerStateToToggle) {
190
- self.__headerState -= headerStateToToggle;
191
- } else {
192
- self.__headerState += headerStateToToggle;
193
- }
194
- return self;
195
- }
196
- hasHeaderState(headerState) {
197
- return (this.getHeaderStyles() & headerState) === headerState;
198
- }
199
- hasHeader() {
200
- return this.getLatest().__headerState !== TableCellHeaderStates.NO_STATUS;
201
- }
202
- updateDOM(prevNode) {
203
- return prevNode.__headerState !== this.__headerState || prevNode.__width !== this.__width || prevNode.__colSpan !== this.__colSpan || prevNode.__rowSpan !== this.__rowSpan || prevNode.__backgroundColor !== this.__backgroundColor;
204
- }
205
- isShadowRoot() {
206
- return true;
207
- }
208
- collapseAtStart() {
209
- return true;
210
- }
211
- canBeEmpty() {
212
- return false;
213
- }
214
- canIndent() {
215
- return false;
216
- }
217
- }
218
- function $convertTableCellNodeElement(domNode) {
219
- const domNode_ = domNode;
220
- const nodeName = domNode.nodeName.toLowerCase();
221
- let width = undefined;
222
- if (PIXEL_VALUE_REG_EXP.test(domNode_.style.width)) {
223
- width = parseFloat(domNode_.style.width);
224
- }
225
- const tableCellNode = $createTableCellNode(nodeName === 'th' ? TableCellHeaderStates.ROW : TableCellHeaderStates.NO_STATUS, domNode_.colSpan, width);
226
- tableCellNode.__rowSpan = domNode_.rowSpan;
227
- const backgroundColor = domNode_.style.backgroundColor;
228
- if (backgroundColor !== '') {
229
- tableCellNode.__backgroundColor = backgroundColor;
230
- }
231
- const style = domNode_.style;
232
- const textDecoration = style.textDecoration.split(' ');
233
- const hasBoldFontWeight = style.fontWeight === '700' || style.fontWeight === 'bold';
234
- const hasLinethroughTextDecoration = textDecoration.includes('line-through');
235
- const hasItalicFontStyle = style.fontStyle === 'italic';
236
- const hasUnderlineTextDecoration = textDecoration.includes('underline');
237
- return {
238
- after: childLexicalNodes => {
239
- if (childLexicalNodes.length === 0) {
240
- childLexicalNodes.push($createParagraphNode());
241
- }
242
- return childLexicalNodes;
243
- },
244
- forChild: (lexicalNode, parentLexicalNode) => {
245
- if ($isTableCellNode(parentLexicalNode) && !$isElementNode(lexicalNode)) {
246
- const paragraphNode = $createParagraphNode();
247
- if ($isLineBreakNode(lexicalNode) && lexicalNode.getTextContent() === '\n') {
248
- return null;
249
- }
250
- if ($isTextNode(lexicalNode)) {
251
- if (hasBoldFontWeight) {
252
- lexicalNode.toggleFormat('bold');
253
- }
254
- if (hasLinethroughTextDecoration) {
255
- lexicalNode.toggleFormat('strikethrough');
256
- }
257
- if (hasItalicFontStyle) {
258
- lexicalNode.toggleFormat('italic');
259
- }
260
- if (hasUnderlineTextDecoration) {
261
- lexicalNode.toggleFormat('underline');
262
- }
263
- }
264
- paragraphNode.append(lexicalNode);
265
- return paragraphNode;
266
- }
267
- return lexicalNode;
268
- },
269
- node: tableCellNode
270
- };
271
- }
272
- function $createTableCellNode(headerState, colSpan = 1, width) {
273
- return $applyNodeReplacement(new TableCellNode(headerState, colSpan, width));
274
- }
275
- function $isTableCellNode(node) {
276
- return node instanceof TableCellNode;
277
- }
278
-
279
- /**
280
- * Copyright (c) Meta Platforms, Inc. and affiliates.
281
- *
282
- * This source code is licensed under the MIT license found in the
283
- * LICENSE file in the root directory of this source tree.
284
- *
285
- */
286
-
287
- const INSERT_TABLE_COMMAND = createCommand('INSERT_TABLE_COMMAND');
288
-
289
- /**
290
- * Copyright (c) Meta Platforms, Inc. and affiliates.
291
- *
292
- * This source code is licensed under the MIT license found in the
293
- * LICENSE file in the root directory of this source tree.
294
- *
295
- */
296
-
297
- /** @noInheritDoc */
298
- class TableRowNode extends ElementNode {
299
- /** @internal */
300
-
301
- static getType() {
302
- return 'tablerow';
303
- }
304
- static clone(node) {
305
- return new TableRowNode(node.__height, node.__key);
306
- }
307
- static importDOM() {
308
- return {
309
- tr: node => ({
310
- conversion: $convertTableRowElement,
311
- priority: 0
312
- })
313
- };
314
- }
315
- static importJSON(serializedNode) {
316
- return $createTableRowNode(serializedNode.height);
317
- }
318
- constructor(height, key) {
319
- super(key);
320
- this.__height = height;
321
- }
322
- exportJSON() {
323
- return {
324
- ...super.exportJSON(),
325
- ...(this.getHeight() && {
326
- height: this.getHeight()
327
- }),
328
- type: 'tablerow',
329
- version: 1
330
- };
331
- }
332
- createDOM(config) {
333
- const element = document.createElement('tr');
334
- if (this.__height) {
335
- element.style.height = `${this.__height}px`;
336
- }
337
- addClassNamesToElement(element, config.theme.tableRow);
338
- return element;
339
- }
340
- isShadowRoot() {
341
- return true;
342
- }
343
- setHeight(height) {
344
- const self = this.getWritable();
345
- self.__height = height;
346
- return this.__height;
347
- }
348
- getHeight() {
349
- return this.getLatest().__height;
350
- }
351
- updateDOM(prevNode) {
352
- return prevNode.__height !== this.__height;
353
- }
354
- canBeEmpty() {
355
- return false;
356
- }
357
- canIndent() {
358
- return false;
359
- }
360
- }
361
- function $convertTableRowElement(domNode) {
362
- const domNode_ = domNode;
363
- let height = undefined;
364
- if (PIXEL_VALUE_REG_EXP.test(domNode_.style.height)) {
365
- height = parseFloat(domNode_.style.height);
366
- }
367
- return {
368
- node: $createTableRowNode(height)
369
- };
370
- }
371
- function $createTableRowNode(height) {
372
- return $applyNodeReplacement(new TableRowNode(height));
373
- }
374
- function $isTableRowNode(node) {
375
- return node instanceof TableRowNode;
376
- }
377
-
378
- /**
379
- * Copyright (c) Meta Platforms, Inc. and affiliates.
380
- *
381
- * This source code is licensed under the MIT license found in the
382
- * LICENSE file in the root directory of this source tree.
383
- *
384
- */
385
-
386
- const CAN_USE_DOM = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined';
387
-
388
- /**
389
- * Copyright (c) Meta Platforms, Inc. and affiliates.
390
- *
391
- * This source code is licensed under the MIT license found in the
392
- * LICENSE file in the root directory of this source tree.
393
- *
394
- */
395
-
396
- function $createTableNodeWithDimensions(rowCount, columnCount, includeHeaders = true) {
397
- const tableNode = $createTableNode();
398
- for (let iRow = 0; iRow < rowCount; iRow++) {
399
- const tableRowNode = $createTableRowNode();
400
- for (let iColumn = 0; iColumn < columnCount; iColumn++) {
401
- let headerState = TableCellHeaderStates.NO_STATUS;
402
- if (typeof includeHeaders === 'object') {
403
- if (iRow === 0 && includeHeaders.rows) {
404
- headerState |= TableCellHeaderStates.ROW;
405
- }
406
- if (iColumn === 0 && includeHeaders.columns) {
407
- headerState |= TableCellHeaderStates.COLUMN;
408
- }
409
- } else if (includeHeaders) {
410
- if (iRow === 0) {
411
- headerState |= TableCellHeaderStates.ROW;
412
- }
413
- if (iColumn === 0) {
414
- headerState |= TableCellHeaderStates.COLUMN;
415
- }
416
- }
417
- const tableCellNode = $createTableCellNode(headerState);
418
- const paragraphNode = $createParagraphNode();
419
- paragraphNode.append($createTextNode());
420
- tableCellNode.append(paragraphNode);
421
- tableRowNode.append(tableCellNode);
422
- }
423
- tableNode.append(tableRowNode);
424
- }
425
- return tableNode;
426
- }
427
- function $getTableCellNodeFromLexicalNode(startingNode) {
428
- const node = $findMatchingParent(startingNode, n => $isTableCellNode(n));
429
- if ($isTableCellNode(node)) {
430
- return node;
431
- }
432
- return null;
433
- }
434
- function $getTableRowNodeFromTableCellNodeOrThrow(startingNode) {
435
- const node = $findMatchingParent(startingNode, n => $isTableRowNode(n));
436
- if ($isTableRowNode(node)) {
437
- return node;
438
- }
439
- throw new Error('Expected table cell to be inside of table row.');
440
- }
441
- function $getTableNodeFromLexicalNodeOrThrow(startingNode) {
442
- const node = $findMatchingParent(startingNode, n => $isTableNode(n));
443
- if ($isTableNode(node)) {
444
- return node;
445
- }
446
- throw new Error('Expected table cell to be inside of table.');
447
- }
448
- function $getTableRowIndexFromTableCellNode(tableCellNode) {
449
- const tableRowNode = $getTableRowNodeFromTableCellNodeOrThrow(tableCellNode);
450
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableRowNode);
451
- return tableNode.getChildren().findIndex(n => n.is(tableRowNode));
452
- }
453
- function $getTableColumnIndexFromTableCellNode(tableCellNode) {
454
- const tableRowNode = $getTableRowNodeFromTableCellNodeOrThrow(tableCellNode);
455
- return tableRowNode.getChildren().findIndex(n => n.is(tableCellNode));
456
- }
457
- function $getTableCellSiblingsFromTableCellNode(tableCellNode, table) {
458
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCellNode);
459
- const {
460
- x,
461
- y
462
- } = tableNode.getCordsFromCellNode(tableCellNode, table);
463
- return {
464
- above: tableNode.getCellNodeFromCords(x, y - 1, table),
465
- below: tableNode.getCellNodeFromCords(x, y + 1, table),
466
- left: tableNode.getCellNodeFromCords(x - 1, y, table),
467
- right: tableNode.getCellNodeFromCords(x + 1, y, table)
468
- };
469
- }
470
- function $removeTableRowAtIndex(tableNode, indexToDelete) {
471
- const tableRows = tableNode.getChildren();
472
- if (indexToDelete >= tableRows.length || indexToDelete < 0) {
473
- throw new Error('Expected table cell to be inside of table row.');
474
- }
475
- const targetRowNode = tableRows[indexToDelete];
476
- targetRowNode.remove();
477
- return tableNode;
478
- }
479
- function $insertTableRow(tableNode, targetIndex, shouldInsertAfter = true, rowCount, table) {
480
- const tableRows = tableNode.getChildren();
481
- if (targetIndex >= tableRows.length || targetIndex < 0) {
482
- throw new Error('Table row target index out of range');
483
- }
484
- const targetRowNode = tableRows[targetIndex];
485
- if ($isTableRowNode(targetRowNode)) {
486
- for (let r = 0; r < rowCount; r++) {
487
- const tableRowCells = targetRowNode.getChildren();
488
- const tableColumnCount = tableRowCells.length;
489
- const newTableRowNode = $createTableRowNode();
490
- for (let c = 0; c < tableColumnCount; c++) {
491
- const tableCellFromTargetRow = tableRowCells[c];
492
- if (!$isTableCellNode(tableCellFromTargetRow)) {
493
- throw Error(`Expected table cell`);
494
- }
495
- const {
496
- above,
497
- below
498
- } = $getTableCellSiblingsFromTableCellNode(tableCellFromTargetRow, table);
499
- let headerState = TableCellHeaderStates.NO_STATUS;
500
- const width = above && above.getWidth() || below && below.getWidth() || undefined;
501
- if (above && above.hasHeaderState(TableCellHeaderStates.COLUMN) || below && below.hasHeaderState(TableCellHeaderStates.COLUMN)) {
502
- headerState |= TableCellHeaderStates.COLUMN;
503
- }
504
- const tableCellNode = $createTableCellNode(headerState, 1, width);
505
- tableCellNode.append($createParagraphNode());
506
- newTableRowNode.append(tableCellNode);
507
- }
508
- if (shouldInsertAfter) {
509
- targetRowNode.insertAfter(newTableRowNode);
510
- } else {
511
- targetRowNode.insertBefore(newTableRowNode);
512
- }
513
- }
514
- } else {
515
- throw new Error('Row before insertion index does not exist.');
516
- }
517
- return tableNode;
518
- }
519
- const getHeaderState = (currentState, possibleState) => {
520
- if (currentState === TableCellHeaderStates.BOTH || currentState === possibleState) {
521
- return possibleState;
522
- }
523
- return TableCellHeaderStates.NO_STATUS;
524
- };
525
- function $insertTableRow__EXPERIMENTAL(insertAfter = true) {
526
- const selection = $getSelection();
527
- if (!($isRangeSelection(selection) || $isTableSelection(selection))) {
528
- throw Error(`Expected a RangeSelection or TableSelection`);
529
- }
530
- const focus = selection.focus.getNode();
531
- const [focusCell,, grid] = $getNodeTriplet(focus);
532
- const [gridMap, focusCellMap] = $computeTableMap(grid, focusCell, focusCell);
533
- const columnCount = gridMap[0].length;
534
- const {
535
- startRow: focusStartRow
536
- } = focusCellMap;
537
- if (insertAfter) {
538
- const focusEndRow = focusStartRow + focusCell.__rowSpan - 1;
539
- const focusEndRowMap = gridMap[focusEndRow];
540
- const newRow = $createTableRowNode();
541
- for (let i = 0; i < columnCount; i++) {
542
- const {
543
- cell,
544
- startRow
545
- } = focusEndRowMap[i];
546
- if (startRow + cell.__rowSpan - 1 <= focusEndRow) {
547
- const currentCell = focusEndRowMap[i].cell;
548
- const currentCellHeaderState = currentCell.__headerState;
549
- const headerState = getHeaderState(currentCellHeaderState, TableCellHeaderStates.COLUMN);
550
- newRow.append($createTableCellNode(headerState).append($createParagraphNode()));
551
- } else {
552
- cell.setRowSpan(cell.__rowSpan + 1);
553
- }
554
- }
555
- const focusEndRowNode = grid.getChildAtIndex(focusEndRow);
556
- if (!$isTableRowNode(focusEndRowNode)) {
557
- throw Error(`focusEndRow is not a TableRowNode`);
558
- }
559
- focusEndRowNode.insertAfter(newRow);
560
- } else {
561
- const focusStartRowMap = gridMap[focusStartRow];
562
- const newRow = $createTableRowNode();
563
- for (let i = 0; i < columnCount; i++) {
564
- const {
565
- cell,
566
- startRow
567
- } = focusStartRowMap[i];
568
- if (startRow === focusStartRow) {
569
- const currentCell = focusStartRowMap[i].cell;
570
- const currentCellHeaderState = currentCell.__headerState;
571
- const headerState = getHeaderState(currentCellHeaderState, TableCellHeaderStates.COLUMN);
572
- newRow.append($createTableCellNode(headerState).append($createParagraphNode()));
573
- } else {
574
- cell.setRowSpan(cell.__rowSpan + 1);
575
- }
576
- }
577
- const focusStartRowNode = grid.getChildAtIndex(focusStartRow);
578
- if (!$isTableRowNode(focusStartRowNode)) {
579
- throw Error(`focusEndRow is not a TableRowNode`);
580
- }
581
- focusStartRowNode.insertBefore(newRow);
582
- }
583
- }
584
- function $insertTableColumn(tableNode, targetIndex, shouldInsertAfter = true, columnCount, table) {
585
- const tableRows = tableNode.getChildren();
586
- const tableCellsToBeInserted = [];
587
- for (let r = 0; r < tableRows.length; r++) {
588
- const currentTableRowNode = tableRows[r];
589
- if ($isTableRowNode(currentTableRowNode)) {
590
- for (let c = 0; c < columnCount; c++) {
591
- const tableRowChildren = currentTableRowNode.getChildren();
592
- if (targetIndex >= tableRowChildren.length || targetIndex < 0) {
593
- throw new Error('Table column target index out of range');
594
- }
595
- const targetCell = tableRowChildren[targetIndex];
596
- if (!$isTableCellNode(targetCell)) {
597
- throw Error(`Expected table cell`);
598
- }
599
- const {
600
- left,
601
- right
602
- } = $getTableCellSiblingsFromTableCellNode(targetCell, table);
603
- let headerState = TableCellHeaderStates.NO_STATUS;
604
- if (left && left.hasHeaderState(TableCellHeaderStates.ROW) || right && right.hasHeaderState(TableCellHeaderStates.ROW)) {
605
- headerState |= TableCellHeaderStates.ROW;
606
- }
607
- const newTableCell = $createTableCellNode(headerState);
608
- newTableCell.append($createParagraphNode());
609
- tableCellsToBeInserted.push({
610
- newTableCell,
611
- targetCell
612
- });
613
- }
614
- }
615
- }
616
- tableCellsToBeInserted.forEach(({
617
- newTableCell,
618
- targetCell
619
- }) => {
620
- if (shouldInsertAfter) {
621
- targetCell.insertAfter(newTableCell);
622
- } else {
623
- targetCell.insertBefore(newTableCell);
624
- }
625
- });
626
- return tableNode;
627
- }
628
- function $insertTableColumn__EXPERIMENTAL(insertAfter = true) {
629
- const selection = $getSelection();
630
- if (!($isRangeSelection(selection) || $isTableSelection(selection))) {
631
- throw Error(`Expected a RangeSelection or TableSelection`);
632
- }
633
- const anchor = selection.anchor.getNode();
634
- const focus = selection.focus.getNode();
635
- const [anchorCell] = $getNodeTriplet(anchor);
636
- const [focusCell,, grid] = $getNodeTriplet(focus);
637
- const [gridMap, focusCellMap, anchorCellMap] = $computeTableMap(grid, focusCell, anchorCell);
638
- const rowCount = gridMap.length;
639
- const startColumn = insertAfter ? Math.max(focusCellMap.startColumn, anchorCellMap.startColumn) : Math.min(focusCellMap.startColumn, anchorCellMap.startColumn);
640
- const insertAfterColumn = insertAfter ? startColumn + focusCell.__colSpan - 1 : startColumn - 1;
641
- const gridFirstChild = grid.getFirstChild();
642
- if (!$isTableRowNode(gridFirstChild)) {
643
- throw Error(`Expected firstTable child to be a row`);
644
- }
645
- let firstInsertedCell = null;
646
- function $createTableCellNodeForInsertTableColumn(headerState = TableCellHeaderStates.NO_STATUS) {
647
- const cell = $createTableCellNode(headerState).append($createParagraphNode());
648
- if (firstInsertedCell === null) {
649
- firstInsertedCell = cell;
650
- }
651
- return cell;
652
- }
653
- let loopRow = gridFirstChild;
654
- rowLoop: for (let i = 0; i < rowCount; i++) {
655
- if (i !== 0) {
656
- const currentRow = loopRow.getNextSibling();
657
- if (!$isTableRowNode(currentRow)) {
658
- throw Error(`Expected row nextSibling to be a row`);
659
- }
660
- loopRow = currentRow;
661
- }
662
- const rowMap = gridMap[i];
663
- const currentCellHeaderState = rowMap[insertAfterColumn < 0 ? 0 : insertAfterColumn].cell.__headerState;
664
- const headerState = getHeaderState(currentCellHeaderState, TableCellHeaderStates.ROW);
665
- if (insertAfterColumn < 0) {
666
- $insertFirst(loopRow, $createTableCellNodeForInsertTableColumn(headerState));
667
- continue;
668
- }
669
- const {
670
- cell: currentCell,
671
- startColumn: currentStartColumn,
672
- startRow: currentStartRow
673
- } = rowMap[insertAfterColumn];
674
- if (currentStartColumn + currentCell.__colSpan - 1 <= insertAfterColumn) {
675
- let insertAfterCell = currentCell;
676
- let insertAfterCellRowStart = currentStartRow;
677
- let prevCellIndex = insertAfterColumn;
678
- while (insertAfterCellRowStart !== i && insertAfterCell.__rowSpan > 1) {
679
- prevCellIndex -= currentCell.__colSpan;
680
- if (prevCellIndex >= 0) {
681
- const {
682
- cell: cell_,
683
- startRow: startRow_
684
- } = rowMap[prevCellIndex];
685
- insertAfterCell = cell_;
686
- insertAfterCellRowStart = startRow_;
687
- } else {
688
- loopRow.append($createTableCellNodeForInsertTableColumn(headerState));
689
- continue rowLoop;
690
- }
691
- }
692
- insertAfterCell.insertAfter($createTableCellNodeForInsertTableColumn(headerState));
693
- } else {
694
- currentCell.setColSpan(currentCell.__colSpan + 1);
695
- }
696
- }
697
- if (firstInsertedCell !== null) {
698
- $moveSelectionToCell(firstInsertedCell);
699
- }
700
- }
701
- function $deleteTableColumn(tableNode, targetIndex) {
702
- const tableRows = tableNode.getChildren();
703
- for (let i = 0; i < tableRows.length; i++) {
704
- const currentTableRowNode = tableRows[i];
705
- if ($isTableRowNode(currentTableRowNode)) {
706
- const tableRowChildren = currentTableRowNode.getChildren();
707
- if (targetIndex >= tableRowChildren.length || targetIndex < 0) {
708
- throw new Error('Table column target index out of range');
709
- }
710
- tableRowChildren[targetIndex].remove();
711
- }
712
- }
713
- return tableNode;
714
- }
715
- function $deleteTableRow__EXPERIMENTAL() {
716
- const selection = $getSelection();
717
- if (!($isRangeSelection(selection) || $isTableSelection(selection))) {
718
- throw Error(`Expected a RangeSelection or TableSelection`);
719
- }
720
- const anchor = selection.anchor.getNode();
721
- const focus = selection.focus.getNode();
722
- const [anchorCell,, grid] = $getNodeTriplet(anchor);
723
- const [focusCell] = $getNodeTriplet(focus);
724
- const [gridMap, anchorCellMap, focusCellMap] = $computeTableMap(grid, anchorCell, focusCell);
725
- const {
726
- startRow: anchorStartRow
727
- } = anchorCellMap;
728
- const {
729
- startRow: focusStartRow
730
- } = focusCellMap;
731
- const focusEndRow = focusStartRow + focusCell.__rowSpan - 1;
732
- if (gridMap.length === focusEndRow - anchorStartRow + 1) {
733
- // Empty grid
734
- grid.remove();
735
- return;
736
- }
737
- const columnCount = gridMap[0].length;
738
- const nextRow = gridMap[focusEndRow + 1];
739
- const nextRowNode = grid.getChildAtIndex(focusEndRow + 1);
740
- for (let row = focusEndRow; row >= anchorStartRow; row--) {
741
- for (let column = columnCount - 1; column >= 0; column--) {
742
- const {
743
- cell,
744
- startRow: cellStartRow,
745
- startColumn: cellStartColumn
746
- } = gridMap[row][column];
747
- if (cellStartColumn !== column) {
748
- // Don't repeat work for the same Cell
749
- continue;
750
- }
751
- // Rows overflowing top have to be trimmed
752
- if (row === anchorStartRow && cellStartRow < anchorStartRow) {
753
- cell.setRowSpan(cell.__rowSpan - (cellStartRow - anchorStartRow));
754
- }
755
- // Rows overflowing bottom have to be trimmed and moved to the next row
756
- if (cellStartRow >= anchorStartRow && cellStartRow + cell.__rowSpan - 1 > focusEndRow) {
757
- cell.setRowSpan(cell.__rowSpan - (focusEndRow - cellStartRow + 1));
758
- if (!(nextRowNode !== null)) {
759
- throw Error(`Expected nextRowNode not to be null`);
760
- }
761
- if (column === 0) {
762
- $insertFirst(nextRowNode, cell);
763
- } else {
764
- const {
765
- cell: previousCell
766
- } = nextRow[column - 1];
767
- previousCell.insertAfter(cell);
768
- }
769
- }
770
- }
771
- const rowNode = grid.getChildAtIndex(row);
772
- if (!$isTableRowNode(rowNode)) {
773
- throw Error(`Expected GridNode childAtIndex(${String(row)}) to be RowNode`);
774
- }
775
- rowNode.remove();
776
- }
777
- if (nextRow !== undefined) {
778
- const {
779
- cell
780
- } = nextRow[0];
781
- $moveSelectionToCell(cell);
782
- } else {
783
- const previousRow = gridMap[anchorStartRow - 1];
784
- const {
785
- cell
786
- } = previousRow[0];
787
- $moveSelectionToCell(cell);
788
- }
789
- }
790
- function $deleteTableColumn__EXPERIMENTAL() {
791
- const selection = $getSelection();
792
- if (!($isRangeSelection(selection) || $isTableSelection(selection))) {
793
- throw Error(`Expected a RangeSelection or TableSelection`);
794
- }
795
- const anchor = selection.anchor.getNode();
796
- const focus = selection.focus.getNode();
797
- const [anchorCell,, grid] = $getNodeTriplet(anchor);
798
- const [focusCell] = $getNodeTriplet(focus);
799
- const [gridMap, anchorCellMap, focusCellMap] = $computeTableMap(grid, anchorCell, focusCell);
800
- const {
801
- startColumn: anchorStartColumn
802
- } = anchorCellMap;
803
- const {
804
- startRow: focusStartRow,
805
- startColumn: focusStartColumn
806
- } = focusCellMap;
807
- const startColumn = Math.min(anchorStartColumn, focusStartColumn);
808
- const endColumn = Math.max(anchorStartColumn + anchorCell.__colSpan - 1, focusStartColumn + focusCell.__colSpan - 1);
809
- const selectedColumnCount = endColumn - startColumn + 1;
810
- const columnCount = gridMap[0].length;
811
- if (columnCount === endColumn - startColumn + 1) {
812
- // Empty grid
813
- grid.selectPrevious();
814
- grid.remove();
815
- return;
816
- }
817
- const rowCount = gridMap.length;
818
- for (let row = 0; row < rowCount; row++) {
819
- for (let column = startColumn; column <= endColumn; column++) {
820
- const {
821
- cell,
822
- startColumn: cellStartColumn
823
- } = gridMap[row][column];
824
- if (cellStartColumn < startColumn) {
825
- if (column === startColumn) {
826
- const overflowLeft = startColumn - cellStartColumn;
827
- // Overflowing left
828
- cell.setColSpan(cell.__colSpan -
829
- // Possible overflow right too
830
- Math.min(selectedColumnCount, cell.__colSpan - overflowLeft));
831
- }
832
- } else if (cellStartColumn + cell.__colSpan - 1 > endColumn) {
833
- if (column === endColumn) {
834
- // Overflowing right
835
- const inSelectedArea = endColumn - cellStartColumn + 1;
836
- cell.setColSpan(cell.__colSpan - inSelectedArea);
837
- }
838
- } else {
839
- cell.remove();
840
- }
841
- }
842
- }
843
- const focusRowMap = gridMap[focusStartRow];
844
- const nextColumn = anchorStartColumn > focusStartColumn ? focusRowMap[anchorStartColumn + anchorCell.__colSpan] : focusRowMap[focusStartColumn + focusCell.__colSpan];
845
- if (nextColumn !== undefined) {
846
- const {
847
- cell
848
- } = nextColumn;
849
- $moveSelectionToCell(cell);
850
- } else {
851
- const previousRow = focusStartColumn < anchorStartColumn ? focusRowMap[focusStartColumn - 1] : focusRowMap[anchorStartColumn - 1];
852
- const {
853
- cell
854
- } = previousRow;
855
- $moveSelectionToCell(cell);
856
- }
857
- }
858
- function $moveSelectionToCell(cell) {
859
- const firstDescendant = cell.getFirstDescendant();
860
- if (firstDescendant == null) {
861
- cell.selectStart();
862
- } else {
863
- firstDescendant.getParentOrThrow().selectStart();
864
- }
865
- }
866
- function $insertFirst(parent, node) {
867
- const firstChild = parent.getFirstChild();
868
- if (firstChild !== null) {
869
- firstChild.insertBefore(node);
870
- } else {
871
- parent.append(node);
872
- }
873
- }
874
- function $unmergeCell() {
875
- const selection = $getSelection();
876
- if (!($isRangeSelection(selection) || $isTableSelection(selection))) {
877
- throw Error(`Expected a RangeSelection or TableSelection`);
878
- }
879
- const anchor = selection.anchor.getNode();
880
- const [cell, row, grid] = $getNodeTriplet(anchor);
881
- const colSpan = cell.__colSpan;
882
- const rowSpan = cell.__rowSpan;
883
- if (colSpan > 1) {
884
- for (let i = 1; i < colSpan; i++) {
885
- cell.insertAfter($createTableCellNode(TableCellHeaderStates.NO_STATUS).append($createParagraphNode()));
886
- }
887
- cell.setColSpan(1);
888
- }
889
- if (rowSpan > 1) {
890
- const [map, cellMap] = $computeTableMap(grid, cell, cell);
891
- const {
892
- startColumn,
893
- startRow
894
- } = cellMap;
895
- let currentRowNode;
896
- for (let i = 1; i < rowSpan; i++) {
897
- const currentRow = startRow + i;
898
- const currentRowMap = map[currentRow];
899
- currentRowNode = (currentRowNode || row).getNextSibling();
900
- if (!$isTableRowNode(currentRowNode)) {
901
- throw Error(`Expected row next sibling to be a row`);
902
- }
903
- let insertAfterCell = null;
904
- for (let column = 0; column < startColumn; column++) {
905
- const currentCellMap = currentRowMap[column];
906
- const currentCell = currentCellMap.cell;
907
- if (currentCellMap.startRow === currentRow) {
908
- insertAfterCell = currentCell;
909
- }
910
- if (currentCell.__colSpan > 1) {
911
- column += currentCell.__colSpan - 1;
912
- }
913
- }
914
- if (insertAfterCell === null) {
915
- for (let j = 0; j < colSpan; j++) {
916
- $insertFirst(currentRowNode, $createTableCellNode(TableCellHeaderStates.NO_STATUS).append($createParagraphNode()));
917
- }
918
- } else {
919
- for (let j = 0; j < colSpan; j++) {
920
- insertAfterCell.insertAfter($createTableCellNode(TableCellHeaderStates.NO_STATUS).append($createParagraphNode()));
921
- }
922
- }
923
- }
924
- cell.setRowSpan(1);
925
- }
926
- }
927
- function $computeTableMap(grid, cellA, cellB) {
928
- const [tableMap, cellAValue, cellBValue] = $computeTableMapSkipCellCheck(grid, cellA, cellB);
929
- if (!(cellAValue !== null)) {
930
- throw Error(`Anchor not found in Grid`);
931
- }
932
- if (!(cellBValue !== null)) {
933
- throw Error(`Focus not found in Grid`);
934
- }
935
- return [tableMap, cellAValue, cellBValue];
936
- }
937
- function $computeTableMapSkipCellCheck(grid, cellA, cellB) {
938
- const tableMap = [];
939
- let cellAValue = null;
940
- let cellBValue = null;
941
- function write(startRow, startColumn, cell) {
942
- const value = {
943
- cell,
944
- startColumn,
945
- startRow
946
- };
947
- const rowSpan = cell.__rowSpan;
948
- const colSpan = cell.__colSpan;
949
- for (let i = 0; i < rowSpan; i++) {
950
- if (tableMap[startRow + i] === undefined) {
951
- tableMap[startRow + i] = [];
952
- }
953
- for (let j = 0; j < colSpan; j++) {
954
- tableMap[startRow + i][startColumn + j] = value;
955
- }
956
- }
957
- if (cellA !== null && cellA.is(cell)) {
958
- cellAValue = value;
959
- }
960
- if (cellB !== null && cellB.is(cell)) {
961
- cellBValue = value;
962
- }
963
- }
964
- function isEmpty(row, column) {
965
- return tableMap[row] === undefined || tableMap[row][column] === undefined;
966
- }
967
- const gridChildren = grid.getChildren();
968
- for (let i = 0; i < gridChildren.length; i++) {
969
- const row = gridChildren[i];
970
- if (!$isTableRowNode(row)) {
971
- throw Error(`Expected GridNode children to be TableRowNode`);
972
- }
973
- const rowChildren = row.getChildren();
974
- let j = 0;
975
- for (const cell of rowChildren) {
976
- if (!$isTableCellNode(cell)) {
977
- throw Error(`Expected TableRowNode children to be TableCellNode`);
978
- }
979
- while (!isEmpty(i, j)) {
980
- j++;
981
- }
982
- write(i, j, cell);
983
- j += cell.__colSpan;
984
- }
985
- }
986
- return [tableMap, cellAValue, cellBValue];
987
- }
988
- function $getNodeTriplet(source) {
989
- let cell;
990
- if (source instanceof TableCellNode) {
991
- cell = source;
992
- } else if ('__type' in source) {
993
- const cell_ = $findMatchingParent(source, $isTableCellNode);
994
- if (!$isTableCellNode(cell_)) {
995
- throw Error(`Expected to find a parent TableCellNode`);
996
- }
997
- cell = cell_;
998
- } else {
999
- const cell_ = $findMatchingParent(source.getNode(), $isTableCellNode);
1000
- if (!$isTableCellNode(cell_)) {
1001
- throw Error(`Expected to find a parent TableCellNode`);
1002
- }
1003
- cell = cell_;
1004
- }
1005
- const row = cell.getParent();
1006
- if (!$isTableRowNode(row)) {
1007
- throw Error(`Expected TableCellNode to have a parent TableRowNode`);
1008
- }
1009
- const grid = row.getParent();
1010
- if (!$isTableNode(grid)) {
1011
- throw Error(`Expected TableRowNode to have a parent GridNode`);
1012
- }
1013
- return [cell, row, grid];
1014
- }
1015
- function $getTableCellNodeRect(tableCellNode) {
1016
- const [cellNode,, gridNode] = $getNodeTriplet(tableCellNode);
1017
- const rows = gridNode.getChildren();
1018
- const rowCount = rows.length;
1019
- const columnCount = rows[0].getChildren().length;
1020
-
1021
- // Create a matrix of the same size as the table to track the position of each cell
1022
- const cellMatrix = new Array(rowCount);
1023
- for (let i = 0; i < rowCount; i++) {
1024
- cellMatrix[i] = new Array(columnCount);
1025
- }
1026
- for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
1027
- const row = rows[rowIndex];
1028
- const cells = row.getChildren();
1029
- let columnIndex = 0;
1030
- for (let cellIndex = 0; cellIndex < cells.length; cellIndex++) {
1031
- // Find the next available position in the matrix, skip the position of merged cells
1032
- while (cellMatrix[rowIndex][columnIndex]) {
1033
- columnIndex++;
1034
- }
1035
- const cell = cells[cellIndex];
1036
- const rowSpan = cell.__rowSpan || 1;
1037
- const colSpan = cell.__colSpan || 1;
1038
-
1039
- // Put the cell into the corresponding position in the matrix
1040
- for (let i = 0; i < rowSpan; i++) {
1041
- for (let j = 0; j < colSpan; j++) {
1042
- cellMatrix[rowIndex + i][columnIndex + j] = cell;
1043
- }
1044
- }
1045
-
1046
- // Return to the original index, row span and column span of the cell.
1047
- if (cellNode === cell) {
1048
- return {
1049
- colSpan,
1050
- columnIndex,
1051
- rowIndex,
1052
- rowSpan
1053
- };
1054
- }
1055
- columnIndex += colSpan;
1056
- }
1057
- }
1058
- return null;
1059
- }
1060
-
1061
- /**
1062
- * Copyright (c) Meta Platforms, Inc. and affiliates.
1063
- *
1064
- * This source code is licensed under the MIT license found in the
1065
- * LICENSE file in the root directory of this source tree.
1066
- *
1067
- */
1068
-
1069
- class TableSelection {
1070
- constructor(tableKey, anchor, focus) {
1071
- this.anchor = anchor;
1072
- this.focus = focus;
1073
- anchor._selection = this;
1074
- focus._selection = this;
1075
- this._cachedNodes = null;
1076
- this.dirty = false;
1077
- this.tableKey = tableKey;
1078
- }
1079
- getStartEndPoints() {
1080
- return [this.anchor, this.focus];
1081
- }
1082
-
1083
- /**
1084
- * Returns whether the Selection is "backwards", meaning the focus
1085
- * logically precedes the anchor in the EditorState.
1086
- * @returns true if the Selection is backwards, false otherwise.
1087
- */
1088
- isBackward() {
1089
- return this.focus.isBefore(this.anchor);
1090
- }
1091
- getCachedNodes() {
1092
- return this._cachedNodes;
1093
- }
1094
- setCachedNodes(nodes) {
1095
- this._cachedNodes = nodes;
1096
- }
1097
- is(selection) {
1098
- if (!$isTableSelection(selection)) {
1099
- return false;
1100
- }
1101
- return this.tableKey === selection.tableKey && this.anchor.is(selection.anchor) && this.focus.is(selection.focus);
1102
- }
1103
- set(tableKey, anchorCellKey, focusCellKey) {
1104
- this.dirty = true;
1105
- this.tableKey = tableKey;
1106
- this.anchor.key = anchorCellKey;
1107
- this.focus.key = focusCellKey;
1108
- this._cachedNodes = null;
1109
- }
1110
- clone() {
1111
- return new TableSelection(this.tableKey, this.anchor, this.focus);
1112
- }
1113
- isCollapsed() {
1114
- return false;
1115
- }
1116
- extract() {
1117
- return this.getNodes();
1118
- }
1119
- insertRawText(text) {
1120
- // Do nothing?
1121
- }
1122
- insertText() {
1123
- // Do nothing?
1124
- }
1125
- insertNodes(nodes) {
1126
- const focusNode = this.focus.getNode();
1127
- if (!$isElementNode(focusNode)) {
1128
- throw Error(`Expected TableSelection focus to be an ElementNode`);
1129
- }
1130
- const selection = $normalizeSelection__EXPERIMENTAL(focusNode.select(0, focusNode.getChildrenSize()));
1131
- selection.insertNodes(nodes);
1132
- }
1133
-
1134
- // TODO Deprecate this method. It's confusing when used with colspan|rowspan
1135
- getShape() {
1136
- const anchorCellNode = $getNodeByKey(this.anchor.key);
1137
- if (!$isTableCellNode(anchorCellNode)) {
1138
- throw Error(`Expected TableSelection anchor to be (or a child of) TableCellNode`);
1139
- }
1140
- const anchorCellNodeRect = $getTableCellNodeRect(anchorCellNode);
1141
- if (!(anchorCellNodeRect !== null)) {
1142
- throw Error(`getCellRect: expected to find AnchorNode`);
1143
- }
1144
- const focusCellNode = $getNodeByKey(this.focus.key);
1145
- if (!$isTableCellNode(focusCellNode)) {
1146
- throw Error(`Expected TableSelection focus to be (or a child of) TableCellNode`);
1147
- }
1148
- const focusCellNodeRect = $getTableCellNodeRect(focusCellNode);
1149
- if (!(focusCellNodeRect !== null)) {
1150
- throw Error(`getCellRect: expected to find focusCellNode`);
1151
- }
1152
- const startX = Math.min(anchorCellNodeRect.columnIndex, focusCellNodeRect.columnIndex);
1153
- const stopX = Math.max(anchorCellNodeRect.columnIndex, focusCellNodeRect.columnIndex);
1154
- const startY = Math.min(anchorCellNodeRect.rowIndex, focusCellNodeRect.rowIndex);
1155
- const stopY = Math.max(anchorCellNodeRect.rowIndex, focusCellNodeRect.rowIndex);
1156
- return {
1157
- fromX: Math.min(startX, stopX),
1158
- fromY: Math.min(startY, stopY),
1159
- toX: Math.max(startX, stopX),
1160
- toY: Math.max(startY, stopY)
1161
- };
1162
- }
1163
- getNodes() {
1164
- const cachedNodes = this._cachedNodes;
1165
- if (cachedNodes !== null) {
1166
- return cachedNodes;
1167
- }
1168
- const anchorNode = this.anchor.getNode();
1169
- const focusNode = this.focus.getNode();
1170
- const anchorCell = $findMatchingParent(anchorNode, $isTableCellNode);
1171
- // todo replace with triplet
1172
- const focusCell = $findMatchingParent(focusNode, $isTableCellNode);
1173
- if (!$isTableCellNode(anchorCell)) {
1174
- throw Error(`Expected TableSelection anchor to be (or a child of) TableCellNode`);
1175
- }
1176
- if (!$isTableCellNode(focusCell)) {
1177
- throw Error(`Expected TableSelection focus to be (or a child of) TableCellNode`);
1178
- }
1179
- const anchorRow = anchorCell.getParent();
1180
- if (!$isTableRowNode(anchorRow)) {
1181
- throw Error(`Expected anchorCell to have a parent TableRowNode`);
1182
- }
1183
- const tableNode = anchorRow.getParent();
1184
- if (!$isTableNode(tableNode)) {
1185
- throw Error(`Expected tableNode to have a parent TableNode`);
1186
- }
1187
- const focusCellGrid = focusCell.getParents()[1];
1188
- if (focusCellGrid !== tableNode) {
1189
- if (!tableNode.isParentOf(focusCell)) {
1190
- // focus is on higher Grid level than anchor
1191
- const gridParent = tableNode.getParent();
1192
- if (!(gridParent != null)) {
1193
- throw Error(`Expected gridParent to have a parent`);
1194
- }
1195
- this.set(this.tableKey, gridParent.getKey(), focusCell.getKey());
1196
- } else {
1197
- // anchor is on higher Grid level than focus
1198
- const focusCellParent = focusCellGrid.getParent();
1199
- if (!(focusCellParent != null)) {
1200
- throw Error(`Expected focusCellParent to have a parent`);
1201
- }
1202
- this.set(this.tableKey, focusCell.getKey(), focusCellParent.getKey());
1203
- }
1204
- return this.getNodes();
1205
- }
1206
-
1207
- // TODO Mapping the whole Grid every time not efficient. We need to compute the entire state only
1208
- // once (on load) and iterate on it as updates occur. However, to do this we need to have the
1209
- // ability to store a state. Killing TableSelection and moving the logic to the plugin would make
1210
- // this possible.
1211
- const [map, cellAMap, cellBMap] = $computeTableMap(tableNode, anchorCell, focusCell);
1212
- let minColumn = Math.min(cellAMap.startColumn, cellBMap.startColumn);
1213
- let minRow = Math.min(cellAMap.startRow, cellBMap.startRow);
1214
- let maxColumn = Math.max(cellAMap.startColumn + cellAMap.cell.__colSpan - 1, cellBMap.startColumn + cellBMap.cell.__colSpan - 1);
1215
- let maxRow = Math.max(cellAMap.startRow + cellAMap.cell.__rowSpan - 1, cellBMap.startRow + cellBMap.cell.__rowSpan - 1);
1216
- let exploredMinColumn = minColumn;
1217
- let exploredMinRow = minRow;
1218
- let exploredMaxColumn = minColumn;
1219
- let exploredMaxRow = minRow;
1220
- function expandBoundary(mapValue) {
1221
- const {
1222
- cell,
1223
- startColumn: cellStartColumn,
1224
- startRow: cellStartRow
1225
- } = mapValue;
1226
- minColumn = Math.min(minColumn, cellStartColumn);
1227
- minRow = Math.min(minRow, cellStartRow);
1228
- maxColumn = Math.max(maxColumn, cellStartColumn + cell.__colSpan - 1);
1229
- maxRow = Math.max(maxRow, cellStartRow + cell.__rowSpan - 1);
1230
- }
1231
- while (minColumn < exploredMinColumn || minRow < exploredMinRow || maxColumn > exploredMaxColumn || maxRow > exploredMaxRow) {
1232
- if (minColumn < exploredMinColumn) {
1233
- // Expand on the left
1234
- const rowDiff = exploredMaxRow - exploredMinRow;
1235
- const previousColumn = exploredMinColumn - 1;
1236
- for (let i = 0; i <= rowDiff; i++) {
1237
- expandBoundary(map[exploredMinRow + i][previousColumn]);
1238
- }
1239
- exploredMinColumn = previousColumn;
1240
- }
1241
- if (minRow < exploredMinRow) {
1242
- // Expand on top
1243
- const columnDiff = exploredMaxColumn - exploredMinColumn;
1244
- const previousRow = exploredMinRow - 1;
1245
- for (let i = 0; i <= columnDiff; i++) {
1246
- expandBoundary(map[previousRow][exploredMinColumn + i]);
1247
- }
1248
- exploredMinRow = previousRow;
1249
- }
1250
- if (maxColumn > exploredMaxColumn) {
1251
- // Expand on the right
1252
- const rowDiff = exploredMaxRow - exploredMinRow;
1253
- const nextColumn = exploredMaxColumn + 1;
1254
- for (let i = 0; i <= rowDiff; i++) {
1255
- expandBoundary(map[exploredMinRow + i][nextColumn]);
1256
- }
1257
- exploredMaxColumn = nextColumn;
1258
- }
1259
- if (maxRow > exploredMaxRow) {
1260
- // Expand on the bottom
1261
- const columnDiff = exploredMaxColumn - exploredMinColumn;
1262
- const nextRow = exploredMaxRow + 1;
1263
- for (let i = 0; i <= columnDiff; i++) {
1264
- expandBoundary(map[nextRow][exploredMinColumn + i]);
1265
- }
1266
- exploredMaxRow = nextRow;
1267
- }
1268
- }
1269
- const nodes = [tableNode];
1270
- let lastRow = null;
1271
- for (let i = minRow; i <= maxRow; i++) {
1272
- for (let j = minColumn; j <= maxColumn; j++) {
1273
- const {
1274
- cell
1275
- } = map[i][j];
1276
- const currentRow = cell.getParent();
1277
- if (!$isTableRowNode(currentRow)) {
1278
- throw Error(`Expected TableCellNode parent to be a TableRowNode`);
1279
- }
1280
- if (currentRow !== lastRow) {
1281
- nodes.push(currentRow);
1282
- }
1283
- nodes.push(cell, ...$getChildrenRecursively(cell));
1284
- lastRow = currentRow;
1285
- }
1286
- }
1287
- if (!isCurrentlyReadOnlyMode()) {
1288
- this._cachedNodes = nodes;
1289
- }
1290
- return nodes;
1291
- }
1292
- getTextContent() {
1293
- const nodes = this.getNodes().filter(node => $isTableCellNode(node));
1294
- let textContent = '';
1295
- for (let i = 0; i < nodes.length; i++) {
1296
- const node = nodes[i];
1297
- const row = node.__parent;
1298
- const nextRow = (nodes[i + 1] || {}).__parent;
1299
- textContent += node.getTextContent() + (nextRow !== row ? '\n' : '\t');
1300
- }
1301
- return textContent;
1302
- }
1303
- }
1304
- function $isTableSelection(x) {
1305
- return x instanceof TableSelection;
1306
- }
1307
- function $createTableSelection() {
1308
- const anchor = $createPoint('root', 0, 'element');
1309
- const focus = $createPoint('root', 0, 'element');
1310
- return new TableSelection('root', anchor, focus);
1311
- }
1312
- function $getChildrenRecursively(node) {
1313
- const nodes = [];
1314
- const stack = [node];
1315
- while (stack.length > 0) {
1316
- const currentNode = stack.pop();
1317
- if (!(currentNode !== undefined)) {
1318
- throw Error(`Stack.length > 0; can't be undefined`);
1319
- }
1320
- if ($isElementNode(currentNode)) {
1321
- stack.unshift(...currentNode.getChildren());
1322
- }
1323
- if (currentNode !== node) {
1324
- nodes.push(currentNode);
1325
- }
1326
- }
1327
- return nodes;
1328
- }
1329
-
1330
- /**
1331
- * Copyright (c) Meta Platforms, Inc. and affiliates.
1332
- *
1333
- * This source code is licensed under the MIT license found in the
1334
- * LICENSE file in the root directory of this source tree.
1335
- *
1336
- */
1337
-
1338
- class TableObserver {
1339
- constructor(editor, tableNodeKey) {
1340
- this.isHighlightingCells = false;
1341
- this.anchorX = -1;
1342
- this.anchorY = -1;
1343
- this.focusX = -1;
1344
- this.focusY = -1;
1345
- this.listenersToRemove = new Set();
1346
- this.tableNodeKey = tableNodeKey;
1347
- this.editor = editor;
1348
- this.table = {
1349
- columns: 0,
1350
- domRows: [],
1351
- rows: 0
1352
- };
1353
- this.tableSelection = null;
1354
- this.anchorCellNodeKey = null;
1355
- this.focusCellNodeKey = null;
1356
- this.anchorCell = null;
1357
- this.focusCell = null;
1358
- this.hasHijackedSelectionStyles = false;
1359
- this.trackTable();
1360
- this.isSelecting = false;
1361
- }
1362
- getTable() {
1363
- return this.table;
1364
- }
1365
- removeListeners() {
1366
- Array.from(this.listenersToRemove).forEach(removeListener => removeListener());
1367
- }
1368
- trackTable() {
1369
- const observer = new MutationObserver(records => {
1370
- this.editor.update(() => {
1371
- let gridNeedsRedraw = false;
1372
- for (let i = 0; i < records.length; i++) {
1373
- const record = records[i];
1374
- const target = record.target;
1375
- const nodeName = target.nodeName;
1376
- if (nodeName === 'TABLE' || nodeName === 'TBODY' || nodeName === 'THEAD' || nodeName === 'TR') {
1377
- gridNeedsRedraw = true;
1378
- break;
1379
- }
1380
- }
1381
- if (!gridNeedsRedraw) {
1382
- return;
1383
- }
1384
- const tableElement = this.editor.getElementByKey(this.tableNodeKey);
1385
- if (!tableElement) {
1386
- throw new Error('Expected to find TableElement in DOM');
1387
- }
1388
- this.table = getTable(tableElement);
1389
- });
1390
- });
1391
- this.editor.update(() => {
1392
- const tableElement = this.editor.getElementByKey(this.tableNodeKey);
1393
- if (!tableElement) {
1394
- throw new Error('Expected to find TableElement in DOM');
1395
- }
1396
- this.table = getTable(tableElement);
1397
- observer.observe(tableElement, {
1398
- attributes: true,
1399
- childList: true,
1400
- subtree: true
1401
- });
1402
- });
1403
- }
1404
- clearHighlight() {
1405
- const editor = this.editor;
1406
- this.isHighlightingCells = false;
1407
- this.anchorX = -1;
1408
- this.anchorY = -1;
1409
- this.focusX = -1;
1410
- this.focusY = -1;
1411
- this.tableSelection = null;
1412
- this.anchorCellNodeKey = null;
1413
- this.focusCellNodeKey = null;
1414
- this.anchorCell = null;
1415
- this.focusCell = null;
1416
- this.hasHijackedSelectionStyles = false;
1417
- this.enableHighlightStyle();
1418
- editor.update(() => {
1419
- const tableNode = $getNodeByKey(this.tableNodeKey);
1420
- if (!$isTableNode(tableNode)) {
1421
- throw new Error('Expected TableNode.');
1422
- }
1423
- const tableElement = editor.getElementByKey(this.tableNodeKey);
1424
- if (!tableElement) {
1425
- throw new Error('Expected to find TableElement in DOM');
1426
- }
1427
- const grid = getTable(tableElement);
1428
- $updateDOMForSelection(editor, grid, null);
1429
- $setSelection(null);
1430
- editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);
1431
- });
1432
- }
1433
- enableHighlightStyle() {
1434
- const editor = this.editor;
1435
- editor.update(() => {
1436
- const tableElement = editor.getElementByKey(this.tableNodeKey);
1437
- if (!tableElement) {
1438
- throw new Error('Expected to find TableElement in DOM');
1439
- }
1440
- removeClassNamesFromElement(tableElement, editor._config.theme.tableSelection);
1441
- tableElement.classList.remove('disable-selection');
1442
- this.hasHijackedSelectionStyles = false;
1443
- });
1444
- }
1445
- disableHighlightStyle() {
1446
- const editor = this.editor;
1447
- editor.update(() => {
1448
- const tableElement = editor.getElementByKey(this.tableNodeKey);
1449
- if (!tableElement) {
1450
- throw new Error('Expected to find TableElement in DOM');
1451
- }
1452
- addClassNamesToElement(tableElement, editor._config.theme.tableSelection);
1453
- this.hasHijackedSelectionStyles = true;
1454
- });
1455
- }
1456
- updateTableTableSelection(selection) {
1457
- if (selection !== null && selection.tableKey === this.tableNodeKey) {
1458
- const editor = this.editor;
1459
- this.tableSelection = selection;
1460
- this.isHighlightingCells = true;
1461
- this.disableHighlightStyle();
1462
- $updateDOMForSelection(editor, this.table, this.tableSelection);
1463
- } else if (selection == null) {
1464
- this.clearHighlight();
1465
- } else {
1466
- this.tableNodeKey = selection.tableKey;
1467
- this.updateTableTableSelection(selection);
1468
- }
1469
- }
1470
- setFocusCellForSelection(cell, ignoreStart = false) {
1471
- const editor = this.editor;
1472
- editor.update(() => {
1473
- const tableNode = $getNodeByKey(this.tableNodeKey);
1474
- if (!$isTableNode(tableNode)) {
1475
- throw new Error('Expected TableNode.');
1476
- }
1477
- const tableElement = editor.getElementByKey(this.tableNodeKey);
1478
- if (!tableElement) {
1479
- throw new Error('Expected to find TableElement in DOM');
1480
- }
1481
- const cellX = cell.x;
1482
- const cellY = cell.y;
1483
- this.focusCell = cell;
1484
- if (this.anchorCell !== null) {
1485
- const domSelection = getDOMSelection(editor._window);
1486
- // Collapse the selection
1487
- if (domSelection) {
1488
- domSelection.setBaseAndExtent(this.anchorCell.elem, 0, this.focusCell.elem, 0);
1489
- }
1490
- }
1491
- if (!this.isHighlightingCells && (this.anchorX !== cellX || this.anchorY !== cellY || ignoreStart)) {
1492
- this.isHighlightingCells = true;
1493
- this.disableHighlightStyle();
1494
- } else if (cellX === this.focusX && cellY === this.focusY) {
1495
- return;
1496
- }
1497
- this.focusX = cellX;
1498
- this.focusY = cellY;
1499
- if (this.isHighlightingCells) {
1500
- const focusTableCellNode = $getNearestNodeFromDOMNode(cell.elem);
1501
- if (this.tableSelection != null && this.anchorCellNodeKey != null && $isTableCellNode(focusTableCellNode) && tableNode.is($findTableNode(focusTableCellNode))) {
1502
- const focusNodeKey = focusTableCellNode.getKey();
1503
- this.tableSelection = this.tableSelection.clone() || $createTableSelection();
1504
- this.focusCellNodeKey = focusNodeKey;
1505
- this.tableSelection.set(this.tableNodeKey, this.anchorCellNodeKey, this.focusCellNodeKey);
1506
- $setSelection(this.tableSelection);
1507
- editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);
1508
- $updateDOMForSelection(editor, this.table, this.tableSelection);
1509
- }
1510
- }
1511
- });
1512
- }
1513
- setAnchorCellForSelection(cell) {
1514
- this.isHighlightingCells = false;
1515
- this.anchorCell = cell;
1516
- this.anchorX = cell.x;
1517
- this.anchorY = cell.y;
1518
- this.editor.update(() => {
1519
- const anchorTableCellNode = $getNearestNodeFromDOMNode(cell.elem);
1520
- if ($isTableCellNode(anchorTableCellNode)) {
1521
- const anchorNodeKey = anchorTableCellNode.getKey();
1522
- this.tableSelection = this.tableSelection != null ? this.tableSelection.clone() : $createTableSelection();
1523
- this.anchorCellNodeKey = anchorNodeKey;
1524
- }
1525
- });
1526
- }
1527
- formatCells(type) {
1528
- this.editor.update(() => {
1529
- const selection = $getSelection();
1530
- if (!$isTableSelection(selection)) {
1531
- {
1532
- throw Error(`Expected grid selection`);
1533
- }
1534
- }
1535
- const formatSelection = $createRangeSelection();
1536
- const anchor = formatSelection.anchor;
1537
- const focus = formatSelection.focus;
1538
- selection.getNodes().forEach(cellNode => {
1539
- if ($isTableCellNode(cellNode) && cellNode.getTextContentSize() !== 0) {
1540
- anchor.set(cellNode.getKey(), 0, 'element');
1541
- focus.set(cellNode.getKey(), cellNode.getChildrenSize(), 'element');
1542
- formatSelection.formatText(type);
1543
- }
1544
- });
1545
- $setSelection(selection);
1546
- this.editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);
1547
- });
1548
- }
1549
- clearText() {
1550
- const editor = this.editor;
1551
- editor.update(() => {
1552
- const tableNode = $getNodeByKey(this.tableNodeKey);
1553
- if (!$isTableNode(tableNode)) {
1554
- throw new Error('Expected TableNode.');
1555
- }
1556
- const selection = $getSelection();
1557
- if (!$isTableSelection(selection)) {
1558
- {
1559
- throw Error(`Expected grid selection`);
1560
- }
1561
- }
1562
- const selectedNodes = selection.getNodes().filter($isTableCellNode);
1563
- if (selectedNodes.length === this.table.columns * this.table.rows) {
1564
- tableNode.selectPrevious();
1565
- // Delete entire table
1566
- tableNode.remove();
1567
- const rootNode = $getRoot();
1568
- rootNode.selectStart();
1569
- return;
1570
- }
1571
- selectedNodes.forEach(cellNode => {
1572
- if ($isElementNode(cellNode)) {
1573
- const paragraphNode = $createParagraphNode();
1574
- const textNode = $createTextNode();
1575
- paragraphNode.append(textNode);
1576
- cellNode.append(paragraphNode);
1577
- cellNode.getChildren().forEach(child => {
1578
- if (child !== paragraphNode) {
1579
- child.remove();
1580
- }
1581
- });
1582
- }
1583
- });
1584
- $updateDOMForSelection(editor, this.table, null);
1585
- $setSelection(null);
1586
- editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);
1587
- });
1588
- }
1589
- }
1590
-
1591
- /**
1592
- * Copyright (c) Meta Platforms, Inc. and affiliates.
1593
- *
1594
- * This source code is licensed under the MIT license found in the
1595
- * LICENSE file in the root directory of this source tree.
1596
- *
1597
- */
1598
-
1599
- const LEXICAL_ELEMENT_KEY = '__lexicalTableSelection';
1600
- const getDOMSelection = targetWindow => CAN_USE_DOM ? (targetWindow || window).getSelection() : null;
1601
- const isMouseDownOnEvent = event => {
1602
- return (event.buttons & 1) === 1;
1603
- };
1604
- function applyTableHandlers(tableNode, tableElement, editor, hasTabHandler) {
1605
- const rootElement = editor.getRootElement();
1606
- if (rootElement === null) {
1607
- throw new Error('No root element.');
1608
- }
1609
- const tableObserver = new TableObserver(editor, tableNode.getKey());
1610
- const editorWindow = editor._window || window;
1611
- attachTableObserverToTableElement(tableElement, tableObserver);
1612
- const createMouseHandlers = () => {
1613
- const onMouseUp = () => {
1614
- tableObserver.isSelecting = false;
1615
- editorWindow.removeEventListener('mouseup', onMouseUp);
1616
- editorWindow.removeEventListener('mousemove', onMouseMove);
1617
- };
1618
- const onMouseMove = moveEvent => {
1619
- // delaying mousemove handler to allow selectionchange handler from LexicalEvents.ts to be executed first
1620
- setTimeout(() => {
1621
- if (!isMouseDownOnEvent(moveEvent) && tableObserver.isSelecting) {
1622
- tableObserver.isSelecting = false;
1623
- editorWindow.removeEventListener('mouseup', onMouseUp);
1624
- editorWindow.removeEventListener('mousemove', onMouseMove);
1625
- return;
1626
- }
1627
- const focusCell = getDOMCellFromTarget(moveEvent.target);
1628
- if (focusCell !== null && (tableObserver.anchorX !== focusCell.x || tableObserver.anchorY !== focusCell.y)) {
1629
- moveEvent.preventDefault();
1630
- tableObserver.setFocusCellForSelection(focusCell);
1631
- }
1632
- }, 0);
1633
- };
1634
- return {
1635
- onMouseMove: onMouseMove,
1636
- onMouseUp: onMouseUp
1637
- };
1638
- };
1639
- tableElement.addEventListener('mousedown', event => {
1640
- setTimeout(() => {
1641
- if (event.button !== 0) {
1642
- return;
1643
- }
1644
- if (!editorWindow) {
1645
- return;
1646
- }
1647
- const anchorCell = getDOMCellFromTarget(event.target);
1648
- if (anchorCell !== null) {
1649
- stopEvent(event);
1650
- tableObserver.setAnchorCellForSelection(anchorCell);
1651
- }
1652
- const {
1653
- onMouseUp,
1654
- onMouseMove
1655
- } = createMouseHandlers();
1656
- tableObserver.isSelecting = true;
1657
- editorWindow.addEventListener('mouseup', onMouseUp);
1658
- editorWindow.addEventListener('mousemove', onMouseMove);
1659
- }, 0);
1660
- });
1661
-
1662
- // Clear selection when clicking outside of dom.
1663
- const mouseDownCallback = event => {
1664
- if (event.button !== 0) {
1665
- return;
1666
- }
1667
- editor.update(() => {
1668
- const selection = $getSelection();
1669
- const target = event.target;
1670
- if ($isTableSelection(selection) && selection.tableKey === tableObserver.tableNodeKey && rootElement.contains(target)) {
1671
- tableObserver.clearHighlight();
1672
- }
1673
- });
1674
- };
1675
- editorWindow.addEventListener('mousedown', mouseDownCallback);
1676
- tableObserver.listenersToRemove.add(() => editorWindow.removeEventListener('mousedown', mouseDownCallback));
1677
- tableObserver.listenersToRemove.add(editor.registerCommand(KEY_ARROW_DOWN_COMMAND, event => $handleArrowKey(editor, event, 'down', tableNode, tableObserver), COMMAND_PRIORITY_HIGH));
1678
- tableObserver.listenersToRemove.add(editor.registerCommand(KEY_ARROW_UP_COMMAND, event => $handleArrowKey(editor, event, 'up', tableNode, tableObserver), COMMAND_PRIORITY_HIGH));
1679
- tableObserver.listenersToRemove.add(editor.registerCommand(KEY_ARROW_LEFT_COMMAND, event => $handleArrowKey(editor, event, 'backward', tableNode, tableObserver), COMMAND_PRIORITY_HIGH));
1680
- tableObserver.listenersToRemove.add(editor.registerCommand(KEY_ARROW_RIGHT_COMMAND, event => $handleArrowKey(editor, event, 'forward', tableNode, tableObserver), COMMAND_PRIORITY_HIGH));
1681
- tableObserver.listenersToRemove.add(editor.registerCommand(KEY_ESCAPE_COMMAND, event => {
1682
- const selection = $getSelection();
1683
- if ($isTableSelection(selection)) {
1684
- const focusCellNode = $findMatchingParent(selection.focus.getNode(), $isTableCellNode);
1685
- if ($isTableCellNode(focusCellNode)) {
1686
- stopEvent(event);
1687
- focusCellNode.selectEnd();
1688
- return true;
1689
- }
1690
- }
1691
- return false;
1692
- }, COMMAND_PRIORITY_HIGH));
1693
- const deleteTextHandler = command => () => {
1694
- const selection = $getSelection();
1695
- if (!$isSelectionInTable(selection, tableNode)) {
1696
- return false;
1697
- }
1698
- if ($isTableSelection(selection)) {
1699
- tableObserver.clearText();
1700
- return true;
1701
- } else if ($isRangeSelection(selection)) {
1702
- const tableCellNode = $findMatchingParent(selection.anchor.getNode(), n => $isTableCellNode(n));
1703
- if (!$isTableCellNode(tableCellNode)) {
1704
- return false;
1705
- }
1706
- const anchorNode = selection.anchor.getNode();
1707
- const focusNode = selection.focus.getNode();
1708
- const isAnchorInside = tableNode.isParentOf(anchorNode);
1709
- const isFocusInside = tableNode.isParentOf(focusNode);
1710
- const selectionContainsPartialTable = isAnchorInside && !isFocusInside || isFocusInside && !isAnchorInside;
1711
- if (selectionContainsPartialTable) {
1712
- tableObserver.clearText();
1713
- return true;
1714
- }
1715
- const nearestElementNode = $findMatchingParent(selection.anchor.getNode(), n => $isElementNode(n));
1716
- const topLevelCellElementNode = nearestElementNode && $findMatchingParent(nearestElementNode, n => $isElementNode(n) && $isTableCellNode(n.getParent()));
1717
- if (!$isElementNode(topLevelCellElementNode) || !$isElementNode(nearestElementNode)) {
1718
- return false;
1719
- }
1720
- if (command === DELETE_LINE_COMMAND && topLevelCellElementNode.getPreviousSibling() === null) {
1721
- // TODO: Fix Delete Line in Table Cells.
1722
- return true;
1723
- }
1724
- }
1725
- return false;
1726
- };
1727
- [DELETE_WORD_COMMAND, DELETE_LINE_COMMAND, DELETE_CHARACTER_COMMAND].forEach(command => {
1728
- tableObserver.listenersToRemove.add(editor.registerCommand(command, deleteTextHandler(command), COMMAND_PRIORITY_CRITICAL));
1729
- });
1730
- const $deleteCellHandler = event => {
1731
- const selection = $getSelection();
1732
- if (!$isSelectionInTable(selection, tableNode)) {
1733
- const nodes = selection ? selection.getNodes() : null;
1734
- if (nodes) {
1735
- const table = nodes.find(node => $isTableNode(node) && node.getKey() === tableObserver.tableNodeKey);
1736
- if ($isTableNode(table)) {
1737
- const parentNode = table.getParent();
1738
- if (!parentNode) {
1739
- return false;
1740
- }
1741
- table.remove();
1742
- }
1743
- }
1744
- return false;
1745
- }
1746
- if ($isTableSelection(selection)) {
1747
- if (event) {
1748
- event.preventDefault();
1749
- event.stopPropagation();
1750
- }
1751
- tableObserver.clearText();
1752
- return true;
1753
- } else if ($isRangeSelection(selection)) {
1754
- const tableCellNode = $findMatchingParent(selection.anchor.getNode(), n => $isTableCellNode(n));
1755
- if (!$isTableCellNode(tableCellNode)) {
1756
- return false;
1757
- }
1758
- }
1759
- return false;
1760
- };
1761
- tableObserver.listenersToRemove.add(editor.registerCommand(KEY_BACKSPACE_COMMAND, $deleteCellHandler, COMMAND_PRIORITY_CRITICAL));
1762
- tableObserver.listenersToRemove.add(editor.registerCommand(KEY_DELETE_COMMAND, $deleteCellHandler, COMMAND_PRIORITY_CRITICAL));
1763
- tableObserver.listenersToRemove.add(editor.registerCommand(CUT_COMMAND, event => {
1764
- const selection = $getSelection();
1765
- if (selection) {
1766
- if (!($isTableSelection(selection) || $isRangeSelection(selection))) {
1767
- return false;
1768
- }
1769
- // Copying to the clipboard is async so we must capture the data
1770
- // before we delete it
1771
- void copyToClipboard(editor, objectKlassEquals(event, ClipboardEvent) ? event : null, $getClipboardDataFromSelection(selection));
1772
- const intercepted = $deleteCellHandler(event);
1773
- if ($isRangeSelection(selection)) {
1774
- selection.removeText();
1775
- }
1776
- return intercepted;
1777
- }
1778
- return false;
1779
- }, COMMAND_PRIORITY_CRITICAL));
1780
- tableObserver.listenersToRemove.add(editor.registerCommand(FORMAT_TEXT_COMMAND, payload => {
1781
- const selection = $getSelection();
1782
- if (!$isSelectionInTable(selection, tableNode)) {
1783
- return false;
1784
- }
1785
- if ($isTableSelection(selection)) {
1786
- tableObserver.formatCells(payload);
1787
- return true;
1788
- } else if ($isRangeSelection(selection)) {
1789
- const tableCellNode = $findMatchingParent(selection.anchor.getNode(), n => $isTableCellNode(n));
1790
- if (!$isTableCellNode(tableCellNode)) {
1791
- return false;
1792
- }
1793
- }
1794
- return false;
1795
- }, COMMAND_PRIORITY_CRITICAL));
1796
- tableObserver.listenersToRemove.add(editor.registerCommand(FORMAT_ELEMENT_COMMAND, formatType => {
1797
- const selection = $getSelection();
1798
- if (!$isTableSelection(selection) || !$isSelectionInTable(selection, tableNode)) {
1799
- return false;
1800
- }
1801
- const anchorNode = selection.anchor.getNode();
1802
- const focusNode = selection.focus.getNode();
1803
- if (!$isTableCellNode(anchorNode) || !$isTableCellNode(focusNode)) {
1804
- return false;
1805
- }
1806
- const [tableMap, anchorCell, focusCell] = $computeTableMap(tableNode, anchorNode, focusNode);
1807
- const maxRow = Math.max(anchorCell.startRow, focusCell.startRow);
1808
- const maxColumn = Math.max(anchorCell.startColumn, focusCell.startColumn);
1809
- const minRow = Math.min(anchorCell.startRow, focusCell.startRow);
1810
- const minColumn = Math.min(anchorCell.startColumn, focusCell.startColumn);
1811
- for (let i = minRow; i <= maxRow; i++) {
1812
- for (let j = minColumn; j <= maxColumn; j++) {
1813
- const cell = tableMap[i][j].cell;
1814
- cell.setFormat(formatType);
1815
- const cellChildren = cell.getChildren();
1816
- for (let k = 0; k < cellChildren.length; k++) {
1817
- const child = cellChildren[k];
1818
- if ($isElementNode(child) && !child.isInline()) {
1819
- child.setFormat(formatType);
1820
- }
1821
- }
1822
- }
1823
- }
1824
- return true;
1825
- }, COMMAND_PRIORITY_CRITICAL));
1826
- tableObserver.listenersToRemove.add(editor.registerCommand(CONTROLLED_TEXT_INSERTION_COMMAND, payload => {
1827
- const selection = $getSelection();
1828
- if (!$isSelectionInTable(selection, tableNode)) {
1829
- return false;
1830
- }
1831
- if ($isTableSelection(selection)) {
1832
- tableObserver.clearHighlight();
1833
- return false;
1834
- } else if ($isRangeSelection(selection)) {
1835
- const tableCellNode = $findMatchingParent(selection.anchor.getNode(), n => $isTableCellNode(n));
1836
- if (!$isTableCellNode(tableCellNode)) {
1837
- return false;
1838
- }
1839
- if (typeof payload === 'string') {
1840
- const edgePosition = $getTableEdgeCursorPosition(editor, selection, tableNode);
1841
- if (edgePosition) {
1842
- $insertParagraphAtTableEdge(edgePosition, tableNode, [$createTextNode(payload)]);
1843
- return true;
1844
- }
1845
- }
1846
- }
1847
- return false;
1848
- }, COMMAND_PRIORITY_CRITICAL));
1849
- if (hasTabHandler) {
1850
- tableObserver.listenersToRemove.add(editor.registerCommand(KEY_TAB_COMMAND, event => {
1851
- const selection = $getSelection();
1852
- if (!$isRangeSelection(selection) || !selection.isCollapsed() || !$isSelectionInTable(selection, tableNode)) {
1853
- return false;
1854
- }
1855
- const tableCellNode = $findCellNode(selection.anchor.getNode());
1856
- if (tableCellNode === null) {
1857
- return false;
1858
- }
1859
- stopEvent(event);
1860
- const currentCords = tableNode.getCordsFromCellNode(tableCellNode, tableObserver.table);
1861
- selectTableNodeInDirection(tableObserver, tableNode, currentCords.x, currentCords.y, !event.shiftKey ? 'forward' : 'backward');
1862
- return true;
1863
- }, COMMAND_PRIORITY_CRITICAL));
1864
- }
1865
- tableObserver.listenersToRemove.add(editor.registerCommand(FOCUS_COMMAND, payload => {
1866
- return tableNode.isSelected();
1867
- }, COMMAND_PRIORITY_HIGH));
1868
- function getObserverCellFromCellNode(tableCellNode) {
1869
- const currentCords = tableNode.getCordsFromCellNode(tableCellNode, tableObserver.table);
1870
- return tableNode.getDOMCellFromCordsOrThrow(currentCords.x, currentCords.y, tableObserver.table);
1871
- }
1872
- tableObserver.listenersToRemove.add(editor.registerCommand(SELECTION_INSERT_CLIPBOARD_NODES_COMMAND, selectionPayload => {
1873
- const {
1874
- nodes,
1875
- selection
1876
- } = selectionPayload;
1877
- const anchorAndFocus = selection.getStartEndPoints();
1878
- const isTableSelection = $isTableSelection(selection);
1879
- const isRangeSelection = $isRangeSelection(selection);
1880
- const isSelectionInsideOfGrid = isRangeSelection && $findMatchingParent(selection.anchor.getNode(), n => $isTableCellNode(n)) !== null && $findMatchingParent(selection.focus.getNode(), n => $isTableCellNode(n)) !== null || isTableSelection;
1881
- if (nodes.length !== 1 || !$isTableNode(nodes[0]) || !isSelectionInsideOfGrid || anchorAndFocus === null) {
1882
- return false;
1883
- }
1884
- const [anchor] = anchorAndFocus;
1885
- const newGrid = nodes[0];
1886
- const newGridRows = newGrid.getChildren();
1887
- const newColumnCount = newGrid.getFirstChildOrThrow().getChildrenSize();
1888
- const newRowCount = newGrid.getChildrenSize();
1889
- const gridCellNode = $findMatchingParent(anchor.getNode(), n => $isTableCellNode(n));
1890
- const gridRowNode = gridCellNode && $findMatchingParent(gridCellNode, n => $isTableRowNode(n));
1891
- const gridNode = gridRowNode && $findMatchingParent(gridRowNode, n => $isTableNode(n));
1892
- if (!$isTableCellNode(gridCellNode) || !$isTableRowNode(gridRowNode) || !$isTableNode(gridNode)) {
1893
- return false;
1894
- }
1895
- const startY = gridRowNode.getIndexWithinParent();
1896
- const stopY = Math.min(gridNode.getChildrenSize() - 1, startY + newRowCount - 1);
1897
- const startX = gridCellNode.getIndexWithinParent();
1898
- const stopX = Math.min(gridRowNode.getChildrenSize() - 1, startX + newColumnCount - 1);
1899
- const fromX = Math.min(startX, stopX);
1900
- const fromY = Math.min(startY, stopY);
1901
- const toX = Math.max(startX, stopX);
1902
- const toY = Math.max(startY, stopY);
1903
- const gridRowNodes = gridNode.getChildren();
1904
- let newRowIdx = 0;
1905
- for (let r = fromY; r <= toY; r++) {
1906
- const currentGridRowNode = gridRowNodes[r];
1907
- if (!$isTableRowNode(currentGridRowNode)) {
1908
- return false;
1909
- }
1910
- const newGridRowNode = newGridRows[newRowIdx];
1911
- if (!$isTableRowNode(newGridRowNode)) {
1912
- return false;
1913
- }
1914
- const gridCellNodes = currentGridRowNode.getChildren();
1915
- const newGridCellNodes = newGridRowNode.getChildren();
1916
- let newColumnIdx = 0;
1917
- for (let c = fromX; c <= toX; c++) {
1918
- const currentGridCellNode = gridCellNodes[c];
1919
- if (!$isTableCellNode(currentGridCellNode)) {
1920
- return false;
1921
- }
1922
- const newGridCellNode = newGridCellNodes[newColumnIdx];
1923
- if (!$isTableCellNode(newGridCellNode)) {
1924
- return false;
1925
- }
1926
- const originalChildren = currentGridCellNode.getChildren();
1927
- newGridCellNode.getChildren().forEach(child => {
1928
- if ($isTextNode(child)) {
1929
- const paragraphNode = $createParagraphNode();
1930
- paragraphNode.append(child);
1931
- currentGridCellNode.append(child);
1932
- } else {
1933
- currentGridCellNode.append(child);
1934
- }
1935
- });
1936
- originalChildren.forEach(n => n.remove());
1937
- newColumnIdx++;
1938
- }
1939
- newRowIdx++;
1940
- }
1941
- return true;
1942
- }, COMMAND_PRIORITY_CRITICAL));
1943
- tableObserver.listenersToRemove.add(editor.registerCommand(SELECTION_CHANGE_COMMAND, () => {
1944
- const selection = $getSelection();
1945
- const prevSelection = $getPreviousSelection();
1946
- if ($isRangeSelection(selection)) {
1947
- const {
1948
- anchor,
1949
- focus
1950
- } = selection;
1951
- const anchorNode = anchor.getNode();
1952
- const focusNode = focus.getNode();
1953
- // Using explicit comparison with table node to ensure it's not a nested table
1954
- // as in that case we'll leave selection resolving to that table
1955
- const anchorCellNode = $findCellNode(anchorNode);
1956
- const focusCellNode = $findCellNode(focusNode);
1957
- const isAnchorInside = !!(anchorCellNode && tableNode.is($findTableNode(anchorCellNode)));
1958
- const isFocusInside = !!(focusCellNode && tableNode.is($findTableNode(focusCellNode)));
1959
- const isPartialyWithinTable = isAnchorInside !== isFocusInside;
1960
- const isWithinTable = isAnchorInside && isFocusInside;
1961
- const isBackward = selection.isBackward();
1962
- if (isPartialyWithinTable) {
1963
- const newSelection = selection.clone();
1964
- if (isFocusInside) {
1965
- const [tableMap] = $computeTableMap(tableNode, focusCellNode, focusCellNode);
1966
- const firstCell = tableMap[0][0].cell;
1967
- const lastCell = tableMap[tableMap.length - 1].at(-1).cell;
1968
- newSelection.focus.set(isBackward ? firstCell.getKey() : lastCell.getKey(), isBackward ? firstCell.getChildrenSize() : lastCell.getChildrenSize(), 'element');
1969
- }
1970
- $setSelection(newSelection);
1971
- $addHighlightStyleToTable(editor, tableObserver);
1972
- } else if (isWithinTable) {
1973
- // Handle case when selection spans across multiple cells but still
1974
- // has range selection, then we convert it into grid selection
1975
- if (!anchorCellNode.is(focusCellNode)) {
1976
- tableObserver.setAnchorCellForSelection(getObserverCellFromCellNode(anchorCellNode));
1977
- tableObserver.setFocusCellForSelection(getObserverCellFromCellNode(focusCellNode), true);
1978
- if (!tableObserver.isSelecting) {
1979
- setTimeout(() => {
1980
- const {
1981
- onMouseUp,
1982
- onMouseMove
1983
- } = createMouseHandlers();
1984
- tableObserver.isSelecting = true;
1985
- editorWindow.addEventListener('mouseup', onMouseUp);
1986
- editorWindow.addEventListener('mousemove', onMouseMove);
1987
- }, 0);
1988
- }
1989
- }
1990
- }
1991
- } else if (selection && $isTableSelection(selection) && selection.is(prevSelection) && selection.tableKey === tableNode.getKey()) {
1992
- // if selection goes outside of the table we need to change it to Range selection
1993
- const domSelection = getDOMSelection(editor._window);
1994
- if (domSelection && domSelection.anchorNode && domSelection.focusNode) {
1995
- const focusNode = $getNearestNodeFromDOMNode(domSelection.focusNode);
1996
- const isFocusOutside = focusNode && !tableNode.is($findTableNode(focusNode));
1997
- const anchorNode = $getNearestNodeFromDOMNode(domSelection.anchorNode);
1998
- const isAnchorInside = anchorNode && tableNode.is($findTableNode(anchorNode));
1999
- if (isFocusOutside && isAnchorInside && domSelection.rangeCount > 0) {
2000
- const newSelection = $createRangeSelectionFromDom(domSelection, editor);
2001
- if (newSelection) {
2002
- newSelection.anchor.set(tableNode.getKey(), selection.isBackward() ? tableNode.getChildrenSize() : 0, 'element');
2003
- domSelection.removeAllRanges();
2004
- $setSelection(newSelection);
2005
- }
2006
- }
2007
- }
2008
- }
2009
- if (selection && !selection.is(prevSelection) && ($isTableSelection(selection) || $isTableSelection(prevSelection)) && tableObserver.tableSelection && !tableObserver.tableSelection.is(prevSelection)) {
2010
- if ($isTableSelection(selection) && selection.tableKey === tableObserver.tableNodeKey) {
2011
- tableObserver.updateTableTableSelection(selection);
2012
- } else if (!$isTableSelection(selection) && $isTableSelection(prevSelection) && prevSelection.tableKey === tableObserver.tableNodeKey) {
2013
- tableObserver.updateTableTableSelection(null);
2014
- }
2015
- return false;
2016
- }
2017
- if (tableObserver.hasHijackedSelectionStyles && !tableNode.isSelected()) {
2018
- $removeHighlightStyleToTable(editor, tableObserver);
2019
- } else if (!tableObserver.hasHijackedSelectionStyles && tableNode.isSelected()) {
2020
- $addHighlightStyleToTable(editor, tableObserver);
2021
- }
2022
- return false;
2023
- }, COMMAND_PRIORITY_CRITICAL));
2024
- tableObserver.listenersToRemove.add(editor.registerCommand(INSERT_PARAGRAPH_COMMAND, () => {
2025
- const selection = $getSelection();
2026
- if (!$isRangeSelection(selection) || !selection.isCollapsed() || !$isSelectionInTable(selection, tableNode)) {
2027
- return false;
2028
- }
2029
- const edgePosition = $getTableEdgeCursorPosition(editor, selection, tableNode);
2030
- if (edgePosition) {
2031
- $insertParagraphAtTableEdge(edgePosition, tableNode);
2032
- return true;
2033
- }
2034
- return false;
2035
- }, COMMAND_PRIORITY_CRITICAL));
2036
- return tableObserver;
2037
- }
2038
- function attachTableObserverToTableElement(tableElement, tableObserver) {
2039
- tableElement[LEXICAL_ELEMENT_KEY] = tableObserver;
2040
- }
2041
- function getTableObserverFromTableElement(tableElement) {
2042
- return tableElement[LEXICAL_ELEMENT_KEY];
2043
- }
2044
- function getDOMCellFromTarget(node) {
2045
- let currentNode = node;
2046
- while (currentNode != null) {
2047
- const nodeName = currentNode.nodeName;
2048
- if (nodeName === 'TD' || nodeName === 'TH') {
2049
- // @ts-expect-error: internal field
2050
- const cell = currentNode._cell;
2051
- if (cell === undefined) {
2052
- return null;
2053
- }
2054
- return cell;
2055
- }
2056
- currentNode = currentNode.parentNode;
2057
- }
2058
- return null;
2059
- }
2060
- function getTable(tableElement) {
2061
- const domRows = [];
2062
- const grid = {
2063
- columns: 0,
2064
- domRows,
2065
- rows: 0
2066
- };
2067
- let currentNode = tableElement.firstChild;
2068
- let x = 0;
2069
- let y = 0;
2070
- domRows.length = 0;
2071
- while (currentNode != null) {
2072
- const nodeMame = currentNode.nodeName;
2073
- if (nodeMame === 'TD' || nodeMame === 'TH') {
2074
- const elem = currentNode;
2075
- const cell = {
2076
- elem,
2077
- hasBackgroundColor: elem.style.backgroundColor !== '',
2078
- highlighted: false,
2079
- x,
2080
- y
2081
- };
2082
-
2083
- // @ts-expect-error: internal field
2084
- currentNode._cell = cell;
2085
- let row = domRows[y];
2086
- if (row === undefined) {
2087
- row = domRows[y] = [];
2088
- }
2089
- row[x] = cell;
2090
- } else {
2091
- const child = currentNode.firstChild;
2092
- if (child != null) {
2093
- currentNode = child;
2094
- continue;
2095
- }
2096
- }
2097
- const sibling = currentNode.nextSibling;
2098
- if (sibling != null) {
2099
- x++;
2100
- currentNode = sibling;
2101
- continue;
2102
- }
2103
- const parent = currentNode.parentNode;
2104
- if (parent != null) {
2105
- const parentSibling = parent.nextSibling;
2106
- if (parentSibling == null) {
2107
- break;
2108
- }
2109
- y++;
2110
- x = 0;
2111
- currentNode = parentSibling;
2112
- }
2113
- }
2114
- grid.columns = x + 1;
2115
- grid.rows = y + 1;
2116
- return grid;
2117
- }
2118
- function $updateDOMForSelection(editor, table, selection) {
2119
- const selectedCellNodes = new Set(selection ? selection.getNodes() : []);
2120
- $forEachTableCell(table, (cell, lexicalNode) => {
2121
- const elem = cell.elem;
2122
- if (selectedCellNodes.has(lexicalNode)) {
2123
- cell.highlighted = true;
2124
- $addHighlightToDOM(editor, cell);
2125
- } else {
2126
- cell.highlighted = false;
2127
- $removeHighlightFromDOM(editor, cell);
2128
- if (!elem.getAttribute('style')) {
2129
- elem.removeAttribute('style');
2130
- }
2131
- }
2132
- });
2133
- }
2134
- function $forEachTableCell(grid, cb) {
2135
- const {
2136
- domRows
2137
- } = grid;
2138
- for (let y = 0; y < domRows.length; y++) {
2139
- const row = domRows[y];
2140
- if (!row) {
2141
- continue;
2142
- }
2143
- for (let x = 0; x < row.length; x++) {
2144
- const cell = row[x];
2145
- if (!cell) {
2146
- continue;
2147
- }
2148
- const lexicalNode = $getNearestNodeFromDOMNode(cell.elem);
2149
- if (lexicalNode !== null) {
2150
- cb(cell, lexicalNode, {
2151
- x,
2152
- y
2153
- });
2154
- }
2155
- }
2156
- }
2157
- }
2158
- function $addHighlightStyleToTable(editor, tableSelection) {
2159
- tableSelection.disableHighlightStyle();
2160
- $forEachTableCell(tableSelection.table, cell => {
2161
- cell.highlighted = true;
2162
- $addHighlightToDOM(editor, cell);
2163
- });
2164
- }
2165
- function $removeHighlightStyleToTable(editor, tableObserver) {
2166
- tableObserver.enableHighlightStyle();
2167
- $forEachTableCell(tableObserver.table, cell => {
2168
- const elem = cell.elem;
2169
- cell.highlighted = false;
2170
- $removeHighlightFromDOM(editor, cell);
2171
- if (!elem.getAttribute('style')) {
2172
- elem.removeAttribute('style');
2173
- }
2174
- });
2175
- }
2176
- const selectTableNodeInDirection = (tableObserver, tableNode, x, y, direction) => {
2177
- const isForward = direction === 'forward';
2178
- switch (direction) {
2179
- case 'backward':
2180
- case 'forward':
2181
- if (x !== (isForward ? tableObserver.table.columns - 1 : 0)) {
2182
- selectTableCellNode(tableNode.getCellNodeFromCordsOrThrow(x + (isForward ? 1 : -1), y, tableObserver.table), isForward);
2183
- } else {
2184
- if (y !== (isForward ? tableObserver.table.rows - 1 : 0)) {
2185
- selectTableCellNode(tableNode.getCellNodeFromCordsOrThrow(isForward ? 0 : tableObserver.table.columns - 1, y + (isForward ? 1 : -1), tableObserver.table), isForward);
2186
- } else if (!isForward) {
2187
- tableNode.selectPrevious();
2188
- } else {
2189
- tableNode.selectNext();
2190
- }
2191
- }
2192
- return true;
2193
- case 'up':
2194
- if (y !== 0) {
2195
- selectTableCellNode(tableNode.getCellNodeFromCordsOrThrow(x, y - 1, tableObserver.table), false);
2196
- } else {
2197
- tableNode.selectPrevious();
2198
- }
2199
- return true;
2200
- case 'down':
2201
- if (y !== tableObserver.table.rows - 1) {
2202
- selectTableCellNode(tableNode.getCellNodeFromCordsOrThrow(x, y + 1, tableObserver.table), true);
2203
- } else {
2204
- tableNode.selectNext();
2205
- }
2206
- return true;
2207
- default:
2208
- return false;
2209
- }
2210
- };
2211
- const adjustFocusNodeInDirection = (tableObserver, tableNode, x, y, direction) => {
2212
- const isForward = direction === 'forward';
2213
- switch (direction) {
2214
- case 'backward':
2215
- case 'forward':
2216
- if (x !== (isForward ? tableObserver.table.columns - 1 : 0)) {
2217
- tableObserver.setFocusCellForSelection(tableNode.getDOMCellFromCordsOrThrow(x + (isForward ? 1 : -1), y, tableObserver.table));
2218
- }
2219
- return true;
2220
- case 'up':
2221
- if (y !== 0) {
2222
- tableObserver.setFocusCellForSelection(tableNode.getDOMCellFromCordsOrThrow(x, y - 1, tableObserver.table));
2223
- return true;
2224
- } else {
2225
- return false;
2226
- }
2227
- case 'down':
2228
- if (y !== tableObserver.table.rows - 1) {
2229
- tableObserver.setFocusCellForSelection(tableNode.getDOMCellFromCordsOrThrow(x, y + 1, tableObserver.table));
2230
- return true;
2231
- } else {
2232
- return false;
2233
- }
2234
- default:
2235
- return false;
2236
- }
2237
- };
2238
- function $isSelectionInTable(selection, tableNode) {
2239
- if ($isRangeSelection(selection) || $isTableSelection(selection)) {
2240
- const isAnchorInside = tableNode.isParentOf(selection.anchor.getNode());
2241
- const isFocusInside = tableNode.isParentOf(selection.focus.getNode());
2242
- return isAnchorInside && isFocusInside;
2243
- }
2244
- return false;
2245
- }
2246
- function selectTableCellNode(tableCell, fromStart) {
2247
- if (fromStart) {
2248
- tableCell.selectStart();
2249
- } else {
2250
- tableCell.selectEnd();
2251
- }
2252
- }
2253
- const BROWSER_BLUE_RGB = '172,206,247';
2254
- function $addHighlightToDOM(editor, cell) {
2255
- const element = cell.elem;
2256
- const node = $getNearestNodeFromDOMNode(element);
2257
- if (!$isTableCellNode(node)) {
2258
- throw Error(`Expected to find LexicalNode from Table Cell DOMNode`);
2259
- }
2260
- const backgroundColor = node.getBackgroundColor();
2261
- if (backgroundColor === null) {
2262
- element.style.setProperty('background-color', `rgb(${BROWSER_BLUE_RGB})`);
2263
- } else {
2264
- element.style.setProperty('background-image', `linear-gradient(to right, rgba(${BROWSER_BLUE_RGB},0.85), rgba(${BROWSER_BLUE_RGB},0.85))`);
2265
- }
2266
- element.style.setProperty('caret-color', 'transparent');
2267
- }
2268
- function $removeHighlightFromDOM(editor, cell) {
2269
- const element = cell.elem;
2270
- const node = $getNearestNodeFromDOMNode(element);
2271
- if (!$isTableCellNode(node)) {
2272
- throw Error(`Expected to find LexicalNode from Table Cell DOMNode`);
2273
- }
2274
- const backgroundColor = node.getBackgroundColor();
2275
- if (backgroundColor === null) {
2276
- element.style.removeProperty('background-color');
2277
- }
2278
- element.style.removeProperty('background-image');
2279
- element.style.removeProperty('caret-color');
2280
- }
2281
- function $findCellNode(node) {
2282
- const cellNode = $findMatchingParent(node, $isTableCellNode);
2283
- return $isTableCellNode(cellNode) ? cellNode : null;
2284
- }
2285
- function $findTableNode(node) {
2286
- const tableNode = $findMatchingParent(node, $isTableNode);
2287
- return $isTableNode(tableNode) ? tableNode : null;
2288
- }
2289
- function $handleArrowKey(editor, event, direction, tableNode, tableObserver) {
2290
- if ((direction === 'up' || direction === 'down') && isTypeaheadMenuInView(editor)) {
2291
- return false;
2292
- }
2293
- const selection = $getSelection();
2294
- if (!$isSelectionInTable(selection, tableNode)) {
2295
- if ($isRangeSelection(selection)) {
2296
- if (selection.isCollapsed() && direction === 'backward') {
2297
- const anchorType = selection.anchor.type;
2298
- const anchorOffset = selection.anchor.offset;
2299
- if (anchorType !== 'element' && !(anchorType === 'text' && anchorOffset === 0)) {
2300
- return false;
2301
- }
2302
- const anchorNode = selection.anchor.getNode();
2303
- if (!anchorNode) {
2304
- return false;
2305
- }
2306
- const parentNode = $findMatchingParent(anchorNode, n => $isElementNode(n) && !n.isInline());
2307
- if (!parentNode) {
2308
- return false;
2309
- }
2310
- const siblingNode = parentNode.getPreviousSibling();
2311
- if (!siblingNode || !$isTableNode(siblingNode)) {
2312
- return false;
2313
- }
2314
- stopEvent(event);
2315
- siblingNode.selectEnd();
2316
- return true;
2317
- } else if (event.shiftKey && (direction === 'up' || direction === 'down')) {
2318
- const focusNode = selection.focus.getNode();
2319
- if ($isRootOrShadowRoot(focusNode)) {
2320
- const selectedNode = selection.getNodes()[0];
2321
- if (selectedNode) {
2322
- const tableCellNode = $findMatchingParent(selectedNode, $isTableCellNode);
2323
- if (tableCellNode && tableNode.isParentOf(tableCellNode)) {
2324
- const firstDescendant = tableNode.getFirstDescendant();
2325
- const lastDescendant = tableNode.getLastDescendant();
2326
- if (!firstDescendant || !lastDescendant) {
2327
- return false;
2328
- }
2329
- const [firstCellNode] = $getNodeTriplet(firstDescendant);
2330
- const [lastCellNode] = $getNodeTriplet(lastDescendant);
2331
- const firstCellCoords = tableNode.getCordsFromCellNode(firstCellNode, tableObserver.table);
2332
- const lastCellCoords = tableNode.getCordsFromCellNode(lastCellNode, tableObserver.table);
2333
- const firstCellDOM = tableNode.getDOMCellFromCordsOrThrow(firstCellCoords.x, firstCellCoords.y, tableObserver.table);
2334
- const lastCellDOM = tableNode.getDOMCellFromCordsOrThrow(lastCellCoords.x, lastCellCoords.y, tableObserver.table);
2335
- tableObserver.setAnchorCellForSelection(firstCellDOM);
2336
- tableObserver.setFocusCellForSelection(lastCellDOM, true);
2337
- return true;
2338
- }
2339
- }
2340
- return false;
2341
- } else {
2342
- const focusParentNode = $findMatchingParent(focusNode, n => $isElementNode(n) && !n.isInline());
2343
- if (!focusParentNode) {
2344
- return false;
2345
- }
2346
- const sibling = direction === 'down' ? focusParentNode.getNextSibling() : focusParentNode.getPreviousSibling();
2347
- if ($isTableNode(sibling) && tableObserver.tableNodeKey === sibling.getKey()) {
2348
- const firstDescendant = sibling.getFirstDescendant();
2349
- const lastDescendant = sibling.getLastDescendant();
2350
- if (!firstDescendant || !lastDescendant) {
2351
- return false;
2352
- }
2353
- const [firstCellNode] = $getNodeTriplet(firstDescendant);
2354
- const [lastCellNode] = $getNodeTriplet(lastDescendant);
2355
- const newSelection = selection.clone();
2356
- newSelection.focus.set((direction === 'up' ? firstCellNode : lastCellNode).getKey(), direction === 'up' ? 0 : lastCellNode.getChildrenSize(), 'element');
2357
- $setSelection(newSelection);
2358
- return true;
2359
- }
2360
- }
2361
- }
2362
- }
2363
- return false;
2364
- }
2365
- if ($isRangeSelection(selection) && selection.isCollapsed()) {
2366
- const {
2367
- anchor,
2368
- focus
2369
- } = selection;
2370
- const anchorCellNode = $findMatchingParent(anchor.getNode(), $isTableCellNode);
2371
- const focusCellNode = $findMatchingParent(focus.getNode(), $isTableCellNode);
2372
- if (!$isTableCellNode(anchorCellNode) || !anchorCellNode.is(focusCellNode)) {
2373
- return false;
2374
- }
2375
- const anchorCellTable = $findTableNode(anchorCellNode);
2376
- if (anchorCellTable !== tableNode && anchorCellTable != null) {
2377
- const anchorCellTableElement = editor.getElementByKey(anchorCellTable.getKey());
2378
- if (anchorCellTableElement != null) {
2379
- tableObserver.table = getTable(anchorCellTableElement);
2380
- return $handleArrowKey(editor, event, direction, anchorCellTable, tableObserver);
2381
- }
2382
- }
2383
- if (direction === 'backward' || direction === 'forward') {
2384
- const anchorType = anchor.type;
2385
- const anchorOffset = anchor.offset;
2386
- const anchorNode = anchor.getNode();
2387
- if (!anchorNode) {
2388
- return false;
2389
- }
2390
- const selectedNodes = selection.getNodes();
2391
- if (selectedNodes.length === 1 && $isDecoratorNode(selectedNodes[0])) {
2392
- return false;
2393
- }
2394
- if (isExitingTableAnchor(anchorType, anchorOffset, anchorNode, direction)) {
2395
- return $handleTableExit(event, anchorNode, tableNode, direction);
2396
- }
2397
- return false;
2398
- }
2399
- const anchorCellDom = editor.getElementByKey(anchorCellNode.__key);
2400
- const anchorDOM = editor.getElementByKey(anchor.key);
2401
- if (anchorDOM == null || anchorCellDom == null) {
2402
- return false;
2403
- }
2404
- let edgeSelectionRect;
2405
- if (anchor.type === 'element') {
2406
- edgeSelectionRect = anchorDOM.getBoundingClientRect();
2407
- } else {
2408
- const domSelection = window.getSelection();
2409
- if (domSelection === null || domSelection.rangeCount === 0) {
2410
- return false;
2411
- }
2412
- const range = domSelection.getRangeAt(0);
2413
- edgeSelectionRect = range.getBoundingClientRect();
2414
- }
2415
- const edgeChild = direction === 'up' ? anchorCellNode.getFirstChild() : anchorCellNode.getLastChild();
2416
- if (edgeChild == null) {
2417
- return false;
2418
- }
2419
- const edgeChildDOM = editor.getElementByKey(edgeChild.__key);
2420
- if (edgeChildDOM == null) {
2421
- return false;
2422
- }
2423
- const edgeRect = edgeChildDOM.getBoundingClientRect();
2424
- const isExiting = direction === 'up' ? edgeRect.top > edgeSelectionRect.top - edgeSelectionRect.height : edgeSelectionRect.bottom + edgeSelectionRect.height > edgeRect.bottom;
2425
- if (isExiting) {
2426
- stopEvent(event);
2427
- const cords = tableNode.getCordsFromCellNode(anchorCellNode, tableObserver.table);
2428
- if (event.shiftKey) {
2429
- const cell = tableNode.getDOMCellFromCordsOrThrow(cords.x, cords.y, tableObserver.table);
2430
- tableObserver.setAnchorCellForSelection(cell);
2431
- tableObserver.setFocusCellForSelection(cell, true);
2432
- } else {
2433
- return selectTableNodeInDirection(tableObserver, tableNode, cords.x, cords.y, direction);
2434
- }
2435
- return true;
2436
- }
2437
- } else if ($isTableSelection(selection)) {
2438
- const {
2439
- anchor,
2440
- focus
2441
- } = selection;
2442
- const anchorCellNode = $findMatchingParent(anchor.getNode(), $isTableCellNode);
2443
- const focusCellNode = $findMatchingParent(focus.getNode(), $isTableCellNode);
2444
- const [tableNodeFromSelection] = selection.getNodes();
2445
- const tableElement = editor.getElementByKey(tableNodeFromSelection.getKey());
2446
- if (!$isTableCellNode(anchorCellNode) || !$isTableCellNode(focusCellNode) || !$isTableNode(tableNodeFromSelection) || tableElement == null) {
2447
- return false;
2448
- }
2449
- tableObserver.updateTableTableSelection(selection);
2450
- const grid = getTable(tableElement);
2451
- const cordsAnchor = tableNode.getCordsFromCellNode(anchorCellNode, grid);
2452
- const anchorCell = tableNode.getDOMCellFromCordsOrThrow(cordsAnchor.x, cordsAnchor.y, grid);
2453
- tableObserver.setAnchorCellForSelection(anchorCell);
2454
- stopEvent(event);
2455
- if (event.shiftKey) {
2456
- const cords = tableNode.getCordsFromCellNode(focusCellNode, grid);
2457
- return adjustFocusNodeInDirection(tableObserver, tableNodeFromSelection, cords.x, cords.y, direction);
2458
- } else {
2459
- focusCellNode.selectEnd();
2460
- }
2461
- return true;
2462
- }
2463
- return false;
2464
- }
2465
- function stopEvent(event) {
2466
- event.preventDefault();
2467
- event.stopImmediatePropagation();
2468
- event.stopPropagation();
2469
- }
2470
- function isTypeaheadMenuInView(editor) {
2471
- // There is no inbuilt way to check if the component picker is in view
2472
- // but we can check if the root DOM element has the aria-controls attribute "typeahead-menu".
2473
- const root = editor.getRootElement();
2474
- if (!root) {
2475
- return false;
2476
- }
2477
- return root.hasAttribute('aria-controls') && root.getAttribute('aria-controls') === 'typeahead-menu';
2478
- }
2479
- function isExitingTableAnchor(type, offset, anchorNode, direction) {
2480
- return isExitingTableElementAnchor(type, anchorNode, direction) || $isExitingTableTextAnchor(type, offset, anchorNode, direction);
2481
- }
2482
- function isExitingTableElementAnchor(type, anchorNode, direction) {
2483
- return type === 'element' && (direction === 'backward' ? anchorNode.getPreviousSibling() === null : anchorNode.getNextSibling() === null);
2484
- }
2485
- function $isExitingTableTextAnchor(type, offset, anchorNode, direction) {
2486
- const parentNode = $findMatchingParent(anchorNode, n => $isElementNode(n) && !n.isInline());
2487
- if (!parentNode) {
2488
- return false;
2489
- }
2490
- const hasValidOffset = direction === 'backward' ? offset === 0 : offset === anchorNode.getTextContentSize();
2491
- return type === 'text' && hasValidOffset && (direction === 'backward' ? parentNode.getPreviousSibling() === null : parentNode.getNextSibling() === null);
2492
- }
2493
- function $handleTableExit(event, anchorNode, tableNode, direction) {
2494
- const anchorCellNode = $findMatchingParent(anchorNode, $isTableCellNode);
2495
- if (!$isTableCellNode(anchorCellNode)) {
2496
- return false;
2497
- }
2498
- const [tableMap, cellValue] = $computeTableMap(tableNode, anchorCellNode, anchorCellNode);
2499
- if (!isExitingCell(tableMap, cellValue, direction)) {
2500
- return false;
2501
- }
2502
- const toNode = $getExitingToNode(anchorNode, direction, tableNode);
2503
- if (!toNode || $isTableNode(toNode)) {
2504
- return false;
2505
- }
2506
- stopEvent(event);
2507
- if (direction === 'backward') {
2508
- toNode.selectEnd();
2509
- } else {
2510
- toNode.selectStart();
2511
- }
2512
- return true;
2513
- }
2514
- function isExitingCell(tableMap, cellValue, direction) {
2515
- const firstCell = tableMap[0][0];
2516
- const lastCell = tableMap[tableMap.length - 1][tableMap[0].length - 1];
2517
- const {
2518
- startColumn,
2519
- startRow
2520
- } = cellValue;
2521
- return direction === 'backward' ? startColumn === firstCell.startColumn && startRow === firstCell.startRow : startColumn === lastCell.startColumn && startRow === lastCell.startRow;
2522
- }
2523
- function $getExitingToNode(anchorNode, direction, tableNode) {
2524
- const parentNode = $findMatchingParent(anchorNode, n => $isElementNode(n) && !n.isInline());
2525
- if (!parentNode) {
2526
- return undefined;
2527
- }
2528
- const anchorSibling = direction === 'backward' ? parentNode.getPreviousSibling() : parentNode.getNextSibling();
2529
- return anchorSibling && $isTableNode(anchorSibling) ? anchorSibling : direction === 'backward' ? tableNode.getPreviousSibling() : tableNode.getNextSibling();
2530
- }
2531
- function $insertParagraphAtTableEdge(edgePosition, tableNode, children) {
2532
- const paragraphNode = $createParagraphNode();
2533
- if (edgePosition === 'first') {
2534
- tableNode.insertBefore(paragraphNode);
2535
- } else {
2536
- tableNode.insertAfter(paragraphNode);
2537
- }
2538
- paragraphNode.append(...(children || []));
2539
- paragraphNode.selectEnd();
2540
- }
2541
- function $getTableEdgeCursorPosition(editor, selection, tableNode) {
2542
- const tableNodeParent = tableNode.getParent();
2543
- if (!tableNodeParent) {
2544
- return undefined;
2545
- }
2546
- const tableNodeParentDOM = editor.getElementByKey(tableNodeParent.getKey());
2547
- if (!tableNodeParentDOM) {
2548
- return undefined;
2549
- }
2550
-
2551
- // TODO: Add support for nested tables
2552
- const domSelection = window.getSelection();
2553
- if (!domSelection || domSelection.anchorNode !== tableNodeParentDOM) {
2554
- return undefined;
2555
- }
2556
- const anchorCellNode = $findMatchingParent(selection.anchor.getNode(), n => $isTableCellNode(n));
2557
- if (!anchorCellNode) {
2558
- return undefined;
2559
- }
2560
- const parentTable = $findMatchingParent(anchorCellNode, n => $isTableNode(n));
2561
- if (!$isTableNode(parentTable) || !parentTable.is(tableNode)) {
2562
- return undefined;
2563
- }
2564
- const [tableMap, cellValue] = $computeTableMap(tableNode, anchorCellNode, anchorCellNode);
2565
- const firstCell = tableMap[0][0];
2566
- const lastCell = tableMap[tableMap.length - 1][tableMap[0].length - 1];
2567
- const {
2568
- startRow,
2569
- startColumn
2570
- } = cellValue;
2571
- const isAtFirstCell = startRow === firstCell.startRow && startColumn === firstCell.startColumn;
2572
- const isAtLastCell = startRow === lastCell.startRow && startColumn === lastCell.startColumn;
2573
- if (isAtFirstCell) {
2574
- return 'first';
2575
- } else if (isAtLastCell) {
2576
- return 'last';
2577
- } else {
2578
- return undefined;
2579
- }
2580
- }
2581
-
2582
- /**
2583
- * Copyright (c) Meta Platforms, Inc. and affiliates.
2584
- *
2585
- * This source code is licensed under the MIT license found in the
2586
- * LICENSE file in the root directory of this source tree.
2587
- *
2588
- */
2589
-
2590
- /** @noInheritDoc */
2591
- class TableNode extends ElementNode {
2592
- static getType() {
2593
- return 'table';
2594
- }
2595
- static clone(node) {
2596
- return new TableNode(node.__key);
2597
- }
2598
- static importDOM() {
2599
- return {
2600
- table: _node => ({
2601
- conversion: $convertTableElement,
2602
- priority: 1
2603
- })
2604
- };
2605
- }
2606
- static importJSON(_serializedNode) {
2607
- return $createTableNode();
2608
- }
2609
- constructor(key) {
2610
- super(key);
2611
- }
2612
- exportJSON() {
2613
- return {
2614
- ...super.exportJSON(),
2615
- type: 'table',
2616
- version: 1
2617
- };
2618
- }
2619
- createDOM(config, editor) {
2620
- const tableElement = document.createElement('table');
2621
- addClassNamesToElement(tableElement, config.theme.table);
2622
- return tableElement;
2623
- }
2624
- updateDOM() {
2625
- return false;
2626
- }
2627
- exportDOM(editor) {
2628
- return {
2629
- ...super.exportDOM(editor),
2630
- after: tableElement => {
2631
- if (tableElement) {
2632
- const newElement = tableElement.cloneNode();
2633
- const colGroup = document.createElement('colgroup');
2634
- const tBody = document.createElement('tbody');
2635
- if (isHTMLElement(tableElement)) {
2636
- tBody.append(...tableElement.children);
2637
- }
2638
- const firstRow = this.getFirstChildOrThrow();
2639
- if (!$isTableRowNode(firstRow)) {
2640
- throw new Error('Expected to find row node.');
2641
- }
2642
- const colCount = firstRow.getChildrenSize();
2643
- for (let i = 0; i < colCount; i++) {
2644
- const col = document.createElement('col');
2645
- colGroup.append(col);
2646
- }
2647
- newElement.replaceChildren(colGroup, tBody);
2648
- return newElement;
2649
- }
2650
- }
2651
- };
2652
- }
2653
- canBeEmpty() {
2654
- return false;
2655
- }
2656
- isShadowRoot() {
2657
- return true;
2658
- }
2659
- getCordsFromCellNode(tableCellNode, table) {
2660
- const {
2661
- rows,
2662
- domRows
2663
- } = table;
2664
- for (let y = 0; y < rows; y++) {
2665
- const row = domRows[y];
2666
- if (row == null) {
2667
- continue;
2668
- }
2669
- const x = row.findIndex(cell => {
2670
- if (!cell) {
2671
- return;
2672
- }
2673
- const {
2674
- elem
2675
- } = cell;
2676
- const cellNode = $getNearestNodeFromDOMNode(elem);
2677
- return cellNode === tableCellNode;
2678
- });
2679
- if (x !== -1) {
2680
- return {
2681
- x,
2682
- y
2683
- };
2684
- }
2685
- }
2686
- throw new Error('Cell not found in table.');
2687
- }
2688
- getDOMCellFromCords(x, y, table) {
2689
- const {
2690
- domRows
2691
- } = table;
2692
- const row = domRows[y];
2693
- if (row == null) {
2694
- return null;
2695
- }
2696
- const index = x < row.length ? x : row.length - 1;
2697
- const cell = row[index];
2698
- if (cell == null) {
2699
- return null;
2700
- }
2701
- return cell;
2702
- }
2703
- getDOMCellFromCordsOrThrow(x, y, table) {
2704
- const cell = this.getDOMCellFromCords(x, y, table);
2705
- if (!cell) {
2706
- throw new Error('Cell not found at cords.');
2707
- }
2708
- return cell;
2709
- }
2710
- getCellNodeFromCords(x, y, table) {
2711
- const cell = this.getDOMCellFromCords(x, y, table);
2712
- if (cell == null) {
2713
- return null;
2714
- }
2715
- const node = $getNearestNodeFromDOMNode(cell.elem);
2716
- if ($isTableCellNode(node)) {
2717
- return node;
2718
- }
2719
- return null;
2720
- }
2721
- getCellNodeFromCordsOrThrow(x, y, table) {
2722
- const node = this.getCellNodeFromCords(x, y, table);
2723
- if (!node) {
2724
- throw new Error('Node at cords not TableCellNode.');
2725
- }
2726
- return node;
2727
- }
2728
- canSelectBefore() {
2729
- return true;
2730
- }
2731
- canIndent() {
2732
- return false;
2733
- }
2734
- }
2735
- function $getElementForTableNode(editor, tableNode) {
2736
- const tableElement = editor.getElementByKey(tableNode.getKey());
2737
- if (tableElement == null) {
2738
- throw new Error('Table Element Not Found');
2739
- }
2740
- return getTable(tableElement);
2741
- }
2742
- function $convertTableElement(_domNode) {
2743
- return {
2744
- node: $createTableNode()
2745
- };
2746
- }
2747
- function $createTableNode() {
2748
- return $applyNodeReplacement(new TableNode());
2749
- }
2750
- function $isTableNode(node) {
2751
- return node instanceof TableNode;
2752
- }
2753
-
2754
- export { $computeTableMap, $computeTableMapSkipCellCheck, $createTableCellNode, $createTableNode, $createTableNodeWithDimensions, $createTableRowNode, $createTableSelection, $deleteTableColumn, $deleteTableColumn__EXPERIMENTAL, $deleteTableRow__EXPERIMENTAL, $findCellNode, $findTableNode, $getElementForTableNode, $getNodeTriplet, $getTableCellNodeFromLexicalNode, $getTableCellNodeRect, $getTableColumnIndexFromTableCellNode, $getTableNodeFromLexicalNodeOrThrow, $getTableRowIndexFromTableCellNode, $getTableRowNodeFromTableCellNodeOrThrow, $insertTableColumn, $insertTableColumn__EXPERIMENTAL, $insertTableRow, $insertTableRow__EXPERIMENTAL, $isTableCellNode, $isTableNode, $isTableRowNode, $isTableSelection, $removeTableRowAtIndex, $unmergeCell, INSERT_TABLE_COMMAND, TableCellHeaderStates, TableCellNode, TableNode, TableObserver, TableRowNode, applyTableHandlers, getDOMCellFromTarget, getTableObserverFromTableElement };