UNPKG

@patreon/studio

Version:

Patreon Studio Design System

40 lines 1.63 kB
import { useRef, useEffect, useState } from 'react'; export function useSwipe({ isActive, handleSwipe }) { const ref = useRef(null); const [currentDirection, setCurrentDirection] = useState(null); const [initialCorrdinates, setInitialCoordinates] = useState({ x: 0, y: 0 }); useEffect(() => { const handleStart = (ev) => { const { screenX, screenY } = ev.changedTouches[0]; setInitialCoordinates({ x: screenX, y: screenY }); setCurrentDirection(null); }; const handleEnd = (ev) => { const { screenX, screenY } = ev.changedTouches[0]; const diffX = initialCorrdinates.x - screenX; const diffY = initialCorrdinates.y - screenY; let nextDirection = null; if (Math.abs(diffX) > Math.abs(diffY)) { nextDirection = diffX > 0 ? 'left' : 'right'; } else { nextDirection = diffY > 0 ? 'up' : 'down'; } handleSwipe(ev, nextDirection); setCurrentDirection(nextDirection); }; if (isActive) { document.addEventListener('touchstart', handleStart); document.addEventListener('touchend', handleEnd); return () => { document.removeEventListener('touchstart', handleStart); document.removeEventListener('touchend', handleEnd); }; } return () => { // do nothing }; }, [handleSwipe, initialCorrdinates, isActive]); return { ref, currentDirection }; } //# sourceMappingURL=index.js.map