All files / roosterjs-content-model-api/lib/publicApi/table insertTable.ts

15% Statements 3/20
0% Branches 0/24
0% Functions 0/2
15% Lines 3/20

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 651x 1x                                       1x                                                                                      
import { createTableStructure } from '../../modelApi/table/createTableStructure';
import {
    createContentModelDocument,
    createSelectionMarker,
    applyTableFormat,
    deleteSelection,
    mergeModel,
    normalizeTable,
    setSelection,
} from 'roosterjs-content-model-dom';
import type { IEditor, TableMetadataFormat } from 'roosterjs-content-model-types';
 
/**
 * Insert table into editor at current selection
 * @param editor The editor instance
 * @param columns Number of columns in table, it also controls the default table cell width:
 * if columns <= 4, width = 120px; if columns <= 6, width = 100px; else width = 70px
 * @param rows Number of rows in table
 * @param format (Optional) The table format. If not passed, the default format will be applied:
 * background color: #FFF; border color: #ABABAB
 */
export function insertTable(
    editor: IEditor,
    columns: number,
    rows: number,
    format?: Partial<TableMetadataFormat>
) {
    editor.focus();
 
    editor.formatContentModel(
        (model, context) => {
            const insertPosition = deleteSelection(model, [], context).insertPoint;
 
            if (insertPosition) {
                const doc = createContentModelDocument();
                const table = createTableStructure(doc, columns, rows);
 
                normalizeTable(table, editor.getPendingFormat() || insertPosition.marker.format);
                // Assign default vertical align
                format = format || { verticalAlign: 'top' };
                applyTableFormat(table, format);
                mergeModel(model, doc, context, {
                    insertPosition,
                    mergeFormat: 'mergeAll',
                });
 
                const firstBlock = table.rows[0]?.cells[0]?.blocks[0];
 
                if (firstBlock?.blockType == 'Paragraph') {
                    const marker = createSelectionMarker(firstBlock.segments[0]?.format);
                    firstBlock.segments.unshift(marker);
                    setSelection(model, marker);
                }
 
                return true;
            } else {
                return false;
            }
        },
        {
            apiName: 'insertTable',
        }
    );
}