feat: add touch swipe support for mobile
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useRef, type ReactNode } from 'react';
|
||||
import { useRef, ReactNode } from 'react';
|
||||
|
||||
interface TouchSwipeProps {
|
||||
children: ReactNode;
|
||||
@@ -17,38 +17,23 @@ export function TouchSwipe({
|
||||
threshold = 50,
|
||||
className = '',
|
||||
}: TouchSwipeProps) {
|
||||
const [touchStart, setTouchStart] = useState<number | null>(null);
|
||||
const [touchEnd, setTouchEnd] = useState<number | null>(null);
|
||||
const touchStartX = useRef(0);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const handleTouchStart = (e: React.TouchEvent) => {
|
||||
setTouchEnd(null);
|
||||
const touch = e.targetTouches[0];
|
||||
if (touch) {
|
||||
setTouchStart(touch.clientX);
|
||||
}
|
||||
touchStartX.current = e.touches[0].clientX;
|
||||
};
|
||||
|
||||
const handleTouchMove = (e: React.TouchEvent) => {
|
||||
const touch = e.targetTouches[0];
|
||||
if (touch) {
|
||||
setTouchEnd(touch.clientX);
|
||||
}
|
||||
};
|
||||
const handleTouchEnd = (e: React.TouchEvent) => {
|
||||
const touchEndX = e.changedTouches[0].clientX;
|
||||
const diff = touchStartX.current - touchEndX;
|
||||
|
||||
const handleTouchEnd = () => {
|
||||
if (!touchStart || !touchEnd) {return;}
|
||||
|
||||
const distance = touchStart - touchEnd;
|
||||
const isLeftSwipe = distance > threshold;
|
||||
const isRightSwipe = distance < -threshold;
|
||||
|
||||
if (isLeftSwipe && onSwipeLeft) {
|
||||
onSwipeLeft();
|
||||
}
|
||||
|
||||
if (isRightSwipe && onSwipeRight) {
|
||||
onSwipeRight();
|
||||
if (Math.abs(diff) > threshold) {
|
||||
if (diff > 0 && onSwipeLeft) {
|
||||
onSwipeLeft();
|
||||
} else if (diff < 0 && onSwipeRight) {
|
||||
onSwipeRight();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -57,7 +42,6 @@ export function TouchSwipe({
|
||||
ref={containerRef}
|
||||
className={className}
|
||||
onTouchStart={handleTouchStart}
|
||||
onTouchMove={handleTouchMove}
|
||||
onTouchEnd={handleTouchEnd}
|
||||
>
|
||||
{children}
|
||||
|
||||
Reference in New Issue
Block a user