-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathrenderTableRow.ts
More file actions
469 lines (437 loc) · 16.9 KB
/
Copy pathrenderTableRow.ts
File metadata and controls
469 lines (437 loc) · 16.9 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
import type {
CellBorders,
DrawingBlock,
Line,
ParagraphBlock,
PartialRowInfo,
SdtMetadata,
TableBlock,
TableBorders,
TableMeasure,
} from '@superdoc/contracts';
import type { ResolvePhysicalFamily } from '@superdoc/font-system';
import { renderTableCell } from './renderTableCell.js';
import {
resolveTableCellBorders,
borderValueToSpec,
resolveTableBorderValue,
hasExplicitCellBorders,
swapCellBordersLR,
} from './border-utils.js';
import { getTableCellGridBounds, type TableCellGridPosition } from './grid-geometry.js';
import type { FragmentRenderContext } from '../renderer.js';
import type { SdtAncestorOptions } from '../sdt/container.js';
type TableRowMeasure = TableMeasure['rows'][number];
type TableRow = TableBlock['rows'][number];
type CellBorderResolutionArgs = {
cellBorders?: CellBorders;
hasBordersAttribute: boolean;
tableBorders?: TableBorders;
cellPosition: TableCellGridPosition;
cellSpacingPx: number;
continuesFromPrev: boolean;
continuesOnNext: boolean;
};
const hasAnyResolvedBorder = (borders: CellBorders): boolean =>
Boolean(borders.top || borders.right || borders.bottom || borders.left);
/**
* Resolves the borders that a rendered cell fragment should paint.
*
* The DOM table painter uses a single-owner border model, so merged cells must
* determine edge ownership from their full occupied grid bounds, not just their
* starting column or row.
*/
const resolveRenderedCellBorders = ({
cellBorders,
hasBordersAttribute,
tableBorders,
cellPosition,
cellSpacingPx,
continuesFromPrev,
continuesOnNext,
}: CellBorderResolutionArgs): CellBorders | undefined => {
const hasExplicitBorders = hasExplicitCellBorders(cellBorders);
if (hasBordersAttribute && !hasExplicitBorders) {
return undefined;
}
if (!tableBorders) {
return hasExplicitBorders
? {
top: cellBorders.top,
right: cellBorders.right,
bottom: cellBorders.bottom,
left: cellBorders.left,
}
: undefined;
}
const cellBounds = getTableCellGridBounds(cellPosition);
const touchesTopBoundary = cellBounds.touchesTopEdge || continuesFromPrev;
const touchesBottomBoundary = cellBounds.touchesBottomEdge || continuesOnNext;
if (hasExplicitBorders) {
if (cellSpacingPx === 0) {
// Collapsed model: avoid double interior borders by using single-owner sides.
// Keep explicit top/left (or table fallbacks), and only render right/bottom on table edges.
// Assumes shared interior edges specify the same border on both adjacent cells (e.g. Google Docs
// round-trips this way). Asymmetric (only one cell’s side set) may miss a line until we add conflict resolution.
return {
top: resolveTableBorderValue(cellBorders.top, touchesTopBoundary ? tableBorders.top : tableBorders.insideH),
right: cellBounds.touchesRightEdge ? resolveTableBorderValue(cellBorders.right, tableBorders.right) : undefined,
bottom: touchesBottomBoundary ? resolveTableBorderValue(cellBorders.bottom, tableBorders.bottom) : undefined,
left: resolveTableBorderValue(
cellBorders.left,
cellBounds.touchesLeftEdge ? tableBorders.left : tableBorders.insideV,
),
};
}
return {
top: resolveTableBorderValue(cellBorders.top, touchesTopBoundary ? tableBorders.top : tableBorders.insideH),
right: resolveTableBorderValue(cellBorders.right, cellBounds.touchesRightEdge ? tableBorders.right : undefined),
bottom: resolveTableBorderValue(cellBorders.bottom, touchesBottomBoundary ? tableBorders.bottom : undefined),
left: resolveTableBorderValue(
cellBorders.left,
cellBounds.touchesLeftEdge ? tableBorders.left : tableBorders.insideV,
),
};
}
if (cellSpacingPx > 0) {
const interiorBorders: CellBorders = {
top: touchesTopBoundary ? undefined : borderValueToSpec(tableBorders.insideH),
right: cellBounds.touchesRightEdge ? undefined : borderValueToSpec(tableBorders.insideV),
bottom: touchesBottomBoundary ? undefined : borderValueToSpec(tableBorders.insideH),
left: cellBounds.touchesLeftEdge ? undefined : borderValueToSpec(tableBorders.insideV),
};
return hasAnyResolvedBorder(interiorBorders) ? interiorBorders : undefined;
}
const baseBorders = resolveTableCellBorders(tableBorders, cellPosition);
return {
top: touchesTopBoundary ? borderValueToSpec(tableBorders.top) : baseBorders.top,
right: baseBorders.right,
bottom: touchesBottomBoundary ? borderValueToSpec(tableBorders.bottom) : baseBorders.bottom,
left: baseBorders.left,
};
};
/**
* Dependencies required for rendering a table row.
*
* Contains all information needed to render cells in a table row, including
* positioning, measurements, border resolution, and rendering functions.
*/
type TableRowRenderDependencies = {
/** Document object for creating DOM elements */
doc: Document;
/** Container element to append cell elements to */
container: HTMLElement;
/** Zero-based index of this row */
rowIndex: number;
/** Vertical position (top edge) in pixels */
y: number;
/** Measurement data for this row (height, cell measurements) */
rowMeasure: TableRowMeasure;
/** Row data (cells, attributes), or undefined for empty rows */
row?: TableRow;
/** Total number of rows in the table (for border resolution) */
totalRows: number;
/** Table-level borders (for resolving cell borders) */
tableBorders?: TableBorders;
/** Column widths array for calculating x positions from gridColumnStart */
columnWidths: number[];
/** All row heights for calculating rowspan cell heights */
allRowHeights: number[];
/** 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;
/** Rendering context */
context: FragmentRenderContext;
/** Function to render a line of paragraph content */
renderLine: (
block: ParagraphBlock,
line: Line,
context: FragmentRenderContext,
lineIndex: number,
isLastLine: boolean,
) => 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;
/** Function to render drawing content (images, shapes, shape groups) */
renderDrawingContent?: (block: DrawingBlock) => HTMLElement;
/** Function to apply SDT metadata as data attributes */
applySdtDataset: (el: HTMLElement | null, metadata?: SdtMetadata | null) => void;
/** 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 cells render SDT container chrome */
onSdtContainerChrome?: () => void;
/**
* If true, this row is the first body row of a continuation fragment.
* MS Word draws borders at split points to visually close the table on each page,
* so we do NOT suppress borders - both fragments draw their edge borders.
*/
continuesFromPrev?: boolean;
/**
* If true, this row is the last body row before a page break continuation.
* MS Word draws borders at split points to visually close the table on each page,
* so we do NOT suppress borders - both fragments draw their edge borders.
*/
continuesOnNext?: boolean;
/**
* Partial row information for mid-row splits.
* Contains per-cell line ranges (fromLineByCell, toLineByCell) for rendering
* only a portion of the row's content.
*/
partialRow?: PartialRowInfo;
/**
* Cell spacing in pixels (border-spacing between cells).
* Applied to cell x positions and row y advancement.
*/
cellSpacingPx?: number;
/** Built-in SDT chrome rendering mode. */
chrome?: 'default' | 'none';
/**
* 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;
};
/**
* Renders all cells in a table row.
*
* Iterates through cells in the row, resolving borders based on cell position,
* and rendering each cell with its content. Cells are positioned horizontally
* by accumulating their widths.
*
* Border resolution logic:
* - Cells with explicit borders use those borders
* - Otherwise, cells use position-based borders from table borders:
* - Edge cells use outer table borders
* - Interior cells use inside borders (insideH, insideV)
* - If no table borders exist, default borders are applied
*
* @param deps - All dependencies required for rendering
*
* @example
* ```typescript
* renderTableRow({
* doc: document,
* container: tableContainer,
* rowIndex: 0,
* y: 0,
* rowMeasure,
* row,
* totalRows: 3,
* tableBorders,
* context,
* renderLine,
* applySdtDataset
* });
* // Appends all cell elements to container
* ```
*/
export const renderTableRow = (deps: TableRowRenderDependencies): void => {
const {
doc,
container,
rowIndex,
y,
rowMeasure,
row,
totalRows,
tableBorders,
columnWidths,
allRowHeights,
tableIndent,
isRtl,
context,
renderLine,
captureLineSnapshot,
renderDrawingContent,
applySdtDataset,
ancestorContainerKey,
ancestorContainerSdt,
ancestorContainerKeys,
ancestorContainerSdts,
onSdtContainerChrome,
continuesFromPrev,
continuesOnNext,
partialRow,
cellSpacingPx = 0,
chrome,
resolvePhysical,
} = deps;
const totalCols = columnWidths.length;
/**
* Calculates the horizontal position (x-coordinate) for a cell based on its grid column index.
*
* Sums the widths of all columns preceding the given column index plus spacing between
* columns (border-spacing). When cellSpacingPx > 0, each column after the first is
* offset by one spacing unit, so x = sum(columnWidths[0..gridColumnStart-1]) + gridColumnStart * cellSpacingPx.
*
* **Bounds Safety:**
* Loop terminates at the minimum of `gridColumnStart` and `columnWidths.length`
* to prevent out-of-bounds array access.
*
* @param gridColumnStart - Zero-based column index in the table grid
* @returns Horizontal position in pixels from the left edge of the table
*
* @example
* ```typescript
* // columnWidths = [100, 150, 200], cellSpacingPx = 4
* calculateXPosition(0) // Returns: cellSpacingPx (space before first column)
* calculateXPosition(1) // Returns: cellSpacingPx + columnWidths[0] + cellSpacingPx
* ```
*/
const calculateXPosition = (gridColumnStart: number): number => {
let x = cellSpacingPx; // space before first column
for (let i = 0; i < gridColumnStart && i < columnWidths.length; i++) {
x += columnWidths[i] + cellSpacingPx;
}
return x;
};
// Total table content width (for RTL mirroring)
// RTL tables mirror cell X positions: rtlX = totalWidth - ltrX - cellWidth
// (ECMA-376 §17.4.1: cells stored logically, displayed right-to-left)
let tableContentWidth = 0;
if (isRtl) {
tableContentWidth = cellSpacingPx;
for (let i = 0; i < columnWidths.length; i++) {
tableContentWidth += columnWidths[i] + cellSpacingPx;
}
}
/**
* Calculates the total height for a cell that spans multiple rows (rowspan).
*
* Sums the heights of consecutive rows starting from `startRowIndex` up to
* the number of rows specified by `rowSpan`. This determines the vertical
* size needed to render a cell that merges multiple rows.
*
* **Bounds Safety:**
* Loop checks both rowSpan count and array bounds to prevent accessing
* non-existent rows.
*
* @param startRowIndex - Zero-based index of the first row in the span
* @param rowSpan - Number of rows the cell spans (typically >= 1)
* @returns Total height in pixels for the cell
*
* @example
* ```typescript
* // allRowHeights = [50, 60, 70, 80]
* calculateRowspanHeight(0, 1) // Returns: 50 (single row)
* calculateRowspanHeight(0, 2) // Returns: 110 (rows 0 and 1)
* calculateRowspanHeight(1, 3) // Returns: 210 (rows 1, 2, and 3)
* calculateRowspanHeight(3, 5) // Returns: 80 (safe - only row 3 exists)
* ```
*/
const calculateRowspanHeight = (startRowIndex: number, rowSpan: number): number => {
let totalHeight = 0;
for (let i = 0; i < rowSpan && startRowIndex + i < allRowHeights.length; i++) {
totalHeight += allRowHeights[startRowIndex + i];
}
return totalHeight;
};
const calculateColspanWidth = (gridColumnStart: number, colSpan: number): number => {
let width = 0;
for (let i = gridColumnStart; i < gridColumnStart + colSpan && i < columnWidths.length; i++) {
width += columnWidths[i];
}
return width;
};
for (let cellIndex = 0; cellIndex < rowMeasure.cells.length; cellIndex += 1) {
const cellMeasure = rowMeasure.cells[cellIndex];
const cell = row?.cells?.[cellIndex];
const gridColumnStart = cellMeasure.gridColumnStart ?? cellIndex;
const rowSpan = cellMeasure.rowSpan ?? 1;
const colSpan = cellMeasure.colSpan ?? 1;
// Calculate x position from gridColumnStart if available, otherwise fallback
let x = calculateXPosition(gridColumnStart);
// Check if cell has any border attribute at all (even if empty - empty means "no borders")
const cellBordersAttr = cell?.attrs?.borders;
const hasBordersAttribute = cellBordersAttr !== undefined;
// For RTL tables, swap left↔right edge detection so borders mirror correctly
// (ECMA-376 Part 4 §14.3.1–14.3.8: left/right borders and margins swap for bidiVisual)
const cellPosition: TableCellGridPosition = {
rowIndex,
rowSpan,
gridColumnStart,
colSpan,
totalRows,
totalCols,
};
// Resolve borders using logical positions, then swap output for RTL.
// The resolver uses touchesLeftEdge/touchesRightEdge which are LOGICAL edges.
// For RTL, logical left = visual right, so we swap the resolved CSS properties
// so borderLeft/borderRight match the correct visual edges.
const resolvedBorders = resolveRenderedCellBorders({
cellBorders: cellBordersAttr,
hasBordersAttribute,
tableBorders,
cellPosition,
cellSpacingPx,
continuesFromPrev: continuesFromPrev === true,
continuesOnNext: continuesOnNext === true,
});
// RTL: swap resolved left↔right so CSS properties match visual edges
const finalBorders = isRtl && resolvedBorders ? swapCellBordersLR(resolvedBorders) : resolvedBorders;
// Calculate cell height - use rowspan height if cell spans multiple rows
// For partial rows, use the partial height instead
let cellHeight: number;
if (partialRow) {
// Use partial row height for mid-row splits
cellHeight = partialRow.partialHeight;
} else if (rowSpan > 1) {
cellHeight = calculateRowspanHeight(rowIndex, rowSpan);
} else {
cellHeight = rowMeasure.height;
}
// Get per-cell line range for partial row rendering
const fromLine = partialRow?.fromLineByCell?.[cellIndex];
const toLine = partialRow?.toLineByCell?.[cellIndex];
// Compute cell width from rescaled columnWidths (SD-1859: mixed-orientation docs
// where cellMeasure.width may reflect landscape measurement but the fragment renders
// in portrait). The columnWidths array is already rescaled by the layout engine.
const computedCellWidth = calculateColspanWidth(gridColumnStart, colSpan);
// RTL: mirror x position so first logical column appears on the right
if (isRtl && computedCellWidth > 0) {
x = tableContentWidth - x - computedCellWidth;
}
// Never use default borders - cells are either explicitly styled or borderless
// This prevents gray borders on cells with borders={} (intentionally borderless)
const { cellElement } = renderTableCell({
doc,
x,
y,
rowHeight: cellHeight,
cellMeasure,
cell,
borders: finalBorders,
useDefaultBorder: false,
renderLine,
captureLineSnapshot,
renderDrawingContent,
context,
applySdtDataset,
ancestorContainerKey,
ancestorContainerSdt,
ancestorContainerKeys,
ancestorContainerSdts,
onSdtContainerChrome,
fromLine,
toLine,
tableIndent,
isRtl,
cellWidth: computedCellWidth > 0 ? computedCellWidth : undefined,
chrome,
resolvePhysical,
});
container.appendChild(cellElement);
}
};