beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
49 lines (48 loc) • 2.01 kB
JavaScript
import { useCallback, useState } from 'react';
import useMouseEvents from './useMouseEvents';
import useConditionalTimeout from './useConditionalTimeout';
import createHandlerSetter from './factory/createHandlerSetter';
import useTouchEvents from './useTouchEvents';
/**
* A hook that facilitates the implementation of the long press functionality on a given target, supporting both mouse and touch events.
*/
const useLongPress = (target, duration = 500) => {
const { onMouseDown, onMouseUp, onMouseLeave } = useMouseEvents(target, false);
const { onTouchStart, onTouchEnd } = useTouchEvents(target, false);
const [isLongPressing, setIsLongPressing] = useState(false);
const [timerOn, startTimer] = useState(false);
const [onLongPressStart, setOnLongPressStart] = createHandlerSetter();
const [onLongPressEnd, setOnLongPressEnd] = createHandlerSetter();
const longPressStart = useCallback((event) => {
event.preventDefault();
startTimer(true);
}, []);
const longPressStop = useCallback((event) => {
if (!isLongPressing)
return;
clearTimeout();
setIsLongPressing(false);
startTimer(false);
event.preventDefault();
if (onLongPressEnd === null || onLongPressEnd === void 0 ? void 0 : onLongPressEnd.current) {
onLongPressEnd.current();
}
}, [isLongPressing]);
const [, clearTimeout] = useConditionalTimeout(() => {
setIsLongPressing(true);
if (onLongPressStart === null || onLongPressStart === void 0 ? void 0 : onLongPressStart.current) {
onLongPressStart.current();
}
}, duration, timerOn);
onMouseDown(longPressStart);
onMouseLeave(longPressStop);
onMouseUp(longPressStop);
onTouchStart(longPressStart);
onTouchEnd(longPressStop);
return Object.freeze({
isLongPressing,
onLongPressStart: setOnLongPressStart,
onLongPressEnd: setOnLongPressEnd
});
};
export default useLongPress;