-
Notifications
You must be signed in to change notification settings - Fork 266
/
use-kinetic-scroll.ts
63 lines (55 loc) 路 2.3 KB
/
use-kinetic-scroll.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
import { useEffect, useRef } from "react";
const useKineticScroll = (
isEnabled: boolean,
callback: () => void,
targetScroller: React.MutableRefObject<HTMLDivElement | null>
) => {
const rafId = useRef<number | null>(null);
const isTouching = useRef(false);
const lastScrollPosition = useRef<number | null>(null);
useEffect(() => {
const handleScroll = () => {
if (!isTouching.current) {
const currentScrollPosition = targetScroller.current?.scrollTop ?? 0;
if (lastScrollPosition.current === currentScrollPosition) {
// Scroll position hasn't changed, stop the animation frame
lastScrollPosition.current = null;
return;
}
lastScrollPosition.current = currentScrollPosition;
callback();
rafId.current = requestAnimationFrame(handleScroll);
}
};
const startTouch = () => {
isTouching.current = true;
lastScrollPosition.current = null; // Reset last scroll position on touch start
if (rafId.current !== null) {
cancelAnimationFrame(rafId.current);
rafId.current = null;
}
};
const endTouch = (event: TouchEvent) => {
if (event.touches.length === 0) {
// All touches have ended
isTouching.current = false;
rafId.current = requestAnimationFrame(handleScroll);
}
};
if (isEnabled && targetScroller.current !== null) {
const element = targetScroller.current;
element.addEventListener("touchstart", startTouch);
element.addEventListener("touchend", endTouch);
element.addEventListener("scroll", handleScroll, { passive: true });
return () => {
element.removeEventListener("touchstart", startTouch);
element.removeEventListener("touchend", endTouch);
element.removeEventListener("scroll", handleScroll);
if (rafId.current !== null) {
cancelAnimationFrame(rafId.current);
}
};
}
}, [isEnabled, targetScroller, callback]);
};
export default useKineticScroll;