All files / roosterjs-content-model-dom/lib/modelApi/selection setSelection.ts

98.96% Statements 95/96
96.59% Branches 85/88
100% Functions 21/21
98.92% Lines 92/93

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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 3161x 1x                                     1x         195x                 300x 300x       300x   300x 311x   311x 1x           300x 1x   1x 1x 1x         300x                   311x   3x     27x       15x 15x 3x   3x 2x   1x       15x       240x           240x 428x           428x                         240x           50x     240x 63x   63x       63x   63x 67x 67x         240x     26x                   27x 27x   27x 25x 52x 52x 112x   112x   112x 27x     112x 97x         2x 2x 3x   3x   3x 2x           27x             33x 33x   58x       33x                                               428x 77x     428x   133x       59x         74x   133x     3x   3x         12x   12x         7x       12x   280x 280x                   295x 88x 88x 88x           417x       115x 69x   46x     115x                   743x 743x 743x    
import { isGeneralSegment } from '../typeCheck/isGeneralSegment';
import { mutateBlock, mutateSegment } from '../common/mutate';
import type {
    MutableType,
    ReadonlyContentModelBlock,
    ReadonlyContentModelBlockGroup,
    ReadonlyContentModelParagraph,
    ReadonlyContentModelSegment,
    ReadonlyContentModelTable,
    ReadonlySelectable,
    ShallowMutableSelectable,
    TableCellCoordinate,
} from 'roosterjs-content-model-types';
 
/**
 * Set selection into Content Model. If the Content Model already has selection, existing selection will be overwritten by the new one.
 * @param group The root level group of Content Model
 * @param start The start selected element. If not passed, existing selection of content model will be cleared
 * @param end The end selected element. If not passed, only the start element will be selected. If passed, all elements between start and end elements will be selected
 */
export function setSelection(
    group: ReadonlyContentModelBlockGroup,
    start?: ReadonlySelectable,
    end?: ReadonlySelectable
) {
    setSelectionToBlockGroup(group, false /*isInSelection*/, start || null, end || null);
}
 
function setSelectionToBlockGroup(
    group: ReadonlyContentModelBlockGroup,
    isInSelection: boolean,
    start: ReadonlySelectable | null,
    end: ReadonlySelectable | null
): boolean {
    return handleSelection(isInSelection, group, start, end, isInSelection => {
        Iif (isGeneralSegment(group) && needToSetSelection(group, isInSelection)) {
            setIsSelected(mutateBlock(group), isInSelection);
        }
 
        const blocksToDelete: number[] = [];
 
        group.blocks.forEach((block, i) => {
            isInSelection = setSelectionToBlock(block, isInSelection, start, end);
 
            if (block.blockType == 'Paragraph' && block.segments.length == 0 && block.isImplicit) {
                blocksToDelete.push(i);
            }
        });
 
        let index: number | undefined;
 
        if (blocksToDelete.length > 0) {
            const mutableGroup = mutateBlock(group);
 
            while ((index = blocksToDelete.pop()) !== undefined) {
                Eif (index >= 0) {
                    mutableGroup.blocks.splice(index, 1);
                }
            }
        }
 
        return isInSelection;
    });
}
 
function setSelectionToBlock(
    block: ReadonlyContentModelBlock,
    isInSelection: boolean,
    start: ReadonlySelectable | null,
    end: ReadonlySelectable | null
) {
    switch (block.blockType) {
        case 'BlockGroup':
            return setSelectionToBlockGroup(block, isInSelection, start, end);
 
        case 'Table':
            return setSelectionToTable(block, isInSelection, start, end);
 
        case 'Divider':
        case 'Entity':
            return handleSelection(isInSelection, block, start, end, isInSelection => {
                if (needToSetSelection(block, isInSelection)) {
                    const mutableBlock = mutateBlock(block);
 
                    if (isInSelection) {
                        mutableBlock.isSelected = true;
                    } else {
                        delete mutableBlock.isSelected;
                    }
                }
 
                return isInSelection;
            });
 
        case 'Paragraph':
            const state: ParagraphSelectionState = {
                segmentsToDelete: [],
                boundaryMarkers: [],
                hasSelectedNonMarker: false,
            };
 
            block.segments.forEach((segment, i) => {
                isInSelection = handleSelection(
                    isInSelection,
                    segment,
                    start,
                    end,
                    isInSelection => {
                        return setSelectionToSegment(
                            block,
                            segment,
                            isInSelection,
                            state,
                            start,
                            end,
                            i
                        );
                    }
                );
            });
 
            if (state.hasSelectedNonMarker) {
                // This paragraph contains a real (non-marker) selected segment, so any leading/trailing
                // selection marker of the range is redundant within this paragraph and can be removed.
                // We only do this within the same paragraph: a boundary marker at a paragraph edge must be
                // kept to distinguish "selection starts at the beginning of this line" from "selection
                // starts at the end of the previous line".
                state.segmentsToDelete.push(...state.boundaryMarkers);
            }
 
            if (state.segmentsToDelete.length > 0) {
                const mutablePara = mutateBlock(block);
 
                let index: number | undefined;
 
                // Sort ascending so the pop()-based splice below always removes the highest index first,
                // keeping the remaining indices valid (boundary markers may sit before queued deletions).
                state.segmentsToDelete.sort((a, b) => a - b);
 
                while ((index = state.segmentsToDelete.pop()) !== undefined) {
                    Eif (index >= 0) {
                        mutablePara.segments.splice(index, 1);
                    }
                }
            }
 
            return isInSelection;
 
        default:
            return isInSelection;
    }
}
 
function setSelectionToTable(
    table: ReadonlyContentModelTable,
    isInSelection: boolean,
    start: ReadonlySelectable | null,
    end: ReadonlySelectable | null
): boolean {
    const first = findCell(table, start);
    const last = end ? findCell(table, end) : first;
 
    if (!isInSelection) {
        for (let row = 0; row < table.rows.length; row++) {
            const currentRow = table.rows[row];
            for (let col = 0; col < currentRow.cells.length; col++) {
                const currentCell = table.rows[row].cells[col];
                const isSelected =
                    row >= first.row && row <= last.row && col >= first.col && col <= last.col;
 
                if (needToSetSelection(currentCell, isSelected)) {
                    setIsSelected(mutateBlock(currentCell), isSelected);
                }
 
                if (!isSelected) {
                    setSelectionToBlockGroup(currentCell, false /*isInSelection*/, start, end);
                }
            }
        }
    } else {
        table.rows.forEach(row =>
            row.cells.forEach(cell => {
                const wasInSelection = isInSelection;
 
                isInSelection = setSelectionToBlockGroup(cell, isInSelection, start, end);
 
                if (wasInSelection && isInSelection) {
                    mutateBlock(cell).isSelected = true;
                }
            })
        );
    }
 
    return isInSelection;
}
 
function findCell(
    table: ReadonlyContentModelTable,
    cell: ReadonlySelectable | null
): TableCellCoordinate {
    let col = -1;
    const row = cell
        ? table.rows.findIndex(
              row => (col = (row.cells as ReadonlyArray<ReadonlySelectable>).indexOf(cell)) >= 0
          )
        : -1;
 
    return { row, col };
}
 
interface ParagraphSelectionState {
    // Indexes of segments to delete after the paragraph is fully processed
    segmentsToDelete: number[];
 
    // Indexes of leading/trailing selection markers of the range that are kept for now, but will be
    // removed if this paragraph also contains a real (non-marker) selected segment
    boundaryMarkers: number[];
 
    // Whether this paragraph contains at least one selected segment that is not a selection marker
    hasSelectedNonMarker: boolean;
}
 
function setSelectionToSegment(
    paragraph: ReadonlyContentModelParagraph,
    segment: ReadonlyContentModelSegment,
    isInSelection: boolean,
    state: ParagraphSelectionState,
    start: ReadonlySelectable | null,
    end: ReadonlySelectable | null,
    i: number
) {
    if (segment.segmentType != 'SelectionMarker' && isInSelection) {
        state.hasSelectedNonMarker = true;
    }
 
    switch (segment.segmentType) {
        case 'SelectionMarker':
            if (!isInSelection || (segment != start && segment != end)) {
                // Delete the selection marker when
                // 1. It is not in selection any more. Or
                // 2. It is in middle of selection, so no need to have it
                state.segmentsToDelete.push(i);
            } else {
                // It is a leading/trailing selection marker of a range selection. Keep it for now, but
                // remember it so it can be removed later if this same paragraph also contains a real
                // (non-marker) selected segment, in which case the marker is redundant.
                state.boundaryMarkers.push(i);
            }
            return isInSelection;
 
        case 'General':
            internalSetSelectionToSegment(paragraph, segment, isInSelection);
 
            return segment != start && segment != end
                ? setSelectionToBlockGroup(segment, isInSelection, start, end)
                : isInSelection;
 
        case 'Image':
            const isSelectedAsImageSelection = start == segment && (!end || end == segment);
 
            internalSetSelectionToSegment(
                paragraph,
                segment,
                isInSelection,
                !segment.isSelectedAsImageSelection != !isSelectedAsImageSelection
                    ? image => (image.isSelectedAsImageSelection = isSelectedAsImageSelection)
                    : undefined
            );
 
            return isInSelection;
        default:
            internalSetSelectionToSegment(paragraph, segment, isInSelection);
            return isInSelection;
    }
}
 
function internalSetSelectionToSegment<T extends ReadonlyContentModelSegment>(
    paragraph: ReadonlyContentModelParagraph,
    segment: T,
    isInSelection: boolean,
    additionAction?: (segment: MutableType<T>) => void
) {
    if (additionAction || needToSetSelection(segment, isInSelection)) {
        mutateSegment(paragraph, segment, mutableSegment => {
            setIsSelected(mutableSegment, isInSelection);
            additionAction?.(mutableSegment);
        });
    }
}
 
function needToSetSelection(selectable: ReadonlySelectable, isSelected: boolean) {
    return !selectable.isSelected != !isSelected;
}
 
function setIsSelected(selectable: ShallowMutableSelectable, value: boolean) {
    if (value) {
        selectable.isSelected = true;
    } else {
        delete selectable.isSelected;
    }
 
    return value;
}
 
function handleSelection(
    isInSelection: boolean,
    model: ReadonlyContentModelBlockGroup | ReadonlyContentModelBlock | ReadonlyContentModelSegment,
    start: ReadonlySelectable | null,
    end: ReadonlySelectable | null,
    callback: (isInSelection: boolean) => boolean
) {
    isInSelection = isInSelection || model == start;
    isInSelection = callback(isInSelection);
    return isInSelection && !!end && model != end;
}