-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseDraggableScroll.ts
More file actions
79 lines (69 loc) · 2.22 KB
/
useDraggableScroll.ts
File metadata and controls
79 lines (69 loc) · 2.22 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
68
69
70
71
72
73
74
75
76
77
78
79
import { useCallback, useRef } from 'react';
interface UseDraggableScrollReturn {
ref: React.RefObject<HTMLDivElement>;
onMouseDown: (e: React.MouseEvent) => void;
onMouseLeave: () => void;
onMouseUp: () => void;
onMouseMove: (e: React.MouseEvent) => void;
onTouchStart: (e: React.TouchEvent) => void;
onTouchMove: (e: React.TouchEvent) => void;
onTouchEnd: () => void;
}
export default function useDraggableScroll(): UseDraggableScrollReturn {
const ref = useRef<HTMLDivElement>(null);
const isDragging = useRef(false);
const startX = useRef(0);
const scrollLeft = useRef(0);
const onMouseDown = useCallback((e: React.MouseEvent) => {
if (!ref.current) return;
isDragging.current = true;
startX.current = e.pageX - ref.current.offsetLeft;
scrollLeft.current = ref.current.scrollLeft;
ref.current.style.cursor = 'grabbing';
}, []);
const onMouseLeave = useCallback(() => {
isDragging.current = false;
if (ref.current) {
ref.current.style.cursor = 'grab';
}
}, []);
const onMouseUp = useCallback(() => {
isDragging.current = false;
if (ref.current) {
ref.current.style.cursor = 'grab';
}
}, []);
const onMouseMove = useCallback((e: React.MouseEvent) => {
if (!isDragging.current || !ref.current) return;
e.preventDefault();
const x = e.pageX - ref.current.offsetLeft;
const walk = (x - startX.current) * 2;
ref.current.scrollLeft = scrollLeft.current - walk;
}, []);
const onTouchStart = useCallback((e: React.TouchEvent) => {
if (!ref.current) return;
isDragging.current = true;
startX.current = e.touches[0].pageX - ref.current.offsetLeft;
scrollLeft.current = ref.current.scrollLeft;
}, []);
const onTouchMove = useCallback((e: React.TouchEvent) => {
if (!isDragging.current || !ref.current) return;
e.preventDefault();
const x = e.touches[0].pageX - ref.current.offsetLeft;
const walk = (x - startX.current) * 2;
ref.current.scrollLeft = scrollLeft.current - walk;
}, []);
const onTouchEnd = useCallback(() => {
isDragging.current = false;
}, []);
return {
ref,
onMouseDown,
onMouseLeave,
onMouseUp,
onMouseMove,
onTouchStart,
onTouchMove,
onTouchEnd,
};
}