All files / molecule/carousel/src slidy.js

63.36% Statements 64/101
45.45% Branches 25/55
65.21% Functions 15/23
67.39% Lines 62/92

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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 2951x 1x 1x 1x 1x     9x 9x 9x       6x 4x 3x       6x                               6x 6x 6x           10x 7x     10x                             10x 10x     10x     10x 10x 10x     10x 10x 10x 10x                   6x 6x                       2x     2x             2x     2x   2x                                                                                                                                                               10x 10x 10x 10x   10x 4x                 10x                 2x     2x   2x   2x 2x     2x     2x                     1x 1x 1x               1x 1x 1x               12x                 10x 10x 10x   10x       10x     10x                    
const LINEAR_ANIMATION = 'linear'
const VALID_SWIPE_DISTANCE = 50
const TRANSITION_END = 'transitionend'
const {abs} = Math
const EVENT_OPTIONS = {passive: false}
 
export function translate(to, moveX, percentatge = 100) {
  const translation = to * percentatge * -1
  const x = moveX ? `calc(${translation}% - ${moveX}px)` : `${translation}%`
  return `translate3d(${x}, 0, 0)`
}
 
export function infiniteIndex(index, end) {
  if (index < 0) return end - 1
  else if (index >= end) return 0
  else return index
}
 
export function clampNumber(x, minValue, maxValue) {
  return Math.min(Math.max(x, minValue), maxValue)
}
 
function getTouchCoordinatesFromEvent(e) {
  return e.targetTouches ? e.targetTouches[0] : e.touches[0]
}
 
/**
 *
 * @param {number} duration
 * @param {string} ease
 * @param {number} index
 * @param {number} x
 * @param {number} percentatge
 */
function getTranslationCSS(duration, ease, index, x, percentatge) {
  const easeCssText = ease !== '' ? `transition-timing-function: ${ease};` : ''
  const durationCssText = duration ? `transition-duration: ${duration}ms;` : ''
  return `${easeCssText}${durationCssText}transform: ${translate(index, x, percentatge)};`
}
 
function cleanContainer(container) {
  // remove all the elements except the last one as it seems to be old data in the HTML
  // that's specially useful for dynamic content
  while (container.childElementCount > 1) {
    container !== null && container.removeChild(container.lastChild)
  }
  // tell that the clean is done
  return true
}
 
export default function slidy(containerDOMEl, options) {
  const {
    doAfterSlide,
    doBeforeSlide,
    ease,
    infiniteLoop,
    initialSlide,
    numOfSlides,
    onNext,
    onPrev,
    slidesDOMEl,
    slideSpeed
  } = options
  let {items} = options
 
  // if frameDOMEl is null, then we do nothing
  Iif (containerDOMEl === null) return
 
  // initialize some variables
  let index = initialSlide
  let isScrolling = false
  let transitionEndCallbackActivated = false
 
  // event handling
  let deltaX = 0
  let deltaY = 0
  let touchOffsetX = 0
  let touchOffsetY = 0
 
  /**
   * translates to a given position in a given time in milliseconds
   *
   * @param  {number} duration time in milliseconds for the transistion
   * @param  {string} ease easing css property
   * @param  {number} x Number of pixels to fine tuning translation
   */
  function _translate(duration, ease = '', x = 0) {
    const percentatge = 100 / numOfSlides
    slidesDOMEl.style.cssText = getTranslationCSS(duration, ease, index, x, percentatge)
  }
 
  /**
   * slide function called by prev, next & touchend
   *
   * determine nextIndex and slide to next postion
   * under restrictions of the defined options
   *
   * @param {boolean} direction 'true' for right, 'false' for left
   */
  function slide(direction) {
    const movement = direction === true ? 1 : -1
 
    // calculate the nextIndex according to the movement
    let nextIndex = index + 1 * movement
 
    /**
     * If the slider has the infiniteLoop option
     * nextIndex will start from the start when arrives to the end
     * and vice versa
     */
    Iif (infiniteLoop) nextIndex = infiniteIndex(nextIndex, items)
 
    // nextIndex should be between 0 and items minus 1
    nextIndex = clampNumber(nextIndex, 0, items - 1)
 
    goTo(nextIndex)
  }
 
  function onTransitionEnd() {
    if (transitionEndCallbackActivated === true) {
      _translate(0)
      transitionEndCallbackActivated = false
    }
  }
 
  function onTouchstart(e) {
    const coords = getTouchCoordinatesFromEvent(e)
    isScrolling = undefined
    touchOffsetX = coords.pageX
    touchOffsetY = coords.pageY
  }
 
  function onTouchmove(e) {
    // ensure swiping with one touch and not pinching
    if (e.touches.length > 1 || (e.scale && e.scale !== 1)) return
 
    const coords = getTouchCoordinatesFromEvent(e)
    deltaX = coords.pageX - touchOffsetX
    deltaY = coords.pageY - touchOffsetY
 
    if (typeof isScrolling === 'undefined') {
      isScrolling = abs(deltaX) < abs(deltaY)
      if (!isScrolling) document.ontouchmove = e => e.preventDefault()
      return
    }
 
    if (!isScrolling) {
      e.preventDefault()
      _translate(0, LINEAR_ANIMATION, deltaX * -1)
    }
  }
 
  function onTouchend() {
    // hack the document to block scroll
    document.ontouchmove = () => true
 
    if (!isScrolling) {
      /**
       * is valid if:
       * -> swipe distance is greater than the specified valid swipe distance
       * -> swipe distance is more then a third of the swipe area
       * @isValidSlide {Boolean}
       */
      const isValid = abs(deltaX) > VALID_SWIPE_DISTANCE
 
      /**
       * is out of bounds if:
       * -> index is 0 and deltaX is greater than 0
       * -> index is the last slide and deltaX is smaller than 0
       * @isOutOfBounds {Boolean}
       */
      const direction = deltaX < 0
      const isOutOfBounds = (direction === false && index === 0) || (direction === true && index === items - 1)
 
      /**
       * If the swipe is valid and we're not out of bounds or is infiniteLoop
       * -> Slide to the direction
       * otherwise: go back to the previous slide with a linear animation
       */
      if (isValid === true && (isOutOfBounds === false || infiniteLoop)) {
        slide(direction)
      } else {
        _translate(slideSpeed, LINEAR_ANIMATION)
      }
    }
 
    // reset variables with the initial values
    deltaX = deltaY = touchOffsetX = touchOffsetY = 0
  }
 
  /**
   * public
   * setup function
   */
  function _setup() {
    slidesDOMEl.addEventListener(TRANSITION_END, onTransitionEnd)
    containerDOMEl.addEventListener('touchstart', onTouchstart, EVENT_OPTIONS)
    containerDOMEl.addEventListener('touchmove', onTouchmove, EVENT_OPTIONS)
    containerDOMEl.addEventListener('touchend', onTouchend, EVENT_OPTIONS)
 
    if (index !== 0) {
      _translate(0)
    }
  }
 
  /**
   * public
   * clean content of the slider
   */
  function clean() {
    return cleanContainer(slidesDOMEl)
  }
 
  /**
   * public
   * @param {number} nextIndex Index number to go to
   */
  function goTo(nextIndex) {
    // if the nextIndex and the current is the same, we don't need to do the slide
    Iif (nextIndex === index) return
 
    // if the nextIndex is possible according to number of items, then use it
    Eif (nextIndex <= items) {
      // execute the callback from the options before sliding
      doBeforeSlide({currentSlide: index, nextSlide: nextIndex})
      // execute the internal callback
      nextIndex > index ? onNext(nextIndex) : onPrev(nextIndex)
      index = nextIndex
    }
    // translate to the next index by a defined duration and ease function
    _translate(slideSpeed, ease)
 
    // execute the callback from the options after sliding
    slidesDOMEl.addEventListener(TRANSITION_END, function cb(e) {
      doAfterSlide({currentSlide: index})
      e.currentTarget.removeEventListener(e.type, cb)
    })
  }
 
  /**
   * public
   * prev function: called on clickhandler
   */
  function prev(e) {
    e.preventDefault()
    e.stopPropagation()
    slide(false)
  }
 
  /**
   * public
   * next function: called on clickhandler
   */
  function next(e) {
    e.preventDefault()
    e.stopPropagation()
    slide(true)
  }
 
  /**
   * public
   * @param {number} newItems Number of items in the slider for dynamic content
   */
  function updateItems(newItems) {
    items = newItems
  }
 
  /**
   * public
   * destroy function: called to gracefully destroy the slidy instance
   */
  function destroy() {
    // remove all touch listeners
    containerDOMEl.removeEventListener('touchstart', onTouchstart, EVENT_OPTIONS)
    containerDOMEl.removeEventListener('touchmove', onTouchmove, EVENT_OPTIONS)
    containerDOMEl.removeEventListener('touchend', onTouchend, EVENT_OPTIONS)
    // remove transition listeners
    slidesDOMEl.removeEventListener(TRANSITION_END, onTransitionEnd)
  }
 
  // trigger initial setup
  _setup()
 
  // expose public api
  return {
    clean,
    destroy,
    goTo,
    next,
    prev,
    slide,
    updateItems
  }
}