-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
useMouse.ts
70 lines (60 loc) Β· 1.56 KB
/
useMouse.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
59
60
61
62
63
64
65
66
67
68
69
70
import {useState, useEffect, useRef, RefObject} from 'react';
export interface State {
docX: number;
docY: number;
posX: number;
posY: number;
elX: number;
elY: number;
elH: number;
elW: number;
}
const useMouse = (ref: RefObject<HTMLElement>): State => {
if (process.env.NODE_ENV === 'development') {
if ((typeof ref !== 'object') || (typeof ref.current === 'undefined')) {
console.error('useMouse expects a single ref argument.');
}
}
const frame = useRef(0);
const [state, setState] = useState<State>({
docX: 0,
docY: 0,
posX: 0,
posY: 0,
elX: 0,
elY: 0,
elH: 0,
elW: 0,
});
useEffect(() => {
const moveHandler = (event: MouseEvent) => {
cancelAnimationFrame(frame.current);
frame.current = requestAnimationFrame(() => {
if (ref && ref.current) {
const {left, top, width: elW, height: elH} = ref.current.getBoundingClientRect();
const posX = left + window.scrollX;
const posY = top + window.scrollY;
const elX = event.pageX - posX;
const elY = event.pageY - posY;
setState({
docX: event.pageX,
docY: event.pageY,
posX,
posY,
elX,
elY,
elH,
elW,
});
}
});
}
document.addEventListener('mousemove', moveHandler);
return () => {
cancelAnimationFrame(frame.current);
document.removeEventListener('mousemove', moveHandler);
};
}, [ref.current])
return state;
}
export default useMouse