forked from pu428f3pz/InternshipProject
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
2.0 KiB
71 lines
2.0 KiB
import * as React from 'react';
|
|
import { useRef } from 'react';
|
|
var SMOOTH_PTG = 14 / 15;
|
|
export default function useMobileTouchMove(inVirtual, listRef, callback) {
|
|
var touchedRef = useRef(false);
|
|
var touchYRef = useRef(0);
|
|
var elementRef = useRef(null); // Smooth scroll
|
|
|
|
var intervalRef = useRef(null);
|
|
/* eslint-disable prefer-const */
|
|
|
|
var cleanUpEvents;
|
|
|
|
var onTouchMove = function onTouchMove(e) {
|
|
if (touchedRef.current) {
|
|
var currentY = Math.ceil(e.touches[0].pageY);
|
|
var offsetY = touchYRef.current - currentY;
|
|
touchYRef.current = currentY;
|
|
|
|
if (callback(offsetY)) {
|
|
e.preventDefault();
|
|
} // Smooth interval
|
|
|
|
|
|
clearInterval(intervalRef.current);
|
|
intervalRef.current = setInterval(function () {
|
|
offsetY *= SMOOTH_PTG;
|
|
|
|
if (!callback(offsetY, true) || Math.abs(offsetY) <= 0.1) {
|
|
clearInterval(intervalRef.current);
|
|
}
|
|
}, 16);
|
|
}
|
|
};
|
|
|
|
var onTouchEnd = function onTouchEnd() {
|
|
touchedRef.current = false;
|
|
cleanUpEvents();
|
|
};
|
|
|
|
var onTouchStart = function onTouchStart(e) {
|
|
cleanUpEvents();
|
|
|
|
if (e.touches.length === 1 && !touchedRef.current) {
|
|
touchedRef.current = true;
|
|
touchYRef.current = Math.ceil(e.touches[0].pageY);
|
|
elementRef.current = e.target;
|
|
elementRef.current.addEventListener('touchmove', onTouchMove);
|
|
elementRef.current.addEventListener('touchend', onTouchEnd);
|
|
}
|
|
};
|
|
|
|
cleanUpEvents = function cleanUpEvents() {
|
|
if (elementRef.current) {
|
|
elementRef.current.removeEventListener('touchmove', onTouchMove);
|
|
elementRef.current.removeEventListener('touchend', onTouchEnd);
|
|
}
|
|
};
|
|
|
|
React.useLayoutEffect(function () {
|
|
if (inVirtual) {
|
|
listRef.current.addEventListener('touchstart', onTouchStart);
|
|
}
|
|
|
|
return function () {
|
|
listRef.current.removeEventListener('touchstart', onTouchStart);
|
|
cleanUpEvents();
|
|
clearInterval(intervalRef.current);
|
|
};
|
|
}, [inVirtual]);
|
|
} |