All files / roosterjs-content-model-api/lib/modelApi/block setModelIndentation.ts

92.39% Statements 85/92
79.01% Branches 64/81
100% Functions 8/8
91.95% Lines 80/87

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 1971x 1x 1x 1x 1x                                                 1x     84x     43x   43x         43x 43x   61x 61x 23x 23x   23x 15x 15x 30x 15x 15x 15x   15x 5x 10x 10x     10x       8x 8x 7x 7x 7x 7x 7x 7x                   7x 7x 7x 7x       7x   7x   1x     8x 5x     38x 38x 38x   38x 40x 40x 40x   40x 36x   36x 3x   33x     36x   36x 4x 3x   3x 3x   1x           43x       23x 18x 18x                           1x 1x                             1x           55x   165x 55x 55x 55x   55x 48x     55x   9x   46x      
import { findListItemsInSameThread } from '../list/findListItemsInSameThread';
import { getListAnnounceData } from '../list/getListAnnounceData';
import { IndentStepInPixel } from '../common/adjustIndentation';
import { splitSelectedParagraphByBr } from './splitSelectedParagraphByBr';
import {
    createListLevel,
    getOperationalBlocks,
    isBlockGroupOfType,
    mutateBlock,
    parseValueWithUnit,
    updateListMetadata,
} from 'roosterjs-content-model-dom';
import type {
    ContentModelBlockFormat,
    ContentModelListItem,
    ContentModelListLevel,
    FormatContentModelContext,
    ReadonlyContentModelBlock,
    ReadonlyContentModelBlockGroup,
    ReadonlyContentModelDocument,
    ReadonlyContentModelListItem,
} from 'roosterjs-content-model-types';
 
/**
 * @param model The content model to set indentation
 * @param indentation The indentation type, 'indent' to indent, 'outdent' to outdent
 * @param length The length of indentation in pixel, default value is 40
 * Set indentation for selected list items or paragraphs
 */
export function setModelIndentation(
    model: ReadonlyContentModelDocument,
    indentation: 'indent' | 'outdent',
    length: number = IndentStepInPixel,
    context?: FormatContentModelContext
) {
    splitSelectedParagraphByBr(model);
 
    const paragraphOrListItem = getOperationalBlocks<ContentModelListItem>(
        model,
        ['ListItem'],
        ['TableCell']
    );
    const isIndent = indentation == 'indent';
    const modifiedBlocks: ReadonlyContentModelBlock[] = [];
 
    paragraphOrListItem.forEach(({ block, parent, path }) => {
        if (isBlockGroupOfType<ContentModelListItem>(block, 'ListItem')) {
            const thread = findListItemsInSameThread(model, block);
            const firstItem = thread[0];
            //if the first item is selected and has only one level, we should add margin to the whole list
            if (isSelected(firstItem) && firstItem.levels.length == 1) {
                const level = block.levels[0];
                const { format } = level;
                const { marginLeft, marginRight } = format;
                const newValue = calculateMarginValue(format, isIndent, length);
                const isRtl = format.direction == 'rtl';
                const originalValue = parseValueWithUnit(isRtl ? marginRight : marginLeft);
 
                if (!isIndent && originalValue == 0) {
                    block.levels.pop();
                } else Eif (newValue !== null) {
                    Iif (isRtl) {
                        level.format.marginRight = newValue + 'px';
                    } else {
                        level.format.marginLeft = newValue + 'px';
                    }
                }
                //if block has only one level, there is not need to check if it is multilevel selection
            } else Eif (block.levels.length == 1 || !isMultilevelSelection(model, block, parent)) {
                if (isIndent) {
                    const threadIdx = thread.indexOf(block);
                    const previousItem = thread[threadIdx - 1];
                    const nextItem = thread[threadIdx + 1];
                    const levelLength = block.levels.length;
                    const lastLevel = block.levels[levelLength - 1];
                    const newLevel: ContentModelListLevel = createListLevel(
                        lastLevel?.listType || 'UL',
                        lastLevel?.format,
                        previousItem && previousItem.levels.length > levelLength
                            ? previousItem.levels[levelLength].dataset
                            : nextItem && nextItem.levels.length > levelLength
                            ? nextItem.levels[levelLength].dataset
                            : undefined
                    );
 
                    updateListMetadata(newLevel, metadata => {
                        metadata = metadata || {};
                        metadata.applyListStyleFromLevel = true;
                        return metadata;
                    });
 
                    // New level is totally new, no need to have these attributes for now
                    delete newLevel.format.startNumberOverride;
 
                    block.levels.push(newLevel);
                } else {
                    block.levels.pop();
                }
 
                if (block.levels.length > 0 && context) {
                    context.announceData = getListAnnounceData([block, ...path]);
                }
            }
        } else Eif (block) {
            let currentBlock: ReadonlyContentModelBlock = block;
            let currentParent: ReadonlyContentModelBlockGroup = parent;
 
            while (currentParent && modifiedBlocks.indexOf(currentBlock) < 0) {
                const index = path.indexOf(currentParent);
                const { format } = mutateBlock(currentBlock);
                const newValue = calculateMarginValue(format, isIndent, length);
 
                if (newValue !== null) {
                    const isRtl = format.direction == 'rtl';
 
                    if (isRtl) {
                        format.marginRight = newValue + 'px';
                    } else {
                        format.marginLeft = newValue + 'px';
                    }
 
                    modifiedBlocks.push(currentBlock);
 
                    break;
                } else if (currentParent.blockGroupType == 'FormatContainer' && index >= 0) {
                    mutateBlock(currentParent);
 
                    currentBlock = currentParent;
                    currentParent = path[index + 1];
                } else {
                    break;
                }
            }
        }
    });
 
    return paragraphOrListItem.length > 0;
}
 
function isSelected(listItem: ReadonlyContentModelListItem) {
    return listItem.blocks.some(block => {
        Eif (block.blockType == 'Paragraph') {
            return block.segments.some(segment => segment.isSelected);
        }
    });
}
 
/*
 * Check if the selection has list items with different levels and the first item of the list is selected, do not create a sub list.
 * Otherwise, the margin of the first item will be changed, and the sub list will be created, creating a unintentional margin difference between the list items.
 */
function isMultilevelSelection(
    model: ReadonlyContentModelDocument,
    listItem: ReadonlyContentModelListItem,
    parent: ReadonlyContentModelBlockGroup
) {
    const listIndex = parent.blocks.indexOf(listItem);
    for (let i = listIndex - 1; i >= 0; i--) {
        const block = parent.blocks[i];
        if (
            isBlockGroupOfType<ContentModelListItem>(block, 'ListItem') &&
            block.levels.length == 1 &&
            isSelected(block)
        ) {
            const firstItem = findListItemsInSameThread(model, block)[0];
            return isSelected(firstItem);
        }
 
        if (!isBlockGroupOfType<ContentModelListItem>(block, 'ListItem')) {
            return false;
        }
    }
    return false;
}
 
function calculateMarginValue(
    format: Readonly<ContentModelBlockFormat>,
    isIndent: boolean,
    Ilength: number = IndentStepInPixel
): number | null {
    const { marginLeft, marginRight, direction } = format;
    const isRtl = direction == 'rtl';
    const originalValue = parseValueWithUnit(isRtl ? marginRight : marginLeft);
    let newValue = (isIndent ? Math.ceil : Math.floor)(originalValue / length) * length;
 
    if (newValue == originalValue) {
        newValue = Math.max(newValue + length * (isIndent ? 1 : -1), 0);
    }
 
    if (newValue == originalValue) {
        // Return null to let caller know nothing is changed
        return null;
    } else {
        return newValue;
    }
}