All files / app/hooks use-modifier-key.ts

0% Statements 0/26
0% Branches 0/13
0% Functions 0/7
0% Lines 0/24

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                                                                                           
import { useCallback, useEffect, useState } from 'react';
 
let timer = 0;
 
export function useModifierKey(key: 'alt' | 'control', delay = 0) {
  const [isPressed, setIsPressed] = useState(false);
 
  const keydownFn = useCallback(
    event => {
      Iif (key === 'alt' && event.altKey) {
        timer = window.setTimeout(() => setIsPressed(true), delay);
      }
      Iif (key === 'control' && event.ctrlKey) {
        timer = window.setTimeout(() => setIsPressed(true), delay);
      }
    },
    [delay, key]
  );
 
  const keyupFn = useCallback(
    event => {
      Iif (key === 'alt' && !event.altKey) {
        clearTimeout(timer);
        setIsPressed(false);
      }
      Iif (key === 'control' && !event.ctrlKey) {
        clearTimeout(timer);
        setIsPressed(false);
      }
    },
    [key]
  );
 
  useEffect(() => {
    document.addEventListener('keydown', keydownFn);
    document.addEventListener('keyup', keyupFn);
    return () => {
      clearTimeout(timer);
      document.removeEventListener('keydown', keydownFn);
      document.removeEventListener('keyupFn', keyupFn);
    };
  }, [keydownFn, keyupFn]);
 
  return { isPressed };
}