All files / src/pages/flowsheet-page/flowsheet/Canvas DebounceHoverObject.tsx

100% Statements 14/14
100% Branches 4/4
100% Functions 4/4
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          33x   33x       27215x 27215x   27215x 527x 310x     527x 525x 13x             512x       527x 389x 389x              
import { SimulationObject, SimulationObjectRead } from "@/api/apiStore.gen";
import { useAppDispatch } from "@/store/hooks";
import { clearHoveredObject, setHoveredObject } from "@/store/ObjectHoverSlice";
import { useEffect, useRef } from "react";
 
const DEBOUNCE_DELAY = 10;
 
const useHoverDebounce = (
  isHovered: boolean,
  simulationObject: SimulationObjectRead,
) => {
  const dispatch = useAppDispatch();
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
 
  useEffect(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
 
    timeoutRef.current = setTimeout(() => {
      if (isHovered) {
        dispatch(
          setHoveredObject({
            simulationObject,
            state: true,
          }),
        );
      } else {
        dispatch(clearHoveredObject());
      }
    }, DEBOUNCE_DELAY);
 
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current); // Clear timer on component unmount
      }
    };
  }, [isHovered, simulationObject, dispatch]);
};
 
export default useHoverDebounce;