| 25 | * one-swipe delete. |
| 26 | */ |
| 27 | export function SwipeableRow({ |
| 28 | children, |
| 29 | leftActions = [], |
| 30 | rightActions = [], |
| 31 | className, |
| 32 | actionWidth = 72, |
| 33 | }: SwipeableRowProps) { |
| 34 | const [translateX, setTranslateX] = useState(0); |
| 35 | const [isDragging, setIsDragging] = useState(false); |
| 36 | const startXRef = useRef<number | null>(null); |
| 37 | const currentXRef = useRef(0); |
| 38 | |
| 39 | const maxLeft = leftActions.length * actionWidth; |
| 40 | const maxRight = rightActions.length * actionWidth; |
| 41 | |
| 42 | const handleTouchStart = useCallback((e: React.TouchEvent) => { |
| 43 | startXRef.current = e.touches[0].clientX; |
| 44 | setIsDragging(true); |
| 45 | }, []); |
| 46 | |
| 47 | const handleTouchMove = useCallback( |
| 48 | (e: React.TouchEvent) => { |
| 49 | if (startXRef.current === null) return; |
| 50 | const dx = e.touches[0].clientX - startXRef.current + currentXRef.current; |
| 51 | const clamped = Math.max(-maxRight, Math.min(maxLeft, dx)); |
| 52 | setTranslateX(clamped); |
| 53 | }, |
| 54 | [maxLeft, maxRight] |
| 55 | ); |
| 56 | |
| 57 | const handleTouchEnd = useCallback(() => { |
| 58 | setIsDragging(false); |
| 59 | startXRef.current = null; |
| 60 | |
| 61 | // Snap: if dragged > half an action width, show actions; otherwise reset |
| 62 | if (translateX < -(actionWidth / 2) && maxRight > 0) { |
| 63 | const snapped = -maxRight; |
| 64 | setTranslateX(snapped); |
| 65 | currentXRef.current = snapped; |
| 66 | } else if (translateX > actionWidth / 2 && maxLeft > 0) { |
| 67 | const snapped = maxLeft; |
| 68 | setTranslateX(snapped); |
| 69 | currentXRef.current = snapped; |
| 70 | } else { |
| 71 | setTranslateX(0); |
| 72 | currentXRef.current = 0; |
| 73 | } |
| 74 | }, [translateX, actionWidth, maxLeft, maxRight]); |
| 75 | |
| 76 | const resetPosition = useCallback(() => { |
| 77 | setTranslateX(0); |
| 78 | currentXRef.current = 0; |
| 79 | }, []); |
| 80 | |
| 81 | return ( |
| 82 | <div className={cn("relative overflow-hidden", className)}> |
| 83 | {/* Left action buttons (revealed on swipe-right) */} |
| 84 | {leftActions.length > 0 && ( |