(
onLongPress: () => void,
{ disabled = false } = {}
)
| 4 | const LONG_PRESS_ALLOWED_MOVE_THRESHOLD = 10; |
| 5 | |
| 6 | export function useLongPress( |
| 7 | onLongPress: () => void, |
| 8 | { disabled = false } = {} |
| 9 | ) { |
| 10 | const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null); |
| 11 | const startX = useRef(0); |
| 12 | const startY = useRef(0); |
| 13 | const moved = useRef(false); |
| 14 | |
| 15 | const start = useCallback( |
| 16 | (e: React.TouchEvent<HTMLElement>) => { |
| 17 | if (disabled) return; |
| 18 | const touch = e.touches[0]; |
| 19 | startX.current = touch.clientX; |
| 20 | startY.current = touch.clientY; |
| 21 | moved.current = false; |
| 22 | |
| 23 | timeoutRef.current = setTimeout(() => { |
| 24 | if (!moved.current) { |
| 25 | onLongPress(); |
| 26 | } |
| 27 | }, LONG_PRESS_DELAY); |
| 28 | }, |
| 29 | [onLongPress, disabled] |
| 30 | ); |
| 31 | |
| 32 | const clear = useCallback(() => { |
| 33 | if (timeoutRef.current) { |
| 34 | clearTimeout(timeoutRef.current); |
| 35 | timeoutRef.current = null; |
| 36 | } |
| 37 | }, []); |
| 38 | |
| 39 | const move = useCallback( |
| 40 | (e: React.TouchEvent<HTMLElement>) => { |
| 41 | const touch = e.touches[0]; |
| 42 | const dx = Math.abs(touch.clientX - startX.current); |
| 43 | const dy = Math.abs(touch.clientY - startY.current); |
| 44 | if ( |
| 45 | dx > LONG_PRESS_ALLOWED_MOVE_THRESHOLD || |
| 46 | dy > LONG_PRESS_ALLOWED_MOVE_THRESHOLD |
| 47 | ) { |
| 48 | moved.current = true; |
| 49 | clear(); |
| 50 | } |
| 51 | }, |
| 52 | [clear] |
| 53 | ); |
| 54 | |
| 55 | return { |
| 56 | onTouchStart: start, |
| 57 | onTouchMove: move, |
| 58 | onTouchEnd: clear, |
| 59 | onTouchCancel: clear, |
| 60 | onMouseLeave: clear, |
| 61 | }; |
| 62 | } |
no test coverage detected