All files / roosterjs-content-model-markdown/lib/modelToMarkdown/creators createMarkdownTable.ts

100% Statements 39/39
100% Branches 5/5
100% Functions 2/2
100% Lines 27/27

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         8x 8x 8x 18x 18x 32x 32x 32x                       32x   18x 18x 8x 8x       8x       8x 8x 15x 15x   1x 1x   2x 2x   12x 12x     8x    
import { createMarkdownBlock } from './createMarkdownBlock';
import type { MarkdownLineBreaks } from '../../constants/markdownLineBreaks';
import type { ListCounter } from './createMarkdownBlockGroup';
import type { ContentModelTable, ContentModelTableRow } from 'roosterjs-content-model-types';
 
/**
 * @internal
 */
export function createMarkdownTable(
    table: ContentModelTable,
    newLinePattern: MarkdownLineBreaks,
    listCounter: ListCounter
): string {
    let markdownString = '';
    const { rows } = table;
    let firstRow = true;
    for (const row of rows) {
        markdownString += '|';
        for (const cell of row.cells) {
            for (const block of cell.blocks) {
                markdownString += createMarkdownBlock(
                    block,
                    newLinePattern,
                    listCounter,
                    {
                        divider: '',
                    },
                    {
                        ignoreLineBreaks: true,
                    }
                );
            }
            markdownString += '|';
        }
        markdownString += newLinePattern.newLine;
        if (firstRow) {
            markdownString += addTableDivider(row);
            firstRow = false;
        }
    }
 
    return markdownString;
}
 
function addTableDivider(headerRow: ContentModelTableRow) {
    let divider = '|';
    const { cells } = headerRow;
    for (const cell of cells) {
        switch (cell.format.textAlign) {
            case 'center':
                divider += ':----:|';
                break;
            case 'end':
                divider += '----:|';
                break;
            default:
                divider += '----|';
                break;
        }
    }
    return divider + '\n';
}