All files / roosterjs-content-model-dom/lib/modelApi/common normalizeContentModel.ts

100% Statements 25/25
90.91% Branches 10/11
100% Functions 1/1
100% Lines 22/22

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 481x 1x 1x 1x                       1x 1509x 3044x   3044x   815x 16x 16x   799x   815x   2149x 2149x   70x 118x 260x 260x       70x     3044x 836x        
import { isBlockEmpty } from './isEmpty';
import { mutateBlock } from './mutate';
import { normalizeParagraph } from './normalizeParagraph';
import { unwrapBlock } from './unwrapBlock';
import type { ReadonlyContentModelBlockGroup } from 'roosterjs-content-model-types';
 
/**
 * For a given content model, normalize it to make the model be consistent.
 * This process includes:
 * - For a list item without any list level, unwrap the list item
 * - For a paragraph, make sure it has BR at the end if it is an empty paragraph
 * - For text segments under paragraph, make sure its space values are correct (use nbsp to replace space when necessary)
 * - For an empty block, remove it
 * @param group The root level block group of content model to normalize
 */
export function normalizeContentModel(group: ReadonlyContentModelBlockGroup) {
    for (let i = group.blocks.length - 1; i >= 0; i--) {
        const block = group.blocks[i];
 
        switch (block.blockType) {
            case 'BlockGroup':
                if (block.blockGroupType == 'ListItem' && block.levels.length == 0) {
                    i += block.blocks.length;
                    unwrapBlock(group, block);
                } else {
                    normalizeContentModel(block);
                }
                break;
            case 'Paragraph':
                normalizeParagraph(block);
                break;
            case 'Table':
                for (let r = 0; r < block.rows.length; r++) {
                    for (let c = 0; c < block.rows[r].cells.length; c++) {
                        Eif (block.rows[r].cells[c]) {
                            normalizeContentModel(block.rows[r].cells[c]);
                        }
                    }
                }
                break;
        }
 
        if (isBlockEmpty(block)) {
            mutateBlock(group).blocks.splice(i, 1);
        }
    }
}