All files / utils/frontend uiUtils.ts

0% Statements 0/42
100% Branches 1/1
100% Functions 1/1
0% Lines 0/42

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                                                                                                                   
'use client';
 
import {
  useCallback, useEffect, useState
} from 'react';
 
export function isElemInView(elem: HTMLElement) {
  const {
    top, left, bottom, right,
  } = elem.getBoundingClientRect();
  return top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}
 
export function useRefIntersection(): [
  (node: HTMLElement | null) => void,
  boolean | null,
  HTMLElement | null
] {
  const [
    node,
    setNode,
  ] = useState<HTMLElement | null>(null);
 
  const [
    refIntersecting,
    setRefIntersecting,
  ] = useState<boolean | null>(null);
 
  const setRef = useCallback(
    (newNode: HTMLElement | null) => {
      // @TODO - fix this, we want the node to be able to be set to null
      if (newNode !== null && newNode !== node) {
        setRefIntersecting(null);
        setNode(newNode);
      }
    },
    [ node, ]
  );
 
  useEffect(() => {
    if (node === null) {
      return;
    }
 
    const observer = new IntersectionObserver(
      ([ entry, ]) => setRefIntersecting(entry.isIntersecting)
    );
    observer.observe(node);
    return () => observer.disconnect();
  }, [ node, ]);
 
  return [
    setRef,
    refIntersecting,
    node,
  ];
}