File size: 2,716 Bytes
9580dce | 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | /**
* useSwipe β detects horizontal swipe gestures via touch events.
*
* Returns handlers to spread onto the target element.
* Only fires when the swipe is primarily horizontal (deltaX > deltaY Γ ratio)
* and exceeds the threshold, so vertical scrolling is not disrupted.
*
* The core detection logic is exported as `detectSwipe` for unit testing.
*/
import { useCallback, useRef } from "react";
// βββ Pure detection logic (testable without DOM) ββββββββββββββββββββββββββββ
export interface SwipePoint {
x: number;
y: number;
}
export type SwipeDirection = "left" | "right" | null;
export interface DetectSwipeOptions {
threshold?: number;
maxVerticalRatio?: number;
}
/**
* Determine the swipe direction from start to end points.
* Returns null if the gesture does not qualify as a swipe.
*/
export function detectSwipe(
start: SwipePoint,
end: SwipePoint,
{ threshold = 60, maxVerticalRatio = 0.5 }: DetectSwipeOptions = {}
): SwipeDirection {
const deltaX = end.x - start.x;
const deltaY = end.y - start.y;
const absDX = Math.abs(deltaX);
const absDY = Math.abs(deltaY);
if (absDX < threshold) return null;
if (absDY / absDX > maxVerticalRatio) return null;
return deltaX < 0 ? "left" : "right";
}
// βββ React hook βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export interface SwipeHandlers {
onTouchStart: (e: React.TouchEvent) => void;
onTouchEnd: (e: React.TouchEvent) => void;
}
export interface UseSwipeOptions extends DetectSwipeOptions {
onSwipeLeft?: () => void;
onSwipeRight?: () => void;
}
export function useSwipe({
threshold = 60,
maxVerticalRatio = 0.5,
onSwipeLeft,
onSwipeRight,
}: UseSwipeOptions = {}): SwipeHandlers {
const startPoint = useRef<SwipePoint | null>(null);
const onTouchStart = useCallback((e: React.TouchEvent) => {
const t = e.changedTouches[0];
startPoint.current = { x: t.clientX, y: t.clientY };
}, []);
const onTouchEnd = useCallback(
(e: React.TouchEvent) => {
if (!startPoint.current) return;
const t = e.changedTouches[0];
const end: SwipePoint = { x: t.clientX, y: t.clientY };
const direction = detectSwipe(startPoint.current, end, {
threshold,
maxVerticalRatio,
});
startPoint.current = null;
if (direction === "left") onSwipeLeft?.();
else if (direction === "right") onSwipeRight?.();
},
[threshold, maxVerticalRatio, onSwipeLeft, onSwipeRight]
);
return { onTouchStart, onTouchEnd };
}
|