51 lines
1.0 KiB
TypeScript
51 lines
1.0 KiB
TypeScript
'use client';
|
|
|
|
import { useRef, ReactNode } from 'react';
|
|
|
|
interface TouchSwipeProps {
|
|
children: ReactNode;
|
|
onSwipeLeft?: () => void;
|
|
onSwipeRight?: () => void;
|
|
threshold?: number;
|
|
className?: string;
|
|
}
|
|
|
|
export function TouchSwipe({
|
|
children,
|
|
onSwipeLeft,
|
|
onSwipeRight,
|
|
threshold = 50,
|
|
className = '',
|
|
}: TouchSwipeProps) {
|
|
const touchStartX = useRef(0);
|
|
const containerRef = useRef<HTMLDivElement>(null);
|
|
|
|
const handleTouchStart = (e: React.TouchEvent) => {
|
|
touchStartX.current = e.touches[0].clientX;
|
|
};
|
|
|
|
const handleTouchEnd = (e: React.TouchEvent) => {
|
|
const touchEndX = e.changedTouches[0].clientX;
|
|
const diff = touchStartX.current - touchEndX;
|
|
|
|
if (Math.abs(diff) > threshold) {
|
|
if (diff > 0 && onSwipeLeft) {
|
|
onSwipeLeft();
|
|
} else if (diff < 0 && onSwipeRight) {
|
|
onSwipeRight();
|
|
}
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div
|
|
ref={containerRef}
|
|
className={className}
|
|
onTouchStart={handleTouchStart}
|
|
onTouchEnd={handleTouchEnd}
|
|
>
|
|
{children}
|
|
</div>
|
|
);
|
|
}
|