-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathuseTouchAndMouse.js
51 lines (42 loc) · 1.24 KB
/
useTouchAndMouse.js
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
import { useRef, useState } from 'react';
// onTouchStart and onMouseDown are required on the target
// onMouseMove and onMouseUp are handled by document listener
// so out of bounds events are captured
export const useTouchAndMouse = (startFunc, moveFunc, endFunc) => {
const [touching, setTouching] = useState(false);
const onTouchStart = (e) => {
setTouching(true);
if (startFunc) startFunc(e);
};
const mouseDownRef = useRef(null);
const onMouseDown = (e) => {
if (touching) return;
if (startFunc) startFunc(e);
mouseDownRef.current = true;
document.addEventListener('mouseup', onMouseUp);
document.addEventListener('mousemove', onMouseMove);
};
const onTouchMove = (e) => {
if (moveFunc) moveFunc(e);
};
const onMouseMove = (e) => {
if (touching) return;
if (moveFunc && mouseDownRef.current) moveFunc(e);
};
const onTouchEnd = (e) => {
if (endFunc) endFunc(e);
};
const onMouseUp = (e) => {
if (touching) return;
if (endFunc) endFunc(e);
mouseDownRef.current = false;
document.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('mousemove', onMouseMove);
};
return {
onTouchStart,
onMouseDown,
onTouchMove,
onTouchEnd,
};
};