All files / roosterjs-content-model-markdown/lib/markdownToModel/creators createTableFromMarkdown.ts

100% Statements 39/39
75% Branches 9/12
100% Functions 5/5
100% Lines 32/32

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 631x   1x                   1x 57x 13x 13x 32x 32x   13x     13x       32x 32x 32x   32x 32x     32x       32x 32x 80x 80x 80x 80x 80x 80x   80x 80x   32x       80x 8x   72x 10x   62x    
import { createParagraphFromMarkdown } from './createParagraphFromMarkdown';
import type { ContentModelTable } from 'roosterjs-content-model-types';
import {
    applyTableFormat,
    createTable,
    createTableCell,
    createTableRow,
} from 'roosterjs-content-model-dom';
 
/**
 * @internal
 */
export function createTableFromMarkdown(tableLines: string[]): ContentModelTable {
    const tableDivider = tableLines[1].split('|').filter(content => content.trim() !== '');
    tableLines.splice(1, 1);
    const table = createTable(0, { borderCollapse: true });
    for (const line of tableLines) {
        createTableModel(line, table, tableDivider);
    }
    applyTableFormat(table, {
        hasHeaderRow: true,
    });
    return table;
}
 
function createTableModel(markdown: string, table: ContentModelTable, tableDivider: string[]) {
    const contents = markdown.split('|');
    Eif (contents[0].trim() === '') {
        contents.shift();
    }
    Eif (contents[contents.length - 1].trim() === '') {
        contents.pop();
    }
 
    addTableRow(table, contents, tableDivider);
}
 
function addTableRow(table: ContentModelTable, contents: string[], tableDivider: string[]) {
    const row = createTableRow();
    let index = 0;
    for (const content of contents) {
        const paragraph = createParagraphFromMarkdown(content);
        const cell = createTableCell();
        cell.blocks.push(paragraph);
        Eif (tableDivider[index]) {
            cell.format.textAlign = getCellAlignment(tableDivider[index]);
        }
        row.cells.push(cell);
        index++;
    }
    table.rows.push(row);
}
 
function getCellAlignment(content: string) {
    if (content.startsWith(':') && content.endsWith(':')) {
        return 'center';
    }
    if (content.endsWith(':')) {
        return 'end';
    }
    return 'start';
}