feat: add touch swipe support for mobile

This commit is contained in:
张翔
2026-02-27 20:29:00 +08:00
parent 1bdb95b5b6
commit aa47a45a95
3 changed files with 112 additions and 106 deletions
+12 -28
View File
@@ -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}