();
- const [focused, setFocused] = useState(true);
- const [rnd, setRnd] = useState(0);
- const [reduced, setReduced] = useState(data);
+};
- useEffect(() => {
- window.addEventListener('blur', () => setFocused(false));
- window.addEventListener('focus', () => setFocused(true));
- const int = interval ? setInterval(() => setRnd(Math.random() * 10), interval) : 0;
+const cx = classNames.bind(styles);
- return () => {
- window.removeEventListener('blur', () => setFocused(false));
- window.removeEventListener('focus', () => () => setFocused(true));
- if (interval) clearInterval(int);
- };
- }, []);
+export default function Carousel(props: Props) {
+ const {
+ slides: data, size, animation, animation: { interval },
+ } = props;
- useEffect(() => {
- if (focused) getNext();
- }, [rnd]);
+ const [current, setCurrent] = useState(0);
+ const [move, setMove] = useState(0);
+ const [slides] = useState(data.length <= 3 ? [...data, ...data, ...data] : data);
+ const [focused, setFocused] = useState(true);
+ const [reduced] = useState(data);
const getPrev = (m = move, c = current) => {
setMove(m + 1);
@@ -52,26 +40,28 @@ const Carousel: React.FC<{
setCurrent(i);
};
- const getNext = (m = move, c = current) => {
- setMove(move - 1);
+ const getNext = useCallback((m = move, c = current) => {
+ setMove(m - 1);
setCurrent(c + 1 >= reduced.length ? 0 : c + 1);
- };
+ }, [current, move, reduced.length]);
- const getOffsets = () => {
- const half = Math.floor(slides.length / 2);
- const gap = half - current;
- let arr = slides.map((s, i) => i - half);
- gap > 0 ? arr.push(...arr.splice(0, gap)) : arr.unshift(...arr.splice(gap));
+ useEffect(() => {
+ window.addEventListener('blur', () => setFocused(false));
+ window.addEventListener('focus', () => setFocused(true));
+ const int = interval ? setInterval(() => focused && getNext(), interval) : 0;
- return arr;
- };
+ return () => {
+ window.removeEventListener('blur', () => setFocused(false));
+ window.removeEventListener('focus', () => () => setFocused(true));
+ if (interval) clearInterval(int);
+ };
+ }, [focused, getNext, interval]);
const cns = {
- dot: (selected: boolean) =>
- cx({
- dot: true,
- selected,
- }),
+ dot: (selected: boolean) => cx({
+ dot: true,
+ selected,
+ }),
};
return (
@@ -86,7 +76,7 @@ const Carousel: React.FC<{
{slides.map((s, key) => (
);
-};
-
-export default Carousel;
+}