All files / roosterjs-content-model-core/lib/corePlugin/copyPaste/utils deleteEmptyList.ts

94.74% Statements 18/19
85.29% Branches 29/34
100% Functions 3/3
94.44% Lines 17/18

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 621x                         4x 2x 1x       2x 2x                     1x 10x 5x 5x         5x 5x 4x   4x       4x     4x           1x          
import {
    getClosestAncestorBlockGroupIndex,
    hasSelectionInBlock,
    hasSelectionInBlockGroup,
    mutateBlock,
} from 'roosterjs-content-model-dom';
import type {
    DeleteSelectionContext,
    DeleteSelectionStep,
    ReadonlyContentModelBlock,
} from 'roosterjs-content-model-types';
 
function isEmptyBlock(block: ReadonlyContentModelBlock | undefined): boolean {
    if (block && block.blockType == 'Paragraph') {
        return block.segments.every(
            segment => segment.segmentType !== 'SelectionMarker' && segment.segmentType == 'Br'
        );
    }
 
    Eif (block && block.blockType == 'BlockGroup') {
        return block.blocks.every(isEmptyBlock);
    }
 
    return !!block;
}
 
/**
 * @internal
 * If the first item o the list is selected in a expanded selection, we need to remove the list item levels
 * @param context A context object provided by formatContentModel API
 */
export const deleteEmptyList: DeleteSelectionStep = (context: DeleteSelectionContext) => {
    const { insertPoint, deleteResult } = context;
    Eif (deleteResult == 'range' && insertPoint?.path) {
        const index = getClosestAncestorBlockGroupIndex(
            insertPoint.path,
            ['ListItem'],
            ['TableCell']
        );
        const item = insertPoint.path[index];
        if (index >= 0 && item && item.blockGroupType == 'ListItem') {
            const listItemIndex = insertPoint.path[index + 1].blocks.indexOf(item);
            const previousBlock =
                listItemIndex > -1
                    ? insertPoint.path[index + 1].blocks[listItemIndex - 1]
                    : undefined;
            const nextBlock =
                listItemIndex > -1
                    ? insertPoint.path[index + 1].blocks[listItemIndex + 1]
                    : undefined;
            if (
                hasSelectionInBlockGroup(item) &&
                (!previousBlock || hasSelectionInBlock(previousBlock)) &&
                nextBlock &&
                isEmptyBlock(nextBlock)
            ) {
                mutateBlock(item).levels = [];
            }
        }
    }
};