-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathrenderTableCell.ts
More file actions
1202 lines (1115 loc) · 45.6 KB
/
Copy pathrenderTableCell.ts
File metadata and controls
1202 lines (1115 loc) · 45.6 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 {
CellBorders,
DrawingBlock,
ImageDrawing,
DrawingMeasure,
Fragment,
ImageBlock,
ImageHyperlink,
ImageMeasure,
Line,
ParagraphBlock,
ParagraphMeasure,
PartialRowInfo,
SdtMetadata,
TableBlock,
TableFragment,
TableMeasure,
WrapExclusion,
WrapTextMode,
} from '@superdoc/contracts';
import { rescaleColumnWidths, normalizeZIndex, getCellSpacingPx } from '@superdoc/contracts';
import type { ResolvePhysicalFamily } from '@superdoc/font-system';
import type { MinimalWordLayout } from '@superdoc/common/list-marker-utils';
import type { FragmentRenderContext, RenderedLineInfo } from '../renderer.js';
import { applySquareWrapExclusionsToLines } from '../utils/anchor-helpers';
import { createBlockImageContent } from '../images/image-block.js';
import { buildImageHyperlinkAnchor } from '../images/hyperlink.js';
import {
getSdtContainerKeyForBlock,
getSdtSiblingBoundaries,
type SdtAncestorOptions,
type SdtBoundaryOptions,
} from '../sdt/container.js';
import { applyCellBorders } from './border-utils.js';
import { renderTableFragment as renderTableFragmentElement } from './renderTableFragment.js';
import { renderParagraphContent } from '../paragraph/renderParagraphContent.js';
type TableRowMeasure = TableMeasure['rows'][number];
type TableCellMeasure = TableRowMeasure['cells'][number];
/**
* Compute the total segment count for a cell's blocks, matching the layout engine's
* recursive getCellLines() expansion. Paragraph blocks contribute their line count,
* embedded tables contribute the sum of their rows' recursive segment counts,
* and other blocks (images, drawings) contribute 1 segment.
*/
export function getCellSegmentCount(cell: TableCellMeasure): number {
if (cell.blocks && cell.blocks.length > 0) {
let total = 0;
for (const block of cell.blocks) {
if (block.kind === 'paragraph') {
total += (block as ParagraphMeasure).lines?.length || 0;
} else if (block.kind === 'table') {
const tableMeasure = block as TableMeasure;
for (const row of tableMeasure.rows) {
total += getEmbeddedRowSegmentCount(row);
}
} else {
const blockHeight = 'height' in block ? (block as { height: number }).height : 0;
if (blockHeight > 0) total += 1;
}
}
return total;
}
if (cell.paragraph) {
return (cell.paragraph as ParagraphMeasure).lines?.length || 0;
}
return 0;
}
/**
* Compute the segment count for a single embedded table row.
* If any cell in the row contains nested tables, recursively expand using the
* tallest cell's segment count. Otherwise, the row is 1 segment.
* This mirrors the layout engine's getEmbeddedRowLines() logic.
*/
function getEmbeddedRowSegmentCount(row: TableRowMeasure): number {
const hasNestedTable = row.cells.some((cell: TableCellMeasure) => cell.blocks?.some((b) => b.kind === 'table'));
if (!hasNestedTable) return 1;
let maxSegments = 0;
for (const cell of row.cells) {
maxSegments = Math.max(maxSegments, getCellSegmentCount(cell));
}
return maxSegments > 0 ? maxSegments : 1;
}
/**
* Compute the total recursive segment count for an embedded table.
*/
function getEmbeddedTableSegmentCount(tableMeasure: TableMeasure): number {
let total = 0;
for (const row of tableMeasure.rows) {
total += getEmbeddedRowSegmentCount(row);
}
return total;
}
/**
* Compute the visible height for a range of table rows, using partial height
* where a row is only partially rendered (mid-row split).
*/
function computeVisibleHeight(
rows: TableMeasure['rows'],
fromRow: number,
toRow: number,
partialRow?: PartialRowInfo,
): number {
let height = 0;
for (let r = fromRow; r < toRow; r++) {
if (partialRow && partialRow.rowIndex === r) {
height += partialRow.partialHeight;
} else {
height += rows[r]?.height || 0;
}
}
return height;
}
/**
* Compute the visible height of a single cell's content for a given segment range.
* Handles paragraphs, embedded tables, and non-paragraph blocks (images, drawings).
* Falls back to cell.paragraph for legacy single-paragraph cells.
*/
function computeCellVisibleHeight(cell: TableCellMeasure, cellFrom: number, cellTo: number): number {
let cellVisHeight = 0;
if (cell.blocks && cell.blocks.length > 0) {
let segIdx = 0;
for (const blk of cell.blocks) {
if (blk.kind === 'paragraph') {
const lines = (blk as ParagraphMeasure).lines || [];
for (const line of lines) {
if (segIdx >= cellFrom && segIdx < cellTo) {
cellVisHeight += line.lineHeight || 0;
}
segIdx++;
}
} else if (blk.kind === 'table') {
const nestedTable = blk as TableMeasure;
for (const nestedRow of nestedTable.rows) {
const nestedRowSegs = getEmbeddedRowSegmentCount(nestedRow);
// TODO: use actual segment heights from getEmbeddedRowLines() instead of
// even split for more precise height when rows have non-uniform line heights.
for (let s = 0; s < nestedRowSegs; s++) {
if (segIdx >= cellFrom && segIdx < cellTo) {
cellVisHeight += (nestedRow.height || 0) / nestedRowSegs;
}
segIdx++;
}
}
} else {
const blkHeight = 'height' in blk ? (blk as { height: number }).height : 0;
if (blkHeight > 0) {
if (segIdx >= cellFrom && segIdx < cellTo) {
cellVisHeight += blkHeight;
}
segIdx++;
}
}
}
} else if (cell.paragraph) {
// Legacy single-paragraph fallback (matches getCellSegmentCount)
const lines = (cell.paragraph as ParagraphMeasure).lines || [];
for (let i = 0; i < lines.length; i++) {
if (i >= cellFrom && i < cellTo) {
cellVisHeight += lines[i].lineHeight || 0;
}
}
}
return cellVisHeight;
}
/**
* Applies inline CSS styles to an element, filtering out null/undefined/empty values.
*
* Only applies styles where the key exists in the element's style object and
* the value is non-null and non-empty. This prevents accidentally clearing
* existing styles with undefined values.
*
* @param el - The HTML element to apply styles to
* @param styles - Partial CSSStyleDeclaration with styles to apply
*/
const applyInlineStyles = (el: HTMLElement, styles: Partial<CSSStyleDeclaration>): void => {
Object.entries(styles).forEach(([key, value]) => {
if (value != null && value !== '' && key in el.style) {
(el.style as unknown as Record<string, string>)[key] = String(value);
}
});
};
/**
* Parameters for rendering a nested table inside a table cell.
*
* When a table cell contains another table (nested/embedded table), we render it
* using the same table rendering infrastructure but with a synthetic TableFragment
* positioned at (0,0) within the cell content area.
*/
type EmbeddedTableRenderParams = {
/** Document object for creating DOM elements */
doc: Document;
/** The nested table block to render */
table: TableBlock;
/** Measurement data for the nested table */
measure: TableMeasure;
/** Available width for the embedded table (render-scale cell content area) */
availableWidth: number;
/** Rendering context (section, page, column info) */
context: FragmentRenderContext;
/** Function to render a line of paragraph content */
renderLine: (
block: ParagraphBlock,
line: Line,
context: FragmentRenderContext,
lineIndex: number,
isLastLine: boolean,
resolvedListTextStartPx?: number,
) => HTMLElement;
/** Optional callback invoked after a table line's final styles/markers are applied. */
captureLineSnapshot?: (
lineEl: HTMLElement,
context: FragmentRenderContext,
options?: { inTableParagraph?: boolean; wrapperEl?: HTMLElement },
) => void;
/** Optional callback to render drawing content (shapes, etc.) */
renderDrawingContent?: (block: DrawingBlock) => HTMLElement;
/** Function to apply SDT metadata as data attributes */
applySdtDataset: (el: HTMLElement | null, metadata?: SdtMetadata | null) => void;
/** Built-in SDT chrome rendering mode. */
chrome?: 'default' | 'none';
/** Starting row index for partial rendering (inclusive, default 0) */
fromRow?: number;
/** Ending row index for partial rendering (exclusive, default all rows) */
toRow?: number;
/** Partial row info for mid-row splits within the embedded table */
partialRow?: PartialRowInfo;
/** Optional SDT boundary overrides for container styling */
sdtBoundary?: SdtBoundaryOptions;
/** Ancestor SDT key used to suppress duplicate container chrome in nested tables */
ancestorContainerKey?: string | null;
/** Ancestor SDT metadata used to suppress duplicate id-less container chrome in nested tables */
ancestorContainerSdt?: SdtMetadata | null;
/** Ancestor SDT keys used to suppress duplicate container chrome in nested tables */
ancestorContainerKeys?: SdtAncestorOptions['ancestorContainerKeys'];
/** Ancestor SDT metadata chain used to suppress duplicate id-less container chrome in nested tables */
ancestorContainerSdts?: SdtAncestorOptions['ancestorContainerSdts'];
/** Receives notification when this embedded table or its descendants render SDT chrome */
onSdtContainerChrome?: () => void;
};
/**
* Version identifier for embedded table block lookups.
* Used to distinguish nested tables from top-level tables in the block lookup map.
*/
/**
* Renders a nested table that appears inside a table cell.
*
* This function creates a synthetic TableFragment positioned at (0,0) within the cell
* and delegates to the standard table fragment renderer. The embedded table reuses the
* same rendering infrastructure as top-level tables but with its own isolated block lookup.
*
* @param params - Parameters including the table block, measure, and rendering callbacks
* @returns The rendered table element ready to be appended to the cell content
*
* @example
* ```typescript
* const tableEl = renderEmbeddedTable({
* doc,
* table: nestedTableBlock,
* measure: nestedTableMeasure,
* context,
* renderLine,
* applySdtDataset,
* });
* cellContent.appendChild(tableEl);
* ```
*/
const renderEmbeddedTable = (
params: EmbeddedTableRenderParams,
): { element: HTMLElement; hasSdtContainerChrome: boolean } => {
const {
doc,
table,
measure,
availableWidth,
context,
renderLine,
captureLineSnapshot,
renderDrawingContent,
applySdtDataset,
chrome,
fromRow: paramFromRow,
toRow: paramToRow,
partialRow: paramPartialRow,
sdtBoundary,
ancestorContainerKey,
ancestorContainerSdt,
ancestorContainerKeys,
ancestorContainerSdts,
onSdtContainerChrome,
} = params;
const effectiveFromRow = paramFromRow ?? 0;
const effectiveToRow = paramToRow ?? table.rows.length;
const visibleHeight = computeVisibleHeight(measure.rows, effectiveFromRow, effectiveToRow, paramPartialRow);
// Rescale column widths when measurement-scale exceeds render-scale (SD-1962).
// Top-level tables get rescaled by layout-engine's rescaleColumnWidths(), but
// embedded tables bypass that path. We reuse the same function here.
const columnWidths = rescaleColumnWidths(measure.columnWidths, measure.totalWidth, availableWidth);
const fragmentWidth = columnWidths ? availableWidth : measure.totalWidth;
const fragment: TableFragment = {
kind: 'table',
blockId: table.id,
fromRow: effectiveFromRow,
toRow: effectiveToRow,
x: 0,
y: 0,
width: fragmentWidth,
height: visibleHeight,
columnWidths,
partialRow: paramPartialRow,
};
const effectiveColumnWidths = columnWidths ?? measure.columnWidths;
const embeddedCellSpacingPx = measure.cellSpacingPx ?? getCellSpacingPx(table.attrs?.cellSpacing);
const applyFragmentFrame = (el: HTMLElement, frag: Fragment): void => {
el.style.left = `${frag.x}px`;
el.style.top = `${frag.y}px`;
el.style.width = `${frag.width}px`;
el.dataset.blockId = frag.blockId;
};
let hasSdtContainerChrome = false;
const tableEl = renderTableFragmentElement({
doc,
fragment,
context,
block: table,
measure,
cellSpacingPx: embeddedCellSpacingPx,
effectiveColumnWidths,
renderLine,
captureLineSnapshot,
renderDrawingContent,
applyFragmentFrame,
applySdtDataset,
chrome,
applyStyles: applyInlineStyles,
sdtBoundary,
ancestorContainerKey,
ancestorContainerSdt,
ancestorContainerKeys,
ancestorContainerSdts,
onSdtContainerChrome: () => {
hasSdtContainerChrome = true;
onSdtContainerChrome?.();
},
});
return { element: tableEl, hasSdtContainerChrome };
};
/**
* Render an embedded table block within a cell, handling segment-based pagination.
*
* Maps the cell's global segment range into the embedded table's local row range,
* computes partial row info when a page break falls mid-row, and delegates to
* renderEmbeddedTable for actual DOM creation.
*/
function renderPartialEmbeddedTable(params: {
doc: Document;
block: TableBlock;
blockMeasure: TableMeasure;
cumulativeLineCount: number;
globalFromLine: number;
globalToLine: number;
contentWidthPx: number;
context: FragmentRenderContext;
renderLine: EmbeddedTableRenderParams['renderLine'];
captureLineSnapshot?: EmbeddedTableRenderParams['captureLineSnapshot'];
renderDrawingContent?: EmbeddedTableRenderParams['renderDrawingContent'];
applySdtDataset: EmbeddedTableRenderParams['applySdtDataset'];
chrome?: EmbeddedTableRenderParams['chrome'];
sdtBoundary?: SdtBoundaryOptions;
ancestorContainerKey?: string | null;
ancestorContainerSdt?: SdtMetadata | null;
ancestorContainerKeys?: SdtAncestorOptions['ancestorContainerKeys'];
ancestorContainerSdts?: SdtAncestorOptions['ancestorContainerSdts'];
onSdtContainerChrome?: () => void;
}): { element: HTMLElement | null; height: number; nextCumulativeLineCount: number; hasSdtContainerChrome: boolean } {
const {
doc,
block,
blockMeasure: tableMeasure,
cumulativeLineCount,
globalFromLine,
globalToLine,
contentWidthPx,
context,
renderLine,
captureLineSnapshot,
renderDrawingContent,
applySdtDataset,
chrome,
sdtBoundary,
ancestorContainerKey,
ancestorContainerSdt,
ancestorContainerKeys,
ancestorContainerSdts,
onSdtContainerChrome,
} = params;
// Compute per-row segment counts (recursive, matching getCellLines/getEmbeddedRowLines).
const rowSegmentCounts = tableMeasure.rows.map((row: TableRowMeasure) => getEmbeddedRowSegmentCount(row));
const totalTableSegments = rowSegmentCounts.reduce((s: number, c: number) => s + c, 0);
const tableStartSegment = cumulativeLineCount;
const nextCumulativeLineCount = cumulativeLineCount + totalTableSegments;
const tableEndSegment = nextCumulativeLineCount;
// Skip entirely if no segments are in the visible range
if (tableEndSegment <= globalFromLine || tableStartSegment >= globalToLine) {
return { element: null, height: 0, nextCumulativeLineCount, hasSdtContainerChrome: false };
}
// Map global line range to local segment range within this embedded table
const localFrom = Math.max(0, globalFromLine - tableStartSegment);
const localTo = Math.min(totalTableSegments, globalToLine - tableStartSegment);
// Determine which rows to render and whether any need partial rendering
let segmentOffset = 0;
let embeddedFromRow = -1;
let embeddedToRow = -1;
// TODO: partialRowInfo is overwritten each iteration — if the visible segment range
// cuts through two different multi-segment rows, only the last one's info survives.
// TableFragment only supports a single partialRow, so fixing this requires a design change.
let partialRowInfo: PartialRowInfo | undefined;
for (let r = 0; r < tableMeasure.rows.length; r++) {
const rowSegs = rowSegmentCounts[r];
const rowStart = segmentOffset;
const rowEnd = segmentOffset + rowSegs;
segmentOffset = rowEnd;
// Skip rows completely outside the range
if (rowEnd <= localFrom || rowStart >= localTo) continue;
if (embeddedFromRow === -1) embeddedFromRow = r;
embeddedToRow = r + 1;
// Check if this row needs partial rendering (multi-segment row spanning the boundary)
if (rowSegs > 1 && (rowStart < localFrom || rowEnd > localTo)) {
const rowLocalFrom = Math.max(0, localFrom - rowStart);
const rowLocalTo = Math.min(rowSegs, localTo - rowStart);
const row = tableMeasure.rows[r];
const fromLineByCell: number[] = [];
const toLineByCell: number[] = [];
let partialHeight = 0;
for (const cell of row.cells) {
const cellTotal = getCellSegmentCount(cell);
const cellFrom = Math.min(rowLocalFrom, cellTotal);
const cellTo = Math.min(rowLocalTo, cellTotal);
fromLineByCell.push(cellFrom);
toLineByCell.push(cellTo);
partialHeight = Math.max(partialHeight, computeCellVisibleHeight(cell, cellFrom, cellTo));
}
partialRowInfo = {
rowIndex: r,
fromLineByCell,
toLineByCell,
isFirstPart: rowLocalFrom === 0,
isLastPart: rowLocalTo >= rowSegs,
partialHeight,
};
}
}
if (embeddedFromRow === -1) {
return { element: null, height: 0, nextCumulativeLineCount, hasSdtContainerChrome: false };
}
const visibleHeight = computeVisibleHeight(tableMeasure.rows, embeddedFromRow, embeddedToRow, partialRowInfo);
const effectiveSdtBoundary = sdtBoundary
? {
...sdtBoundary,
isStart: (sdtBoundary.isStart ?? true) && localFrom === 0,
isEnd: (sdtBoundary.isEnd ?? true) && localTo >= totalTableSegments,
showLabel: sdtBoundary.showLabel === undefined ? undefined : sdtBoundary.showLabel && localFrom === 0,
}
: undefined;
const tableWrapper = doc.createElement('div');
tableWrapper.style.position = 'relative';
tableWrapper.style.width = '100%';
tableWrapper.style.height = `${visibleHeight}px`;
tableWrapper.style.flexShrink = '0';
tableWrapper.style.boxSizing = 'border-box';
const tableResult = renderEmbeddedTable({
doc,
table: block,
measure: tableMeasure,
availableWidth: contentWidthPx,
context: { ...context, section: 'body' },
renderLine,
captureLineSnapshot,
renderDrawingContent,
applySdtDataset,
chrome,
fromRow: embeddedFromRow,
toRow: embeddedToRow,
partialRow: partialRowInfo,
sdtBoundary: effectiveSdtBoundary,
ancestorContainerKey,
ancestorContainerSdt,
ancestorContainerKeys,
ancestorContainerSdts,
onSdtContainerChrome,
});
tableWrapper.appendChild(tableResult.element);
return {
element: tableWrapper,
height: visibleHeight,
nextCumulativeLineCount,
hasSdtContainerChrome: tableResult.hasSdtContainerChrome,
};
}
/**
* Dependencies required for rendering a table cell.
*
* Contains positioning, sizing, content, and rendering functions needed to
* create a table cell DOM element with its content.
*/
type TableCellRenderDependencies = {
/** Document object for creating DOM elements */
doc: Document;
/** Horizontal position (left edge) in pixels */
x: number;
/** Vertical position (top edge) in pixels */
y: number;
/** Height of the row containing this cell */
rowHeight: number;
/** Measurement data for this cell (width, paragraph layout) */
cellMeasure: TableRowMeasure['cells'][number];
/** Cell data (content, attributes), or undefined for empty cells */
cell?: TableBlock['rows'][number]['cells'][number];
/** Resolved borders for this cell */
borders?: CellBorders;
/** Whether to apply default border if no borders specified */
useDefaultBorder?: boolean;
/** Function to render a line of paragraph content */
renderLine: (
block: ParagraphBlock,
line: Line,
context: FragmentRenderContext,
lineIndex: number,
isLastLine: boolean,
resolvedListTextStartPx?: number,
) => HTMLElement;
/** Optional callback invoked after a table line's final styles/markers are applied. */
captureLineSnapshot?: (
lineEl: HTMLElement,
context: FragmentRenderContext,
options?: { inTableParagraph?: boolean; wrapperEl?: HTMLElement },
) => void;
/**
* Optional callback function to render drawing content (vectorShapes, shapeGroups).
* If provided, this callback is used to render DrawingBlocks with drawingKind of 'vectorShape' or 'shapeGroup'.
* The callback receives a DrawingBlock and must return an HTMLElement.
* The returned element will have width: 100% and height: 100% styles applied automatically.
* If undefined, a placeholder element with diagonal stripes pattern is rendered instead.
*/
renderDrawingContent?: (block: DrawingBlock) => HTMLElement;
/** Rendering context */
context: FragmentRenderContext;
/** Function to apply SDT metadata as data attributes */
applySdtDataset: (el: HTMLElement | null, metadata?: SdtMetadata | null) => void;
/** Built-in SDT chrome rendering mode. */
chrome?: 'default' | 'none';
/** Ancestor SDT container key for suppressing duplicate container styling in cells */
ancestorContainerKey?: string | null;
/** Ancestor SDT metadata for suppressing duplicate id-less container styling in cells */
ancestorContainerSdt?: SdtMetadata | null;
/** Ancestor SDT keys for suppressing duplicate container styling in cells */
ancestorContainerKeys?: SdtAncestorOptions['ancestorContainerKeys'];
/** Ancestor SDT metadata chain for suppressing duplicate id-less container styling in cells */
ancestorContainerSdts?: SdtAncestorOptions['ancestorContainerSdts'];
/** Receives notification when this cell or descendants render SDT container chrome */
onSdtContainerChrome?: () => void;
/** Table indent in pixels (applied to table fragment positioning) */
tableIndent?: number;
/** Whether the table is visually right-to-left (w:bidiVisual, ECMA-376 §17.4.1) */
isRtl?: boolean;
/** Computed cell width from rescaled columnWidths (overrides cellMeasure.width when present) */
cellWidth?: number;
/** Starting line index for partial row rendering (inclusive) */
fromLine?: number;
/** Ending line index for partial row rendering (exclusive), -1 means render to end */
toLine?: number;
/**
* Per-document logical->physical font resolver for in-cell list markers and drop caps. Threaded
* from the renderer's per-document resolver so they paint the same physical family they were
* measured in. Undefined falls back to the global resolver.
*/
resolvePhysical?: ResolvePhysicalFamily;
};
/**
* Result of rendering a table cell.
*/
export type TableCellRenderResult = {
/** The cell container element (with borders, background, sizing, and content as child) */
cellElement: HTMLElement;
};
/**
* Renders a table cell as a DOM element.
*
* Creates a single cell element with content as a child:
* - cellElement: Absolutely-positioned container with borders, background, sizing, padding,
* and content rendered inside. Cell uses overflow:hidden to clip any overflow.
*
* Handles:
* - Cell borders (explicit or default)
* - Background colors
* - Vertical alignment (top, center, bottom)
* - Cell padding (applied directly to cell element)
* - Empty cells
*
* **Multi-Block Cell Rendering:**
* - Iterates through all blocks in the cell (cell.blocks or cell.paragraph)
* - Each block is rendered sequentially and stacked vertically
* - Only paragraph blocks are currently rendered (other block types are ignored)
*
* **Backward Compatibility:**
* - Supports legacy cell.paragraph field (single paragraph)
* - Falls back to empty array if neither cell.blocks nor cell.paragraph is present
* - Handles mismatches between blockMeasures and cellBlocks arrays using bounds checking
*
* **Empty Cell Handling:**
* - Cells with no blocks render only the cell container (no content inside)
* - Empty blocks arrays are safe (no content rendered)
*
* @param deps - All dependencies required for rendering
* @returns Object containing cellElement (content is rendered inside as child)
*
* @example
* ```typescript
* const { cellElement } = renderTableCell({
* doc: document,
* x: 100,
* y: 50,
* rowHeight: 30,
* cellMeasure,
* cell,
* borders,
* useDefaultBorder: false,
* renderLine,
* renderDrawingContent: (block) => {
* // Custom drawing renderer for vectorShapes and shapeGroups
* const el = document.createElement('div');
* // Render drawing content...
* return el;
* },
* context,
* applySdtDataset
* });
* container.appendChild(cellElement);
* ```
*/
export const renderTableCell = (deps: TableCellRenderDependencies): TableCellRenderResult => {
const {
doc,
x,
y,
rowHeight,
cellMeasure,
cell,
borders,
useDefaultBorder,
renderLine,
captureLineSnapshot,
renderDrawingContent,
context,
applySdtDataset,
chrome,
ancestorContainerKey,
ancestorContainerSdt,
ancestorContainerKeys,
ancestorContainerSdts,
onSdtContainerChrome,
tableIndent,
isRtl,
cellWidth,
fromLine,
toLine,
resolvePhysical,
} = deps;
const attrs = cell?.attrs;
const padding = attrs?.padding || { top: 0, left: 4, right: 4, bottom: 0 };
const buildTableImageHyperlinkAnchor = (
imageEl: HTMLElement,
hyperlink: ImageHyperlink | undefined,
display: 'block' | 'inline-block',
): HTMLElement => buildImageHyperlinkAnchor(doc, imageEl, hyperlink, display);
// RTL: swap left↔right cell margins (ECMA-376 Part 4 §14.3.3–14.3.4, §14.3.7–14.3.8)
const paddingLeft = isRtl ? (padding.right ?? 4) : (padding.left ?? 4);
const paddingTop = padding.top ?? 0;
const paddingRight = isRtl ? (padding.left ?? 4) : (padding.right ?? 4);
const paddingBottom = padding.bottom ?? 0;
const cellEl = doc.createElement('div');
cellEl.style.position = 'absolute';
cellEl.style.left = `${x}px`;
cellEl.style.top = `${y}px`;
cellEl.style.width = `${cellWidth ?? cellMeasure.width}px`;
cellEl.style.height = `${rowHeight}px`;
cellEl.style.boxSizing = 'border-box';
// Cell clips all overflow - no scrollbars, content just gets clipped at boundaries
cellEl.style.overflow = 'hidden';
// Apply padding directly to cell so content is positioned correctly
cellEl.style.paddingLeft = `${paddingLeft}px`;
cellEl.style.paddingTop = `${paddingTop}px`;
cellEl.style.paddingRight = `${paddingRight}px`;
cellEl.style.paddingBottom = `${paddingBottom}px`;
if (borders) {
applyCellBorders(cellEl, borders);
} else if (useDefaultBorder) {
cellEl.style.border = '1px solid rgba(0,0,0,0.6)';
}
if (cell?.attrs?.background) {
cellEl.style.backgroundColor = cell.attrs.background;
}
// Support multi-block cells with backward compatibility
const cellBlocks = cell?.blocks ?? (cell?.paragraph ? [cell.paragraph] : []);
const blockMeasures = cellMeasure?.blocks ?? (cellMeasure?.paragraph ? [cellMeasure.paragraph] : []);
const sdtContainerKeys = cellBlocks.map((block) =>
block.kind === 'paragraph' || block.kind === 'table' ? getSdtContainerKeyForBlock(block) : null,
);
const sdtBoundaries = getSdtSiblingBoundaries(sdtContainerKeys);
if (cellBlocks.length > 0 && blockMeasures.length > 0) {
// Content is a child of the cell, positioned relative to it
// Cell's overflow:hidden handles clipping, no explicit width needed
const content = doc.createElement('div');
content.style.position = 'relative';
content.style.width = '100%';
content.style.height = '100%';
content.style.display = 'flex';
content.style.flexDirection = 'column';
if (cell?.attrs?.verticalAlign === 'center') {
content.style.justifyContent = 'center';
} else if (cell?.attrs?.verticalAlign === 'bottom') {
content.style.justifyContent = 'flex-end';
} else {
content.style.justifyContent = 'flex-start';
}
// Append content to cell (content is now a child, not a sibling)
cellEl.appendChild(content);
// Establish a local stacking context so anchored objects can reliably layer above/below text.
// (Needed for negative z-index behindDoc behavior.)
content.style.zIndex = '0';
// Calculate total segments across all blocks for proper global index mapping.
// Embedded tables expand recursively (matching the layout engine's getCellLines()
// which uses getEmbeddedRowLines() for recursive nested table expansion).
// Non-paragraph blocks (images, drawings) occupy 1 segment each when height > 0,
// including anchored blocks (matching getCellLines() in layout-table.ts).
const blockLineCounts: number[] = [];
for (let i = 0; i < Math.min(blockMeasures.length, cellBlocks.length); i++) {
const bm = blockMeasures[i];
if (bm.kind === 'paragraph') {
blockLineCounts.push((bm as ParagraphMeasure).lines?.length || 0);
} else if (bm.kind === 'table') {
// Embedded tables: recursively count segments (matches getCellLines expansion)
blockLineCounts.push(getEmbeddedTableSegmentCount(bm as TableMeasure));
} else {
// Non-paragraph/non-table blocks (images, drawings) occupy 1 segment when
// their height > 0, matching getCellLines() in layout-table.ts which only
// counts non-paragraph blocks with positive height.
const blockHeight = 'height' in bm ? (bm as { height: number }).height : 0;
blockLineCounts.push(blockHeight > 0 ? 1 : 0);
}
}
const totalLines = blockLineCounts.reduce((a, b) => a + b, 0);
// Determine global line range to render
const globalFromLine = fromLine ?? 0;
const globalToLine = toLine === -1 || toLine === undefined ? totalLines : toLine;
const effectiveCellWidth = cellWidth ?? cellMeasure.width;
const contentWidthPx = Math.max(0, effectiveCellWidth - paddingLeft - paddingRight);
const contentHeightPx = Math.max(0, rowHeight - paddingTop - paddingBottom);
let flowCursorY = 0;
const anchoredBlocks: Array<{ block: ImageBlock | DrawingBlock; measure: ImageMeasure | DrawingMeasure }> = [];
const renderedLines: RenderedLineInfo[] = [];
let cumulativeLineCount = 0; // Track cumulative line count across blocks
for (let i = 0; i < Math.min(blockMeasures.length, cellBlocks.length); i++) {
const blockMeasure = blockMeasures[i];
const block = cellBlocks[i];
if (blockMeasure.kind === 'table' && block?.kind === 'table') {
const result = renderPartialEmbeddedTable({
doc,
block: block as TableBlock,
blockMeasure: blockMeasure as TableMeasure,
cumulativeLineCount,
globalFromLine,
globalToLine,
contentWidthPx,
context,
renderLine,
captureLineSnapshot,
renderDrawingContent,
applySdtDataset,
chrome,
sdtBoundary: sdtBoundaries[i],
ancestorContainerKey,
ancestorContainerSdt,
ancestorContainerKeys,
ancestorContainerSdts,
onSdtContainerChrome,
});
cumulativeLineCount = result.nextCumulativeLineCount;
if (result.element) {
content.appendChild(result.element);
flowCursorY += result.height;
}
if (result.hasSdtContainerChrome) {
cellEl.style.overflow = 'visible';
}
continue;
}
if (blockMeasure.kind === 'image' && block?.kind === 'image') {
if (block.anchor?.isAnchored) {
anchoredBlocks.push({ block, measure: blockMeasure as ImageMeasure });
// Advance cumulative count only when height > 0 to stay aligned with
// getCellLines() which only counts non-paragraph blocks with positive height.
if (blockMeasure.height > 0) {
cumulativeLineCount += 1;
}
continue;
}
// Non-paragraph blocks occupy 1 segment in the combined line/segment index.
const imgSegmentIndex = cumulativeLineCount;
cumulativeLineCount += 1;
if (imgSegmentIndex < globalFromLine || imgSegmentIndex >= globalToLine) {
continue;
}
const imageWrapper = doc.createElement('div');
imageWrapper.style.position = 'relative';
imageWrapper.style.width = `${blockMeasure.width}px`;
imageWrapper.style.height = `${blockMeasure.height}px`;
imageWrapper.style.flexShrink = '0';
imageWrapper.style.maxWidth = '100%';
imageWrapper.style.boxSizing = 'border-box';
applySdtDataset(imageWrapper, (block as ImageBlock).attrs?.sdt);
imageWrapper.appendChild(
createBlockImageContent({
doc,
block,
className: 'superdoc-table-image',
clipContainer: imageWrapper,
imageDisplay: 'block',
buildImageHyperlinkAnchor: buildTableImageHyperlinkAnchor,
}),
);
content.appendChild(imageWrapper);
flowCursorY += blockMeasure.height;
continue;
}
if (blockMeasure.kind === 'drawing' && block?.kind === 'drawing') {
if (block.anchor?.isAnchored) {
anchoredBlocks.push({ block, measure: blockMeasure as DrawingMeasure });
// Advance cumulative count only when height > 0 to stay aligned with
// getCellLines() which only counts non-paragraph blocks with positive height.
if (blockMeasure.height > 0) {
cumulativeLineCount += 1;
}
continue;
}
// Non-paragraph blocks occupy 1 segment in the combined line/segment index.
const drawSegmentIndex = cumulativeLineCount;
cumulativeLineCount += 1;
if (drawSegmentIndex < globalFromLine || drawSegmentIndex >= globalToLine) {
continue;
}
const drawingWrapper = doc.createElement('div');
drawingWrapper.style.position = 'relative';
drawingWrapper.style.width = `${blockMeasure.width}px`;
drawingWrapper.style.height = `${blockMeasure.height}px`;
drawingWrapper.style.flexShrink = '0';
drawingWrapper.style.maxWidth = '100%';
drawingWrapper.style.boxSizing = 'border-box';
applySdtDataset(drawingWrapper, (block as DrawingBlock).attrs as SdtMetadata | undefined);
const drawingInner = doc.createElement('div');
drawingInner.classList.add('superdoc-table-drawing');
drawingInner.style.width = '100%';
drawingInner.style.height = '100%';
drawingInner.style.display = 'flex';
drawingInner.style.alignItems = 'center';
drawingInner.style.justifyContent = 'center';
drawingInner.style.overflow = 'hidden';
if (block.drawingKind === 'image' && 'src' in block && block.src) {
drawingInner.appendChild(
createBlockImageContent({
doc,
block: block as ImageDrawing,
className: 'superdoc-drawing-image',
clipContainer: drawingInner,
imageDisplay: 'block',
buildImageHyperlinkAnchor: buildTableImageHyperlinkAnchor,
}),
);
} else if (renderDrawingContent) {
// Use the callback for other drawing types (vectorShape, shapeGroup, etc.)
const drawingContent = renderDrawingContent(block as DrawingBlock);
drawingContent.style.width = '100%';
drawingContent.style.height = '100%';
drawingInner.appendChild(drawingContent);
} else {
// Fallback placeholder when no rendering callback is provided
const placeholder = doc.createElement('div');
placeholder.classList.add('superdoc-drawing-placeholder');
placeholder.style.width = '100%';
placeholder.style.height = '100%';
const stripePattern =
'repeating-linear-gradient(45deg, rgba(15,23,42,0.1), rgba(15,23,42,0.1) 6px, rgba(15,23,42,0.2) 6px, rgba(15,23,42,0.2) 12px)';
// Set both shorthand and longhand to handle partial CSS property support in test DOMs.
placeholder.style.background = stripePattern;
placeholder.style.backgroundImage = stripePattern;
placeholder.style.border = '1px dashed rgba(15, 23, 42, 0.3)';
drawingInner.appendChild(placeholder);
}
drawingWrapper.appendChild(drawingInner);
content.appendChild(drawingWrapper);
flowCursorY += blockMeasure.height;
continue;
}
if (blockMeasure.kind === 'paragraph' && block?.kind === 'paragraph') {
const paragraphMeasure = blockMeasure as ParagraphMeasure;
const lines = paragraphMeasure.lines;
const blockLineCount = lines?.length || 0;
const isLastBlockInCell = i === Math.min(blockMeasures.length, cellBlocks.length) - 1;
const wordLayout = (block.attrs?.wordLayout ?? null) as MinimalWordLayout | null;
// Calculate the global line indices for this block
const blockStartGlobal = cumulativeLineCount;
const blockEndGlobal = cumulativeLineCount + blockLineCount;
// Skip blocks entirely before/after the global range
if (blockEndGlobal <= globalFromLine) {
cumulativeLineCount += blockLineCount;
continue;
}
if (blockStartGlobal >= globalToLine) {
cumulativeLineCount += blockLineCount;
continue;
}
// Calculate local line indices within this block
const localStartLine = Math.max(0, globalFromLine - blockStartGlobal);
const localEndLine = Math.min(blockLineCount, globalToLine - blockStartGlobal);
// Create wrapper for this paragraph's SDT metadata
// Use absolute positioning within the content container to stack blocks vertically
const paraWrapper = doc.createElement('div');
paraWrapper.style.position = 'relative';
paraWrapper.style.left = '0';
paraWrapper.style.width = '100%';