-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathtables-adapter.ts
More file actions
3173 lines (2719 loc) Β· 107 KB
/
tables-adapter.ts
File metadata and controls
3173 lines (2719 loc) Β· 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Editor } from '../core/Editor.js';
import { v4 as uuidv4 } from 'uuid';
import type {
BlockNodeAddress,
CreateTableInput,
CreateTableResult,
CreateTableSuccessResult,
MutationOptions,
TableLocator,
TableMutationResult,
TablesMoveInput,
TablesSetLayoutInput,
TablesSetAltTextInput,
TablesConvertFromTextInput,
TablesSplitInput,
TablesConvertToTextInput,
TablesInsertRowInput,
TablesDeleteRowInput,
TablesSetRowHeightInput,
TablesSetRowOptionsInput,
TablesInsertColumnInput,
TablesDeleteColumnInput,
TablesSetColumnWidthInput,
TablesDistributeColumnsInput,
TablesInsertCellInput,
TablesDeleteCellInput,
TablesMergeCellsInput,
TablesUnmergeCellsInput,
TablesSplitCellInput,
TablesSetCellPropertiesInput,
TablesSortInput,
TablesSetStyleInput,
TablesClearStyleInput,
TablesSetStyleOptionInput,
TablesSetBorderInput,
TablesClearBorderInput,
TablesApplyBorderPresetInput,
TablesSetShadingInput,
TablesClearShadingInput,
TablesSetTablePaddingInput,
TablesSetCellPaddingInput,
TablesSetCellSpacingInput,
TablesClearCellSpacingInput,
TablesGetInput,
TablesGetOutput,
TablesGetCellsInput,
TablesGetCellsOutput,
TableCellInfo,
TablesGetPropertiesInput,
TablesGetPropertiesOutput,
} from '@superdoc/document-api';
import type { Transaction } from 'prosemirror-state';
import { TableMap } from 'prosemirror-tables';
import { clearIndexCache, getBlockIndex } from './helpers/index-cache.js';
import {
resolveTableLocator,
resolveTableCreateLocation,
resolveRowLocator,
resolveColumnLocator,
resolveCellLocator,
resolveMergeRangeLocator,
getTableColumnCount,
toTableFailure,
} from './helpers/table-target-resolver.js';
import { rejectTrackedMode, ensureTrackedCapability, requireEditorCommand } from './helpers/mutation-helpers.js';
import { collectTrackInsertRefsInRange } from './helpers/tracked-change-refs.js';
import { applyDirectMutationMeta, applyTrackedMutationMeta } from './helpers/transaction-meta.js';
import { DocumentApiAdapterError } from './errors.js';
import { toBlockAddress, findBlockById, findBlockByNodeIdOnly } from './helpers/node-address-resolver.js';
import { insertRowAtIndex } from '../extensions/table/tableHelpers/appendRows.js';
import { twipsToPixels } from '../core/super-converter/helpers.js';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const POINTS_TO_PIXELS = 96 / 72;
const POINTS_TO_TWIPS = 20;
const PIXELS_TO_TWIPS = 1440 / 96;
const DEFAULT_TABLE_GRID_WIDTH_TWIPS = 1500;
function generateParaId(): string {
return Array.from({ length: 8 }, () => Math.floor(Math.random() * 16).toString(16))
.join('')
.toUpperCase();
}
function notYetImplemented(operationName: string): never {
throw new DocumentApiAdapterError('CAPABILITY_UNAVAILABLE', `${operationName} is not yet implemented.`, {
reason: 'not_implemented',
});
}
function buildTableSuccess(
tableAddress?: BlockNodeAddress,
trackedChangeRefs?: { kind: 'entity'; entityType: 'trackedChange'; entityId: string }[],
): TableMutationResult {
return {
success: true,
table: tableAddress,
trackedChangeRefs,
};
}
/**
* Produces top-level node attrs that pm-adapter reads for rendering.
* Mirrors the extraction logic in tbl-translator.js (lines 84-140).
*
* INVARIANT: every setter that writes tableProperties on a TABLE NODE
* via setNodeMarkup MUST spread the return value into the attrs object.
* This ensures layout/rendering sees updated values immediately.
*
* SCOPE: table nodes only. Do NOT call this for cell-node mutations
* (those use tableCellProperties, not tableProperties).
*
* See also: tbl-translator.js lines 84-140 (import-time extraction).
* If you change one, you must change the other.
*/
function syncExtractedTableAttrs(tp: Record<string, unknown>): Record<string, unknown> {
const extracted: Record<string, unknown> = {};
// Direct pass-through fields (importer lines 85-88)
extracted.tableStyleId = tp.tableStyleId ?? null;
extracted.justification = tp.justification ?? null;
extracted.tableLayout = tp.tableLayout ?? null;
extracted.borders = tp.borders ?? null;
// tableIndent β importer converts twipsβpixels (line 89)
const indent = tp.tableIndent as { value?: number; type?: string } | undefined;
if (indent?.value != null) {
extracted.tableIndent = {
width: twipsToPixels(indent.value),
type: indent.type,
};
} else {
extracted.tableIndent = null;
}
// tableCellSpacing + borderCollapse derivation (importer lines 90, 109-111)
const spacing = tp.tableCellSpacing as { value?: number; type?: string } | undefined;
if (spacing?.value != null) {
extracted.tableCellSpacing = {
w: String(spacing.value),
type: spacing.type ?? 'dxa',
};
extracted.borderCollapse = 'separate';
} else {
extracted.tableCellSpacing = null;
extracted.borderCollapse = null;
}
// tableWidth β importer handles pct vs dxa vs auto (lines 113-140)
const tw = tp.tableWidth as { value?: number; type?: string } | undefined;
if (tw) {
if (tw.type === 'pct' && typeof tw.value === 'number') {
extracted.tableWidth = { value: tw.value, type: 'pct' };
} else if (tw.type === 'auto') {
extracted.tableWidth = { width: 0, type: 'auto' };
} else if (tw.value != null) {
const widthPx = twipsToPixels(tw.value);
extracted.tableWidth = widthPx != null ? { width: widthPx, type: tw.type } : null;
} else {
extracted.tableWidth = null;
}
} else {
extracted.tableWidth = null;
}
return extracted;
}
function normalizeGridWidth(width: unknown): { col: number } {
if (typeof width === 'number' && Number.isFinite(width)) {
return { col: Math.round(width) };
}
if (width && typeof width === 'object') {
const col = (width as { col?: unknown }).col;
if (typeof col === 'number' && Number.isFinite(col)) {
return { col: Math.round(col) };
}
}
return { col: DEFAULT_TABLE_GRID_WIDTH_TWIPS };
}
function normalizeGridColumns(grid: unknown): { columns: { col: number }[]; format: 'array' | 'object' } | null {
if (Array.isArray(grid)) {
if (grid.length === 0) return null;
return { columns: grid.map((width) => normalizeGridWidth(width)), format: 'array' };
}
if (grid && typeof grid === 'object') {
const rawColWidths = (grid as { colWidths?: unknown }).colWidths;
if (Array.isArray(rawColWidths) && rawColWidths.length > 0) {
return { columns: rawColWidths.map((width) => normalizeGridWidth(width)), format: 'object' };
}
}
return null;
}
function serializeGridColumns(
originalGrid: unknown,
normalized: { columns: { col: number }[]; format: 'array' | 'object' },
): unknown {
if (normalized.format === 'array') {
return normalized.columns;
}
return { ...(originalGrid as Record<string, unknown>), colWidths: normalized.columns };
}
function insertGridColumnWidth(grid: unknown, insertIndex: number): unknown | null {
const normalized = normalizeGridColumns(grid);
if (!normalized) return null;
const colWidths = normalized.columns.slice();
const boundedIndex = Math.max(0, Math.min(insertIndex, colWidths.length));
const template =
colWidths[Math.min(boundedIndex, colWidths.length - 1)] ??
colWidths[colWidths.length - 1] ??
normalizeGridWidth(null);
colWidths.splice(boundedIndex, 0, { ...template });
return serializeGridColumns(grid, { ...normalized, columns: colWidths });
}
function removeGridColumnWidth(grid: unknown, deleteIndex: number): unknown | null {
const normalized = normalizeGridColumns(grid);
if (!normalized || normalized.columns.length <= 1) return null;
const colWidths = normalized.columns.slice();
const boundedIndex = Math.max(0, Math.min(deleteIndex, colWidths.length - 1));
colWidths.splice(boundedIndex, 1);
return serializeGridColumns(grid, { ...normalized, columns: colWidths });
}
type TableBorderEdgeForCells = 'top' | 'bottom' | 'left' | 'right' | 'insideH' | 'insideV';
type CellBorderSide = 'top' | 'bottom' | 'left' | 'right';
function isBoundaryEdge(edge: string): edge is TableBorderEdgeForCells {
return (
edge === 'top' ||
edge === 'bottom' ||
edge === 'left' ||
edge === 'right' ||
edge === 'insideH' ||
edge === 'insideV'
);
}
function cellSidesForEdge(
edge: TableBorderEdgeForCells,
row: number,
col: number,
lastRow: number,
lastCol: number,
): CellBorderSide[] {
switch (edge) {
case 'top':
return row === 0 ? ['top'] : [];
case 'bottom':
return row === lastRow ? ['bottom'] : [];
case 'left':
return col === 0 ? ['left'] : [];
case 'right':
return col === lastCol ? ['right'] : [];
case 'insideH':
return [row < lastRow ? 'bottom' : null, row > 0 ? 'top' : null].filter(
(side): side is CellBorderSide => side != null,
);
case 'insideV':
return [col < lastCol ? 'right' : null, col > 0 ? 'left' : null].filter(
(side): side is CellBorderSide => side != null,
);
default:
return [];
}
}
function tableBorderToCellBorder(border: Record<string, unknown>): Record<string, unknown> {
const val = typeof border.val === 'string' ? border.val : 'single';
const color = typeof border.color === 'string' ? border.color : 'auto';
const sizeEighthPoints = typeof border.size === 'number' ? border.size : 0;
const sizePx = val === 'none' || val === 'nil' ? 0 : (sizeEighthPoints / 8) * POINTS_TO_PIXELS;
return {
val,
color,
size: sizePx,
space: 0,
};
}
function applyTableEdgeToCellBorders(
tr: Transaction,
tablePos: number,
tableNode: import('prosemirror-model').Node,
edge: TableBorderEdgeForCells,
borderSpec: Record<string, unknown>,
): void {
const map = TableMap.get(tableNode);
const tableStart = tablePos + 1;
const seen = new Set<number>();
const mapFrom = tr.mapping.maps.length;
const lastRow = map.height - 1;
const lastCol = map.width - 1;
const cellBorder = tableBorderToCellBorder(borderSpec);
for (let row = 0; row < map.height; row++) {
for (let col = 0; col < map.width; col++) {
const relPos = map.map[row * map.width + col]!;
if (seen.has(relPos)) continue;
seen.add(relPos);
const targetSides = cellSidesForEdge(edge, row, col, lastRow, lastCol);
if (targetSides.length === 0) continue;
const cellNode = tableNode.nodeAt(relPos);
if (!cellNode) continue;
const cellAttrs = cellNode.attrs as Record<string, unknown>;
const borders = { ...((cellAttrs.borders ?? {}) as Record<string, unknown>) };
for (const side of targetSides) {
borders[side] = { ...cellBorder };
}
tr.setNodeMarkup(tr.mapping.slice(mapFrom).map(tableStart + relPos), null, {
...cellAttrs,
borders,
});
}
}
}
function applyTableBorderPresetToCellBorders(
tr: Transaction,
tablePos: number,
tableNode: import('prosemirror-model').Node,
preset: 'none' | 'box' | 'all' | 'grid' | 'custom',
): void {
if (preset === 'custom') return;
const map = TableMap.get(tableNode);
const tableStart = tablePos + 1;
const seen = new Set<number>();
const mapFrom = tr.mapping.maps.length;
const lastRow = map.height - 1;
const lastCol = map.width - 1;
const noneBorder = tableBorderToCellBorder({ val: 'none', color: 'auto', size: 0 });
const singleBorder = tableBorderToCellBorder({ val: 'single', color: '000000', size: 4 });
for (let row = 0; row < map.height; row++) {
for (let col = 0; col < map.width; col++) {
const relPos = map.map[row * map.width + col]!;
if (seen.has(relPos)) continue;
seen.add(relPos);
const cellNode = tableNode.nodeAt(relPos);
if (!cellNode) continue;
const cellAttrs = cellNode.attrs as Record<string, unknown>;
const borders = { ...((cellAttrs.borders ?? {}) as Record<string, unknown>) };
if (preset === 'none') {
borders.top = { ...noneBorder };
borders.bottom = { ...noneBorder };
borders.left = { ...noneBorder };
borders.right = { ...noneBorder };
} else if (preset === 'box') {
borders.top = row === 0 ? { ...singleBorder } : { ...noneBorder };
borders.bottom = row === lastRow ? { ...singleBorder } : { ...noneBorder };
borders.left = col === 0 ? { ...singleBorder } : { ...noneBorder };
borders.right = col === lastCol ? { ...singleBorder } : { ...noneBorder };
} else {
// 'all' | 'grid'
borders.top = { ...singleBorder };
borders.bottom = { ...singleBorder };
borders.left = { ...singleBorder };
borders.right = { ...singleBorder };
}
tr.setNodeMarkup(tr.mapping.slice(mapFrom).map(tableStart + relPos), null, {
...cellAttrs,
borders,
});
}
}
}
/** Flattened row locator shape accepted by {@link resolveRowLocator}. */
type RowLocatorFields = {
target?: BlockNodeAddress;
nodeId?: string;
tableTarget?: BlockNodeAddress;
tableNodeId?: string;
rowIndex?: number;
};
/** Removes `n` columns from a cell's colspan, adjusting colwidth accordingly (mirrors prosemirror-tables internal). */
function removeColSpan(attrs: Record<string, unknown>, pos: number, n = 1): Record<string, unknown> {
const result: Record<string, unknown> = { ...attrs, colspan: ((attrs.colspan as number) || 1) - n };
if (result.colwidth) {
result.colwidth = (result.colwidth as number[]).slice();
(result.colwidth as number[]).splice(pos, n);
if (!(result.colwidth as number[]).some((w) => (w as number) > 0)) result.colwidth = null;
}
return result;
}
/** Adds `n` columns to a cell's colspan, adjusting colwidth accordingly (mirrors prosemirror-tables internal). */
function addColSpan(attrs: Record<string, unknown>, pos: number, n = 1): Record<string, unknown> {
const result: Record<string, unknown> = { ...attrs, colspan: ((attrs.colspan as number) || 1) + n };
if (result.colwidth) {
result.colwidth = (result.colwidth as number[]).slice();
for (let i = 0; i < n; i++) (result.colwidth as number[]).splice(pos, 0, 0);
}
return result;
}
/** Inserts a column at `col` in the table (before that column index). Follows prosemirror-tables addColumn pattern. */
function addColumnToTable(tr: Transaction, tablePos: number, col: number): void {
const tableNode = tr.doc.nodeAt(tablePos);
if (!tableNode || tableNode.type.name !== 'table') return;
const map = TableMap.get(tableNode);
const tableStart = tablePos + 1;
const mapStart = tr.mapping.maps.length;
for (let row = 0; row < map.height; row++) {
const index = row * map.width + col;
const pos = map.map[index];
const cell = tableNode.nodeAt(pos);
if (!cell) continue;
if (col > 0 && map.map[index - 1] === pos) {
// Cell spans from the left β expand colspan
tr.setNodeMarkup(
tr.mapping.slice(mapStart).map(tableStart + pos),
null,
addColSpan(cell.attrs as Record<string, unknown>, col - map.colCount(pos)),
);
row += (((cell.attrs as Record<string, unknown>).rowspan as number) || 1) - 1;
} else {
// Insert a new empty cell
const refType = col > 0 ? (tableNode.nodeAt(map.map[index - 1])?.type ?? cell.type) : cell.type;
const cellPos = map.positionAt(row, col, tableNode);
tr.insert(tr.mapping.slice(mapStart).map(tableStart + cellPos), refType.createAndFill()!);
row += ((cell.attrs?.rowspan as number) || 1) - 1;
}
}
}
/** Removes a column at `col` from the table. Follows prosemirror-tables removeColumn pattern. */
function removeColumnFromTable(tr: Transaction, tablePos: number, col: number): void {
const tableNode = tr.doc.nodeAt(tablePos);
if (!tableNode || tableNode.type.name !== 'table') return;
const map = TableMap.get(tableNode);
const tableStart = tablePos + 1;
const mapStart = tr.mapping.maps.length;
for (let row = 0; row < map.height; ) {
const index = row * map.width + col;
const pos = map.map[index];
const cell = tableNode.nodeAt(pos);
if (!cell) {
row++;
continue;
}
const attrs = cell.attrs as Record<string, unknown>;
const rowspan = (attrs.rowspan as number) || 1;
if ((col > 0 && map.map[index - 1] === pos) || (col < map.width - 1 && map.map[index + 1] === pos)) {
// Cell spans beyond this column β reduce colspan
tr.setNodeMarkup(
tr.mapping.slice(mapStart).map(tableStart + pos),
null,
removeColSpan(attrs, col - map.colCount(pos)),
);
} else {
// Delete the cell entirely
const start = tr.mapping.slice(mapStart).map(tableStart + pos);
tr.delete(start, start + cell.nodeSize);
}
row += rowspan;
}
}
// ---------------------------------------------------------------------------
// Batch 2 β Table lifecycle + layout
// ---------------------------------------------------------------------------
/**
* tables.delete β delete an entire table.
*/
export function tablesDeleteAdapter(
editor: Editor,
input: TableLocator,
options?: MutationOptions,
): TableMutationResult {
const mode = options?.changeMode ?? 'direct';
if (mode === 'tracked') {
ensureTrackedCapability(editor, { operation: 'tables.delete' });
}
const { candidate } = resolveTableLocator(editor, input, 'tables.delete');
if (options?.dryRun) {
return buildTableSuccess(toBlockAddress(candidate));
}
try {
const tr = editor.state.tr;
tr.delete(candidate.pos, candidate.end);
if (mode === 'tracked') applyTrackedMutationMeta(tr);
else applyDirectMutationMeta(tr);
editor.dispatch(tr);
clearIndexCache(editor);
return buildTableSuccess();
} catch {
return toTableFailure('INVALID_TARGET', 'Table deletion could not be applied.');
}
}
/**
* tables.clearContents β clear all text content from a table, keeping structure.
*/
export function tablesClearContentsAdapter(
editor: Editor,
input: TableLocator,
options?: MutationOptions,
): TableMutationResult {
rejectTrackedMode('tables.clearContents', options);
const { candidate, address } = resolveTableLocator(editor, input, 'tables.clearContents');
if (options?.dryRun) {
return buildTableSuccess(address);
}
try {
const tr = editor.state.tr;
const tableNode = candidate.node;
const tableStart = candidate.pos;
const schema = editor.state.schema;
const emptyParagraph = schema.nodes.paragraph?.createAndFill();
if (!emptyParagraph) {
return toTableFailure('INVALID_TARGET', 'Cannot create empty paragraph for cell replacement.');
}
// Walk rows and cells, replacing each cell's content with an empty paragraph.
// Process in reverse order to avoid position shifting.
const replacements: Array<{ from: number; to: number }> = [];
tableNode.forEach((row, rowOffset) => {
row.forEach((cell, cellOffset) => {
const cellStart = tableStart + 1 + rowOffset + 1 + cellOffset + 1; // +1 for each node boundary
const cellEnd = cellStart + cell.content.size;
replacements.push({ from: cellStart, to: cellEnd });
});
});
// Apply replacements in reverse to maintain position integrity.
for (let i = replacements.length - 1; i >= 0; i--) {
const { from, to } = replacements[i]!;
tr.replaceWith(from, to, emptyParagraph);
}
applyDirectMutationMeta(tr);
editor.dispatch(tr);
clearIndexCache(editor);
return buildTableSuccess(address);
} catch {
return toTableFailure('INVALID_TARGET', 'Table content clearing could not be applied.');
}
}
/**
* tables.move β move a table to a new document location.
*/
export function tablesMoveAdapter(
editor: Editor,
input: TablesMoveInput,
options?: MutationOptions,
): TableMutationResult {
rejectTrackedMode('tables.move', options);
const { candidate } = resolveTableLocator(editor, input, 'tables.move');
if (options?.dryRun) {
return buildTableSuccess(toBlockAddress(candidate));
}
try {
const tr = editor.state.tr;
const tableSlice = candidate.node;
const tablePos = candidate.pos;
const tableEnd = candidate.end;
// Resolve destination BEFORE deleting (positions will shift).
const destPos = resolveTableCreateLocation(editor, input.destination, 'tables.move');
// Delete the table from its current position.
tr.delete(tablePos, tableEnd);
// Map the destination position through the deletion mapping.
const mappedDest = tr.mapping.map(destPos);
// Insert the table at the mapped destination.
tr.insert(mappedDest, tableSlice);
applyDirectMutationMeta(tr);
editor.dispatch(tr);
clearIndexCache(editor);
// Resolve the table at its new position to return its address.
// The nodeId is preserved because we moved the same node.
return buildTableSuccess();
} catch {
return toTableFailure('INVALID_TARGET', 'Table move could not be applied.');
}
}
/**
* tables.setLayout β update table layout properties.
*/
export function tablesSetLayoutAdapter(
editor: Editor,
input: TablesSetLayoutInput,
options?: MutationOptions,
): TableMutationResult {
rejectTrackedMode('tables.setLayout', options);
const { candidate, address } = resolveTableLocator(editor, input, 'tables.setLayout');
if (options?.dryRun) {
return buildTableSuccess(address);
}
try {
const tr = editor.state.tr;
const currentAttrs = candidate.node.attrs as Record<string, unknown>;
const currentTableProps = (currentAttrs.tableProperties ?? {}) as Record<string, unknown>;
const updatedTableProps = { ...currentTableProps };
if (input.preferredWidth !== undefined) {
updatedTableProps.tableWidth = { value: input.preferredWidth, type: 'dxa' };
}
if (input.alignment !== undefined) {
updatedTableProps.justification = input.alignment;
}
if (input.leftIndentPt !== undefined) {
updatedTableProps.tableIndent = { value: Math.round(input.leftIndentPt * 20), type: 'dxa' };
}
if (input.autoFitMode !== undefined) {
if (input.autoFitMode === 'fixedWidth') {
updatedTableProps.tableLayout = 'fixed';
} else if (input.autoFitMode === 'fitWindow') {
updatedTableProps.tableLayout = 'autofit';
// fitWindow = autofit + percentage width (always 100%).
// preferredWidth input is intentionally ignored β it's twips, not percent.
updatedTableProps.tableWidth = { value: 5000, type: 'pct' };
} else {
// fitContents
updatedTableProps.tableLayout = 'autofit';
}
}
if (input.tableDirection !== undefined) {
updatedTableProps.rightToLeft = input.tableDirection === 'rtl';
}
tr.setNodeMarkup(candidate.pos, null, {
...currentAttrs,
tableProperties: updatedTableProps,
...syncExtractedTableAttrs(updatedTableProps),
});
applyDirectMutationMeta(tr);
editor.dispatch(tr);
clearIndexCache(editor);
return buildTableSuccess(address);
} catch {
return toTableFailure('INVALID_TARGET', 'Table layout update could not be applied.');
}
}
/**
* tables.setAltText β update table alt text (caption/description).
*/
export function tablesSetAltTextAdapter(
editor: Editor,
input: TablesSetAltTextInput,
options?: MutationOptions,
): TableMutationResult {
rejectTrackedMode('tables.setAltText', options);
const { candidate, address } = resolveTableLocator(editor, input, 'tables.setAltText');
if (options?.dryRun) {
return buildTableSuccess(address);
}
try {
const tr = editor.state.tr;
const currentAttrs = candidate.node.attrs as Record<string, unknown>;
const currentTableProps = (currentAttrs.tableProperties ?? {}) as Record<string, unknown>;
const updatedTableProps = { ...currentTableProps };
if (input.title !== undefined) {
updatedTableProps.caption = input.title;
}
if (input.description !== undefined) {
updatedTableProps.description = input.description;
}
tr.setNodeMarkup(candidate.pos, null, {
...currentAttrs,
tableProperties: updatedTableProps,
...syncExtractedTableAttrs(updatedTableProps),
});
applyDirectMutationMeta(tr);
editor.dispatch(tr);
clearIndexCache(editor);
return buildTableSuccess(address);
} catch {
return toTableFailure('INVALID_TARGET', 'Table alt text update could not be applied.');
}
}
// ---------------------------------------------------------------------------
// Batch 3 β Row operations
// ---------------------------------------------------------------------------
/**
* tables.insertRow β insert one or more rows above/below a reference row.
*/
export function tablesInsertRowAdapter(
editor: Editor,
input: TablesInsertRowInput,
options?: MutationOptions,
): TableMutationResult {
const mode = options?.changeMode ?? 'direct';
if (mode === 'tracked') {
ensureTrackedCapability(editor, { operation: 'tables.insertRow' });
}
const resolved = resolveRowLocator(editor, input, 'tables.insertRow');
const { table, rowIndex } = resolved;
if (options?.dryRun) {
return buildTableSuccess(table.address);
}
try {
const tr = editor.state.tr;
const tablePos = table.candidate.pos;
const count = input.count ?? 1;
const schema = editor.state.schema;
for (let i = 0; i < count; i++) {
// Re-read the table from the (possibly modified) transaction
const currentTableNode = tr.doc.nodeAt(tablePos);
if (!currentTableNode || currentTableNode.type.name !== 'table') break;
const insertIdx = input.position === 'above' ? rowIndex + i : rowIndex + 1 + i;
const sourceIdx = input.position === 'above' ? rowIndex + i : rowIndex;
insertRowAtIndex({
tr,
tablePos,
tableNode: currentTableNode,
sourceRowIndex: Math.min(sourceIdx, currentTableNode.childCount - 1),
insertIndex: Math.min(insertIdx, currentTableNode.childCount),
schema,
});
}
if (mode === 'tracked') applyTrackedMutationMeta(tr);
else applyDirectMutationMeta(tr);
editor.dispatch(tr);
clearIndexCache(editor);
return buildTableSuccess(table.address);
} catch {
return toTableFailure('INVALID_TARGET', 'Row insertion could not be applied.');
}
}
/**
* tables.deleteRow β delete a row from a table.
* Follows the prosemirror-tables removeRow pattern for rowspan handling.
*/
export function tablesDeleteRowAdapter(
editor: Editor,
input: TablesDeleteRowInput,
options?: MutationOptions,
): TableMutationResult {
const mode = options?.changeMode ?? 'direct';
if (mode === 'tracked') {
ensureTrackedCapability(editor, { operation: 'tables.deleteRow' });
}
const resolved = resolveRowLocator(editor, input as RowLocatorFields, 'tables.deleteRow');
const { table, rowIndex, rowNode, rowPos } = resolved;
const tableNode = table.candidate.node;
const tablePos = table.candidate.pos;
const tableStart = tablePos + 1;
if (tableNode.childCount <= 1) {
return toTableFailure('NO_OP', 'Cannot delete the last row of a table.');
}
if (options?.dryRun) {
return buildTableSuccess(table.address);
}
try {
const tr = editor.state.tr;
const map = TableMap.get(tableNode);
const nextRowPos = rowPos + rowNode.nodeSize;
// Step 1: Delete the row (following prosemirror-tables removeRow pattern).
const mapFrom = tr.mapping.maps.length;
tr.delete(rowPos, nextRowPos);
// Step 2: Handle cells with rowspan that intersect the deleted row.
const seen = new Set<number>();
for (let col = 0, index = rowIndex * map.width; col < map.width; col++, index++) {
const pos = map.map[index];
if (seen.has(pos)) continue;
seen.add(pos);
const cell = tableNode.nodeAt(pos);
if (!cell) continue;
const attrs = cell.attrs as Record<string, unknown>;
const rowspan = (attrs.rowspan as number) || 1;
const colspan = (attrs.colspan as number) || 1;
if (rowIndex > 0 && pos === map.map[index - map.width]) {
// Cell starts above the deleted row β decrement its rowspan.
tr.setNodeMarkup(tr.mapping.slice(mapFrom).map(tableStart + pos), null, { ...attrs, rowspan: rowspan - 1 });
col += colspan - 1;
} else if (rowIndex < map.height - 1 && pos === map.map[index + map.width]) {
// Cell starts in the deleted row but spans below β insert copy into the next row.
const copy = cell.type.create({ ...attrs, rowspan: rowspan - 1 }, cell.content);
const newPos = map.positionAt(rowIndex + 1, col, tableNode);
tr.insert(tr.mapping.slice(mapFrom).map(tableStart + newPos), copy);
col += colspan - 1;
}
}
if (mode === 'tracked') applyTrackedMutationMeta(tr);
else applyDirectMutationMeta(tr);
editor.dispatch(tr);
clearIndexCache(editor);
return buildTableSuccess(table.address);
} catch {
return toTableFailure('INVALID_TARGET', 'Row deletion could not be applied.');
}
}
/**
* tables.setRowHeight β set the height and sizing rule of a row.
*/
export function tablesSetRowHeightAdapter(
editor: Editor,
input: TablesSetRowHeightInput,
options?: MutationOptions,
): TableMutationResult {
rejectTrackedMode('tables.setRowHeight', options);
const resolved = resolveRowLocator(editor, input as RowLocatorFields, 'tables.setRowHeight');
const { table, rowPos, rowNode } = resolved;
if (options?.dryRun) {
return buildTableSuccess(table.address);
}
try {
const tr = editor.state.tr;
const currentAttrs = rowNode.attrs as Record<string, unknown>;
const currentRowProps = (currentAttrs.tableRowProperties ?? {}) as Record<string, unknown>;
const heightTwips = Math.round(input.heightPt * POINTS_TO_TWIPS); // points β twips
const heightPx = Math.round(input.heightPt * POINTS_TO_PIXELS); // points β px
const updatedRowProps = {
...currentRowProps,
rowHeight: { value: heightTwips, rule: input.rule },
};
const newAttrs = {
...currentAttrs,
rowHeight: heightPx,
tableRowProperties: updatedRowProps,
};
tr.setNodeMarkup(rowPos, null, newAttrs);
applyDirectMutationMeta(tr);
editor.dispatch(tr);
clearIndexCache(editor);
return buildTableSuccess(table.address);
} catch {
return toTableFailure('INVALID_TARGET', 'Row height update could not be applied.');
}
}
/**
* tables.distributeRows β equalize all row heights in a table.
*/
export function tablesDistributeRowsAdapter(
editor: Editor,
input: TableLocator,
options?: MutationOptions,
): TableMutationResult {
rejectTrackedMode('tables.distributeRows', options);
const { candidate, address } = resolveTableLocator(editor, input, 'tables.distributeRows');
if (options?.dryRun) {
return buildTableSuccess(address);
}
try {
const tr = editor.state.tr;
const tableNode = candidate.node;
const tablePos = candidate.pos;
// Compute total height from rows with explicit heights.
let totalHeight = 0;
let explicitCount = 0;
for (let i = 0; i < tableNode.childCount; i++) {
const height = (tableNode.child(i).attrs as Record<string, unknown>).rowHeight as number | null;
if (height != null && height > 0) {
totalHeight += height;
explicitCount++;
}
}
if (explicitCount === 0) {
// No explicit heights β nothing to distribute.
return buildTableSuccess(address);
}
const avgHeight = Math.round(totalHeight / tableNode.childCount);
let rowPos = tablePos + 1;
for (let i = 0; i < tableNode.childCount; i++) {
const row = tableNode.child(i);
const currentAttrs = row.attrs as Record<string, unknown>;
const currentRowProps = (currentAttrs.tableRowProperties ?? {}) as Record<string, unknown>;
const heightTwips = Math.round(avgHeight * PIXELS_TO_TWIPS); // px β twips
tr.setNodeMarkup(rowPos, null, {
...currentAttrs,
rowHeight: avgHeight,
tableRowProperties: {
...currentRowProps,
rowHeight: {
value: heightTwips,
rule: (currentRowProps.rowHeight as Record<string, unknown>)?.rule ?? 'atLeast',
},
},
});
rowPos += row.nodeSize;
}
applyDirectMutationMeta(tr);
editor.dispatch(tr);
clearIndexCache(editor);
return buildTableSuccess(address);
} catch {
return toTableFailure('INVALID_TARGET', 'Row distribution could not be applied.');
}
}
/**
* tables.setRowOptions β set row-level options (allowBreakAcrossPages, repeatHeader).
*/
export function tablesSetRowOptionsAdapter(
editor: Editor,
input: TablesSetRowOptionsInput,
options?: MutationOptions,
): TableMutationResult {
rejectTrackedMode('tables.setRowOptions', options);
const resolved = resolveRowLocator(editor, input as RowLocatorFields, 'tables.setRowOptions');
const { table, rowPos, rowNode } = resolved;
if (options?.dryRun) {
return buildTableSuccess(table.address);
}
try {
const tr = editor.state.tr;
const currentAttrs = rowNode.attrs as Record<string, unknown>;
const currentRowProps = (currentAttrs.tableRowProperties ?? {}) as Record<string, unknown>;
const rowPropUpdates: Record<string, unknown> = {};
const attrUpdates: Record<string, unknown> = {};