(options: TouchGestureOptions = {})
| 26 | } |
| 27 | |
| 28 | export function useTouchGesture(options: TouchGestureOptions = {}): TouchGestureHandlers { |
| 29 | const { |
| 30 | threshold = 50, |
| 31 | velocityThreshold = 0.2, |
| 32 | onSwipe, |
| 33 | onSwipeLeft, |
| 34 | onSwipeRight, |
| 35 | onSwipeUp, |
| 36 | onSwipeDown, |
| 37 | onLongPress, |
| 38 | longPressDelay = 500, |
| 39 | } = options; |
| 40 | |
| 41 | const startRef = useRef<{ x: number; y: number; time: number } | null>(null); |
| 42 | const longPressTimer = useRef<ReturnType<typeof setTimeout> | null>(null); |
| 43 | const hasMoved = useRef(false); |
| 44 | |
| 45 | const onTouchStart = useCallback( |
| 46 | (e: React.TouchEvent) => { |
| 47 | const touch = e.touches[0]; |
| 48 | startRef.current = { x: touch.clientX, y: touch.clientY, time: Date.now() }; |
| 49 | hasMoved.current = false; |
| 50 | |
| 51 | if (onLongPress) { |
| 52 | longPressTimer.current = setTimeout(() => { |
| 53 | if (!hasMoved.current) onLongPress(); |
| 54 | }, longPressDelay); |
| 55 | } |
| 56 | }, |
| 57 | [onLongPress, longPressDelay] |
| 58 | ); |
| 59 | |
| 60 | const onTouchMove = useCallback((_e: React.TouchEvent) => { |
| 61 | hasMoved.current = true; |
| 62 | if (longPressTimer.current) { |
| 63 | clearTimeout(longPressTimer.current); |
| 64 | longPressTimer.current = null; |
| 65 | } |
| 66 | }, []); |
| 67 | |
| 68 | const onTouchEnd = useCallback( |
| 69 | (e: React.TouchEvent) => { |
| 70 | if (longPressTimer.current) { |
| 71 | clearTimeout(longPressTimer.current); |
| 72 | longPressTimer.current = null; |
| 73 | } |
| 74 | |
| 75 | if (!startRef.current) return; |
| 76 | |
| 77 | const touch = e.changedTouches[0]; |
| 78 | const dx = touch.clientX - startRef.current.x; |
| 79 | const dy = touch.clientY - startRef.current.y; |
| 80 | const dt = Date.now() - startRef.current.time; |
| 81 | startRef.current = null; |
| 82 | |
| 83 | if (dt === 0) return; |
| 84 | const velocity = Math.sqrt(dx * dx + dy * dy) / dt; |
| 85 |
no outgoing calls
no test coverage detected