-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (49 loc) · 1.45 KB
/
index.js
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
import { useEffect, useRef, useState } from "react";
import { debounce } from "debounce";
function useSlider({ hasPadding = false } = {}) {
const sliderRef = useRef(null);
const [scrollStatus, setScrollStatus] = useState(null);
const scrollTo = (direction) => () => {
const slider = sliderRef.current;
const childIndex = hasPadding ? 1 : 0;
slider.scrollBy({
left:
direction === "right"
? slider.children[childIndex].offsetWidth
: -slider.children[childIndex].offsetWidth,
behavior: "smooth",
});
};
useEffect(() => {
const slider = sliderRef.current;
if (!slider || slider.scrollWidth < slider.offsetWidth) return;
setScrollStatus("left");
const callback = debounce(
({ target: { scrollLeft, scrollWidth, offsetWidth } }) => {
if (scrollLeft === 0) {
setScrollStatus("left");
} else if (scrollLeft - scrollWidth + offsetWidth === 0) {
setScrollStatus("right");
} else {
setScrollStatus("center");
}
},
10
);
slider.addEventListener("scroll", callback);
return () => {
if (!slider) return;
slider.removeEventListener("scroll", callback);
};
}, [sliderRef]);
const isOverflown = (element) =>
element &&
element.offsetLeft + element.offsetWidth > element.parentNode.offsetWidth;
return {
sliderRef,
scrollTo,
scrollStatus,
isOverflown,
};
}
export { useSlider };