@viveeditor/ext-table 0.1.0 → 1.0.0-rc.1

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.
package/dist/index.js CHANGED
@@ -1,8 +1,135 @@
1
- import { defineExtension } from "@viveeditor/core";
2
- import { Plugin, TextSelection } from "prosemirror-state";
3
- import { TableMap, TableView, addColumnAfter, addColumnBefore, addRow, addRowAfter, addRowBefore, columnResizing, deleteColumn, deleteRow, deleteTable, goToNextCell, isInTable, mergeCells, selectedRect, splitCell, tableEditing, tableNodeTypes, tableNodes, toggleHeaderColumn, toggleHeaderRow } from "prosemirror-tables";
1
+ import { attributeValidator, cleanAttribute, defineExtension, limitDepth, normalizeColor, nullOr } from "@viveeditor/core";
2
+ import { Plugin, PluginKey, TextSelection } from "prosemirror-state";
3
+ import { CellSelection, TableMap, TableView, addColumnAfter, addColumnBefore, addRow, addRowAfter, addRowBefore, columnResizing, columnResizingPluginKey, deleteColumn, deleteRow, deleteTable, goToNextCell, isInTable, mergeCells, selectedRect, selectionCell, splitCell, tableEditing, tableNodeTypes, tableNodes, toggleHeaderColumn, toggleHeaderRow, updateColumnsOnResize } from "prosemirror-tables";
4
+ import { Decoration, DecorationSet } from "prosemirror-view";
4
5
  // src/index.ts
5
6
  const FALLBACK_WIDTH = 120;
7
+ const FALLBACK_HEIGHT = 32;
8
+ const MIN_ROW_HEIGHT = 24;
9
+ const MAX_ROW_HEIGHT = 2e3;
10
+ const MAX_SPAN = 100;
11
+ const MAX_COLUMN_WIDTH = 99999;
12
+ const ROW_HANDLE = 4;
13
+ const COLUMN_HANDLE = 5;
14
+ const PIXELS = /^(\d+(?:\.\d+)?)px$/;
15
+ const VERTICAL = ["middle", "bottom"];
16
+ const TEXT_ALIGN = [
17
+ "center",
18
+ "right",
19
+ "justify"
20
+ ];
21
+ const BORDERS = ["rows", "none"];
22
+ const PLAIN = /* @__PURE__ */ new Set(["#ffffff", "white"]);
23
+ const BORDER_COLOR = "--vive-table-border-color";
24
+ const BORDER_COLOR_DECLARATION = /--vive-table-border-color\s*:\s*([^;]*)/i;
25
+ function cellBackground(value) {
26
+ const color = normalizeColor(value);
27
+ return color && !PLAIN.has(color) ? color : null;
28
+ }
29
+ function cellVertical(value) {
30
+ return VERTICAL.includes(value) ? value : null;
31
+ }
32
+ function cellTextAlign(value) {
33
+ const align = typeof value === "string" ? value.trim().toLowerCase() : value;
34
+ return TEXT_ALIGN.includes(align) ? align : null;
35
+ }
36
+ function rowHeightOf(value) {
37
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return null;
38
+ return Math.min(MAX_ROW_HEIGHT, Math.max(MIN_ROW_HEIGHT, Math.round(value)));
39
+ }
40
+ function parseRowHeight(dom) {
41
+ const pixels = PIXELS.exec(dom.style.height.trim());
42
+ return pixels ? rowHeightOf(Number(pixels[1])) : null;
43
+ }
44
+ function renderRow(node) {
45
+ const height = rowHeightOf(node.attrs.height);
46
+ return height ? [
47
+ "tr",
48
+ { style: `height: ${height}px` },
49
+ 0
50
+ ] : ["tr", 0];
51
+ }
52
+ function tableBorder(value) {
53
+ return BORDERS.includes(value) ? value : null;
54
+ }
55
+ function tableStyleOf(node) {
56
+ return {
57
+ width: node.attrs.width === "full" ? "full" : null,
58
+ align: node.attrs.align === "center" ? "center" : null,
59
+ border: tableBorder(node.attrs.border),
60
+ striped: node.attrs.striped === true,
61
+ borderColor: normalizeColor(node.attrs.borderColor)
62
+ };
63
+ }
64
+ function addStyle(attrs, declaration) {
65
+ attrs.style = typeof attrs.style === "string" ? `${attrs.style}; ${declaration}` : declaration;
66
+ }
67
+ const valid = (accepts, what) => attributeValidator(nullOr(accepts), `table ${what}`);
68
+ function spanOf(value) {
69
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_SPAN ? value : null;
70
+ }
71
+ const isColumnWidth = (width) => typeof width === "number" && Number.isFinite(width) && width >= 0 && width <= MAX_COLUMN_WIDTH;
72
+ function columnWidthsOf(value) {
73
+ if (!Array.isArray(value) || value.length === 0 || value.length > MAX_SPAN) return null;
74
+ return value.every(isColumnWidth) ? value : null;
75
+ }
76
+ const CELL_ATTRIBUTES = {
77
+ textAlign: {
78
+ ...cleanAttribute(cellTextAlign, "table cell alignment", null),
79
+ getFromDOM: (dom) => cellTextAlign(dom.style.textAlign || dom.getAttribute("align")),
80
+ setDOMAttr: (value, attrs) => {
81
+ const align = cellTextAlign(value);
82
+ if (align) addStyle(attrs, `text-align: ${align}`);
83
+ }
84
+ },
85
+ background: {
86
+ ...cleanAttribute(cellBackground, "table cell background", null),
87
+ getFromDOM: (dom) => cellBackground(dom.style.backgroundColor),
88
+ setDOMAttr: (value, attrs) => {
89
+ const color = cellBackground(value);
90
+ if (color) addStyle(attrs, `background-color: ${color}`);
91
+ }
92
+ },
93
+ verticalAlign: {
94
+ ...cleanAttribute(cellVertical, "table cell vertical alignment", null),
95
+ getFromDOM: (dom) => cellVertical(dom.style.verticalAlign || dom.getAttribute("valign")),
96
+ setDOMAttr: (value, attrs) => {
97
+ const align = cellVertical(value);
98
+ if (align) addStyle(attrs, `vertical-align: ${align}`);
99
+ }
100
+ }
101
+ };
102
+ function setCellStyle(name, value) {
103
+ return (state, dispatch) => {
104
+ if (!isInTable(state)) return false;
105
+ const cells = [];
106
+ const { selection } = state;
107
+ if (selection instanceof CellSelection) selection.forEachCell((node, position) => {
108
+ cells.push({
109
+ node,
110
+ position
111
+ });
112
+ });
113
+ else {
114
+ const $cell = selectionCell(state);
115
+ if ($cell.nodeAfter) cells.push({
116
+ node: $cell.nodeAfter,
117
+ position: $cell.pos
118
+ });
119
+ }
120
+ const changed = cells.filter(({ node }) => node.attrs[name] !== value);
121
+ if (changed.length === 0) return false;
122
+ if (dispatch) {
123
+ const transaction = state.tr;
124
+ for (const { node, position } of changed) transaction.setNodeMarkup(position, void 0, {
125
+ ...node.attrs,
126
+ [name]: value
127
+ });
128
+ dispatch(transaction);
129
+ }
130
+ return true;
131
+ };
132
+ }
6
133
  function count(value, fallback, max) {
7
134
  return typeof value === "number" && Number.isInteger(value) && value >= 1 ? Math.min(value, max) : fallback;
8
135
  }
@@ -17,17 +144,152 @@ function columnWidths(table) {
17
144
  });
18
145
  return widths;
19
146
  }
147
+ function tableAttributes(style) {
148
+ const attrs = {};
149
+ if (style.width) attrs["data-width"] = style.width;
150
+ if (style.align) attrs["data-align"] = style.align;
151
+ if (style.border) attrs["data-border"] = style.border;
152
+ if (style.striped) attrs["data-striped"] = "true";
153
+ return attrs;
154
+ }
155
+ function parseTable(dom) {
156
+ const declaration = BORDER_COLOR_DECLARATION.exec(dom.getAttribute("style") ?? "");
157
+ return {
158
+ width: dom.getAttribute("data-width") === "full" ? "full" : null,
159
+ align: dom.getAttribute("data-align") === "center" ? "center" : null,
160
+ border: tableBorder(dom.getAttribute("data-border")),
161
+ striped: dom.getAttribute("data-striped") === "true",
162
+ borderColor: normalizeColor(declaration?.[1])
163
+ };
164
+ }
20
165
  function renderTable(node, cellMinWidth) {
166
+ const style = tableStyleOf(node);
167
+ const attrs = tableAttributes(style);
21
168
  const widths = columnWidths(node);
22
- if (widths.every((width) => width === null)) return ["table", ["tbody", 0]];
23
- const total = widths.reduce((sum, width) => sum + (width ?? cellMinWidth), 0);
169
+ const sized = !widths.every((width) => width === null);
170
+ const declarations = [];
171
+ if (sized) {
172
+ const total = widths.reduce((sum, width) => sum + (width ?? cellMinWidth), 0);
173
+ const property = widths.includes(null) || style.width === "full" ? "min-width" : "width";
174
+ declarations.push(`${property}: ${total}px`);
175
+ }
176
+ if (style.borderColor) declarations.push(`${BORDER_COLOR}: ${style.borderColor}`);
177
+ if (declarations.length > 0) attrs.style = declarations.join("; ");
178
+ if (!sized) return [
179
+ "table",
180
+ attrs,
181
+ ["tbody", 0]
182
+ ];
24
183
  return [
25
184
  "table",
26
- { style: `${widths.includes(null) ? "min-width" : "width"}: ${total}px` },
185
+ attrs,
27
186
  ["colgroup", ...widths.map((width) => ["col", width ? { style: `width: ${width}px` } : {}])],
28
187
  ["tbody", 0]
29
188
  ];
30
189
  }
190
+ function syncTable(table, node) {
191
+ const style = tableStyleOf(node);
192
+ const attrs = tableAttributes(style);
193
+ for (const name of [
194
+ "data-width",
195
+ "data-align",
196
+ "data-border",
197
+ "data-striped"
198
+ ]) {
199
+ const value = attrs[name];
200
+ if (value === void 0) table.removeAttribute(name);
201
+ else if (table.getAttribute(name) !== value) table.setAttribute(name, value);
202
+ }
203
+ if (style.borderColor) table.style.setProperty(BORDER_COLOR, style.borderColor);
204
+ else table.style.removeProperty(BORDER_COLOR);
205
+ if (style.width === "full" && table.style.width) {
206
+ table.style.minWidth = table.style.width;
207
+ table.style.width = "";
208
+ }
209
+ }
210
+ const inGripLayer = (node) => node instanceof Element && node.closest(".table-touch-grips") !== null;
211
+ var StyledTableView = class extends TableView {
212
+ constructor(node, cellMinWidth) {
213
+ super(node, cellMinWidth);
214
+ syncTable(this.table, node);
215
+ }
216
+ update(node) {
217
+ if (!super.update(node)) return false;
218
+ syncTable(this.table, this.node);
219
+ return true;
220
+ }
221
+ ignoreMutation(record) {
222
+ if (inGripLayer(record.target)) return true;
223
+ if (record.type === "childList" && record.target === this.dom) {
224
+ const nodes = [...record.addedNodes, ...record.removedNodes];
225
+ if (nodes.length > 0 && nodes.every(inGripLayer)) return true;
226
+ }
227
+ return super.ignoreMutation(record);
228
+ }
229
+ };
230
+ function tablePosition(state) {
231
+ if (!isInTable(state)) return null;
232
+ return selectedRect(state).tableStart - 1;
233
+ }
234
+ function setTableAttr(name, value) {
235
+ return (state, dispatch) => {
236
+ const position = tablePosition(state);
237
+ const table = position === null ? null : state.doc.nodeAt(position);
238
+ if (position === null || !table) return false;
239
+ if (dispatch) dispatch(state.tr.setNodeMarkup(position, void 0, {
240
+ ...table.attrs,
241
+ [name]: value
242
+ }));
243
+ return true;
244
+ };
245
+ }
246
+ function selectCells(kind) {
247
+ return (state, dispatch) => {
248
+ if (!isInTable(state)) return false;
249
+ if (dispatch) {
250
+ const { selection } = state;
251
+ const $anchor = selection instanceof CellSelection ? selection.$anchorCell : selectionCell(state);
252
+ const $head = selection instanceof CellSelection ? selection.$headCell : $anchor;
253
+ let next;
254
+ if (kind === "row") next = CellSelection.rowSelection($anchor, $head);
255
+ else if (kind === "column") next = CellSelection.colSelection($anchor, $head);
256
+ else {
257
+ const { map, tableStart } = selectedRect(state);
258
+ const first = map.map[0] ?? 0;
259
+ const last = map.map[map.map.length - 1] ?? first;
260
+ next = CellSelection.create(state.doc, tableStart + first, tableStart + last);
261
+ }
262
+ dispatch(state.tr.setSelection(next));
263
+ }
264
+ return true;
265
+ };
266
+ }
267
+ function distributeColumns(cellMinWidth) {
268
+ return (state, dispatch) => {
269
+ if (!isInTable(state)) return false;
270
+ const { map, table, tableStart } = selectedRect(state);
271
+ const widths = columnWidths(table);
272
+ if (widths.every((width) => width === null)) return false;
273
+ if (dispatch) {
274
+ const total = widths.reduce((sum, width) => sum + (width ?? cellMinWidth), 0);
275
+ const base = Math.floor(total / map.width);
276
+ const extra = total - base * map.width;
277
+ const equal = Array.from({ length: map.width }, (_column, index) => index < extra ? base + 1 : base);
278
+ const transaction = state.tr;
279
+ for (const position of new Set(map.map)) {
280
+ const cell = table.nodeAt(position);
281
+ if (!cell) continue;
282
+ const { left, right } = map.findCell(position);
283
+ transaction.setNodeMarkup(tableStart + position, void 0, {
284
+ ...cell.attrs,
285
+ colwidth: equal.slice(left, right)
286
+ });
287
+ }
288
+ dispatch(transaction);
289
+ }
290
+ return true;
291
+ };
292
+ }
31
293
  function createTable(schema, rows, cols, headerRow) {
32
294
  const types = tableNodeTypes(schema);
33
295
  const cell = (header) => {
@@ -74,59 +336,589 @@ const appendRow = (state, dispatch) => {
74
336
  }
75
337
  return true;
76
338
  };
339
+ function columnCells(map, column) {
340
+ const cells = /* @__PURE__ */ new Set();
341
+ for (let row = 0; row < map.height; row++) {
342
+ const position = map.map[row * map.width + column];
343
+ if (position !== void 0) cells.add(position);
344
+ }
345
+ return [...cells];
346
+ }
347
+ function knownColumnWidth(table, map, cells, column) {
348
+ return cells.map((position) => {
349
+ const colwidth = table.nodeAt(position)?.attrs.colwidth;
350
+ return Array.isArray(colwidth) ? colwidth[column - map.colCount(position)] : null;
351
+ }).find((width) => typeof width === "number" && width > 0);
352
+ }
353
+ function writeColumnWidth(transaction, table, tableStart, column, width) {
354
+ const map = TableMap.get(table);
355
+ for (const position of columnCells(map, column)) {
356
+ const cell = table.nodeAt(position);
357
+ if (!cell) continue;
358
+ const colspan = Number(cell.attrs.colspan);
359
+ const colwidth = cell.attrs.colwidth;
360
+ const widths = Array.isArray(colwidth) ? colwidth.map((value) => typeof value === "number" ? value : 0) : Array.from({ length: colspan }, () => 0);
361
+ widths[column - map.colCount(position)] = width;
362
+ transaction.setNodeMarkup(tableStart + position, void 0, {
363
+ ...cell.attrs,
364
+ colwidth: widths
365
+ });
366
+ }
367
+ return transaction;
368
+ }
77
369
  function resizeColumn(delta, cellMinWidth) {
78
370
  return (state, dispatch, view) => {
79
371
  if (!isInTable(state) || !Number.isFinite(delta) || delta === 0) return false;
80
372
  if (!dispatch) return true;
81
373
  const { map, table, tableStart, left } = selectedRect(state);
82
- const cells = /* @__PURE__ */ new Set();
83
- for (let row = 0; row < map.height; row++) {
84
- const position = map.map[row * map.width + left];
85
- if (position !== void 0) cells.add(position);
86
- }
87
- const known = [...cells].map((position) => {
88
- const colwidth = table.nodeAt(position)?.attrs.colwidth;
89
- return Array.isArray(colwidth) ? colwidth[left - map.colCount(position)] : null;
90
- }).find((width) => typeof width === "number" && width > 0);
91
- const first = [...cells][0];
374
+ const cells = columnCells(map, left);
375
+ const known = knownColumnWidth(table, map, cells, left);
376
+ const first = cells[0];
92
377
  const dom = first === void 0 ? null : view?.nodeDOM(tableStart + first);
93
378
  const measured = dom instanceof HTMLElement ? dom.offsetWidth : 0;
94
379
  const width = Math.max(cellMinWidth, Math.round((known ?? (measured || FALLBACK_WIDTH)) + delta));
95
- const transaction = state.tr;
96
- for (const position of cells) {
97
- const cell = table.nodeAt(position);
98
- if (!cell) continue;
99
- const colspan = Number(cell.attrs.colspan);
100
- const colwidth = cell.attrs.colwidth;
101
- const widths = Array.isArray(colwidth) ? colwidth.map((value) => typeof value === "number" ? value : 0) : Array.from({ length: colspan }, () => 0);
102
- widths[left - map.colCount(position)] = width;
103
- transaction.setNodeMarkup(tableStart + position, void 0, {
104
- ...cell.attrs,
105
- colwidth: widths
380
+ dispatch(writeColumnWidth(state.tr, table, tableStart, left, width));
381
+ return true;
382
+ };
383
+ }
384
+ function selectedRows(state) {
385
+ if (!isInTable(state)) return [];
386
+ const { table, tableStart, top, bottom } = selectedRect(state);
387
+ const rows = [];
388
+ table.forEach((node, offset, index) => {
389
+ if (index >= top && index < bottom) rows.push({
390
+ node,
391
+ position: tableStart + offset
392
+ });
393
+ });
394
+ return rows;
395
+ }
396
+ function setRowHeight(height) {
397
+ return (state, dispatch) => {
398
+ const changed = selectedRows(state).filter(({ node }) => node.attrs.height !== height);
399
+ if (changed.length === 0) return false;
400
+ if (dispatch) {
401
+ const transaction = state.tr;
402
+ for (const { node, position } of changed) transaction.setNodeMarkup(position, void 0, {
403
+ ...node.attrs,
404
+ height
106
405
  });
406
+ dispatch(transaction);
107
407
  }
108
- dispatch(transaction);
109
408
  return true;
110
409
  };
111
410
  }
411
+ function resizeRow(delta) {
412
+ return (state, dispatch, view) => {
413
+ const rows = selectedRows(state);
414
+ const first = rows[0];
415
+ if (!first || !Number.isFinite(delta) || delta === 0) return false;
416
+ if (!dispatch) return true;
417
+ const known = rows.map(({ node }) => rowHeightOf(node.attrs.height)).find((height) => height !== null);
418
+ const dom = view?.nodeDOM(first.position);
419
+ const measured = dom instanceof HTMLElement ? dom.offsetHeight : 0;
420
+ return setRowHeight(rowHeightOf(Math.max(MIN_ROW_HEIGHT, Math.max(known ?? 0, measured || FALLBACK_HEIGHT) + delta)))(state, dispatch);
421
+ };
422
+ }
423
+ function rowHeight(state) {
424
+ const heights = selectedRows(state).map(({ node }) => rowHeightOf(node.attrs.height));
425
+ const first = heights[0] ?? null;
426
+ return heights.every((height) => height === first) ? first : null;
427
+ }
428
+ const rowResizingKey = new PluginKey("tableRowResizing");
429
+ const IDLE = {
430
+ row: -1,
431
+ drag: null
432
+ };
433
+ function rowAt(state, position) {
434
+ if (position < 0) return null;
435
+ const node = state.doc.nodeAt(position);
436
+ return node?.type.spec.tableRole === "row" ? node : null;
437
+ }
438
+ function rowAtPointer(view, event) {
439
+ const target = event.target instanceof Element ? event.target.closest("td, th") : null;
440
+ if (!(target instanceof HTMLElement) || !view.dom.contains(target)) return -1;
441
+ const box = target.getBoundingClientRect();
442
+ if (event.clientX - box.left <= COLUMN_HANDLE || box.right - event.clientX <= COLUMN_HANDLE) return -1;
443
+ const below = box.bottom - event.clientY <= ROW_HANDLE;
444
+ if (!below && event.clientY - box.top > ROW_HANDLE) return -1;
445
+ const $inside = view.state.doc.resolve(view.posAtDOM(target, 0));
446
+ let depth = $inside.depth;
447
+ while (depth > 0 && !String($inside.node(depth).type.spec.tableRole).endsWith("cell")) depth--;
448
+ if (depth < 2) return -1;
449
+ const table = $inside.node(depth - 2);
450
+ const tableStart = $inside.start(depth - 2);
451
+ const rect = TableMap.get(table).findCell($inside.before(depth) - tableStart);
452
+ const index = below ? rect.bottom - 1 : rect.top - 1;
453
+ if (index < 0) return -1;
454
+ let position = tableStart;
455
+ for (let row = 0; row < index; row++) position += table.child(row).nodeSize;
456
+ return position;
457
+ }
458
+ function rowDecorations(state) {
459
+ const resize = rowResizingKey.getState(state) ?? IDLE;
460
+ const row = rowAt(state, resize.row);
461
+ if (!row) return DecorationSet.empty;
462
+ const $row = state.doc.resolve(resize.row);
463
+ const table = $row.parent;
464
+ const tableStart = $row.start();
465
+ const index = $row.index();
466
+ const map = TableMap.get(table);
467
+ const edge = index === map.height - 1 ? " row-resize-edge" : "";
468
+ const decorations = [];
469
+ for (const position of new Set(map.map.slice(index * map.width, (index + 1) * map.width))) {
470
+ const cell = table.nodeAt(position);
471
+ if (!cell || map.findCell(position).bottom !== index + 1) continue;
472
+ const from = tableStart + position;
473
+ decorations.push(Decoration.node(from, from + cell.nodeSize, { class: `row-resize-handle${edge}` }));
474
+ }
475
+ if (resize.drag?.moved) decorations.push(Decoration.node(resize.row, resize.row + row.nodeSize, {
476
+ class: "row-resizing",
477
+ style: `--vive-row-height: ${resize.drag.height}px`
478
+ }));
479
+ return DecorationSet.create(state.doc, decorations);
480
+ }
481
+ function rowResizing() {
482
+ let stop = null;
483
+ const current = (view) => rowResizingKey.getState(view.state) ?? IDLE;
484
+ const update = (view, next) => {
485
+ view.dispatch(view.state.tr.setMeta(rowResizingKey, {
486
+ ...current(view),
487
+ ...next
488
+ }));
489
+ };
490
+ const startDrag = (view, event, row) => {
491
+ const dom = view.nodeDOM(row);
492
+ if (!(dom instanceof HTMLElement)) return false;
493
+ const startHeight = dom.getBoundingClientRect().height;
494
+ update(view, { drag: {
495
+ startY: event.clientY,
496
+ startHeight,
497
+ height: Math.round(startHeight),
498
+ moved: false
499
+ } });
500
+ const owner = dom.ownerDocument.defaultView ?? window;
501
+ const finish = () => {
502
+ stop?.();
503
+ const { row: position, drag } = current(view);
504
+ const transaction = view.state.tr.setMeta(rowResizingKey, {
505
+ row: position,
506
+ drag: null
507
+ });
508
+ const node = rowAt(view.state, position);
509
+ if (drag?.moved && node) transaction.setNodeMarkup(position, void 0, {
510
+ ...node.attrs,
511
+ height: rowHeightOf(drag.height)
512
+ });
513
+ view.dispatch(transaction);
514
+ };
515
+ const move = (moveEvent) => {
516
+ if (moveEvent.buttons === 0) {
517
+ finish();
518
+ return;
519
+ }
520
+ const drag = current(view).drag;
521
+ if (!drag) return;
522
+ const height = rowHeightOf(drag.startHeight + moveEvent.clientY - drag.startY);
523
+ if (height === null || height === drag.height && drag.moved) return;
524
+ update(view, { drag: {
525
+ ...drag,
526
+ height,
527
+ moved: true
528
+ } });
529
+ };
530
+ owner.addEventListener("mousemove", move);
531
+ owner.addEventListener("mouseup", finish);
532
+ stop = () => {
533
+ owner.removeEventListener("mousemove", move);
534
+ owner.removeEventListener("mouseup", finish);
535
+ stop = null;
536
+ };
537
+ event.preventDefault();
538
+ return true;
539
+ };
540
+ return new Plugin({
541
+ key: rowResizingKey,
542
+ state: {
543
+ init: () => IDLE,
544
+ apply: (transaction, previous) => {
545
+ const meta = transaction.getMeta(rowResizingKey);
546
+ if (meta) return meta;
547
+ if (previous.row < 0 || !transaction.docChanged) return previous;
548
+ const mapped = transaction.mapping.mapResult(previous.row, 1);
549
+ return mapped.deleted ? IDLE : {
550
+ ...previous,
551
+ row: mapped.pos
552
+ };
553
+ }
554
+ },
555
+ view: () => ({ destroy: () => stop?.() }),
556
+ props: {
557
+ attributes: (state) => (rowResizingKey.getState(state)?.row ?? -1) >= 0 ? { class: "row-resize-cursor" } : {},
558
+ decorations: rowDecorations,
559
+ handleDOMEvents: {
560
+ mousemove: (view, event) => {
561
+ const resize = current(view);
562
+ if (resize.drag) return false;
563
+ const column = columnResizingPluginKey.getState(view.state);
564
+ const row = !view.editable || column && (column.activeHandle > -1 || column.dragging) ? -1 : rowAtPointer(view, event);
565
+ if (row !== resize.row) update(view, { row });
566
+ return false;
567
+ },
568
+ mouseleave: (view) => {
569
+ const resize = current(view);
570
+ if (resize.row >= 0 && !resize.drag) update(view, { row: -1 });
571
+ return false;
572
+ },
573
+ mousedown: (view, event) => {
574
+ const { row, drag } = current(view);
575
+ if (row < 0 || drag || !view.editable || event.button !== 0) return false;
576
+ return startDrag(view, event, row);
577
+ },
578
+ dblclick: (view, event) => {
579
+ const { row } = current(view);
580
+ const node = rowAt(view.state, row);
581
+ if (!node || !view.editable) return false;
582
+ event.preventDefault();
583
+ if (node.attrs.height !== null) view.dispatch(view.state.tr.setNodeMarkup(row, void 0, {
584
+ ...node.attrs,
585
+ height: null
586
+ }));
587
+ return true;
588
+ }
589
+ }
590
+ }
591
+ });
592
+ }
593
+ const GRIP_LAYER = "table-touch-grips";
594
+ const GRIP_SIZE = 44;
595
+ const GRIP_SLOP = 4;
596
+ const SCROLL_SETTLE = 160;
597
+ function gripTarget(state) {
598
+ if (!isInTable(state)) return null;
599
+ const { map, tableStart, top, left, bottom, right } = selectedRect(state);
600
+ const first = map.map[top * map.width + left];
601
+ const last = map.map[(bottom - 1) * map.width + right - 1];
602
+ if (first === void 0 || last === void 0) return null;
603
+ return {
604
+ table: tableStart - 1,
605
+ column: right - 1,
606
+ row: bottom - 1,
607
+ first: tableStart + first,
608
+ last: tableStart + last
609
+ };
610
+ }
611
+ function rowPosition(state, table, index) {
612
+ const node = state.doc.nodeAt(table);
613
+ let position = table + 1;
614
+ for (let row = 0; node && row < index; row++) position += node.child(row).nodeSize;
615
+ return position;
616
+ }
617
+ function clamp(value, min, max) {
618
+ return Math.round(Math.max(min, Math.min(value, max)));
619
+ }
620
+ function placeGrip(grip, x, y, width, height) {
621
+ const across = grip.dataset.axis === "column" ? 3 : 10;
622
+ const along = 13 - across;
623
+ const pillX = clamp(x, across, width - across);
624
+ const pillY = clamp(y, along, height - along);
625
+ const left = clamp(pillX - GRIP_SIZE / 2, 0, width - GRIP_SIZE);
626
+ const top = clamp(pillY - GRIP_SIZE / 2, 0, height - GRIP_SIZE);
627
+ grip.style.cssText = `left: ${left}px; top: ${top}px; --vive-grip-x: ${pillX - left}px; --vive-grip-y: ${pillY - top}px`;
628
+ }
629
+ function capture(element, pointer) {
630
+ try {
631
+ element.setPointerCapture(pointer);
632
+ return true;
633
+ } catch {
634
+ return false;
635
+ }
636
+ }
637
+ function touchResizing(cellMinWidth) {
638
+ return new Plugin({ view: (view) => {
639
+ const document = view.dom.ownerDocument;
640
+ const owner = document.defaultView ?? window;
641
+ const layer = document.createElement("div");
642
+ layer.className = GRIP_LAYER;
643
+ layer.contentEditable = "false";
644
+ layer.setAttribute("aria-hidden", "true");
645
+ layer.hidden = true;
646
+ let touch = false;
647
+ let paused = false;
648
+ let scrolling = false;
649
+ let settle;
650
+ let drag = null;
651
+ const listeners = [];
652
+ const listen = (target, type, handler, options) => {
653
+ target.addEventListener(type, handler, options);
654
+ listeners.push(() => target.removeEventListener(type, handler, options));
655
+ };
656
+ const elementAt = (position) => {
657
+ const dom = view.nodeDOM(position);
658
+ return dom instanceof HTMLElement ? dom : null;
659
+ };
660
+ const tableAt = (position) => elementAt(position)?.querySelector(":scope > table") ?? null;
661
+ const render = () => {
662
+ const target = touch && !paused && !scrolling && view.editable ? gripTarget(view.state) : null;
663
+ const wrapper = target && elementAt(target.table);
664
+ const table = target && tableAt(target.table);
665
+ const first = target && elementAt(target.first);
666
+ const last = target && elementAt(target.last);
667
+ if (!wrapper || !table || !first || !last) {
668
+ layer.hidden = true;
669
+ return;
670
+ }
671
+ if (layer.parentNode !== wrapper) wrapper.append(layer);
672
+ const box = wrapper.getBoundingClientRect();
673
+ const x = box.left + wrapper.clientLeft - wrapper.scrollLeft;
674
+ const y = box.top + wrapper.clientTop - wrapper.scrollTop;
675
+ const from = first.getBoundingClientRect();
676
+ const to = last.getBoundingClientRect();
677
+ const width = Math.max(wrapper.clientWidth, table.offsetLeft + table.offsetWidth);
678
+ const height = table.offsetTop + table.offsetHeight;
679
+ placeGrip(columnGrip, to.right - x, (from.top + to.bottom) / 2 - y, width, height);
680
+ placeGrip(rowGrip, (from.left + to.right) / 2 - x, to.bottom - y, width, height);
681
+ layer.hidden = false;
682
+ };
683
+ const preview = (current, value) => {
684
+ const { table, column, row } = current.target;
685
+ if (current.axis === "row") {
686
+ const resize = {
687
+ row: rowPosition(view.state, table, row),
688
+ drag: {
689
+ startY: current.origin,
690
+ startHeight: current.start,
691
+ height: value ?? 0,
692
+ moved: true
693
+ }
694
+ };
695
+ view.dispatch(view.state.tr.setMeta(rowResizingKey, value === null ? IDLE : resize));
696
+ return;
697
+ }
698
+ const node = view.state.doc.nodeAt(table);
699
+ const dom = tableAt(table);
700
+ const colgroup = dom?.querySelector(":scope > colgroup");
701
+ if (node && dom && colgroup) updateColumnsOnResize(node, colgroup, dom, cellMinWidth, value === null ? void 0 : column, value ?? void 0);
702
+ render();
703
+ };
704
+ const commit = (finished) => {
705
+ const { state } = view;
706
+ const { table, column, row } = finished.target;
707
+ const node = state.doc.nodeAt(table);
708
+ if (finished.axis === "column") {
709
+ if (node?.type.spec.tableRole === "table") view.dispatch(writeColumnWidth(state.tr, node, table + 1, column, finished.value));
710
+ return;
711
+ }
712
+ const position = rowPosition(state, table, row);
713
+ const current = rowAt(state, position);
714
+ const height = rowHeightOf(finished.value);
715
+ const transaction = state.tr.setMeta(rowResizingKey, IDLE);
716
+ if (current && current.attrs.height !== height) transaction.setNodeMarkup(position, void 0, {
717
+ ...current.attrs,
718
+ height
719
+ });
720
+ view.dispatch(transaction);
721
+ };
722
+ const start = (axis, event) => {
723
+ const target = gripTarget(view.state);
724
+ const node = target && view.state.doc.nodeAt(target.table);
725
+ if (event.pointerType === "mouse" || !target || !node || drag || !view.editable) return;
726
+ event.preventDefault();
727
+ event.stopPropagation();
728
+ if (event.currentTarget instanceof Element) capture(event.currentTarget, event.pointerId);
729
+ let base;
730
+ if (axis === "column") {
731
+ const map = TableMap.get(node);
732
+ const col = tableAt(target.table)?.querySelector(":scope > colgroup")?.children[target.column];
733
+ base = knownColumnWidth(node, map, columnCells(map, target.column), target.column) ?? (Math.round(col?.getBoundingClientRect().width ?? 0) || FALLBACK_WIDTH);
734
+ } else {
735
+ const dom = elementAt(rowPosition(view.state, target.table, target.row));
736
+ base = Math.round(dom?.getBoundingClientRect().height ?? 0) || FALLBACK_HEIGHT;
737
+ }
738
+ const origin = axis === "column" ? event.clientX : event.clientY;
739
+ drag = {
740
+ axis,
741
+ pointer: event.pointerId,
742
+ origin,
743
+ start: base,
744
+ value: base,
745
+ moved: false,
746
+ target
747
+ };
748
+ layer.dataset.dragging = axis;
749
+ };
750
+ const move = (event) => {
751
+ if (!drag || event.pointerId !== drag.pointer) return;
752
+ event.preventDefault();
753
+ const delta = (drag.axis === "column" ? event.clientX : event.clientY) - drag.origin;
754
+ if (!drag.moved && Math.abs(delta) < GRIP_SLOP) return;
755
+ drag.moved = true;
756
+ drag.value = drag.axis === "column" ? Math.max(cellMinWidth, Math.round(drag.start + delta)) : rowHeightOf(drag.start + delta) ?? MIN_ROW_HEIGHT;
757
+ preview(drag, drag.value);
758
+ };
759
+ const tap = (event) => {
760
+ layer.hidden = true;
761
+ const found = view.posAtCoords({
762
+ left: event.clientX,
763
+ top: event.clientY
764
+ });
765
+ if (found) {
766
+ const $position = view.state.doc.resolve(found.pos);
767
+ view.dispatch(view.state.tr.setSelection(TextSelection.near($position)));
768
+ }
769
+ view.focus();
770
+ render();
771
+ };
772
+ const end = (event, cancelled) => {
773
+ const finished = drag;
774
+ if (!finished || event.pointerId !== finished.pointer) return;
775
+ drag = null;
776
+ delete layer.dataset.dragging;
777
+ if (finished.moved && cancelled) preview(finished, null);
778
+ else if (finished.moved) commit(finished);
779
+ else if (!cancelled) tap(event);
780
+ render();
781
+ };
782
+ const grip = (axis) => {
783
+ const element = document.createElement("div");
784
+ element.className = "table-touch-grip";
785
+ element.dataset.axis = axis;
786
+ listen(element, "pointerdown", (event) => start(axis, event));
787
+ listen(element, "pointermove", (event) => move(event));
788
+ listen(element, "pointerup", (event) => end(event, false));
789
+ listen(element, "pointercancel", (event) => end(event, true));
790
+ listen(element, "touchstart", (event) => {
791
+ event.preventDefault();
792
+ event.stopPropagation();
793
+ }, { passive: false });
794
+ layer.append(element);
795
+ return element;
796
+ };
797
+ const columnGrip = grip("column");
798
+ const rowGrip = grip("row");
799
+ const pointer = (type) => {
800
+ const next = type === "touch" || type === "pen";
801
+ if (next === touch && !paused) return;
802
+ touch = next;
803
+ paused = false;
804
+ render();
805
+ };
806
+ const pause = () => {
807
+ if (drag || paused) return;
808
+ paused = true;
809
+ render();
810
+ };
811
+ listen(view.dom, "pointerdown", (event) => pointer(event.pointerType));
812
+ listen(view.dom, "touchstart", () => pointer("touch"), { passive: true });
813
+ listen(view.dom, "keydown", pause);
814
+ listen(view.dom, "beforeinput", pause);
815
+ listen(view.dom, "blur", pause);
816
+ listen(owner, "resize", render);
817
+ listen(owner, "scroll", () => {
818
+ if (!touch || drag) return;
819
+ clearTimeout(settle);
820
+ settle = setTimeout(() => {
821
+ scrolling = false;
822
+ render();
823
+ }, SCROLL_SETTLE);
824
+ if (scrolling) return;
825
+ scrolling = true;
826
+ render();
827
+ }, {
828
+ capture: true,
829
+ passive: true
830
+ });
831
+ return {
832
+ update: () => render(),
833
+ destroy: () => {
834
+ clearTimeout(settle);
835
+ for (const remove of listeners) remove();
836
+ layer.remove();
837
+ }
838
+ };
839
+ } });
840
+ }
112
841
  function tableSpecs(cellMinWidth) {
113
842
  const specs = tableNodes({
114
843
  tableGroup: "block",
115
844
  cellContent: "block+",
116
- cellAttributes: {}
845
+ cellAttributes: CELL_ATTRIBUTES
117
846
  });
118
847
  return {
119
848
  table: {
120
849
  ...specs.table,
121
850
  content: "tableRow+",
851
+ attrs: {
852
+ width: {
853
+ default: null,
854
+ validate: valid((value) => value === "full", "width")
855
+ },
856
+ align: {
857
+ default: null,
858
+ validate: valid((value) => value === "center", "alignment")
859
+ },
860
+ border: {
861
+ default: null,
862
+ validate: valid((value) => tableBorder(value) !== null, "border")
863
+ },
864
+ striped: {
865
+ default: false,
866
+ validate: attributeValidator((value) => typeof value === "boolean", "table stripes")
867
+ },
868
+ borderColor: cleanAttribute(normalizeColor, "table border colour", null)
869
+ },
870
+ parseDOM: [{
871
+ tag: "table",
872
+ getAttrs: (dom) => parseTable(dom)
873
+ }],
122
874
  toDOM: (node) => renderTable(node, cellMinWidth)
123
875
  },
124
876
  tableRow: {
125
877
  ...specs.table_row,
126
- content: "(tableCell | tableHeader)*"
878
+ content: "(tableCell | tableHeader)*",
879
+ attrs: { height: cleanAttribute(rowHeightOf, "table row height", null) },
880
+ parseDOM: [{
881
+ tag: "tr",
882
+ getAttrs: (dom) => ({ height: parseRowHeight(dom) })
883
+ }],
884
+ toDOM: renderRow
885
+ },
886
+ tableCell: cellSpec(specs.table_cell),
887
+ tableHeader: cellSpec(specs.table_header)
888
+ };
889
+ }
890
+ function parsedCell(attrs) {
891
+ const colspan = spanOf(attrs.colspan) ?? 1;
892
+ const colwidth = columnWidthsOf(attrs.colwidth);
893
+ return {
894
+ ...attrs,
895
+ colspan,
896
+ rowspan: spanOf(attrs.rowspan) ?? 1,
897
+ colwidth: colwidth?.length === colspan ? colwidth : null
898
+ };
899
+ }
900
+ function cellSpec(spec) {
901
+ const extra = Object.fromEntries(Object.entries(CELL_ATTRIBUTES).map(([name, { default: initial, validate, clean }]) => [name, {
902
+ default: initial,
903
+ validate,
904
+ clean
905
+ }]));
906
+ return {
907
+ ...spec,
908
+ attrs: {
909
+ ...spec.attrs,
910
+ ...extra,
911
+ colspan: cleanAttribute(spanOf, "table cell span", 1),
912
+ rowspan: cleanAttribute(spanOf, "table cell span", 1),
913
+ colwidth: cleanAttribute(columnWidthsOf, "table column widths", null)
127
914
  },
128
- tableCell: specs.table_cell,
129
- tableHeader: specs.table_header
915
+ ...spec.parseDOM ? { parseDOM: spec.parseDOM.map((rule) => ({
916
+ ...rule,
917
+ getAttrs: (dom) => {
918
+ const attrs = rule.getAttrs ? rule.getAttrs(dom) : {};
919
+ return attrs ? parsedCell(attrs) : attrs;
920
+ }
921
+ })) } : {}
130
922
  };
131
923
  }
132
924
  const Table = defineExtension({
@@ -137,9 +929,10 @@ const Table = defineExtension({
137
929
  cellMinWidth: 48,
138
930
  maxSize: 20
139
931
  },
932
+ schemaOptions: (options) => ({ cellMinWidth: options.cellMinWidth }),
140
933
  nodes: (options) => tableSpecs(options.cellMinWidth),
141
934
  commands: ({ schema, options }) => ({
142
- insertTable: (insert) => insertTable(schema, insert ?? {}, options.maxSize),
935
+ insertTable: (insert) => limitDepth(insertTable(schema, insert ?? {}, options.maxSize)),
143
936
  deleteTable: () => deleteTable,
144
937
  addRowBefore: () => addRowBefore,
145
938
  addRowAfter: () => addRowAfter,
@@ -151,21 +944,65 @@ const Table = defineExtension({
151
944
  splitCell: () => splitCell,
152
945
  toggleHeaderRow: () => toggleHeaderRow,
153
946
  toggleHeaderColumn: () => toggleHeaderColumn,
154
- resizeColumn: (delta) => resizeColumn(delta, options.cellMinWidth)
947
+ resizeColumn: (delta) => resizeColumn(delta, options.cellMinWidth),
948
+ setRowHeight: (height) => height === null || rowHeightOf(height) !== null ? setRowHeight(rowHeightOf(height)) : () => false,
949
+ resizeRow: (delta) => resizeRow(delta),
950
+ setCellBackground: (color) => {
951
+ const value = cellBackground(color);
952
+ return color !== null && value === null ? () => false : setCellStyle("background", value);
953
+ },
954
+ setCellVerticalAlign: (align) => {
955
+ const value = cellVertical(align);
956
+ return align !== null && value === null ? () => false : setCellStyle("verticalAlign", value);
957
+ },
958
+ setCellTextAlign: (align) => {
959
+ const value = cellTextAlign(align);
960
+ return align !== null && value === null ? () => false : setCellStyle("textAlign", value);
961
+ },
962
+ setTableWidth: (width) => width === null || width === "full" ? setTableAttr("width", width) : () => false,
963
+ setTableAlign: (align) => align === null || align === "center" ? setTableAttr("align", align) : () => false,
964
+ setTableBorder: (border) => border === null || tableBorder(border) ? setTableAttr("border", border) : () => false,
965
+ setTableStriped: (striped) => typeof striped === "boolean" ? setTableAttr("striped", striped) : () => false,
966
+ setTableBorderColor: (color) => {
967
+ const value = normalizeColor(color);
968
+ return color !== null && value === null ? () => false : setTableAttr("borderColor", value);
969
+ },
970
+ selectRow: () => selectCells("row"),
971
+ selectColumn: () => selectCells("column"),
972
+ selectTable: () => selectCells("table"),
973
+ distributeColumns: () => distributeColumns(options.cellMinWidth)
974
+ }),
975
+ queries: () => ({
976
+ inTable: (state) => isInTable(state),
977
+ cellStyle: (state) => {
978
+ if (!isInTable(state)) return null;
979
+ const attrs = selectionCell(state).nodeAfter?.attrs;
980
+ return {
981
+ background: cellBackground(attrs?.background),
982
+ verticalAlign: cellVertical(attrs?.verticalAlign),
983
+ textAlign: cellTextAlign(attrs?.textAlign)
984
+ };
985
+ },
986
+ tableStyle: (state) => {
987
+ const position = tablePosition(state);
988
+ const table = position === null ? null : state.doc.nodeAt(position);
989
+ return table ? tableStyleOf(table) : null;
990
+ },
991
+ rowHeight: (state) => rowHeight(state)
155
992
  }),
156
- queries: () => ({ inTable: (state) => isInTable(state) }),
157
993
  keymap: () => ({
158
994
  Tab: (state, dispatch) => goToNextCell(1)(state, dispatch) || appendRow(state, dispatch),
159
995
  "Shift-Tab": goToNextCell(-1)
160
996
  }),
161
997
  plugins: ({ options }) => {
162
998
  let escaped = false;
163
- const view = (node) => new TableView(node, options.cellMinWidth);
999
+ const view = (node) => new StyledTableView(node, options.cellMinWidth);
164
1000
  return [
165
1001
  options.resizable ? columnResizing({
166
1002
  cellMinWidth: options.cellMinWidth,
167
- View: TableView
1003
+ View: StyledTableView
168
1004
  }) : new Plugin({ props: { nodeViews: { table: view } } }),
1005
+ ...options.resizable ? [rowResizing(), touchResizing(options.cellMinWidth)] : [],
169
1006
  tableEditing(),
170
1007
  new Plugin({ props: { handleDOMEvents: { keydown: (editorView, event) => {
171
1008
  if (event.key === "Escape") {