All files / roosterjs-content-model-plugins/lib/imageEdit/utils normalizeImageSelection.ts

100% Statements 12/12
100% Branches 10/10
100% Functions 1/1
100% Lines 12/12

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 321x                   1x 6x 6x 6x 5x 5x 5x               1x 1x 1x   5x      
import { mutateBlock } from 'roosterjs-content-model-dom';
import type { ImageAndParagraph } from '../types/ImageAndParagraph';
 
/**
 * Selecting directly on the image will only capture the image segment.
 * However, if the selection is made while the image is within a wrapper, it will capture the span that encloses the image.
 * In the last case, the selection will be marked as <---SelectionMarker---><---Image---><---SelectionMarker--->.
 * To fix this behavior the extra selection markers are removed.
 * @internal
 */
export function normalizeImageSelection(imageAndParagraph: ImageAndParagraph) {
    const paragraph = imageAndParagraph.paragraph;
    const index = paragraph.segments.indexOf(imageAndParagraph.image);
    if (index > 0) {
        const markerBefore = paragraph.segments[index - 1];
        const markerAfter = paragraph.segments[index + 1];
        if (
            markerBefore &&
            markerAfter &&
            markerAfter.segmentType == 'SelectionMarker' &&
            markerBefore.segmentType == 'SelectionMarker' &&
            markerAfter.isSelected &&
            markerBefore.isSelected
        ) {
            const mutatedParagraph = mutateBlock(paragraph);
            mutatedParagraph.segments.splice(index - 1, 1);
            mutatedParagraph.segments.splice(index, 1);
        }
        return imageAndParagraph;
    }
}