All files / src/Onboarding/hooks useOnboardingSlider.js

61.29% Statements 19/31
45.45% Branches 5/11
30% Functions 3/10
62.06% Lines 18/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    1x   1x   40x 40x   40x 40x 40x   40x         40x           40x       40x       40x       40x   40x 1x               40x     40x     40x                          
import { useState, useEffect, useCallback, useRef } from 'react';
 
const autoplayDelay = 50; // 5000ms divided by 100 for smoother animation
 
const useOnboardingSlider = ({ isAutoPlayAnimation, sliderData, animationClass }) => {
 
  const [currentSlide, setCurrentSlide] = useState(0);
  const [autoplay, setAutoplay] = useState(true);
 
  const progressRef = useRef(0);
  const mainContainerEleRef = useRef(null);
  const totalSlidesArrayLen = sliderData.length;
 
  const handleSliderIndexChange = useCallback((index) => {
    progressRef.current = 0
    setCurrentSlide(index);
  }, []);
 
  const handleSliderNext = useCallback(() => {
    progressRef.current = 0;
    setCurrentSlide(prev => prev + 1);
    setAutoplay(false);
  }, []);
 
  const handleMouseEnter = useCallback(() => {
    setAutoplay(false);
  }, []);
 
  const handleMouseLeave = useCallback(() => {
    setAutoplay(true);
  }, []);
 
  const handleAnimationEnd = useCallback(() => {
    mainContainerEleRef.current && mainContainerEleRef.current.classList.remove(animationClass);
  }, [animationClass]);
 
  useEffect(() => {
    let progressInterval;
    if (autoplay && isAutoPlayAnimation && totalSlidesArrayLen > 1) {
      progressInterval = setInterval(() => {
        progressRef.current = progressRef.current < 100 ? progressRef.current + 1 : 0;
        if (progressRef.current === 0) {
          setCurrentSlide((currentSlide + 1) % totalSlidesArrayLen)
        }
      }, autoplayDelay);
    }
 
    return () => clearInterval(progressInterval);
  }, [autoplay, currentSlide, isAutoPlayAnimation]);
 
  const translateMovementVal = -currentSlide * 100
 
 
  return {
    sliderIndex: currentSlide,
    isAnimationPaused: !autoplay,
    translateMovementVal,
    mainContainerEleRef,
    handleMouseEnter,
    handleMouseLeave,
    handleSliderIndexChange,
    handleSliderNext,
    handleAnimationEnd
  };
};
 
export default useOnboardingSlider;