All files / src/helpers size.js

92% Statements 23/25
90% Branches 9/10
100% Functions 5/5
95.45% Lines 21/22

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                21x 8x   8x 8x   8x 2x 1x             2x 2x 4x   2x 2x     6x 6x 6x     6x   6x   6x 2x   1x 1x      
import { debounce } from "../utils";
 
/**
 * Call back a provided function
 * whenever element changed it's size
 * @param {HTMLElement} element
 * @param {Function} cb
 */
export const watchElementSize = (element, cb) => {
  Iif (!window || typeof window !== "object") return
 
  const delayedCallback = debounce(cb, 150);
  let cancelled = false;
 
  if (window.ResizeObserver) {
    const resizeObserver = new ResizeObserver(entries => {
      for (const entry of entries) {
        delayedCallback({
          width: entry.contentRect.width,
          height: entry.contentRect.height
        });
      }
    });
    resizeObserver.observe(element);
    return () => {
      if (cancelled) return;
 
      cancelled = true;
      resizeObserver.disconnect();
    };
  } else {
    const handleWindowResize = () => {
      const rect = element.getBoundingClientRect();
      delayedCallback({ width: rect.width, height: rect.height });
    };
 
    window.addEventListener("resize", handleWindowResize);
 
    handleWindowResize();
 
    return () => {
      if (cancelled)  return;
 
      cancelled = true;
      window.removeEventListener("resize", handleWindowResize);
    };
  }
}