-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuse-drag-drop.ts
54 lines (45 loc) · 1.33 KB
/
use-drag-drop.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
/* eslint-disable @typescript-eslint/no-explicit-any */
import React from 'react'
export interface DragDropType {
x: number;
y: number;
coords: {
x: number;
y: number;
}
}
const useDragDrop = () => {
const [position, setPosition] = React.useState<DragDropType>({ x: 0, y: 0, coords: { x: 0, y: 0 } });
const handleMouseMove = React.useRef((e: any) => {
setPosition((pos) => {
const xDiff = pos.coords.x - e.pageX;
const yDiff = pos.coords.y - e.pageY;
return {
x: pos.x - xDiff,
y: pos.y - yDiff,
coords: {
x: e.pageX,
y: e.pageY
}
};
});
});
const handleMouseDown = (e: any) => {
const { pageX } = e;
const { pageY } = e;
setPosition((pos) => ({
...pos,
coords: {
x: pageX,
y: pageY
}
}));
document.addEventListener('mousemove', handleMouseMove.current);
};
const handleMouseUp = () => {
document.removeEventListener('mousemove', handleMouseMove.current);
setPosition((pos) => ({ ...pos, coords: { x: 0, y: 0 } }));
};
return [position , setPosition , handleMouseDown , handleMouseUp]
}
export default useDragDrop;