This commit is contained in:
2025-11-02 22:25:00 +01:00
parent 74aacbc1eb
commit 626b6c16e0
3 changed files with 311 additions and 0 deletions
+73
View File
@@ -0,0 +1,73 @@
import { useCallback, useEffect, useRef } from 'react';
const defaultFilter = (event) => {
if (!event) {
return false;
}
const { type, button, pointerType, isPrimary } = event;
const isPointerUp = type === 'pointerup';
const buttonValid =
button == null || button === 0 || (isPointerUp && (button === -1 || button === 0));
if (!buttonValid) {
return false;
}
if (pointerType === 'touch' && isPrimary === false) {
return false;
}
return true;
};
const usePointerTap = ({
onSingle,
onDouble,
delay = 240,
filter = defaultFilter,
} = {}) => {
const timerRef = useRef(null);
useEffect(() => () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
}, []);
return useCallback(
(event, metadata = undefined) => {
if (!filter(event)) {
return;
}
if (typeof event.persist === 'function') {
event.persist();
}
const context = {
clientX: event.clientX,
clientY: event.clientY,
pointerType: event.pointerType,
event,
data: metadata,
};
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
if (typeof onDouble === 'function') {
onDouble(context);
}
return;
}
timerRef.current = setTimeout(() => {
timerRef.current = null;
if (typeof onSingle === 'function') {
onSingle(context);
}
}, delay);
},
[delay, filter, onDouble, onSingle],
);
};
export default usePointerTap;