feat: add mobile optimization with hooks and touch components

This commit is contained in:
张翔
2026-02-13 14:46:21 +08:00
parent e829451fa3
commit 7914decdaf
7 changed files with 396 additions and 0 deletions
+60
View File
@@ -0,0 +1,60 @@
'use client';
import { useState, useRef, useEffect, type 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 [touchStart, setTouchStart] = useState<number | null>(null);
const [touchEnd, setTouchEnd] = useState<number | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
const handleTouchStart = (e: React.TouchEvent) => {
setTouchEnd(null);
setTouchStart(e.targetTouches[0].clientX);
};
const handleTouchMove = (e: React.TouchEvent) => {
setTouchEnd(e.targetTouches[0].clientX);
};
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();
}
};
return (
<div
ref={containerRef}
className={className}
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
>
{children}
</div>
);
}