All files / react-app/src/hooks/useIdle index.ts

95.23% Statements 20/21
50% Branches 1/2
88.88% Functions 8/9
94.73% Lines 18/19

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        73x             73x                       25x 25x 25x     25x 11x 3x       25x 11x 7x   7x 7x     7x         55x   11x 55x       25x    
// credit: https://github.com/mantinedev/mantine/blob/master/packages/@mantine/hooks/src/use-idle/use-idle.ts
 
import { useEffect, useRef, useState } from "react";
 
const DEFAULT_EVENTS: (keyof DocumentEventMap)[] = [
  "keypress",
  "mousemove",
  "touchmove",
  "click",
  "scroll",
];
const DEFAULT_OPTIONS = {
  events: DEFAULT_EVENTS,
  initialState: true,
};
 
export function useIdle(
  timeout: number,
  options?: Partial<{
    events: (keyof DocumentEventMap)[];
    initialState: boolean;
  }>,
) {
  const { events, initialState } = { ...DEFAULT_OPTIONS, ...options };
  const [idle, setIdle] = useState<boolean>(initialState);
  const timer = useRef<number>();
 
  // start tracking idleness on useIdle mount
  useEffect(() => {
    timer.current = window.setTimeout(() => {
      setIdle(true);
    }, timeout);
  }, [timeout, events]);
 
  useEffect(() => {
    const handleEvents = () => {
      setIdle(false);
 
      Eif (timer.current) {
        window.clearTimeout(timer.current);
      }
 
      timer.current = window.setTimeout(() => {
        setIdle(true);
      }, timeout);
    };
 
    events.forEach((event) => document.addEventListener(event, handleEvents));
 
    return () => {
      events.forEach((event) => document.removeEventListener(event, handleEvents));
    };
  }, [timeout]);
 
  return idle;
}