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

87.5% Statements 14/16
72.22% Branches 13/18
100% Functions 1/1
87.5% Lines 14/16

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          1x         5x 5x   5x   5x 5x 4x       1x   1x 1x         1x   1x 1x         1x    
import type { DOMInsertPoint, IEditor } from 'roosterjs-content-model-types';
 
/**
 * @internal Get insertion point from coordinate.
 */
export function getNodePositionFromEvent(
    editor: IEditor,
    x: number,
    y: number
): DOMInsertPoint | null {
    const doc = editor.getDocument();
    const domHelper = editor.getDOMHelper();
 
    Eif ('caretPositionFromPoint' in doc) {
        // Firefox, Chrome, Edge, Safari, Opera
        const pos = (doc as any).caretPositionFromPoint(x, y);
        if (pos && domHelper.isNodeInEditor(pos.offsetNode)) {
            return { node: pos.offsetNode, offset: pos.offset };
        }
    }
 
    Eif (doc.caretRangeFromPoint) {
        // Safari
        const range = doc.caretRangeFromPoint(x, y);
        Iif (range && domHelper.isNodeInEditor(range.startContainer)) {
            return { node: range.startContainer, offset: range.startOffset };
        }
    }
 
    Eif (doc.elementFromPoint) {
        // Fallback
        const element = doc.elementFromPoint(x, y);
        Iif (element && domHelper.isNodeInEditor(element)) {
            return { node: element, offset: 0 };
        }
    }
 
    return null;
}