47 lines
1.1 KiB
JavaScript
47 lines
1.1 KiB
JavaScript
import { useState, useEffect } from 'react';
|
|
|
|
const useLongTap = (onLongTap, duration = 500) => {
|
|
const [isPressing, setIsPressing] = useState(false);
|
|
const [startTime, setStartTime] = useState(null);
|
|
|
|
useEffect(() => {
|
|
if (isPressing && startTime) {
|
|
const elapsedTime = performance.now() - startTime;
|
|
if (elapsedTime >= duration) {
|
|
onLongTap();
|
|
setIsPressing(false);
|
|
setStartTime(null);
|
|
}
|
|
}
|
|
}, [isPressing, startTime, onLongTap, duration]);
|
|
|
|
const handlePointerDown = (event) => {
|
|
setIsPressing(true);
|
|
setStartTime(performance.now());
|
|
};
|
|
|
|
const handlePointerUp = () => {
|
|
setIsPressing(false);
|
|
setStartTime(null);
|
|
};
|
|
|
|
const handlePointerCancel = () => {
|
|
setIsPressing(false);
|
|
setStartTime(null);
|
|
};
|
|
|
|
const handlePointerOut = () => {
|
|
setIsPressing(false);
|
|
setStartTime(null);
|
|
};
|
|
|
|
return {
|
|
onPointerDown: handlePointerDown,
|
|
onPointerUp: handlePointerUp,
|
|
onPointerCancel: handlePointerCancel,
|
|
onPointerOut: handlePointerOut,
|
|
};
|
|
};
|
|
|
|
export { useLongTap };
|