ente/src/utils/common/useLongPress.ts

28 lines
823 B
TypeScript
Raw Normal View History

2021-03-20 14:58:12 +00:00
// https://stackoverflow.com/a/54749871/2760968
2021-05-29 06:27:52 +00:00
import {useState, useEffect} from 'react';
2021-03-20 14:58:12 +00:00
export default function useLongPress(callback: () => void, ms = 300) {
const [startLongPress, setStartLongPress] = useState(false);
useEffect(() => {
let timerId: NodeJS.Timeout;
if (startLongPress) {
2021-05-29 06:27:52 +00:00
timerId = setTimeout(callback, ms);
2021-03-20 14:58:12 +00:00
} else {
2021-05-29 06:27:52 +00:00
clearTimeout(timerId);
2021-03-20 14:58:12 +00:00
}
return () => {
2021-05-29 06:27:52 +00:00
clearTimeout(timerId);
2021-03-20 14:58:12 +00:00
};
}, [callback, ms, startLongPress]);
return {
onMouseDown: () => setStartLongPress(true),
onMouseUp: () => setStartLongPress(false),
onMouseLeave: () => setStartLongPress(false),
onTouchStart: () => setStartLongPress(true),
onTouchEnd: () => setStartLongPress(false),
};
2021-05-29 06:27:52 +00:00
}