ente/web/packages/shared/hooks/useLongPress.ts
2024-03-01 12:21:07 +05:30

28 lines
825 B
TypeScript

// https://stackoverflow.com/a/54749871/2760968
import { useEffect, useState } from "react";
export default function useLongPress(callback: () => void, ms = 300) {
const [startLongPress, setStartLongPress] = useState(false);
useEffect(() => {
let timerId: NodeJS.Timeout;
if (startLongPress) {
timerId = setTimeout(callback, ms);
} else {
clearTimeout(timerId);
}
return () => {
clearTimeout(timerId);
};
}, [callback, ms, startLongPress]);
return {
onMouseDown: () => setStartLongPress(true),
onMouseUp: () => setStartLongPress(false),
onMouseLeave: () => setStartLongPress(false),
onTouchStart: () => setStartLongPress(true),
onTouchEnd: () => setStartLongPress(false),
};
}