All files / src/affix util.ts

23.53% Statements 4/17
10.53% Branches 2/19
50% Functions 3/6
23.53% Lines 4/17

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        2x                                                                           2x 2x 2x              
import { AffixProps, AffixTargetType } from "./AffixProps";
import { injectValue } from "../_util/inject-value";
 
export function getTarget(target: AffixProps["target"]) {
  return injectValue<[], AffixTargetType>(target)() || window;
}
 
export function getRect(target: AffixTargetType): ClientRect {
  if (target && target !== window) {
    return (target as HTMLElement).getBoundingClientRect();
  }
  return {
    top: 0,
    bottom: window.innerHeight,
    left: 0,
    right: window.innerWidth,
    width: window.innerWidth,
    height: window.innerHeight,
  };
}
 
export function getFixed(
  target: AffixProps["target"],
  placeholder: HTMLDivElement,
  offset: number,
  isTop: boolean = true
): number {
  if (typeof offset === "undefined") {
    return undefined;
  }
  const targetElement = getRect(getTarget(target));
  if (isTop && targetElement.top > getRect(placeholder).top - offset) {
    return offset + targetElement.top;
  }
  if (!isTop && targetElement.bottom < getRect(placeholder).bottom + offset) {
    return offset + window.innerHeight - targetElement.bottom;
  }
  return undefined;
}
 
export function throttle(fn: Function) {
  let rafId;
  return (...args) => {
    Eif (!rafId) {
      rafId = requestAnimationFrame(() => {
        rafId = null;
        fn(...args);
      });
    }
  };
}