Created
April 26, 2023 01:42
-
-
Save AbePlays/e277406edffaa6591fbbe938ddb9f2ab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, type TouchEvent } from 'react' | |
interface SwipeInput { | |
onSwipedLeft: () => void | |
onSwipedRight: () => void | |
} | |
interface SwipeOutput { | |
onTouchStart: (e: TouchEvent) => void | |
onTouchMove: (e: TouchEvent) => void | |
onTouchEnd: () => void | |
} | |
export default function useSwipe(input: SwipeInput): SwipeOutput { | |
const [touchStart, setTouchStart] = useState(0) | |
const [touchEnd, setTouchEnd] = useState(0) | |
const minSwipeDistance = 50 | |
function onTouchStart(e: TouchEvent) { | |
setTouchEnd(0) // otherwise the swipe is fired even with usual touch events | |
setTouchStart(e.targetTouches[0].clientX) | |
} | |
const onTouchMove = (e: TouchEvent) => setTouchEnd(e.targetTouches[0].clientX) | |
function onTouchEnd() { | |
if (!touchStart || !touchEnd) return | |
const distance = touchStart - touchEnd | |
const isLeftSwipe = distance > minSwipeDistance | |
const isRightSwipe = distance < -minSwipeDistance | |
if (isLeftSwipe) { | |
input.onSwipedLeft() | |
} | |
if (isRightSwipe) { | |
input.onSwipedRight() | |
} | |
} | |
return { | |
onTouchStart, | |
onTouchMove, | |
onTouchEnd, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment