UNPKG

@vnmfify/core

Version:

```shell npm i @vnmfify/core -S ```

89 lines (82 loc) 2.79 kB
import { useCallback, useEffect, useRef } from "react"; var MIN_DISTANCE = 10; export var TouchDirection; (function (TouchDirection) { TouchDirection["Horizontal"] = "horizontal"; TouchDirection["Vertical"] = "vertical"; })(TouchDirection || (TouchDirection = {})); function getDirection(x, y) { if (x > y && x > MIN_DISTANCE) { return TouchDirection.Horizontal; } if (y > x && y > MIN_DISTANCE) { return TouchDirection.Vertical; } } function emptyFunction() {} export function useTouch() { var touchRef = useRef({ startX: 0, startY: 0, deltaX: 0, deltaY: 0, offsetX: 0, offsetY: 0, isVertical: () => false, isHorizontal: () => false, start: emptyFunction, move: emptyFunction, reset: emptyFunction }); var isVertical = useCallback(() => touchRef.current.direction === TouchDirection.Vertical, []); var isHorizontal = useCallback(() => touchRef.current.direction === TouchDirection.Horizontal, []); var reset = useCallback(function () { touchRef.current.deltaX = 0; touchRef.current.deltaY = 0; touchRef.current.offsetX = 0; touchRef.current.offsetY = 0; touchRef.current.direction = undefined; }, []); var start = useCallback(function (event) { reset(); touchRef.current.startX = event.touches[0].clientX; touchRef.current.startY = event.touches[0].clientY; }, [reset]); var move = useCallback(function (event) { var touch = event.touches[0]; touchRef.current.deltaX = touch.clientX < 0 ? 0 : touch.clientX - touchRef.current.startX; touchRef.current.deltaY = touch.clientY - touchRef.current.startY; touchRef.current.offsetX = Math.abs(touchRef.current.deltaX); touchRef.current.offsetY = Math.abs(touchRef.current.deltaY); if (!touchRef.current.direction) { touchRef.current.direction = getDirection(touchRef.current.offsetX, touchRef.current.offsetY); } }, []); useEffect(() => { if (touchRef.current.isHorizontal !== isHorizontal) { touchRef.current.isHorizontal = isHorizontal; } }, [touchRef, isHorizontal]); useEffect(() => { if (touchRef.current.isVertical !== isVertical) { touchRef.current.isVertical = isVertical; } }, [touchRef, isVertical]); useEffect(() => { if (touchRef.current.reset !== reset) { touchRef.current.reset = reset; } }, [touchRef, reset]); useEffect(() => { if (touchRef.current.start !== start) { touchRef.current.start = start; } }, [touchRef, start]); useEffect(() => { if (touchRef.current.move !== move) { touchRef.current.move = move; } }, [touchRef, move]); return touchRef.current; } //# sourceMappingURL=touch.js.map