All files / src/hooks useLongPress.ts

0% Statements 0/36
0% Branches 0/1
0% Functions 0/1
0% Lines 0/36

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                                                                                             
import { useCallback, useRef } from 'react';
 
interface LongPressOptions {
  onLongPress: (e: React.TouchEvent | React.MouseEvent) => void;
  onClick?: () => void;
  delay?: number;
}
 
export function useLongPress({ onLongPress, onClick, delay = 500 }: LongPressOptions) {
  const timeoutRef = useRef<number | null>(null);
  const targetRef = useRef<EventTarget | null>(null);
  const longPressTriggered = useRef(false);
 
  const start = useCallback(
    (e: React.TouchEvent | React.MouseEvent) => {
      longPressTriggered.current = false;
      targetRef.current = e.target;
      timeoutRef.current = window.setTimeout(() => {
        longPressTriggered.current = true;
        onLongPress(e);
      }, delay);
    },
    [onLongPress, delay]
  );
 
  const clear = useCallback(
    (e: React.TouchEvent | React.MouseEvent, shouldTriggerClick = true) => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }
      if (shouldTriggerClick && !longPressTriggered.current && onClick && targetRef.current === e.target) {
        onClick();
      }
    },
    [onClick]
  );
 
  return {
    onMouseDown: start,
    onMouseUp: (e: React.MouseEvent) => clear(e, true),
    onMouseLeave: (e: React.MouseEvent) => clear(e, false),
    onTouchStart: start,
    onTouchEnd: (e: React.TouchEvent) => clear(e, true),
  };
}