forked from streamich/react-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseLongPress.ts
58 lines (48 loc) · 1.48 KB
/
useLongPress.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { useCallback, useRef } from 'react';
import { off, on } from './misc/util';
interface Options {
isPreventDefault?: boolean;
delay?: number;
}
const isTouchEvent = (ev: Event): ev is TouchEvent => {
return 'touches' in ev;
};
const preventDefault = (ev: Event) => {
if (!isTouchEvent(ev)) return;
if (ev.touches.length < 2 && ev.preventDefault) {
ev.preventDefault();
}
};
const useLongPress = (
callback: (e: TouchEvent | MouseEvent) => void,
{ isPreventDefault = true, delay = 300 }: Options = {}
) => {
const timeout = useRef<ReturnType<typeof setTimeout>>();
const target = useRef<EventTarget>();
const start = useCallback(
(event: TouchEvent | MouseEvent) => {
// prevent ghost click on mobile devices
if (isPreventDefault && event.target) {
on(event.target, 'touchend', preventDefault, { passive: false });
target.current = event.target;
}
timeout.current = setTimeout(() => callback(event), delay);
},
[callback, delay, isPreventDefault]
);
const clear = useCallback(() => {
// clearTimeout and removeEventListener
timeout.current && clearTimeout(timeout.current);
if (isPreventDefault && target.current) {
off(target.current, 'touchend', preventDefault);
}
}, [isPreventDefault]);
return {
onMouseDown: (e: any) => start(e),
onTouchStart: (e: any) => start(e),
onMouseUp: clear,
onMouseLeave: clear,
onTouchEnd: clear,
} as const;
};
export default useLongPress;