-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathuseDraggingContainer.ts
More file actions
67 lines (51 loc) · 1.79 KB
/
useDraggingContainer.ts
File metadata and controls
67 lines (51 loc) · 1.79 KB
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
import { useRef, useState } from "react";
type DragDirectionType = "X" | "Y";
export default function useDraggingContainer(dragDirection: DragDirectionType) {
const containerRef = useRef<HTMLElement | null>(null);
const [isStartDragging, setIsStartDragging] = useState(false);
const currentRef = useRef(0);
const standardRef = useRef(0);
const [dragged, setDragged] = useState(0);
function handleMouseDown(event: React.MouseEvent<HTMLElement, MouseEvent>) {
setIsStartDragging(true);
const page = dragDirection === "X" ? event.pageX : event.pageY;
currentRef.current = page;
initializeForDragged(page);
}
function initializeForDragged(standard: number) {
setDragged(0);
standardRef.current = standard;
}
function handleMouseMove(event: React.MouseEvent<HTMLElement, MouseEvent>) {
const container = containerRef.current;
if (!container) return;
if (!isStartDragging) return;
const page = dragDirection === "X" ? event.pageX : event.pageY;
moveContainerByCurrent(container, page);
setDragged(Math.abs(page - standardRef.current));
}
function moveContainerByCurrent(container: HTMLElement, movedMouseX: number) {
dragDirection === "X"
? (container.scrollLeft += currentRef.current - movedMouseX)
: (container.scrollTop += currentRef.current - movedMouseX);
currentRef.current = movedMouseX;
}
function handleMouseUpOrLeave() {
reset();
}
function reset() {
setIsStartDragging(false);
currentRef.current = 0;
standardRef.current = 0;
}
return {
scrollableContainerProps: {
ref: containerRef,
onMouseDown: handleMouseDown,
onMouseMove: handleMouseMove,
onMouseUp: handleMouseUpOrLeave,
onMouseLeave: handleMouseUpOrLeave,
},
isDragging: dragged > 10,
};
}