@pixerate/editor 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +30 -0
  2. package/THIRD_PARTY_NOTICES.md +11 -0
  3. package/dist/agent/index.cjs +174 -11
  4. package/dist/agent/index.cjs.map +1 -1
  5. package/dist/agent/index.d.cts +18 -4
  6. package/dist/agent/index.d.ts +18 -4
  7. package/dist/agent/index.js +167 -4
  8. package/dist/agent/index.js.map +1 -1
  9. package/dist/{arrangeShortcuts-B8O3f8-P.d.cts → arrange-BICutYPk.d.cts} +243 -29
  10. package/dist/{arrangeShortcuts-sLlD2rSX.d.ts → arrange-BICutYPk.d.ts} +243 -29
  11. package/dist/builtins-CdPcLwwF.d.cts +176 -0
  12. package/dist/builtins-Chj6zv_O.d.ts +176 -0
  13. package/dist/canvas/index.cjs +3917 -19
  14. package/dist/canvas/index.cjs.map +1 -1
  15. package/dist/canvas/index.d.cts +1232 -7
  16. package/dist/canvas/index.d.ts +1232 -7
  17. package/dist/canvas/index.js +3916 -18
  18. package/dist/canvas/index.js.map +1 -1
  19. package/dist/chunk-3CC7OPUQ.cjs +831 -0
  20. package/dist/chunk-3CC7OPUQ.cjs.map +1 -0
  21. package/dist/{chunk-AL6JMGWW.cjs → chunk-CS6NZWWA.cjs} +24 -24
  22. package/dist/{chunk-AL6JMGWW.cjs.map → chunk-CS6NZWWA.cjs.map} +1 -1
  23. package/dist/{chunk-C7P22VIP.cjs → chunk-EWCOFSCQ.cjs} +17 -6
  24. package/dist/chunk-EWCOFSCQ.cjs.map +1 -0
  25. package/dist/chunk-HDYMLS3X.cjs +409 -0
  26. package/dist/chunk-HDYMLS3X.cjs.map +1 -0
  27. package/dist/{chunk-X4N4WUKB.cjs → chunk-IFHKKVXH.cjs} +150 -38
  28. package/dist/chunk-IFHKKVXH.cjs.map +1 -0
  29. package/dist/{chunk-ECCCYKGL.js → chunk-JOIREKL7.js} +63 -39
  30. package/dist/chunk-JOIREKL7.js.map +1 -0
  31. package/dist/chunk-KRGXUQ2Y.js +1696 -0
  32. package/dist/chunk-KRGXUQ2Y.js.map +1 -0
  33. package/dist/{chunk-QGYDWPRM.js → chunk-MHEPLBFB.js} +2 -2
  34. package/dist/chunk-MR2764X2.js +831 -0
  35. package/dist/chunk-MR2764X2.js.map +1 -0
  36. package/dist/{chunk-7WISYZFO.cjs → chunk-NFVBT3UZ.cjs} +67 -43
  37. package/dist/chunk-NFVBT3UZ.cjs.map +1 -0
  38. package/dist/{chunk-WSQKHXW7.cjs → chunk-NQF32I6Z.cjs} +1209 -457
  39. package/dist/chunk-NQF32I6Z.cjs.map +1 -0
  40. package/dist/{chunk-IXHSYOVY.js → chunk-Q2OHWD2A.js} +638 -866
  41. package/dist/chunk-Q2OHWD2A.js.map +1 -0
  42. package/dist/{chunk-NAXVVS5I.js → chunk-QJSOZFCZ.js} +2 -2
  43. package/dist/{chunk-V3CHHWOE.cjs → chunk-RRREAOVM.cjs} +4 -4
  44. package/dist/{chunk-V3CHHWOE.cjs.map → chunk-RRREAOVM.cjs.map} +1 -1
  45. package/dist/{chunk-UAKDG62Z.js → chunk-SWE3NPOU.js} +116 -4
  46. package/dist/chunk-SWE3NPOU.js.map +1 -0
  47. package/dist/chunk-TXXNBDQX.cjs +1696 -0
  48. package/dist/chunk-TXXNBDQX.cjs.map +1 -0
  49. package/dist/chunk-UBCFIABU.js +409 -0
  50. package/dist/chunk-UBCFIABU.js.map +1 -0
  51. package/dist/{chunk-RR7F5GUM.js → chunk-X7HXL2SB.js} +941 -189
  52. package/dist/chunk-X7HXL2SB.js.map +1 -0
  53. package/dist/{chunk-PO6A6QQH.cjs → chunk-YOMYSFJU.cjs} +742 -970
  54. package/dist/chunk-YOMYSFJU.cjs.map +1 -0
  55. package/dist/{chunk-FH6F67DN.js → chunk-ZRNHGAQT.js} +17 -6
  56. package/dist/{chunk-FH6F67DN.js.map → chunk-ZRNHGAQT.js.map} +1 -1
  57. package/dist/commands/index.cjs +352 -4
  58. package/dist/commands/index.cjs.map +1 -1
  59. package/dist/commands/index.d.cts +37 -108
  60. package/dist/commands/index.d.ts +37 -108
  61. package/dist/commands/index.js +351 -3
  62. package/dist/commands/index.js.map +1 -1
  63. package/dist/compare/index.cjs +3 -3
  64. package/dist/compare/index.js +2 -2
  65. package/dist/{controller-BIJiNoVs.d.cts → controller-CxXGOEmy.d.cts} +209 -13
  66. package/dist/{controller-BIJiNoVs.d.ts → controller-CxXGOEmy.d.ts} +209 -13
  67. package/dist/export/index.cjs +36 -0
  68. package/dist/export/index.cjs.map +1 -0
  69. package/dist/export/index.d.cts +243 -0
  70. package/dist/export/index.d.ts +243 -0
  71. package/dist/export/index.js +36 -0
  72. package/dist/export/index.js.map +1 -0
  73. package/dist/extensions/index.cjs +54 -6
  74. package/dist/extensions/index.cjs.map +1 -1
  75. package/dist/extensions/index.d.cts +7 -2
  76. package/dist/extensions/index.d.ts +7 -2
  77. package/dist/extensions/index.js +59 -11
  78. package/dist/{index-7a6bHTLy.d.ts → index-B273Zllk.d.ts} +211 -207
  79. package/dist/{index-Csd5qI8u.d.cts → index-jcJwmBYt.d.cts} +211 -207
  80. package/dist/index.cjs +144 -32
  81. package/dist/index.cjs.map +1 -1
  82. package/dist/index.d.cts +49 -13
  83. package/dist/index.d.ts +49 -13
  84. package/dist/index.js +136 -24
  85. package/dist/index.js.map +1 -1
  86. package/dist/registry-CED5C0lA.d.cts +204 -0
  87. package/dist/registry-CED5C0lA.d.ts +204 -0
  88. package/dist/{registry-D32LpIc4.d.cts → registry-D0GADKc7.d.cts} +1 -1
  89. package/dist/{registry-evKTP4ls.d.ts → registry-DhVUZioj.d.ts} +1 -1
  90. package/dist/serializers/index.cjs +4 -4
  91. package/dist/serializers/index.d.cts +2 -1
  92. package/dist/serializers/index.d.ts +2 -1
  93. package/dist/serializers/index.js +3 -3
  94. package/dist/spreadsheet/index.cjs +33 -3
  95. package/dist/spreadsheet/index.cjs.map +1 -1
  96. package/dist/spreadsheet/index.d.cts +106 -3
  97. package/dist/spreadsheet/index.d.ts +106 -3
  98. package/dist/spreadsheet/index.js +32 -2
  99. package/package.json +10 -1
  100. package/dist/chunk-7WISYZFO.cjs.map +0 -1
  101. package/dist/chunk-C7P22VIP.cjs.map +0 -1
  102. package/dist/chunk-ECCCYKGL.js.map +0 -1
  103. package/dist/chunk-IXHSYOVY.js.map +0 -1
  104. package/dist/chunk-PO6A6QQH.cjs.map +0 -1
  105. package/dist/chunk-RR7F5GUM.js.map +0 -1
  106. package/dist/chunk-UAKDG62Z.js.map +0 -1
  107. package/dist/chunk-WSQKHXW7.cjs.map +0 -1
  108. package/dist/chunk-X4N4WUKB.cjs.map +0 -1
  109. package/dist/types-DX4Mh4SL.d.cts +0 -217
  110. package/dist/types-DX4Mh4SL.d.ts +0 -217
  111. /package/dist/{chunk-QGYDWPRM.js.map → chunk-MHEPLBFB.js.map} +0 -0
  112. /package/dist/{chunk-NAXVVS5I.js.map → chunk-QJSOZFCZ.js.map} +0 -0
@@ -0,0 +1,409 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunkIFHKKVXHcjs = require('./chunk-IFHKKVXH.cjs');
4
+
5
+ // src/extensions/table/extension.ts
6
+ var _core = require('@tiptap/core');
7
+ var _model = require('@tiptap/pm/model');
8
+ var _extensiontable = require('@tiptap/extension-table'); var _Table = _interopRequireWildcard(_extensiontable);
9
+ var _extensiontablerow = require('@tiptap/extension-table-row'); var _TableRow = _interopRequireWildcard(_extensiontablerow);
10
+ var _extensiontableheader = require('@tiptap/extension-table-header'); var _TableHeader = _interopRequireWildcard(_extensiontableheader);
11
+ var _extensiontablecell = require('@tiptap/extension-table-cell'); var _TableCell = _interopRequireWildcard(_extensiontablecell);
12
+ var resolveExt = (mod, name) => _optionalChain([mod, 'optionalAccess', _ => _[name]]) || _optionalChain([mod, 'optionalAccess', _2 => _2.default, 'optionalAccess', _3 => _3[name]]) || _optionalChain([mod, 'optionalAccess', _4 => _4.default, 'optionalAccess', _5 => _5.default]) || _optionalChain([mod, 'optionalAccess', _6 => _6.default]) || mod;
13
+ var BaseTable = resolveExt(_Table, "Table");
14
+ var BaseTableRow = resolveExt(_TableRow, "TableRow");
15
+ var BaseTableHeader = resolveExt(_TableHeader, "TableHeader");
16
+ var BaseTableCell = resolveExt(_TableCell, "TableCell");
17
+ var ALIGNMENTS = /* @__PURE__ */ new Set(["left", "center", "right", "justify"]);
18
+ function normalizeTableCellAlignment(value) {
19
+ const v = typeof value === "string" ? value.trim().toLowerCase() : "";
20
+ return ALIGNMENTS.has(v) ? v : null;
21
+ }
22
+ var COLOR_REGEX = /^(?:#[0-9a-f]{3,8}|(?:rgb|rgba|hsl|hsla)\(\s*[-0-9.%\s,/deg]+\)|[a-z]{3,20})$/i;
23
+ function normalizeTableCellColor(value) {
24
+ const v = typeof value === "string" ? value.trim() : "";
25
+ if (!v || v.length > 64 || !COLOR_REGEX.test(v)) return null;
26
+ if (/^(?:inherit|initial|unset|revert|transparent)$/i.test(v)) return null;
27
+ return v;
28
+ }
29
+ var cellAttributes = () => ({
30
+ align: {
31
+ default: null,
32
+ parseHTML: (element) => normalizeTableCellAlignment(_optionalChain([element, 'access', _7 => _7.style, 'optionalAccess', _8 => _8.textAlign]) || element.getAttribute("align")),
33
+ renderHTML: (attrs) => {
34
+ const align = normalizeTableCellAlignment(attrs.align);
35
+ return align ? { style: `text-align: ${align}` } : {};
36
+ }
37
+ },
38
+ backgroundColor: {
39
+ default: null,
40
+ parseHTML: (element) => normalizeTableCellColor(
41
+ element.getAttribute("data-background-color") || _optionalChain([element, 'access', _9 => _9.style, 'optionalAccess', _10 => _10.backgroundColor]) || element.getAttribute("bgcolor")
42
+ ),
43
+ renderHTML: (attrs) => {
44
+ const color = normalizeTableCellColor(attrs.backgroundColor);
45
+ return color ? { style: `background-color: ${color}`, "data-background-color": color } : {};
46
+ }
47
+ }
48
+ });
49
+ var children = (node) => {
50
+ const list = [];
51
+ node.forEach((child) => list.push(child));
52
+ return list;
53
+ };
54
+ var hasSpan = (cell) => (_nullishCoalesce(cell.attrs.colspan, () => ( 1))) > 1 || (_nullishCoalesce(cell.attrs.rowspan, () => ( 1))) > 1;
55
+ function isGfmTable(node) {
56
+ const rows = children(node);
57
+ if (rows.length === 0) return false;
58
+ const width = rows[0].childCount;
59
+ return rows.every(
60
+ (row, r) => row.childCount === width && children(row).every(
61
+ (cell) => (r === 0 ? cell.type.name === "tableHeader" : cell.type.name === "tableCell") && !hasSpan(cell) && cell.childCount === 1 && cell.firstChild.type.name === "paragraph"
62
+ )
63
+ );
64
+ }
65
+ var DELIMITERS = { left: ":---", center: ":---:", right: "---:" };
66
+ function serializeTableMarkdown(state, node) {
67
+ if (!isGfmTable(node)) {
68
+ const html = _core.getHTMLFromFragment.call(void 0, _model.Fragment.from(node), node.type.schema);
69
+ state.write(html.replace(/\n{2,}/g, "\n"));
70
+ state.closeBlock(node);
71
+ return;
72
+ }
73
+ const previous = state.inTable;
74
+ state.inTable = true;
75
+ children(node).forEach((row, r) => {
76
+ if (r) state.ensureNewLine();
77
+ state.write("| ");
78
+ children(row).forEach((cell, c) => {
79
+ if (c) state.write(" | ");
80
+ const paragraph = cell.firstChild;
81
+ const start = state.out.length;
82
+ if (paragraph.childCount) state.renderInline(paragraph);
83
+ const text = state.out.slice(start);
84
+ state.out = state.out.slice(0, start) + text.replace(/\n/g, " ").replace(/\|/g, "\\|");
85
+ });
86
+ state.write(" |");
87
+ if (r === 0) {
88
+ const delimiter = children(row).map((cell) => _nullishCoalesce(DELIMITERS[cell.attrs.align], () => ( "---")));
89
+ state.ensureNewLine();
90
+ state.write(`| ${delimiter.join(" | ")} |`);
91
+ }
92
+ });
93
+ state.inTable = previous;
94
+ state.closeBlock(node);
95
+ }
96
+ var DEFAULT_TABLE_OPTIONS = {
97
+ resizable: true,
98
+ handleWidth: 5,
99
+ cellMinWidth: 25,
100
+ lastColumnResizable: true,
101
+ allowTableNodeSelection: true,
102
+ HTMLAttributes: { class: "pixerate-table" },
103
+ cellHTMLAttributes: {},
104
+ headerHTMLAttributes: {},
105
+ rowHTMLAttributes: {}
106
+ };
107
+ var Table = BaseTable.extend({
108
+ addStorage() {
109
+ return { markdown: { serialize: serializeTableMarkdown } };
110
+ }
111
+ });
112
+ var TableRow = BaseTableRow;
113
+ var TableCell = BaseTableCell.extend({
114
+ addAttributes() {
115
+ return { ..._optionalChain([this, 'access', _11 => _11.parent, 'optionalCall', _12 => _12()]), ...cellAttributes() };
116
+ }
117
+ });
118
+ var TableHeader = BaseTableHeader.extend({
119
+ addAttributes() {
120
+ return { ..._optionalChain([this, 'access', _13 => _13.parent, 'optionalCall', _14 => _14()]), ...cellAttributes() };
121
+ }
122
+ });
123
+ function createTableExtensions(options = {}) {
124
+ const o = { ...DEFAULT_TABLE_OPTIONS, ...options };
125
+ return [
126
+ Table.configure({
127
+ resizable: o.resizable,
128
+ handleWidth: o.handleWidth,
129
+ cellMinWidth: o.cellMinWidth,
130
+ lastColumnResizable: o.lastColumnResizable,
131
+ allowTableNodeSelection: o.allowTableNodeSelection,
132
+ HTMLAttributes: o.HTMLAttributes
133
+ }),
134
+ TableRow.configure({ HTMLAttributes: o.rowHTMLAttributes }),
135
+ TableHeader.configure({ HTMLAttributes: o.headerHTMLAttributes }),
136
+ TableCell.configure({ HTMLAttributes: o.cellHTMLAttributes })
137
+ ];
138
+ }
139
+
140
+ // src/extensions/table/actions.ts
141
+ var _tables = require('@tiptap/pm/tables');
142
+ var TABLE_ACTIONS = [
143
+ { action: "insertTable", label: "Insert Table", description: "Inserts a table (rows, cols, withHeaderRow) at the cursor.", keywords: ["table", "grid", "new"] },
144
+ { action: "addRowBefore", label: "Insert Row Above", description: "Adds a row above the current row.", keywords: ["row", "add", "above"] },
145
+ { action: "addRowAfter", label: "Insert Row Below", description: "Adds a row below the current row.", keywords: ["row", "add", "below"] },
146
+ { action: "deleteRow", label: "Delete Row", description: "Deletes the selected rows.", keywords: ["row", "remove"] },
147
+ { action: "addColumnBefore", label: "Insert Column Left", description: "Adds a column left of the current column.", keywords: ["column", "add", "left", "before"] },
148
+ { action: "addColumnAfter", label: "Insert Column Right", description: "Adds a column right of the current column.", keywords: ["column", "add", "right", "after"] },
149
+ { action: "deleteColumn", label: "Delete Column", description: "Deletes the selected columns.", keywords: ["column", "remove"] },
150
+ { action: "deleteTable", label: "Delete Table", description: "Deletes the table around the cursor.", keywords: ["table", "remove"] },
151
+ { action: "mergeCells", label: "Merge Cells", description: "Merges the selected cells into one.", keywords: ["combine", "join", "span"] },
152
+ { action: "splitCell", label: "Split Cell", description: "Splits a merged cell back into single cells.", keywords: ["unmerge", "span"] },
153
+ { action: "toggleHeaderRow", label: "Toggle Header Row", description: "Turns the first row into header cells, or back.", keywords: ["header", "row", "th"] },
154
+ { action: "toggleHeaderColumn", label: "Toggle Header Column", description: "Turns the first column into header cells, or back.", keywords: ["header", "column", "th"] },
155
+ { action: "toggleHeaderCell", label: "Toggle Header Cell", description: "Turns the selected cells into header cells, or back.", keywords: ["header", "cell", "th"] },
156
+ { action: "goToNextCell", label: "Next Cell", description: "Moves the cursor to the next cell.", keywords: ["tab", "navigate"] },
157
+ { action: "goToPreviousCell", label: "Previous Cell", description: "Moves the cursor to the previous cell.", keywords: ["shift tab", "navigate"] },
158
+ { action: "setCellAlignment", label: "Align Cells\u2026", description: "Sets the horizontal alignment (align: left | center | right | justify | null) of the selected cells.", keywords: ["align", "left", "center", "right"] },
159
+ { action: "setCellBackground", label: "Cell Background\u2026", description: "Sets the background color (color: CSS color or null) of the selected cells.", keywords: ["shading", "fill", "color"] }
160
+ ];
161
+ var DEFAULT_TABLE_TOOLBAR = [
162
+ { id: "addRowBefore", action: "addRowBefore", label: "+ Row \u2191", title: "Insert row above", group: "rows" },
163
+ { id: "addRowAfter", action: "addRowAfter", label: "+ Row \u2193", title: "Insert row below", group: "rows" },
164
+ { id: "deleteRow", action: "deleteRow", label: "\u2212 Row", title: "Delete row", group: "rows" },
165
+ { id: "addColumnBefore", action: "addColumnBefore", label: "+ Col \u2190", title: "Insert column left", group: "columns" },
166
+ { id: "addColumnAfter", action: "addColumnAfter", label: "+ Col \u2192", title: "Insert column right", group: "columns" },
167
+ { id: "deleteColumn", action: "deleteColumn", label: "\u2212 Col", title: "Delete column", group: "columns" },
168
+ { id: "mergeCells", action: "mergeCells", label: "Merge", title: "Merge cells", group: "cells" },
169
+ { id: "splitCell", action: "splitCell", label: "Split", title: "Split cell", group: "cells" },
170
+ { id: "toggleHeaderRow", action: "toggleHeaderRow", label: "Header row", title: "Toggle header row", group: "headers", active: (s) => s.headerRow },
171
+ { id: "toggleHeaderColumn", action: "toggleHeaderColumn", label: "Header col", title: "Toggle header column", group: "headers", active: (s) => s.headerColumn },
172
+ { id: "toggleHeaderCell", action: "toggleHeaderCell", label: "Header cell", title: "Toggle header cell", group: "headers", active: (s) => s.headerCell },
173
+ { id: "alignLeft", action: "setCellAlignment", params: { align: "left" }, label: "Left", title: "Align cell left", group: "align", active: (s) => s.cellAlignment === "left" },
174
+ { id: "alignCenter", action: "setCellAlignment", params: { align: "center" }, label: "Center", title: "Align cell center", group: "align", active: (s) => s.cellAlignment === "center" },
175
+ { id: "alignRight", action: "setCellAlignment", params: { align: "right" }, label: "Right", title: "Align cell right", group: "align", active: (s) => s.cellAlignment === "right" },
176
+ { id: "deleteTable", action: "deleteTable", label: "Delete table", title: "Delete table", group: "table" }
177
+ ];
178
+ var MAX_TABLE_ROWS = 100;
179
+ var MAX_TABLE_COLUMNS = 50;
180
+ var live = (editor) => !!editor && !editor.isDestroyed;
181
+ function isTableEnabled(editor) {
182
+ return live(editor) && !!editor.schema.nodes.table && !!editor.schema.nodes.tableRow;
183
+ }
184
+ function isSelectionInTable(state) {
185
+ if (!state.schema.nodes.table) return false;
186
+ return state.selection instanceof _tables.CellSelection || _tables.isInTable.call(void 0, state);
187
+ }
188
+ function shouldShowTableBubbleMenu({ editor, state }) {
189
+ return editor.isEditable && isSelectionInTable(state);
190
+ }
191
+ var isInt = (value, min, max) => typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
192
+ var can = (editor, run) => {
193
+ try {
194
+ return !!run(editor.can().chain()).run();
195
+ } catch (e) {
196
+ return false;
197
+ }
198
+ };
199
+ function getTableActionState(editor, action, params = {}) {
200
+ if (!live(editor)) return "The editor is not available.";
201
+ if (!isTableEnabled(editor)) return "Tables are not enabled in this editor.";
202
+ if (!editor.isEditable) return "The editor is read-only.";
203
+ const state = editor.state;
204
+ const inTable = isSelectionInTable(state);
205
+ if (action === "insertTable") {
206
+ if (inTable) return "Tables cannot be nested: move the cursor out of the table first.";
207
+ if (params.rows !== void 0 && !isInt(params.rows, 1, MAX_TABLE_ROWS)) {
208
+ return `Rows must be a whole number from 1 to ${MAX_TABLE_ROWS}.`;
209
+ }
210
+ if (params.cols !== void 0 && !isInt(params.cols, 1, MAX_TABLE_COLUMNS)) {
211
+ return `Columns must be a whole number from 1 to ${MAX_TABLE_COLUMNS}.`;
212
+ }
213
+ return can(editor, (c) => c.insertTable({ rows: 1, cols: 1 })) ? true : "A table cannot be inserted here.";
214
+ }
215
+ if (!inTable) return "Place the cursor in a table first.";
216
+ switch (action) {
217
+ case "mergeCells":
218
+ case "splitCell": {
219
+ if (_chunkIFHKKVXHcjs.isTrackChangesEnabled.call(void 0, editor)) {
220
+ return `${action === "mergeCells" ? "Merging" : "Splitting"} cells cannot be tracked: turn off Track Changes first.`;
221
+ }
222
+ if (action === "mergeCells") {
223
+ return can(editor, (c) => c.mergeCells()) ? true : "Select two or more adjacent cells to merge.";
224
+ }
225
+ return can(editor, (c) => c.splitCell()) ? true : "Only a merged cell can be split.";
226
+ }
227
+ case "deleteRow":
228
+ case "deleteColumn": {
229
+ const rect = _tables.selectedRect.call(void 0, state);
230
+ const all = action === "deleteRow" ? rect.top === 0 && rect.bottom === rect.map.height : rect.left === 0 && rect.right === rect.map.width;
231
+ const what = action === "deleteRow" ? "rows" : "columns";
232
+ if (all || !can(editor, (c) => c[action]())) return `These are all the ${what}: delete the table instead.`;
233
+ return true;
234
+ }
235
+ case "goToNextCell":
236
+ return can(editor, (c) => c.goToNextCell()) ? true : "This is the last cell.";
237
+ case "goToPreviousCell":
238
+ return can(editor, (c) => c.goToPreviousCell()) ? true : "This is the first cell.";
239
+ case "setCellAlignment":
240
+ if (params.align !== void 0 && params.align !== null && !normalizeTableCellAlignment(params.align)) {
241
+ return 'Alignment must be "left", "center", "right", "justify" or null.';
242
+ }
243
+ if (!_optionalChain([editor, 'access', _15 => _15.schema, 'access', _16 => _16.nodes, 'access', _17 => _17.tableCell, 'optionalAccess', _18 => _18.spec, 'access', _19 => _19.attrs, 'optionalAccess', _20 => _20.align])) return "Cell alignment is not supported by this schema.";
244
+ return true;
245
+ case "setCellBackground":
246
+ if (params.color !== void 0 && params.color !== null && !normalizeTableCellColor(params.color)) {
247
+ return "Color must be a CSS color such as #fde68a, rgb(\u2026) or a color name, or null.";
248
+ }
249
+ if (!_optionalChain([editor, 'access', _21 => _21.schema, 'access', _22 => _22.nodes, 'access', _23 => _23.tableCell, 'optionalAccess', _24 => _24.spec, 'access', _25 => _25.attrs, 'optionalAccess', _26 => _26.backgroundColor])) return "Cell backgrounds are not supported by this schema.";
250
+ return true;
251
+ default:
252
+ return can(editor, (c) => c[action]()) ? true : "This table action is not available here.";
253
+ }
254
+ }
255
+ function runTableAction(editor, action, params = {}, options = {}) {
256
+ if (getTableActionState(editor, action, params) !== true) return false;
257
+ const ed = editor;
258
+ let chain = ed.chain();
259
+ if (options.focus) chain = chain.focus();
260
+ switch (action) {
261
+ case "insertTable":
262
+ chain = chain.insertTable({
263
+ rows: _nullishCoalesce(params.rows, () => ( 3)),
264
+ cols: _nullishCoalesce(params.cols, () => ( 3)),
265
+ withHeaderRow: _nullishCoalesce(params.withHeaderRow, () => ( true))
266
+ });
267
+ break;
268
+ case "setCellAlignment":
269
+ chain = chain.setCellAttribute("align", normalizeTableCellAlignment(params.align));
270
+ break;
271
+ case "setCellBackground":
272
+ chain = chain.setCellAttribute("backgroundColor", normalizeTableCellColor(params.color));
273
+ break;
274
+ default:
275
+ chain = chain[action]();
276
+ }
277
+ return !!chain.run();
278
+ }
279
+ var NO_ACTIONS = Object.fromEntries(
280
+ TABLE_ACTIONS.map(({ action }) => [action, { enabled: false, reason: "The editor is not available." }])
281
+ );
282
+ var EMPTY_TABLE_STATE = Object.freeze({
283
+ enabled: false,
284
+ inTable: false,
285
+ cellSelection: false,
286
+ rows: 0,
287
+ columns: 0,
288
+ row: -1,
289
+ column: -1,
290
+ headerRow: false,
291
+ headerColumn: false,
292
+ headerCell: false,
293
+ cellAlignment: null,
294
+ cellBackground: null,
295
+ actions: NO_ACTIONS
296
+ });
297
+ function getTableState(editor) {
298
+ if (!live(editor)) return EMPTY_TABLE_STATE;
299
+ const actions = Object.fromEntries(
300
+ TABLE_ACTIONS.map(({ action }) => {
301
+ const result = getTableActionState(editor, action);
302
+ return [action, result === true ? { enabled: true } : { enabled: false, reason: result }];
303
+ })
304
+ );
305
+ const state = editor.state;
306
+ const base = { ...EMPTY_TABLE_STATE, enabled: isTableEnabled(editor), actions };
307
+ if (!base.enabled || !isSelectionInTable(state)) return base;
308
+ try {
309
+ const rect = _tables.selectedRect.call(void 0, state);
310
+ const { map, table } = rect;
311
+ const cellAt = (row, col) => table.nodeAt(map.map[row * map.width + col]);
312
+ const allHeaders = (positions) => positions.length > 0 && positions.every((pos) => _optionalChain([table, 'access', _27 => _27.nodeAt, 'call', _28 => _28(pos), 'optionalAccess', _29 => _29.type, 'access', _30 => _30.name]) === "tableHeader");
313
+ const firstRow = map.cellsInRect({ left: 0, right: map.width, top: 0, bottom: 1 });
314
+ const firstColumn = map.cellsInRect({ left: 0, right: 1, top: 0, bottom: map.height });
315
+ const cell = cellAt(rect.top, rect.left);
316
+ return {
317
+ ...base,
318
+ inTable: true,
319
+ cellSelection: state.selection instanceof _tables.CellSelection,
320
+ rows: map.height,
321
+ columns: map.width,
322
+ row: rect.top,
323
+ column: rect.left,
324
+ headerRow: allHeaders(firstRow),
325
+ headerColumn: allHeaders(firstColumn),
326
+ headerCell: _optionalChain([cell, 'optionalAccess', _31 => _31.type, 'access', _32 => _32.name]) === "tableHeader",
327
+ cellAlignment: normalizeTableCellAlignment(_optionalChain([cell, 'optionalAccess', _33 => _33.attrs, 'access', _34 => _34.align])),
328
+ cellBackground: normalizeTableCellColor(_optionalChain([cell, 'optionalAccess', _35 => _35.attrs, 'access', _36 => _36.backgroundColor]))
329
+ };
330
+ } catch (e2) {
331
+ return { ...base, inTable: true };
332
+ }
333
+ }
334
+ var stateKey = (state) => JSON.stringify(state);
335
+ function createTableStore(editor) {
336
+ const listeners = /* @__PURE__ */ new Set();
337
+ let snapshot = getTableState(editor);
338
+ let key = stateKey(snapshot);
339
+ const update = () => {
340
+ const next = getTableState(editor);
341
+ const nextKey = stateKey(next);
342
+ if (nextKey === key) return;
343
+ snapshot = next;
344
+ key = nextKey;
345
+ listeners.forEach((listener) => listener());
346
+ };
347
+ const detach = () => {
348
+ _optionalChain([editor, 'optionalAccess', _37 => _37.off, 'call', _38 => _38("transaction", update)]);
349
+ _optionalChain([editor, 'optionalAccess', _39 => _39.off, 'call', _40 => _40("update", update)]);
350
+ _optionalChain([editor, 'optionalAccess', _41 => _41.off, 'call', _42 => _42("focus", update)]);
351
+ _optionalChain([editor, 'optionalAccess', _43 => _43.off, 'call', _44 => _44("destroy", update)]);
352
+ };
353
+ return {
354
+ getSnapshot: () => {
355
+ if (!listeners.size) {
356
+ const next = getTableState(editor);
357
+ const nextKey = stateKey(next);
358
+ if (nextKey !== key) {
359
+ snapshot = next;
360
+ key = nextKey;
361
+ }
362
+ }
363
+ return snapshot;
364
+ },
365
+ subscribe(listener) {
366
+ if (!listeners.size && editor) {
367
+ update();
368
+ editor.on("transaction", update);
369
+ editor.on("update", update);
370
+ editor.on("focus", update);
371
+ editor.on("destroy", update);
372
+ }
373
+ listeners.add(listener);
374
+ return () => {
375
+ listeners.delete(listener);
376
+ if (!listeners.size) detach();
377
+ };
378
+ },
379
+ destroy() {
380
+ detach();
381
+ listeners.clear();
382
+ }
383
+ };
384
+ }
385
+
386
+
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+
400
+
401
+
402
+
403
+
404
+
405
+
406
+
407
+
408
+ exports.normalizeTableCellAlignment = normalizeTableCellAlignment; exports.normalizeTableCellColor = normalizeTableCellColor; exports.isGfmTable = isGfmTable; exports.DEFAULT_TABLE_OPTIONS = DEFAULT_TABLE_OPTIONS; exports.Table = Table; exports.TableRow = TableRow; exports.TableCell = TableCell; exports.TableHeader = TableHeader; exports.createTableExtensions = createTableExtensions; exports.TABLE_ACTIONS = TABLE_ACTIONS; exports.DEFAULT_TABLE_TOOLBAR = DEFAULT_TABLE_TOOLBAR; exports.MAX_TABLE_ROWS = MAX_TABLE_ROWS; exports.MAX_TABLE_COLUMNS = MAX_TABLE_COLUMNS; exports.isTableEnabled = isTableEnabled; exports.isSelectionInTable = isSelectionInTable; exports.shouldShowTableBubbleMenu = shouldShowTableBubbleMenu; exports.getTableActionState = getTableActionState; exports.runTableAction = runTableAction; exports.EMPTY_TABLE_STATE = EMPTY_TABLE_STATE; exports.getTableState = getTableState; exports.createTableStore = createTableStore;
409
+ //# sourceMappingURL=chunk-HDYMLS3X.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/chunk-HDYMLS3X.cjs","../src/extensions/table/extension.ts","../src/extensions/table/actions.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACJA,oCAAqD;AACrD,yCAAuD;AACvD,gHAAwB;AACxB,6HAA2B;AAC3B,yIAA8B;AAC9B,iIAA4B;AAE5B,IAAM,WAAA,EAAa,CAAC,GAAA,EAAU,IAAA,EAAA,mBAC5B,GAAA,0BAAA,CAAM,IAAI,IAAA,mBAAK,GAAA,6BAAK,OAAA,4BAAA,CAAU,IAAI,IAAA,mBAAK,GAAA,6BAAK,OAAA,6BAAS,UAAA,mBAAW,GAAA,6BAAK,UAAA,GAAW,GAAA;AAElF,IAAM,UAAA,EAAY,UAAA,CAAW,MAAA,EAAQ,OAAO,CAAA;AAC5C,IAAM,aAAA,EAAe,UAAA,CAAW,SAAA,EAAW,UAAU,CAAA;AACrD,IAAM,gBAAA,EAAkB,UAAA,CAAW,YAAA,EAAc,aAAa,CAAA;AAC9D,IAAM,cAAA,EAAgB,UAAA,CAAW,UAAA,EAAY,WAAW,CAAA;AAKxD,IAAM,WAAA,kBAAa,IAAI,GAAA,CAAwB,CAAC,MAAA,EAAQ,QAAA,EAAU,OAAA,EAAS,SAAS,CAAC,CAAA;AAG9E,SAAS,2BAAA,CAA4B,KAAA,EAA2C;AACrF,EAAA,MAAM,EAAA,EAAI,OAAO,MAAA,IAAU,SAAA,EAAW,KAAA,CAAM,IAAA,CAAK,CAAA,CAAE,WAAA,CAAY,EAAA,EAAI,EAAA;AACnE,EAAA,OAAO,UAAA,CAAW,GAAA,CAAI,CAAuB,EAAA,EAAK,EAAA,EAA2B,IAAA;AAC/E;AAQA,IAAM,YAAA,EACJ,gFAAA;AAGK,SAAS,uBAAA,CAAwB,KAAA,EAA+B;AACrE,EAAA,MAAM,EAAA,EAAI,OAAO,MAAA,IAAU,SAAA,EAAW,KAAA,CAAM,IAAA,CAAK,EAAA,EAAI,EAAA;AACrD,EAAA,GAAA,CAAI,CAAC,EAAA,GAAK,CAAA,CAAE,OAAA,EAAS,GAAA,GAAM,CAAC,WAAA,CAAY,IAAA,CAAK,CAAC,CAAA,EAAG,OAAO,IAAA;AACxD,EAAA,GAAA,CAAI,iDAAA,CAAkD,IAAA,CAAK,CAAC,CAAA,EAAG,OAAO,IAAA;AACtE,EAAA,OAAO,CAAA;AACT;AAGA,IAAM,eAAA,EAAiB,CAAA,EAAA,GAAA,CAAO;AAAA,EAC5B,KAAA,EAAO;AAAA,IACL,OAAA,EAAS,IAAA;AAAA,IACT,SAAA,EAAW,CAAC,OAAA,EAAA,GACV,2BAAA,iBAA4B,OAAA,qBAAQ,KAAA,6BAAO,YAAA,GAAa,OAAA,CAAQ,YAAA,CAAa,OAAO,CAAC,CAAA;AAAA,IACvF,UAAA,EAAY,CAAC,KAAA,EAAA,GAA+B;AAC1C,MAAA,MAAM,MAAA,EAAQ,2BAAA,CAA4B,KAAA,CAAM,KAAK,CAAA;AACrD,MAAA,OAAO,MAAA,EAAQ,EAAE,KAAA,EAAO,CAAA,YAAA,EAAe,KAAK,CAAA,EAAA;AAC9C,IAAA;AACF,EAAA;AACiB,EAAA;AACN,IAAA;AAEP,IAAA;AAC8C,MAAA;AAG9C,IAAA;AAC0C,IAAA;AACE,MAAA;AACC,MAAA;AAC/C,IAAA;AACF,EAAA;AACF;AAM4C;AACT,EAAA;AACO,EAAA;AACjC,EAAA;AACT;AAEkE;AAOP;AAC/B,EAAA;AACI,EAAA;AACR,EAAA;AACV,EAAA;AAGR,IAAA;AAEkC,MAAA;AAIlC,IAAA;AACJ,EAAA;AACF;AAE4E;AAOT;AAC1C,EAAA;AAC0B,IAAA;AAEN,IAAA;AACpB,IAAA;AACrB,IAAA;AACF,EAAA;AACuB,EAAA;AACP,EAAA;AACmB,EAAA;AACN,IAAA;AACX,IAAA;AACmB,IAAA;AACT,MAAA;AACD,MAAA;AAGC,MAAA;AACqB,MAAA;AACH,MAAA;AACG,MAAA;AAC9C,IAAA;AACe,IAAA;AACH,IAAA;AAC0B,MAAA;AACjB,MAAA;AACsB,MAAA;AAC5C,IAAA;AACD,EAAA;AACe,EAAA;AACK,EAAA;AACvB;AA2B2D;AAC9C,EAAA;AACE,EAAA;AACC,EAAA;AACO,EAAA;AACI,EAAA;AACiB,EAAA;AACrB,EAAA;AACE,EAAA;AACH,EAAA;AACtB;AAGsC;AACvB,EAAA;AACqB,IAAA;AAClC,EAAA;AACD;AAEuB;AAGsB;AAC5B,EAAA;AACiC,IAAA;AACjD,EAAA;AACD;AAGiD;AAChC,EAAA;AACiC,IAAA;AACjD,EAAA;AACD;AAS8F;AAC5C,EAAA;AAC1C,EAAA;AACW,IAAA;AACD,MAAA;AACE,MAAA;AACC,MAAA;AACO,MAAA;AACI,MAAA;AACT,MAAA;AACnB,IAAA;AACsC,IAAA;AACG,IAAA;AACF,IAAA;AAC1C,EAAA;AACF;ADxFmD;AACA;AEzIhB;AAkDsB;AACP,EAAA;AACf,EAAA;AACD,EAAA;AACY,EAAA;AACR,EAAA;AACD,EAAA;AACF,EAAA;AACe,EAAA;AACF,EAAA;AACF,EAAA;AACR,EAAA;AACG,EAAA;AACF,EAAA;AACS,EAAA;AACT,EAAA;AACA,EAAA;AACC,EAAA;AACxC;AAmBkE;AAClB,EAAA;AACF,EAAA;AACG,EAAA;AACd,EAAA;AACD,EAAA;AACc,EAAA;AACG,EAAA;AACF,EAAA;AACd,EAAA;AACG,EAAA;AACF,EAAA;AACa,EAAA;AACE,EAAA;AACD,EAAA;AACJ,EAAA;AAC9C;AAE8B;AACG;AAEyD;AAGf;AAC5B,EAAA;AAC/C;AAGgE;AACxB,EAAA;AACJ,EAAA;AACpC;AAM0D;AACT,EAAA;AACjD;AAGmB;AAEgD;AAC7D,EAAA;AACqC,IAAA;AACjC,EAAA;AACC,IAAA;AACT,EAAA;AACF;AASE;AAE0B,EAAA;AACU,EAAA;AACL,EAAA;AACV,EAAA;AACmB,EAAA;AAEV,EAAA;AACR,IAAA;AAC2B,IAAA;AACtC,MAAA;AACT,IAAA;AAC+C,IAAA;AACtC,MAAA;AACT,IAAA;AAC0C,IAAA;AAC5C,EAAA;AAEqB,EAAA;AAEL,EAAA;AACT,IAAA;AACa,IAAA;AACmB,MAAA;AACG,QAAA;AACtC,MAAA;AAC6B,MAAA;AACa,QAAA;AAC1C,MAAA;AAC2C,MAAA;AAC7C,IAAA;AACK,IAAA;AACgB,IAAA;AAEY,MAAA;AAEtB,MAAA;AAE6B,MAAA;AACO,MAAA;AACtC,MAAA;AACT,IAAA;AACK,IAAA;AACuC,MAAA;AACvC,IAAA;AAC0C,MAAA;AAC1C,IAAA;AACsC,MAAA;AAChC,QAAA;AACT,MAAA;AACyC,MAAA;AAClC,MAAA;AACJ,IAAA;AACsC,MAAA;AAChC,QAAA;AACT,MAAA;AACyC,MAAA;AAClC,MAAA;AACT,IAAA;AAC2C,MAAA;AAC7C,EAAA;AACF;AAc+B;AAGiB,EAAA;AACnC,EAAA;AACe,EAAA;AACa,EAAA;AACvB,EAAA;AACT,IAAA;AACuB,MAAA;AACH,QAAA;AACA,QAAA;AACkB,QAAA;AACxC,MAAA;AACD,MAAA;AACG,IAAA;AACqC,MAAA;AACxC,MAAA;AACG,IAAA;AAC4B,MAAA;AAC/B,MAAA;AACF,IAAA;AACwB,MAAA;AAC1B,EAAA;AACmB,EAAA;AACrB;AAkC0B;AACqB,EAAA;AAC/C;AAE2D;AAChD,EAAA;AACA,EAAA;AACM,EAAA;AACT,EAAA;AACG,EAAA;AACJ,EAAA;AACG,EAAA;AACG,EAAA;AACG,EAAA;AACF,EAAA;AACG,EAAA;AACC,EAAA;AACP,EAAA;AACV;AAG4E;AACjD,EAAA;AACH,EAAA;AACa,IAAA;AACW,MAAA;AACE,MAAA;AAC9C,IAAA;AACH,EAAA;AACqB,EAAA;AACqC,EAAA;AACT,EAAA;AAC7C,EAAA;AAC6B,IAAA;AACR,IAAA;AACuC,IAAA;AAElD,IAAA;AACgC,IAAA;AACG,IAAA;AACR,IAAA;AAChC,IAAA;AACF,MAAA;AACM,MAAA;AACiC,MAAA;AAChC,MAAA;AACG,MAAA;AACH,MAAA;AACG,MAAA;AACiB,MAAA;AACM,MAAA;AACJ,MAAA;AACW,MAAA;AACH,MAAA;AAC1C,IAAA;AACM,EAAA;AAC0B,IAAA;AAClC,EAAA;AACF;AAE4D;AAcoB;AACxC,EAAA;AACH,EAAA;AACR,EAAA;AAEN,EAAA;AACc,IAAA;AACJ,IAAA;AACR,IAAA;AACV,IAAA;AACL,IAAA;AACoC,IAAA;AAC5C,EAAA;AACqB,EAAA;AACc,oBAAA;AACL,oBAAA;AACD,oBAAA;AACE,oBAAA;AAC/B,EAAA;AAEO,EAAA;AACc,IAAA;AACI,MAAA;AACc,QAAA;AACJ,QAAA;AACR,QAAA;AACR,UAAA;AACL,UAAA;AACR,QAAA;AACF,MAAA;AACO,MAAA;AACT,IAAA;AACoB,IAAA;AACa,MAAA;AACtB,QAAA;AACwB,QAAA;AAEL,QAAA;AACD,QAAA;AACE,QAAA;AAC7B,MAAA;AACsB,MAAA;AACT,MAAA;AACc,QAAA;AACG,QAAA;AAC9B,MAAA;AACF,IAAA;AACU,IAAA;AACD,MAAA;AACS,MAAA;AAClB,IAAA;AACF,EAAA;AACF;AF1BmD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/chunk-HDYMLS3X.cjs","sourcesContent":[null,"import { getHTMLFromFragment, type Extensions } from \"@tiptap/core\";\nimport { Fragment, type Node as ProsemirrorNode } from \"@tiptap/pm/model\";\nimport * as _Table from \"@tiptap/extension-table\";\nimport * as _TableRow from \"@tiptap/extension-table-row\";\nimport * as _TableHeader from \"@tiptap/extension-table-header\";\nimport * as _TableCell from \"@tiptap/extension-table-cell\";\n\nconst resolveExt = (mod: any, name: string) =>\n mod?.[name] || mod?.default?.[name] || mod?.default?.default || mod?.default || mod;\n\nconst BaseTable = resolveExt(_Table, \"Table\");\nconst BaseTableRow = resolveExt(_TableRow, \"TableRow\");\nconst BaseTableHeader = resolveExt(_TableHeader, \"TableHeader\");\nconst BaseTableCell = resolveExt(_TableCell, \"TableCell\");\n\n/** Horizontal alignment of a table cell (`align` attribute). */\nexport type TableCellAlignment = \"left\" | \"center\" | \"right\" | \"justify\";\n\nconst ALIGNMENTS = new Set<TableCellAlignment>([\"left\", \"center\", \"right\", \"justify\"]);\n\n/** Returns a valid cell alignment, or `null`. */\nexport function normalizeTableCellAlignment(value: unknown): TableCellAlignment | null {\n const v = typeof value === \"string\" ? value.trim().toLowerCase() : \"\";\n return ALIGNMENTS.has(v as TableCellAlignment) ? (v as TableCellAlignment) : null;\n}\n\n/**\n * Color values allowed as a cell background: hex, `rgb()/rgba()/hsl()/hsla()`\n * with numeric arguments, or a CSS color keyword. Anything else (e.g.\n * `url(...)`, `expression(...)`, `;`) is rejected because the value ends up in\n * a `style` attribute.\n */\nconst COLOR_REGEX =\n /^(?:#[0-9a-f]{3,8}|(?:rgb|rgba|hsl|hsla)\\(\\s*[-0-9.%\\s,/deg]+\\)|[a-z]{3,20})$/i;\n\n/** Returns a safe CSS color for a cell background, or `null`. */\nexport function normalizeTableCellColor(value: unknown): string | null {\n const v = typeof value === \"string\" ? value.trim() : \"\";\n if (!v || v.length > 64 || !COLOR_REGEX.test(v)) return null;\n if (/^(?:inherit|initial|unset|revert|transparent)$/i.test(v)) return null;\n return v;\n}\n\n/** Cell attributes added on top of TipTap's `colspan` / `rowspan` / `colwidth`. */\nconst cellAttributes = () => ({\n align: {\n default: null,\n parseHTML: (element: HTMLElement) =>\n normalizeTableCellAlignment(element.style?.textAlign || element.getAttribute(\"align\")),\n renderHTML: (attrs: Record<string, any>) => {\n const align = normalizeTableCellAlignment(attrs.align);\n return align ? { style: `text-align: ${align}` } : {};\n },\n },\n backgroundColor: {\n default: null,\n parseHTML: (element: HTMLElement) =>\n normalizeTableCellColor(\n element.getAttribute(\"data-background-color\") ||\n element.style?.backgroundColor ||\n element.getAttribute(\"bgcolor\"),\n ),\n renderHTML: (attrs: Record<string, any>) => {\n const color = normalizeTableCellColor(attrs.backgroundColor);\n return color ? { style: `background-color: ${color}`, \"data-background-color\": color } : {};\n },\n },\n});\n\n// ---------------------------------------------------------------------------\n// Markdown (tiptap-markdown)\n// ---------------------------------------------------------------------------\n\nconst children = (node: ProsemirrorNode) => {\n const list: ProsemirrorNode[] = [];\n node.forEach((child) => list.push(child));\n return list;\n};\n\nconst hasSpan = (cell: ProsemirrorNode) => (cell.attrs.colspan ?? 1) > 1 || (cell.attrs.rowspan ?? 1) > 1;\n\n/**\n * Whether a table can be written as a GFM pipe table: the first row is all\n * header cells, the other rows have none, no cell spans rows or columns, and\n * every cell holds a single paragraph.\n */\nexport function isGfmTable(node: ProsemirrorNode): boolean {\n const rows = children(node);\n if (rows.length === 0) return false;\n const width = rows[0].childCount;\n return rows.every(\n (row, r) =>\n row.childCount === width &&\n children(row).every(\n (cell) =>\n (r === 0 ? cell.type.name === \"tableHeader\" : cell.type.name === \"tableCell\") &&\n !hasSpan(cell) &&\n cell.childCount === 1 &&\n cell.firstChild!.type.name === \"paragraph\",\n ),\n );\n}\n\nconst DELIMITERS: Record<string, string> = { left: \":---\", center: \":---:\", right: \"---:\" };\n\n/**\n * tiptap-markdown serializer for tables: GFM pipe tables (with column\n * alignment from the header cells and `|` escaped) when `isGfmTable`, HTML\n * otherwise (spans, header columns, multi-paragraph cells).\n */\nfunction serializeTableMarkdown(state: any, node: ProsemirrorNode) {\n if (!isGfmTable(node)) {\n const html = getHTMLFromFragment(Fragment.from(node), node.type.schema);\n // An HTML block must start on its own line and contain no blank lines.\n state.write(html.replace(/\\n{2,}/g, \"\\n\"));\n state.closeBlock(node);\n return;\n }\n const previous = state.inTable;\n state.inTable = true;\n children(node).forEach((row, r) => {\n if (r) state.ensureNewLine();\n state.write(\"| \");\n children(row).forEach((cell, c) => {\n if (c) state.write(\" | \");\n const paragraph = cell.firstChild!;\n // Render in place (mid-line, so no block prefix is added), then escape\n // the cell's pipes and line breaks, which would end the cell or row.\n const start = state.out.length;\n if (paragraph.childCount) state.renderInline(paragraph);\n const text: string = state.out.slice(start);\n state.out = state.out.slice(0, start) + text.replace(/\\n/g, \" \").replace(/\\|/g, \"\\\\|\");\n });\n state.write(\" |\");\n if (r === 0) {\n const delimiter = children(row).map((cell) => DELIMITERS[cell.attrs.align] ?? \"---\");\n state.ensureNewLine();\n state.write(`| ${delimiter.join(\" | \")} |`);\n }\n });\n state.inTable = previous;\n state.closeBlock(node);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions\n// ---------------------------------------------------------------------------\n\nexport interface RichTextTableOptions {\n /** Drag column borders to resize columns (stored as `colwidth`). Default `true`. */\n resizable: boolean;\n /** Width of the resize handle in pixels. Default 5. */\n handleWidth: number;\n /** Minimum cell width in pixels. Default 25. */\n cellMinWidth: number;\n /** Whether the last column can be resized. Default `true`. */\n lastColumnResizable: boolean;\n /** Allow selecting the whole table as a node (click its border, Esc from a cell selection). Default `true`. */\n allowTableNodeSelection: boolean;\n /** HTML attributes of the `<table>` element. */\n HTMLAttributes: Record<string, any>;\n /** HTML attributes of `<td>` elements. */\n cellHTMLAttributes: Record<string, any>;\n /** HTML attributes of `<th>` elements. */\n headerHTMLAttributes: Record<string, any>;\n /** HTML attributes of `<tr>` elements. */\n rowHTMLAttributes: Record<string, any>;\n}\n\nexport const DEFAULT_TABLE_OPTIONS: RichTextTableOptions = {\n resizable: true,\n handleWidth: 5,\n cellMinWidth: 25,\n lastColumnResizable: true,\n allowTableNodeSelection: true,\n HTMLAttributes: { class: \"pixerate-table\" },\n cellHTMLAttributes: {},\n headerHTMLAttributes: {},\n rowHTMLAttributes: {},\n};\n\n/** TipTap's `Table` with the GFM-aware markdown serializer. */\nexport const Table = BaseTable.extend({\n addStorage() {\n return { markdown: { serialize: serializeTableMarkdown } };\n },\n});\n\nexport const TableRow = BaseTableRow;\n\n/** TipTap's `TableCell` plus `align` and `backgroundColor` attributes. */\nexport const TableCell = BaseTableCell.extend({\n addAttributes() {\n return { ...this.parent?.(), ...cellAttributes() };\n },\n});\n\n/** TipTap's `TableHeader` plus `align` and `backgroundColor` attributes. */\nexport const TableHeader = BaseTableHeader.extend({\n addAttributes() {\n return { ...this.parent?.(), ...cellAttributes() };\n },\n});\n\n/**\n * The table extensions (`table`, `tableRow`, `tableHeader`, `tableCell`)\n * configured for rich documents: resizable columns, header rows, columns and\n * cells, `colspan` / `rowspan` from imported HTML, cell alignment and\n * background, table node selection and GFM markdown. `createRichTextPreset`\n * adds them unless `table: false`.\n */\nexport function createTableExtensions(options: Partial<RichTextTableOptions> = {}): Extensions {\n const o = { ...DEFAULT_TABLE_OPTIONS, ...options };\n return [\n Table.configure({\n resizable: o.resizable,\n handleWidth: o.handleWidth,\n cellMinWidth: o.cellMinWidth,\n lastColumnResizable: o.lastColumnResizable,\n allowTableNodeSelection: o.allowTableNodeSelection,\n HTMLAttributes: o.HTMLAttributes,\n }),\n TableRow.configure({ HTMLAttributes: o.rowHTMLAttributes }),\n TableHeader.configure({ HTMLAttributes: o.headerHTMLAttributes }),\n TableCell.configure({ HTMLAttributes: o.cellHTMLAttributes }),\n ];\n}\n","import type { Editor } from \"@tiptap/core\";\nimport type { EditorState } from \"@tiptap/pm/state\";\nimport { CellSelection, isInTable, selectedRect } from \"@tiptap/pm/tables\";\nimport { isTrackChangesEnabled } from \"../track-changes\";\nimport {\n normalizeTableCellAlignment,\n normalizeTableCellColor,\n type TableCellAlignment,\n} from \"./extension\";\n\n/** Table operations shared by the command registry, the toolbars and agent tools. */\nexport type TableAction =\n | \"insertTable\"\n | \"addRowBefore\"\n | \"addRowAfter\"\n | \"deleteRow\"\n | \"addColumnBefore\"\n | \"addColumnAfter\"\n | \"deleteColumn\"\n | \"deleteTable\"\n | \"mergeCells\"\n | \"splitCell\"\n | \"toggleHeaderRow\"\n | \"toggleHeaderColumn\"\n | \"toggleHeaderCell\"\n | \"goToNextCell\"\n | \"goToPreviousCell\"\n | \"setCellAlignment\"\n | \"setCellBackground\";\n\n/** Parameters of `insertTable`, `setCellAlignment` and `setCellBackground`. */\nexport interface TableActionParams {\n /** `insertTable`: number of rows (1–100, default 3). */\n rows?: number;\n /** `insertTable`: number of columns (1–50, default 3). */\n cols?: number;\n /** `insertTable`: make the first row a header row (default `true`). */\n withHeaderRow?: boolean;\n /** `setCellAlignment`: `left`, `center`, `right`, `justify`, or `null` to clear. */\n align?: TableCellAlignment | null;\n /** `setCellBackground`: a CSS color, or `null` to clear. */\n color?: string | null;\n}\n\nexport interface TableActionInfo {\n action: TableAction;\n label: string;\n description: string;\n keywords: readonly string[];\n}\n\n/** Every table action with its label, in toolbar order. */\nexport const TABLE_ACTIONS: readonly TableActionInfo[] = [\n { action: \"insertTable\", label: \"Insert Table\", description: \"Inserts a table (rows, cols, withHeaderRow) at the cursor.\", keywords: [\"table\", \"grid\", \"new\"] },\n { action: \"addRowBefore\", label: \"Insert Row Above\", description: \"Adds a row above the current row.\", keywords: [\"row\", \"add\", \"above\"] },\n { action: \"addRowAfter\", label: \"Insert Row Below\", description: \"Adds a row below the current row.\", keywords: [\"row\", \"add\", \"below\"] },\n { action: \"deleteRow\", label: \"Delete Row\", description: \"Deletes the selected rows.\", keywords: [\"row\", \"remove\"] },\n { action: \"addColumnBefore\", label: \"Insert Column Left\", description: \"Adds a column left of the current column.\", keywords: [\"column\", \"add\", \"left\", \"before\"] },\n { action: \"addColumnAfter\", label: \"Insert Column Right\", description: \"Adds a column right of the current column.\", keywords: [\"column\", \"add\", \"right\", \"after\"] },\n { action: \"deleteColumn\", label: \"Delete Column\", description: \"Deletes the selected columns.\", keywords: [\"column\", \"remove\"] },\n { action: \"deleteTable\", label: \"Delete Table\", description: \"Deletes the table around the cursor.\", keywords: [\"table\", \"remove\"] },\n { action: \"mergeCells\", label: \"Merge Cells\", description: \"Merges the selected cells into one.\", keywords: [\"combine\", \"join\", \"span\"] },\n { action: \"splitCell\", label: \"Split Cell\", description: \"Splits a merged cell back into single cells.\", keywords: [\"unmerge\", \"span\"] },\n { action: \"toggleHeaderRow\", label: \"Toggle Header Row\", description: \"Turns the first row into header cells, or back.\", keywords: [\"header\", \"row\", \"th\"] },\n { action: \"toggleHeaderColumn\", label: \"Toggle Header Column\", description: \"Turns the first column into header cells, or back.\", keywords: [\"header\", \"column\", \"th\"] },\n { action: \"toggleHeaderCell\", label: \"Toggle Header Cell\", description: \"Turns the selected cells into header cells, or back.\", keywords: [\"header\", \"cell\", \"th\"] },\n { action: \"goToNextCell\", label: \"Next Cell\", description: \"Moves the cursor to the next cell.\", keywords: [\"tab\", \"navigate\"] },\n { action: \"goToPreviousCell\", label: \"Previous Cell\", description: \"Moves the cursor to the previous cell.\", keywords: [\"shift tab\", \"navigate\"] },\n { action: \"setCellAlignment\", label: \"Align Cells…\", description: \"Sets the horizontal alignment (align: left | center | right | justify | null) of the selected cells.\", keywords: [\"align\", \"left\", \"center\", \"right\"] },\n { action: \"setCellBackground\", label: \"Cell Background…\", description: \"Sets the background color (color: CSS color or null) of the selected cells.\", keywords: [\"shading\", \"fill\", \"color\"] },\n];\n\n/** A button of the table toolbars (`TableToolbar` in React and Svelte). */\nexport interface TableToolbarItem {\n /** Unique id (also the button's `data-action`). */\n id: string;\n action: TableAction;\n params?: TableActionParams;\n /** Short button text. */\n label: string;\n /** Accessible name and tooltip. */\n title: string;\n /** Items of one group are separated from the next group. */\n group: string;\n /** Toggle buttons: whether the button shows as pressed. */\n active?: (state: TableState) => boolean;\n}\n\n/** The default table toolbar: rows, columns, cells, headers, alignment, delete. */\nexport const DEFAULT_TABLE_TOOLBAR: readonly TableToolbarItem[] = [\n { id: \"addRowBefore\", action: \"addRowBefore\", label: \"+ Row ↑\", title: \"Insert row above\", group: \"rows\" },\n { id: \"addRowAfter\", action: \"addRowAfter\", label: \"+ Row ↓\", title: \"Insert row below\", group: \"rows\" },\n { id: \"deleteRow\", action: \"deleteRow\", label: \"− Row\", title: \"Delete row\", group: \"rows\" },\n { id: \"addColumnBefore\", action: \"addColumnBefore\", label: \"+ Col ←\", title: \"Insert column left\", group: \"columns\" },\n { id: \"addColumnAfter\", action: \"addColumnAfter\", label: \"+ Col →\", title: \"Insert column right\", group: \"columns\" },\n { id: \"deleteColumn\", action: \"deleteColumn\", label: \"− Col\", title: \"Delete column\", group: \"columns\" },\n { id: \"mergeCells\", action: \"mergeCells\", label: \"Merge\", title: \"Merge cells\", group: \"cells\" },\n { id: \"splitCell\", action: \"splitCell\", label: \"Split\", title: \"Split cell\", group: \"cells\" },\n { id: \"toggleHeaderRow\", action: \"toggleHeaderRow\", label: \"Header row\", title: \"Toggle header row\", group: \"headers\", active: (s) => s.headerRow },\n { id: \"toggleHeaderColumn\", action: \"toggleHeaderColumn\", label: \"Header col\", title: \"Toggle header column\", group: \"headers\", active: (s) => s.headerColumn },\n { id: \"toggleHeaderCell\", action: \"toggleHeaderCell\", label: \"Header cell\", title: \"Toggle header cell\", group: \"headers\", active: (s) => s.headerCell },\n { id: \"alignLeft\", action: \"setCellAlignment\", params: { align: \"left\" }, label: \"Left\", title: \"Align cell left\", group: \"align\", active: (s) => s.cellAlignment === \"left\" },\n { id: \"alignCenter\", action: \"setCellAlignment\", params: { align: \"center\" }, label: \"Center\", title: \"Align cell center\", group: \"align\", active: (s) => s.cellAlignment === \"center\" },\n { id: \"alignRight\", action: \"setCellAlignment\", params: { align: \"right\" }, label: \"Right\", title: \"Align cell right\", group: \"align\", active: (s) => s.cellAlignment === \"right\" },\n { id: \"deleteTable\", action: \"deleteTable\", label: \"Delete table\", title: \"Delete table\", group: \"table\" },\n];\n\nexport const MAX_TABLE_ROWS = 100;\nexport const MAX_TABLE_COLUMNS = 50;\n\nconst live = (editor: Editor | null | undefined): editor is Editor => !!editor && !editor.isDestroyed;\n\n/** Whether the editor's schema has the table nodes (`createRichTextPreset({ table })`). */\nexport function isTableEnabled(editor: Editor | null | undefined): boolean {\n return live(editor) && !!editor.schema.nodes.table && !!editor.schema.nodes.tableRow;\n}\n\n/** Whether the selection (cursor, text or cell selection) is inside a table. */\nexport function isSelectionInTable(state: EditorState): boolean {\n if (!state.schema.nodes.table) return false;\n return state.selection instanceof CellSelection || isInTable(state);\n}\n\n/**\n * `shouldShow` for a table bubble menu (TipTap's `BubbleMenuPlugin`): shown\n * while an editable editor's selection is in a table, even a collapsed cursor.\n */\nexport function shouldShowTableBubbleMenu({ editor, state }: { editor: Editor; state: EditorState }): boolean {\n return editor.isEditable && isSelectionInTable(state);\n}\n\nconst isInt = (value: unknown, min: number, max: number) =>\n typeof value === \"number\" && Number.isInteger(value) && value >= min && value <= max;\n\nconst can = (editor: Editor, run: (chain: any) => any): boolean => {\n try {\n return !!run(editor.can().chain()).run();\n } catch {\n return false;\n }\n};\n\n/**\n * Whether a table action can run: `true`, or the reason it cannot (e.g.\n * \"Place the cursor in a table first.\").\n */\nexport function getTableActionState(\n editor: Editor | null | undefined,\n action: TableAction,\n params: TableActionParams = {},\n): true | string {\n if (!live(editor)) return \"The editor is not available.\";\n if (!isTableEnabled(editor)) return \"Tables are not enabled in this editor.\";\n if (!editor.isEditable) return \"The editor is read-only.\";\n const state = editor.state;\n const inTable = isSelectionInTable(state);\n\n if (action === \"insertTable\") {\n if (inTable) return \"Tables cannot be nested: move the cursor out of the table first.\";\n if (params.rows !== undefined && !isInt(params.rows, 1, MAX_TABLE_ROWS)) {\n return `Rows must be a whole number from 1 to ${MAX_TABLE_ROWS}.`;\n }\n if (params.cols !== undefined && !isInt(params.cols, 1, MAX_TABLE_COLUMNS)) {\n return `Columns must be a whole number from 1 to ${MAX_TABLE_COLUMNS}.`;\n }\n return can(editor, (c) => c.insertTable({ rows: 1, cols: 1 })) ? true : \"A table cannot be inserted here.\";\n }\n\n if (!inTable) return \"Place the cursor in a table first.\";\n\n switch (action) {\n case \"mergeCells\":\n case \"splitCell\": {\n if (isTrackChangesEnabled(editor)) {\n return `${action === \"mergeCells\" ? \"Merging\" : \"Splitting\"} cells cannot be tracked: turn off Track Changes first.`;\n }\n if (action === \"mergeCells\") {\n return can(editor, (c) => c.mergeCells()) ? true : \"Select two or more adjacent cells to merge.\";\n }\n return can(editor, (c) => c.splitCell()) ? true : \"Only a merged cell can be split.\";\n }\n case \"deleteRow\":\n case \"deleteColumn\": {\n // prosemirror-tables only refuses to delete every row/column when dispatching.\n const rect = selectedRect(state);\n const all = action === \"deleteRow\"\n ? rect.top === 0 && rect.bottom === rect.map.height\n : rect.left === 0 && rect.right === rect.map.width;\n const what = action === \"deleteRow\" ? \"rows\" : \"columns\";\n if (all || !can(editor, (c) => c[action]())) return `These are all the ${what}: delete the table instead.`;\n return true;\n }\n case \"goToNextCell\":\n return can(editor, (c) => c.goToNextCell()) ? true : \"This is the last cell.\";\n case \"goToPreviousCell\":\n return can(editor, (c) => c.goToPreviousCell()) ? true : \"This is the first cell.\";\n case \"setCellAlignment\":\n if (params.align !== undefined && params.align !== null && !normalizeTableCellAlignment(params.align)) {\n return 'Alignment must be \"left\", \"center\", \"right\", \"justify\" or null.';\n }\n if (!editor.schema.nodes.tableCell?.spec.attrs?.align) return \"Cell alignment is not supported by this schema.\";\n return true;\n case \"setCellBackground\":\n if (params.color !== undefined && params.color !== null && !normalizeTableCellColor(params.color)) {\n return \"Color must be a CSS color such as #fde68a, rgb(…) or a color name, or null.\";\n }\n if (!editor.schema.nodes.tableCell?.spec.attrs?.backgroundColor) return \"Cell backgrounds are not supported by this schema.\";\n return true;\n default:\n return can(editor, (c) => c[action]()) ? true : \"This table action is not available here.\";\n }\n}\n\nexport interface RunTableActionOptions {\n /** Focus the editor (toolbars). Default `false`. */\n focus?: boolean;\n}\n\n/**\n * Runs a table action. Returns `false` (and changes nothing) when it cannot\n * run; check `getTableActionState` for the reason.\n */\nexport function runTableAction(\n editor: Editor | null | undefined,\n action: TableAction,\n params: TableActionParams = {},\n options: RunTableActionOptions = {},\n): boolean {\n if (getTableActionState(editor, action, params) !== true) return false;\n const ed = editor as Editor;\n let chain: any = ed.chain();\n if (options.focus) chain = chain.focus();\n switch (action) {\n case \"insertTable\":\n chain = chain.insertTable({\n rows: params.rows ?? 3,\n cols: params.cols ?? 3,\n withHeaderRow: params.withHeaderRow ?? true,\n });\n break;\n case \"setCellAlignment\":\n chain = chain.setCellAttribute(\"align\", normalizeTableCellAlignment(params.align));\n break;\n case \"setCellBackground\":\n chain = chain.setCellAttribute(\"backgroundColor\", normalizeTableCellColor(params.color));\n break;\n default:\n chain = chain[action]();\n }\n return !!chain.run();\n}\n\nexport interface TableActionStatus {\n enabled: boolean;\n /** Why the action cannot run (only when `enabled` is false). */\n reason?: string;\n}\n\n/** The table at the selection and what can be done there. */\nexport interface TableState {\n /** The schema has tables. */\n enabled: boolean;\n /** The selection is inside a table. */\n inTable: boolean;\n /** Cells are selected (a `CellSelection`). */\n cellSelection: boolean;\n /** Size of the table (0 outside a table). */\n rows: number;\n columns: number;\n /** Row and column (0-based) of the selection's first cell, or -1. */\n row: number;\n column: number;\n /** The first row / first column are all header cells. */\n headerRow: boolean;\n headerColumn: boolean;\n /** The cell at the selection is a header cell. */\n headerCell: boolean;\n /** Alignment / background of the cell at the selection. */\n cellAlignment: TableCellAlignment | null;\n cellBackground: string | null;\n /** Enablement of every action (with the default params). */\n actions: Record<TableAction, TableActionStatus>;\n}\n\nconst NO_ACTIONS = Object.fromEntries(\n TABLE_ACTIONS.map(({ action }) => [action, { enabled: false, reason: \"The editor is not available.\" }]),\n) as Record<TableAction, TableActionStatus>;\n\nexport const EMPTY_TABLE_STATE: TableState = Object.freeze({\n enabled: false,\n inTable: false,\n cellSelection: false,\n rows: 0,\n columns: 0,\n row: -1,\n column: -1,\n headerRow: false,\n headerColumn: false,\n headerCell: false,\n cellAlignment: null,\n cellBackground: null,\n actions: NO_ACTIONS,\n}) as TableState;\n\n/** Computes the table state at the editor's selection. */\nexport function getTableState(editor: Editor | null | undefined): TableState {\n if (!live(editor)) return EMPTY_TABLE_STATE;\n const actions = Object.fromEntries(\n TABLE_ACTIONS.map(({ action }) => {\n const result = getTableActionState(editor, action);\n return [action, result === true ? { enabled: true } : { enabled: false, reason: result }];\n }),\n ) as Record<TableAction, TableActionStatus>;\n const state = editor.state;\n const base: TableState = { ...EMPTY_TABLE_STATE, enabled: isTableEnabled(editor), actions };\n if (!base.enabled || !isSelectionInTable(state)) return base;\n try {\n const rect = selectedRect(state);\n const { map, table } = rect;\n const cellAt = (row: number, col: number) => table.nodeAt(map.map[row * map.width + col]);\n const allHeaders = (positions: number[]) =>\n positions.length > 0 && positions.every((pos) => table.nodeAt(pos)?.type.name === \"tableHeader\");\n const firstRow = map.cellsInRect({ left: 0, right: map.width, top: 0, bottom: 1 });\n const firstColumn = map.cellsInRect({ left: 0, right: 1, top: 0, bottom: map.height });\n const cell = cellAt(rect.top, rect.left);\n return {\n ...base,\n inTable: true,\n cellSelection: state.selection instanceof CellSelection,\n rows: map.height,\n columns: map.width,\n row: rect.top,\n column: rect.left,\n headerRow: allHeaders(firstRow),\n headerColumn: allHeaders(firstColumn),\n headerCell: cell?.type.name === \"tableHeader\",\n cellAlignment: normalizeTableCellAlignment(cell?.attrs.align),\n cellBackground: normalizeTableCellColor(cell?.attrs.backgroundColor),\n };\n } catch {\n return { ...base, inTable: true };\n }\n}\n\nconst stateKey = (state: TableState) => JSON.stringify(state);\n\nexport interface TableStore {\n getSnapshot(): TableState;\n subscribe(listener: () => void): () => void;\n destroy(): void;\n}\n\n/**\n * An external store of `getTableState(editor)` for UI bindings (React's\n * `useSyncExternalStore`, Svelte runes). The snapshot object only changes\n * when the state does, and the store listens to the editor only while it\n * has subscribers.\n */\nexport function createTableStore(editor: Editor | null | undefined): TableStore {\n const listeners = new Set<() => void>();\n let snapshot = getTableState(editor);\n let key = stateKey(snapshot);\n\n const update = () => {\n const next = getTableState(editor);\n const nextKey = stateKey(next);\n if (nextKey === key) return;\n snapshot = next;\n key = nextKey;\n listeners.forEach((listener) => listener());\n };\n const detach = () => {\n editor?.off(\"transaction\", update);\n editor?.off(\"update\", update);\n editor?.off(\"focus\", update);\n editor?.off(\"destroy\", update);\n };\n\n return {\n getSnapshot: () => {\n if (!listeners.size) {\n const next = getTableState(editor);\n const nextKey = stateKey(next);\n if (nextKey !== key) {\n snapshot = next;\n key = nextKey;\n }\n }\n return snapshot;\n },\n subscribe(listener) {\n if (!listeners.size && editor) {\n update();\n editor.on(\"transaction\", update);\n // `setEditable` emits `update` without a transaction.\n editor.on(\"update\", update);\n editor.on(\"focus\", update);\n editor.on(\"destroy\", update);\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (!listeners.size) detach();\n };\n },\n destroy() {\n detach();\n listeners.clear();\n },\n };\n}\n"]}