All files / roosterjs-content-model-core/lib/coreApi/getVisibleViewport getVisibleViewport.ts

100% Statements 15/15
75% Branches 6/8
100% Functions 8/8
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 591x               1x 55x   55x                                                               110x 55x 56x   56x   55x 56x 56x 56x 56x     55x    
import { normalizeRect } from 'roosterjs-content-model-dom';
import type { GetVisibleViewport, Rect } from 'roosterjs-content-model-types';
 
/**
 * @internal
 * Retrieves the rect of the visible viewport of the editor.
 * @param core The EditorCore object
 */
export const getVisibleViewport: GetVisibleViewport = core => {
    const scrollContainer = core.domEvent.scrollContainer;
 
    return getIntersectedRect(
        scrollContainer == core.physicalRoot
            ? [scrollContainer]
            : [scrollContainer, core.physicalRoot]
    );
};
 
/**
 * Get the intersected Rect of elements provided
 *
 * @example
 * The result of the following Elements Rects would be:
    {
        top: Element2.top,
        bottom: Element1.bottom,
        left: Element2.left,
        right: Element2.right
    }
    +-------------------------+
    | Element 1               |
    |   +-----------------+   |
    |   | Element2        |   |
    |   |                 |   |
    |   |                 |   |
    +-------------------------+
        |                 |
        +-----------------+
 
 * @param elements Elements to use.
 * @param additionalRects additional rects to use
 * @returns If the Rect is valid return the rect, if not, return null.
 */
function getIntersectedRect(elements: HTMLElement[], EadditionalRects: Rect[] = []): Rect | null {
    const rects = elements
        .map(element => normalizeRect(element.getBoundingClientRect()))
        .concat(additionalRects)
        .filter((rect: Rect | null): rect is Rect => !!rect);
 
    const result: Rect = {
        top: Math.max(...rects.map(r => r.top)),
        bottom: Math.min(...rects.map(r => r.bottom)),
        left: Math.max(...rects.map(r => r.left)),
        right: Math.min(...rects.map(r => r.right)),
    };
 
    return result.top < result.bottom && result.left < result.right ? result : null;
}