All files / roosterjs-content-model-api/lib/modelApi/common clearModelFormat.ts

100% Statements 86/86
91.04% Branches 61/67
100% Functions 18/18
100% Lines 75/75

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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 2331x 1x                                                         1x           16x   16x     19x 16x 13x   13x 3x         3x       19x 14x 5x 2x                       16x     16x         3x 3x 13x   9x 10x   10x 10x 10x         16x     16x   16x       16x 1x 1x 1x       1x     1x               16x 18x   18x 1x     18x               2x 8x 2x   2x 2x   2x 2x 2x         2x 1x                 10x           10x 4x     4x 4x   4x 3x         3x 3x   3x                     13x       13x 4x   4x   9x               10x 1x   1x 1x   9x 9x 9x         18x   12x       9x   9x      
import { adjustWordSelection } from '../selection/adjustWordSelection';
import {
    applyTableFormat,
    createFormatContainer,
    getClosestAncestorBlockGroupIndex,
    iterateSelections,
    mutateBlock,
    mutateSegments,
    updateTableCellMetadata,
    updateTableMetadata,
} from 'roosterjs-content-model-dom';
import type {
    ContentModelSegmentFormat,
    ContentModelTable,
    ReadonlyContentModelBlock,
    ReadonlyContentModelBlockGroup,
    ReadonlyContentModelDocument,
    ReadonlyContentModelFormatContainer,
    ReadonlyContentModelListItem,
    ReadonlySelectable,
    ReadonlyTableSelectionContext,
    ShallowMutableContentModelBlock,
    ShallowMutableContentModelFormatContainer,
    ShallowMutableContentModelSegment,
    ShallowMutableContentModelTable,
} from 'roosterjs-content-model-types';
 
/**
 * @internal
 */
export function clearModelFormat(
    model: ReadonlyContentModelDocument,
    blocksToClear: [ReadonlyContentModelBlockGroup[], ShallowMutableContentModelBlock][],
    segmentsToClear: ShallowMutableContentModelSegment[],
    tablesToClear: [ContentModelTable, boolean][]
): boolean {
    let pendingStructureChange = false;
 
    iterateSelections(
        model,
        (path, tableContext, block, segments) => {
            if (segments) {
                if (block?.blockType == 'Paragraph') {
                    const [, mutableSegments] = mutateSegments(block, segments);
 
                    segmentsToClear.push(...mutableSegments);
                } else Eif (
                    path[0].blockGroupType == 'ListItem' &&
                    segments.length == 1 &&
                    path[0].formatHolder == segments[0]
                ) {
                    segmentsToClear.push(mutateBlock(path[0]).formatHolder);
                }
            }
 
            if (block) {
                blocksToClear.push([path, mutateBlock(block)]);
            } else if (tableContext) {
                clearTableCellFormat(tableContext, tablesToClear);
            }
        },
        {
            // When there is a default format to apply, we know how to handle segment format under list.
            // So no need to clear format of list number.
            // Otherwise, we will clear all format of selected text. And since they are under LI tag, we
            // also need to clear the format of LI (format holder) so that the format is really cleared
            includeListFormatHolder: model.format ? 'never' : 'anySegment',
        }
    );
 
    const marker = segmentsToClear[0];
 
    // 2. If selection is collapsed, add selection to whole word to clear if any
    if (
        blocksToClear.length == 1 &&
        isOnlySelectionMarkerSelected(blocksToClear[0][1]) &&
        blocksToClear.length == 1
    ) {
        segmentsToClear.splice(0, segmentsToClear.length, ...adjustWordSelection(model, marker));
        pendingStructureChange = clearListFormat(blocksToClear[0][0]) || pendingStructureChange;
    } else if (blocksToClear.length > 1 || blocksToClear.some(x => isWholeBlockSelected(x[1]))) {
        // 2. If a full block or multiple blocks are selected, clear block format
        for (let i = blocksToClear.length - 1; i >= 0; i--) {
            const [path, block] = blocksToClear[i];
 
            clearBlockFormat(path, block);
            pendingStructureChange = clearListFormat(path) || pendingStructureChange;
            clearContainerFormat(path, block);
        }
    }
 
    // 3. Finally clear format for segments
    clearSegmentsFormat(segmentsToClear, model.format);
 
    // 4. Clear format for table if any
    createTablesFormat(tablesToClear);
 
    return pendingStructureChange;
}
 
function createTablesFormat(tablesToClear: [ContentModelTable, boolean][]) {
    tablesToClear.forEach(x => {
        const [table, isWholeTableSelected] = x;
        Eif (isWholeTableSelected) {
            table.format = {
                useBorderBox: table.format.useBorderBox,
                borderCollapse: table.format.borderCollapse,
            };
            updateTableMetadata(table, () => null);
        }
 
        applyTableFormat(table, undefined /*newFormat*/, true);
    });
}
 
function clearSegmentsFormat(
    segmentsToClear: ShallowMutableContentModelSegment[],
    defaultSegmentFormat: Readonly<ContentModelSegmentFormat> | undefined
) {
    segmentsToClear.forEach(x => {
        x.format = { ...(defaultSegmentFormat || {}) };
 
        if (x.link) {
            delete x.link.format.textColor;
        }
 
        delete x.code;
    });
}
 
function clearTableCellFormat(
    tableContext: ReadonlyTableSelectionContext | undefined,
    tablesToClear: [ShallowMutableContentModelTable, boolean][]
) {
    Eif (tableContext) {
        const { table, colIndex, rowIndex, isWholeTableSelected } = tableContext;
        const cell = table.rows[rowIndex].cells[colIndex];
 
        Eif (cell.isSelected) {
            const mutableCell = mutateBlock(cell);
 
            updateTableCellMetadata(mutableCell, () => null);
            mutableCell.isHeader = false;
            mutableCell.format = {
                useBorderBox: cell.format.useBorderBox,
            };
        }
 
        if (!tablesToClear.find(x => x[0] == table)) {
            tablesToClear.push([mutateBlock(table), isWholeTableSelected]);
        }
    }
}
 
function clearContainerFormat(
    path: ReadonlyContentModelBlockGroup[],
    block: ShallowMutableContentModelBlock
) {
    const containerPathIndex = getClosestAncestorBlockGroupIndex(
        path,
        ['FormatContainer'],
        ['TableCell']
    );
 
    if (containerPathIndex >= 0 && containerPathIndex < path.length - 1) {
        const container = mutateBlock(
            path[containerPathIndex] as ReadonlyContentModelFormatContainer
        );
        const containerIndex = path[containerPathIndex + 1].blocks.indexOf(container);
        const blockIndex = container.blocks.indexOf(block);
 
        if (blockIndex >= 0 && containerIndex >= 0) {
            const newContainer: ShallowMutableContentModelFormatContainer = createFormatContainer(
                container.tagName,
                container.format
            );
 
            container.blocks.splice(blockIndex, 1);
            newContainer.blocks = container.blocks.splice(blockIndex);
 
            mutateBlock(path[containerPathIndex + 1]).blocks.splice(
                containerIndex + 1,
                0,
                block,
                newContainer
            );
        }
    }
}
 
function clearListFormat(path: ReadonlyContentModelBlockGroup[]) {
    const listItem = path[getClosestAncestorBlockGroupIndex(path, ['ListItem'], ['TableCell'])] as
        | ReadonlyContentModelListItem
        | undefined;
 
    if (listItem) {
        mutateBlock(listItem).levels = [];
 
        return true;
    } else {
        return false;
    }
}
 
function clearBlockFormat(
    path: ReadonlyContentModelBlockGroup[],
    block: ShallowMutableContentModelBlock
) {
    if (block.blockType == 'Divider') {
        const index = path[0].blocks.indexOf(block);
 
        Eif (index >= 0) {
            mutateBlock(path[0]).blocks.splice(index, 1);
        }
    } else Eif (block.blockType == 'Paragraph') {
        block.format = {};
        delete block.decorator;
    }
}
 
function isOnlySelectionMarkerSelected(block: ReadonlyContentModelBlock) {
    const segments = block.blockType == 'Paragraph' ? block.segments.filter(x => x.isSelected) : [];
 
    return segments.length == 1 && segments[0].segmentType == 'SelectionMarker';
}
 
function isWholeBlockSelected(block: ReadonlyContentModelBlock) {
    return (
        (block as ReadonlySelectable).isSelected ||
        (block.blockType == 'Paragraph' && block.segments.every(x => x.isSelected))
    );
}