-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseMousePosition.ts
48 lines (38 loc) · 1.38 KB
/
useMousePosition.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
import { type MouseEvent, useEffect, useRef, useState } from 'react';
export function useMousePosition<T extends HTMLElement = any>(
options: { resetOnExit?: boolean } = { resetOnExit: false },
) {
const [position, setPosition] = useState({ x: 0, y: 0 });
const ref = useRef<T>();
const setMousePosition = (event: MouseEvent<HTMLElement>) => {
if (ref.current) {
const rect = event.currentTarget.getBoundingClientRect();
const x = Math.max(
0,
Math.round(event.pageX - rect.left - (window.pageXOffset || window.scrollX)),
);
const y = Math.max(
0,
Math.round(event.pageY - rect.top - (window.pageYOffset || window.scrollY)),
);
setPosition({ x, y });
} else {
setPosition({ x: event.clientX, y: event.clientY });
}
};
const resetMousePosition = () => setPosition({ x: 0, y: 0 });
useEffect(() => {
const element = ref?.current ? ref.current : document;
element.addEventListener('mousemove', setMousePosition as any);
if (options.resetOnExit) {
element.addEventListener('mouseleave', resetMousePosition as any);
}
return () => {
element.removeEventListener('mousemove', setMousePosition as any);
if (options.resetOnExit) {
element.removeEventListener('mouseleave', resetMousePosition as any);
}
};
}, [ref.current]);
return { ref, ...position };
}