RotNot / src /hooks /use-swipe.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
2.72 kB
/**
* 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 };
}