All files / roosterjs-content-model-core/lib/corePlugin/selection isSingleImageInSelection.ts

100% Statements 18/18
93.75% Branches 15/16
100% Functions 3/3
100% Lines 14/14

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 431x         1x 8x   8x 8x   8x 4x 4x 2x     6x         8x 4x             4x                   8x    
import { isElementOfType, isNodeOfType } from 'roosterjs-content-model-dom';
 
/**
 * @internal
 */
export function isSingleImageInSelection(selection: Selection | Range): HTMLImageElement | null {
    const { startNode, endNode, startOffset, endOffset } = getProps(selection);
 
    const max = Math.max(startOffset, endOffset);
    const min = Math.min(startOffset, endOffset);
 
    if (startNode && endNode && startNode == endNode && max - min == 1) {
        const node = startNode?.childNodes.item(min);
        if (isNodeOfType(node, 'ELEMENT_NODE') && isElementOfType(node, 'img')) {
            return node;
        }
    }
    return null;
}
function getProps(
    selection: Selection | Range
): { startNode: Node | null; endNode: Node | null; startOffset: number; endOffset: number } {
    if (isSelection(selection)) {
        return {
            startNode: selection.anchorNode,
            endNode: selection.focusNode,
            startOffset: selection.anchorOffset,
            endOffset: selection.focusOffset,
        };
    } else {
        return {
            startNode: selection.startContainer,
            endNode: selection.endContainer,
            startOffset: selection.startOffset,
            endOffset: selection.endOffset,
        };
    }
}
 
function isSelection(selection: Selection | Range): selection is Selection {
    return !!(selection as Selection).getRangeAt;
}