All files / molecule/carousel/src CarouselContainer.js

83.33% Statements 40/48
80% Branches 28/35
86.66% Functions 13/15
82.22% Lines 37/45

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278                        1x                                           22x           22x 22x 22x 22x   91x   22x   11x 6x           22x     10x                               2x                                       1x 1x 1x             1x             1x     1x 1x             1x             1x     10x 10x               10x                     10x 10x 10x               10x               22x 22x     22x               22x 22x   22x                                                                 38x                             1x                                                                                        
import {Children, useEffect, useRef, useState} from 'react'
 
import cx from 'classnames'
import PropTypes from 'prop-types'
 
import useControlledState from '@s-ui/react-hooks/lib/useControlledState'
 
import CarouselArrow from './CarouselArrow.js'
import CarouselItem from './CarouselItem.js'
import {destroySlider, getItemsToRender, handleFn} from './settings.js'
import slidy from './slidy.js'
 
const CarouselContainer = ({
  arrowLeft,
  arrowRight,
  children,
  classNameBase,
  onNext,
  onPrevious,
  onSlide,
  onDestroy,
  onInit,
  onSlideAfter,
  onSlideBefore,
  ease,
  hasInfiniteLoop,
  defaultSlide,
  slide,
  itemsToPreload,
  hasKeyboardNavigation,
  numOfSlides,
  hasArrows,
  slideSpeed
}) => {
  const [slidyInstance, setSlidyInstance] = useState({
    goTo: handleFn(),
    next: handleFn(),
    prev: handleFn(),
    updateItems: handleFn()
  })
  const [index, setIndex, , initialSlide] = useControlledState(slide, defaultSlide)
  const [maxIndex, setMaxIndex] = useState(initialSlide)
  const sliderContainerDOMEl = useRef(null)
  const slidesDOMEl = useRef(null)
 
  const items = Children.toArray(children).filter(child => child !== null)
 
  useEffect(
    () => {
      if (slide !== index) {
        handleFn(slidyInstance.goTo)(slide)
      }
    },
    [slide, index] // eslint-disable-line
  )
 
  useEffect(
    () => {
      let handleKeyboard
      const slidyInstance = slidy(sliderContainerDOMEl.current, {
        ease,
        doAfterSlide: ({currentSlide, ...other}, ...args) =>
          handleFn(onSlideAfter)(
            {
              currentSlide,
              ...other,
              index,
              itemsLength: items.length,
              initialSlide,
              numOfSlides,
              maxIndex
            },
            ...args
          ),
        doBeforeSlide: ({currentSlide, nextSlide, ...other}, ...args) =>
          handleFn(onSlideBefore)(
            {
              currentSlide,
              nextSlide,
              ...other,
              index,
              itemsLength: items.length,
              defaultSlide,
              numOfSlides,
              maxIndex
            },
            ...args
          ),
        numOfSlides,
        slideSpeed,
        infiniteLoop: hasInfiniteLoop,
        slidesDOMEl: slidesDOMEl.current,
        initialSlide: index,
        items: items.length,
        onNext: nextIndex => {
          setIndex(nextIndex)
          nextIndex > maxIndex && setMaxIndex(nextIndex)
          handleFn(onNext)({
            index: nextIndex,
            itemsLength: items.length,
            initialSlide,
            numOfSlides,
            maxIndex
          })
          handleFn(onSlide)({
            index: nextIndex,
            itemsLength: items.length,
            initialSlide,
            numOfSlides,
            maxIndex
          })
          return nextIndex
        },
        onPrev: nextIndex => {
          setIndex(nextIndex)
          handleFn(onPrevious)({
            index: nextIndex,
            itemsLength: items.length,
            initialSlide,
            numOfSlides,
            maxIndex
          })
          handleFn(onSlide)({
            index: nextIndex,
            itemsLength: items.length,
            initialSlide,
            numOfSlides,
            maxIndex
          })
          return nextIndex
        }
      })
      setSlidyInstance(slidyInstance)
      handleFn(onInit)({
        index,
        itemsLength: items.length,
        initialSlide,
        numOfSlides,
        maxIndex
      })
 
      Iif (hasKeyboardNavigation) {
        handleKeyboard = e => {
          if (e.keyCode === 39) {
            handleFn(slidyInstance.next)(e)
          } else if (e.keyCode === 37) {
            handleFn(slidyInstance.prev)(e)
          }
        }
        document.addEventListener('keydown', handleKeyboard)
      }
 
      return () => {
        destroySlider(slidyInstance, () =>
          handleFn(onDestroy)({
            initialSlide,
            itemsLength: items.length,
            numOfSlides,
            index,
            maxIndex
          })
        )
        Iif (hasKeyboardNavigation) {
          document.removeEventListener('keydown', handleKeyboard)
        }
      }
    },
    [] // eslint-disable-line
  )
 
  useEffect(function () {
    slidyInstance && handleFn(slidyInstance.updateItems)(items.length)
  })
 
  const itemsToRender = getItemsToRender({
    index,
    maxIndex,
    items,
    itemsToPreload,
    numOfSlides
  })
 
  const handlePrev = e => handleFn(slidyInstance.prev)(e)
  const handleNext = e => items.length > numOfSlides && handleFn(slidyInstance.next)(e)
 
  return (
    <>
      <CarouselArrow
        className={cx(
          `${classNameBase}-arrow`,
          `${classNameBase}-arrowLeft`,
          arrowLeft ? `${classNameBase}-arrowCustom` : `${classNameBase}-prev`
        )}
        label={arrowLeft ? null : 'Previous'}
        role={arrowLeft ? null : 'button'}
        hasArrows={hasArrows}
        disabled={index === 0 && !hasInfiniteLoop}
        onClick={handlePrev}
      >
        {arrowLeft}
      </CarouselArrow>
      <CarouselArrow
        className={cx(
          `${classNameBase}-arrow`,
          `${classNameBase}-arrowRight`,
          arrowRight ? `${classNameBase}-arrowCustom` : `${classNameBase}-next`
        )}
        label={arrowRight ? null : 'Next'}
        role={arrowRight ? null : 'button'}
        hasArrows={hasArrows}
        disabled={(items.length <= numOfSlides || index === items.length - numOfSlides) && !hasInfiniteLoop}
        onClick={handleNext}
      >
        {arrowRight}
      </CarouselArrow>
      <div ref={sliderContainerDOMEl}>
        <ul className={cx(`${classNameBase}-itemsList`)} ref={slidesDOMEl}>
          {Children.map(itemsToRender, (child, currentIndex) => (
            <CarouselItem
              data-index={currentIndex}
              aria-hidden={currentIndex < index || currentIndex > index + numOfSlides}
              classNameBase={classNameBase}
              itemsLength={numOfSlides}
            >
              {child}
            </CarouselItem>
          ))}
        </ul>
      </div>
    </>
  )
}
 
CarouselContainer.propTypes = {
  /** Element to be used as the left arrow for the slider */
  arrowLeft: PropTypes.element,
  /** Element to be used as the right arrow for the slider */
  arrowRight: PropTypes.element,
  /** Children to be used as slides for the slider */
  children: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired,
  /** Class base to create all clases for elements. Styles might break if you modify it. */
  classNameBase: PropTypes.string,
  /** Function that will be executed AFTER destroying the slider. Useful for clean up stuff */
  onDestroy: PropTypes.func,
  /** Function that will be executed AFTER initializing  the slider */
  onInit: PropTypes.func,
  /** Function that will be executed AFTER slide transition has ended */
  onSlideAfter: PropTypes.func,
  /** change index handler **/
  onSlide: PropTypes.func,
  /** Function that will be executed BEFORE slide is happening */
  onSlideBefore: PropTypes.func,
  /** next handler **/
  onNext: PropTypes.func,
  /** previous handler **/
  onPrevious: PropTypes.func,
  /** Ease mode to use on translations */
  ease: PropTypes.string,
  /** Indicates if the slider will start with the first slide once it ends */
  hasInfiniteLoop: PropTypes.bool,
  /** Determine the first slide to start with */
  defaultSlide: PropTypes.number,
  /** Determine the number of items that will be preloaded */
  itemsToPreload: PropTypes.number,
  /** Activate navigation by keyboard */
  hasKeyboardNavigation: PropTypes.bool,
  /** Number of slides to show at once */
  numOfSlides: PropTypes.number,
  /** Determine if arrows should be shown */
  hasArrows: PropTypes.bool,
  /** Change dynamically the slide number, perfect to use with dots */
  slide: PropTypes.number,
  /** Determine the speed of the sliding animation */
  slideSpeed: PropTypes.number
}
 
export default CarouselContainer