All files / roosterjs-content-model-dom/lib/domToModel/processors tableProcessor.ts

98.33% Statements 177/180
88.24% Branches 105/119
100% Functions 9/9
98.15% Lines 159/162

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 4281x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                   1x         86x       86x   86x 86x 86x 86x 86x   86x 22x     86x   86x 86x 86x           86x 86x   86x 86x 86x 86x 86x   142x 142x 142x   142x   142x           128x 14x       142x   142x 142x 142x   142x   128x           128x               142x 142x             142x   142x 576x       288x   288x 288x 288x 104x 104x 104x 104x   104x 77x   77x 77x 57x   57x         77x 55x             288x       288x           288x             288x     288x   288x           288x           288x   288x 288x       294x 294x                     311x 311x             311x   311x   311x 311x     311x     288x 117x     288x   288x 288x   288x 288x   288x 288x       311x   311x                 7x                 142x 311x                   142x     86x   86x   86x 142x 142x   142x 13x   13x 19x           19x 19x       142x 55x               35x   35x 35x 38x 38x 76x 35x 35x     38x 35x       35x       172x 172x   172x 172x   172x 172x 172x       172x 131x 131x 4x   127x 127x       172x               86x 86x   86x 95x 6x   6x 13x 12x   12x   12x 15x     15x           15x 15x               86x       86x     35x     2x   2x               49x         137x            
import { addBlock } from '../../modelApi/common/addBlock';
import { createTable } from '../../modelApi/creators/createTable';
import { createTableCell } from '../../modelApi/creators/createTableCell';
import { getBoundingClientRect } from '../utils/getBoundingClientRect';
import { getSelectionRootNode } from '../../domUtils/selection/getSelectionRootNode';
import { isElementOfType } from '../../domUtils/isElementOfType';
import { isNodeOfType } from '../../domUtils/isNodeOfType';
import { parseFormat } from '../utils/parseFormat';
import { parseValueWithUnit } from '../../formatHandlers/utils/parseValueWithUnit';
import { stackFormat } from '../utils/stackFormat';
import type {
    ContentModelTableCellFormat,
    DatasetFormat,
    DomToModelContext,
    ElementProcessor,
    SizeFormat,
} from 'roosterjs-content-model-types';
 
/**
 * Content Model Element Processor for table
 *
 * For Table with merged/splitted cells, HTML uses colSpan and rowSpan attributes to specify how it should be rendered.
 * To make it easier to edit a table, we will use a different way to describe table.
 *
 * 1. For a m * n table (m rows, n columns), we always create a m * n array for the cells.
 * 2. For a regular table cell, it is mapped to one item of this array
 * 3. For a merged/splitted table cell, it will has colSpan/rowSpan value. We also created TableCell model for those spanned
 * cells, and use "spanLeft" and "spanAbove" to mark its state
 * 4. When edit table, we always edit on this mapped m * n array because it always has an item for each cell
 * 5. When write back to DOM, we create TD/TH elements for those non-spanned cells, and mark its colSpan/rowSpan value according
 * its neighbour cell's spanLeft/spanAbove attribute
 * @param group The parent block group
 * @param parent Parent DOM node to process
 * @param context DOM to Content Model context
 */
export const tableProcessor: ElementProcessor<HTMLTableElement> = (
    group,
    tableElement,
    context
) => {
    stackFormat(
        context,
        { segment: 'shallowCloneForBlock', paragraph: 'shallowCloneForGroup' },
        () => {
            parseFormat(tableElement, context.formatParsers.block, context.blockFormat, context);
 
            const table = createTable(tableElement.rows.length, context.blockFormat);
            const tableSelection = context.selection?.type == 'table' ? context.selection : null;
            const selectedTable = tableSelection?.table;
            const hasTableSelection = selectedTable == tableElement;
            const recalculateTableSize = shouldRecalculateTableSize(tableElement, context);
 
            if (context.allowCacheElement) {
                table.cachedElement = tableElement;
            }
 
            context.domIndexer?.onTable(tableElement, table);
 
            parseFormat(tableElement, context.formatParsers.table, table.format, context);
            parseFormat(tableElement, context.formatParsers.tableBorder, table.format, context);
            parseFormat(
                tableElement,
                context.formatParsers.segmentOnBlock,
                context.segmentFormat,
                context
            );
            parseFormat(tableElement, context.formatParsers.dataset, table.dataset, context);
            addBlock(group, table);
 
            const columnPositions: (number | undefined)[] = [0];
            const hasColGroup = processColGroup(tableElement, context, columnPositions);
            const rowPositions: number[] = [0];
            const zoomScale = context.zoomScale || 1;
            let maxColumns = 0;
 
            for (let row = 0; row < tableElement.rows.length; row++) {
                const tr = tableElement.rows[row];
                const tableRow = table.rows[row];
 
                const tbody = tr.parentNode;
 
                if (
                    isNodeOfType(tbody, 'ELEMENT_NODE') &&
                    (isElementOfType(tbody, 'tbody') ||
                        isElementOfType(tbody, 'thead') ||
                        isElementOfType(tbody, 'tfoot'))
                ) {
                    parseFormat(tbody, context.formatParsers.tableRow, tableRow.format, context);
                } else Iif (context.allowCacheElement) {
                    tableRow.cachedElement = tr;
                }
 
                parseFormat(tr, context.formatParsers.tableRow, tableRow.format, context);
 
                stackFormat(context, { paragraph: 'shallowClone', segment: 'shallowClone' }, () => {
                    const parent = tr.parentElement;
                    const isInTableSection = parent && getIsInTableSection(parent);
 
                    if (isInTableSection) {
                        // If there is TBODY around TR, retrieve format from TBODY first, in case some format are declared there
                        parseFormat(
                            parent,
                            context.formatParsers.block,
                            context.blockFormat,
                            context
                        );
                        parseFormat(
                            parent,
                            context.formatParsers.segmentOnBlock,
                            context.segmentFormat,
                            context
                        );
                    }
 
                    parseFormat(tr, context.formatParsers.block, context.blockFormat, context);
                    parseFormat(
                        tr,
                        context.formatParsers.segmentOnBlock,
                        context.segmentFormat,
                        context
                    );
 
                    tableRow.height = parseInt(tr.style.height) || 0;
 
                    for (
                        let sourceCol = 0, targetCol = 0;
                        sourceCol < tr.cells.length;
                        sourceCol++
                    ) {
                        for (; tableRow.cells[targetCol]; targetCol++) {}
 
                        const td = tr.cells[sourceCol];
                        const hasSelectionBeforeCell = context.isInSelection;
                        if (recalculateTableSize) {
                            const colEnd = targetCol + td.colSpan;
                            const rowEnd = row + td.rowSpan;
                            const needCalcWidth = columnPositions[colEnd] === undefined;
                            const needCalcHeight = rowPositions[rowEnd] === undefined;
 
                            if (needCalcWidth || needCalcHeight) {
                                const rect = getBoundingClientRect(td);
 
                                Eif (rect.width > 0 || rect.height > 0) {
                                    if (needCalcWidth) {
                                        const pos = columnPositions[targetCol];
 
                                        columnPositions[colEnd] =
                                            (typeof pos == 'number' ? pos : 0) +
                                            rect.width / zoomScale;
                                    }
 
                                    if (needCalcHeight) {
                                        rowPositions[rowEnd] =
                                            rowPositions[row] + rect.height / zoomScale;
                                    }
                                }
                            }
                        }
 
                        stackFormat(
                            context,
                            { paragraph: 'shallowClone', segment: 'shallowClone' },
                            () => {
                                parseFormat(
                                    td,
                                    context.formatParsers.block,
                                    context.blockFormat,
                                    context
                                );
                                parseFormat(
                                    td,
                                    context.formatParsers.segmentOnTableCell,
                                    context.segmentFormat,
                                    context
                                );
 
                                const cellFormat: ContentModelTableCellFormat = {
                                    ...context.blockFormat,
                                };
                                const dataset: DatasetFormat = {};
 
                                parseFormat(
                                    td,
                                    context.formatParsers.tableCell,
                                    cellFormat,
                                    context
                                );
                                parseFormat(
                                    td,
                                    context.formatParsers.tableBorder,
                                    cellFormat,
                                    context
                                );
                                parseFormat(td, context.formatParsers.dataset, dataset, context);
 
                                for (
                                    let colSpan = 1;
                                    colSpan <= (td.colSpan == 0 ? 1 : td.colSpan);
                                    colSpan++, targetCol++
                                ) {
                                    for (
                                        let rowSpan = 1;
                                        // RowSpan of 0 means it should span to the end of the table
                                        // https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/td#rowspan
                                        rowSpan <=
                                        (td.rowSpan == 0
                                            ? isInTableSection
                                                ? translateRowSpanZero(parent, td)
                                                : 1
                                            : td.rowSpan);
                                        rowSpan++
                                    ) {
                                        const hasTd = colSpan == 1 && rowSpan == 1;
                                        const cell = createTableCell(
                                            colSpan > 1,
                                            rowSpan > 1,
                                            td.tagName == 'TH',
                                            cellFormat
                                        );
 
                                        cell.dataset = { ...dataset };
 
                                        const spannedRow = table.rows[row + rowSpan - 1];
 
                                        Eif (spannedRow) {
                                            spannedRow.cells[targetCol] = cell;
                                        }
 
                                        if (hasTd) {
                                            // When there is COLGROUP, width on table cell should be ignored, so we should not cache the table cell,
                                            // and always recreate it when write back using the table formats
                                            if (context.allowCacheElement && !hasColGroup) {
                                                cell.cachedElement = td;
                                            }
 
                                            const { listParent, levels } = context.listFormat;
 
                                            context.listFormat.listParent = undefined;
                                            context.listFormat.levels = [];
 
                                            try {
                                                context.elementProcessors.child(cell, td, context);
                                            } finally {
                                                context.listFormat.listParent = listParent;
                                                context.listFormat.levels = levels;
                                            }
                                        }
 
                                        const hasSelectionAfterCell = context.isInSelection;
 
                                        if (
                                            (hasSelectionBeforeCell && hasSelectionAfterCell) ||
                                            (hasTableSelection &&
                                                tableSelection &&
                                                row >= tableSelection.firstRow &&
                                                row <= tableSelection.lastRow &&
                                                targetCol >= tableSelection.firstColumn &&
                                                targetCol <= tableSelection.lastColumn)
                                        ) {
                                            cell.isSelected = true;
                                        }
                                    }
                                }
                            }
                        );
                    }
                });
 
                for (let col = 0; col < tableRow.cells.length; col++) {
                    Iif (!tableRow.cells[col]) {
                        tableRow.cells[col] = createTableCell(
                            false,
                            false,
                            false,
                            context.blockFormat
                        );
                    }
                }
 
                maxColumns = Math.max(maxColumns, tableRow.cells.length);
            }
 
            table.widths = calcSizes(columnPositions);
 
            const heights = calcSizes(rowPositions);
 
            for (let i = 0; i < table.rows.length; i++) {
                const row = table.rows[i];
                const currentLength = row.cells.length;
 
                if (currentLength > 0 && currentLength < maxColumns) {
                    const lastCell = row.cells[currentLength - 1];
 
                    for (let col = currentLength; col < maxColumns; col++) {
                        const spanCell = createTableCell(
                            true, // spanLeft
                            false,
                            lastCell.isHeader,
                            lastCell.format
                        );
                        spanCell.dataset = { ...lastCell.dataset };
                        row.cells[col] = spanCell;
                    }
                }
 
                if (heights[i] > 0) {
                    row.height = heights[i];
                }
            }
        }
    );
};
 
function translateRowSpanZero(parent: HTMLTableSectionElement, td: HTMLTableCellElement) {
    const amountOfRows = parent.rows.length;
 
    let tdIndex = -1;
    for (let i = 0; i < parent.rows.length; i++) {
        const row = parent.rows[i];
        for (let j = 0; j < row.cells.length; j++) {
            if (row.cells[j] === td) {
                tdIndex = i;
                break;
            }
        }
        if (tdIndex !== -1) {
            break;
        }
    }
 
    return amountOfRows - tdIndex;
}
 
function calcSizes(positions: (number | undefined)[]): number[] {
    const result: number[] = [];
    let lastPos = 0;
 
    for (let i = positions.length - 1; i >= 0; i--) {
        const pos = positions[i];
 
        Eif (typeof pos == 'number') {
            lastPos = pos;
            break;
        }
    }
 
    for (let i = positions.length - 2; i >= 0; i--) {
        const pos = positions[i];
        if (pos === undefined) {
            result[i] = 0;
        } else {
            result[i] = lastPos - pos;
            lastPos = pos;
        }
    }
 
    return result;
}
 
function processColGroup(
    table: HTMLElement,
    context: DomToModelContext,
    result: (number | undefined)[]
): boolean {
    let lastPos = 0;
    let hasColGroup = false;
 
    for (let child = table.firstChild; child; child = child.nextSibling) {
        if (isNodeOfType(child, 'ELEMENT_NODE') && child.tagName == 'COLGROUP') {
            hasColGroup = true;
 
            for (let col = child.firstChild; col; col = col.nextSibling) {
                if (isNodeOfType(col, 'ELEMENT_NODE') && col.tagName == 'COL') {
                    const colFormat: SizeFormat = {};
 
                    parseFormat(col, context.formatParsers.tableColumn, colFormat, context);
 
                    for (let i = 0; i < parseInt(col.getAttribute('span') ?? '1'); i++) {
                        Iif (colFormat.width === undefined) {
                            result.push(undefined);
                        } else {
                            const width = parseValueWithUnit(
                                colFormat.width ?? '',
                                undefined /*element*/,
                                'px'
                            );
 
                            result.push(width + lastPos);
                            lastPos += width;
                        }
                    }
                }
            }
        }
    }
 
    return hasColGroup;
}
 
function shouldRecalculateTableSize(table: HTMLTableElement, context: DomToModelContext): boolean {
    switch (context.recalculateTableSize) {
        case true:
        case 'all':
            return true;
 
        case 'selected':
            const selectionRoot = getSelectionRootNode(context.selection);
 
            return (
                !!selectionRoot &&
                (selectionRoot == table ||
                    table.contains(selectionRoot) ||
                    selectionRoot.contains(table))
            );
 
        default:
            return false;
    }
}
 
function getIsInTableSection(element: HTMLElement): element is HTMLTableSectionElement {
    return (
        isElementOfType(element, 'tbody') ||
        isElementOfType(element, 'thead') ||
        isElementOfType(element, 'tfoot')
    );
}