mirror of
https://github.com/outline/outline.git
synced 2026-11-25 23:24:06 +03:00
* fix: swipe * fix: noTouchEnd not needed * Revert "fix: noTouchEnd not needed" This reverts commitcda9a0e49b. * Revert "fix: swipe" This reverts commitc05a50be2c. * fix: fire upon single swipe detection * chore: `useSwipe`
77 lines
1.9 KiB
TypeScript
77 lines
1.9 KiB
TypeScript
import { isNumber } from "lodash";
|
|
import { useRef } from "react";
|
|
|
|
type Props = {
|
|
onSwipeRight: () => void;
|
|
onSwipeLeft: () => void;
|
|
onSwipeUp: () => void;
|
|
onSwipeDown: () => void;
|
|
};
|
|
|
|
export default function useSwipe({
|
|
onSwipeRight,
|
|
onSwipeLeft,
|
|
onSwipeUp,
|
|
onSwipeDown,
|
|
}: Props) {
|
|
const touchXStart = useRef<number>();
|
|
const touchXEnd = useRef<number>();
|
|
const touchYStart = useRef<number>();
|
|
const touchYEnd = useRef<number>();
|
|
|
|
const resetTouchPoints = () => {
|
|
touchXStart.current = undefined;
|
|
touchXEnd.current = undefined;
|
|
touchYStart.current = undefined;
|
|
touchYEnd.current = undefined;
|
|
};
|
|
|
|
const onTouchStart = (e: React.TouchEvent<HTMLImageElement>) => {
|
|
touchXStart.current = e.changedTouches[0].screenX;
|
|
touchYStart.current = e.changedTouches[0].screenY;
|
|
};
|
|
|
|
const onTouchMove = (e: React.TouchEvent<HTMLImageElement>) => {
|
|
if (isNumber(touchXStart.current) && isNumber(touchYStart.current)) {
|
|
touchXEnd.current = e.changedTouches[0].screenX;
|
|
touchYEnd.current = e.changedTouches[0].screenY;
|
|
const dx = touchXEnd.current - touchXStart.current;
|
|
const dy = touchYEnd.current - touchYStart.current;
|
|
|
|
const swipeRight = dx > 0 && Math.abs(dy) < Math.abs(dx);
|
|
if (swipeRight) {
|
|
resetTouchPoints();
|
|
return onSwipeRight();
|
|
}
|
|
|
|
const swipeLeft = dx < 0 && Math.abs(dy) < Math.abs(dx);
|
|
if (swipeLeft) {
|
|
resetTouchPoints();
|
|
return onSwipeLeft();
|
|
}
|
|
|
|
const swipeDown = dy > 0 && Math.abs(dy) > Math.abs(dx);
|
|
if (swipeDown) {
|
|
resetTouchPoints();
|
|
return onSwipeDown();
|
|
}
|
|
|
|
const swipeUp = dy < 0 && Math.abs(dy) > Math.abs(dx);
|
|
if (swipeUp) {
|
|
resetTouchPoints();
|
|
return onSwipeUp();
|
|
}
|
|
}
|
|
};
|
|
|
|
const onTouchCancel = () => {
|
|
resetTouchPoints();
|
|
};
|
|
|
|
return {
|
|
onTouchStart,
|
|
onTouchMove,
|
|
onTouchCancel,
|
|
};
|
|
}
|