All files / src/support/dom offset.ts

100% Statements 6/6
100% Branches 6/6
100% Functions 2/2
100% Lines 6/6

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              7x                 7x 8x 8x                       7x 2x            
import { getBoundingClientRect } from 'support/dom/dimensions';
 
export interface XY<T = number> {
  x: T;
  y: T;
}
 
const zeroObj: XY = {
  x: 0,
  y: 0,
};
 
/**
 * Returns the offset- left and top coordinates of the passed element relative to the document. If the element is null the top and left values are 0.
 * @param elm The element of which the offset- top and left coordinates shall be returned.
 */
export const absoluteCoordinates = (elm: HTMLElement | null | undefined): XY => {
  const rect = elm ? getBoundingClientRect(elm) : 0;
  return rect
    ? {
        x: rect.left + window.pageYOffset,
        y: rect.top + window.pageXOffset,
      }
    : zeroObj;
};
 
/**
 * Returns the offset- left and top coordinates of the passed element. If the element is null the top and left values are 0.
 * @param elm The element of which the offset- top and left coordinates shall be returned.
 */
export const offsetCoordinates = (elm: HTMLElement | null | undefined): XY =>
  elm
    ? {
        x: elm.offsetLeft,
        y: elm.offsetTop,
      }
    : zeroObj;