All files / roosterjs-content-model-api/lib/publicApi/utils formatTableWithContentModel.ts

100% Statements 22/22
87.5% Branches 7/8
100% Functions 2/2
100% Lines 20/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 65 66 67 68 69 701x 1x                                               1x           8x   8x   8x 6x   6x   6x 3x   3x 3x   3x 3x 3x       6x   6x 2x     6x   2x                  
import { ensureFocusableParagraphForTable } from '../../modelApi/table/ensureFocusableParagraphForTable';
import {
    createSelectionMarker,
    hasMetadata,
    setParagraphNotImplicit,
    hasSelectionInBlock,
    applyTableFormat,
    getFirstSelectedTable,
    normalizeTable,
    setSelection,
    mutateBlock,
} from 'roosterjs-content-model-dom';
import type {
    IEditor,
    ShallowMutableContentModelTable,
    TableSelection,
} from 'roosterjs-content-model-types';
 
/**
 * Invoke a callback to format the selected table using Content Model
 * @param editor The editor object
 * @param apiName Name of API this calling this function. This is mostly for logging.
 * @param callback The callback to format the table. It will be called with current selected table. If no table is selected, it will not be called.
 * @param selectionOverride Override the current selection. If we want to format a table even currently it is not selected, we can use this parameter to override current selection
 */
export function formatTableWithContentModel(
    editor: IEditor,
    apiName: string,
    callback: (tableModel: ShallowMutableContentModelTable) => void,
    selectionOverride?: TableSelection
) {
    editor.formatContentModel(
        model => {
            const [readonlyTableModel, path] = getFirstSelectedTable(model);
 
            if (readonlyTableModel) {
                const tableModel = mutateBlock(readonlyTableModel);
 
                callback(tableModel);
 
                if (!hasSelectionInBlock(tableModel)) {
                    const paragraph = ensureFocusableParagraphForTable(model, path, tableModel);
 
                    Eif (paragraph) {
                        const marker = createSelectionMarker(model.format);
 
                        paragraph.segments.unshift(marker);
                        setParagraphNotImplicit(paragraph);
                        setSelection(model, marker);
                    }
                }
 
                normalizeTable(tableModel, model.format);
 
                if (hasMetadata(tableModel)) {
                    applyTableFormat(tableModel, undefined /*newFormat*/, true /*keepCellShade*/);
                }
 
                return true;
            } else {
                return false;
            }
        },
        {
            apiName,
            selectionOverride,
        }
    );
}