All files / src Carousel.vue

60.8% Statements 76/125
57.66% Branches 64/111
72.97% Functions 27/37
59.17% Lines 71/120
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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 4933x     3x       3x   3x   3x   3x   3x   3x   3x   3x   12x   3x             20x                                                                                                                                                                                   22x     10x     22x     20x           22x     20x     20x     5x         5x 2x 3x 3x       20x   20x   20x                         21x 21x   21x 21x     1x         4x       4x 4x     4x   4x     21x 21x     21x 21x     7x 7x 7x                                                                                                                                           21x 21x 21x 21x     21x 14x 31x 31x 31x   31x         21x 8x 8x         20x 20x   20x         20x 20x     1x 1x 1x 1x         3x 3x 42x 3x                                                                                                                                                                                                                                                                                                                                          
<template>
  <div class="carousel">
    <div
      class="carousel-wrapper"
      ref="carousel-wrapper">
      <div
        ref="carousel-inner"
        class="carousel-inner"
        v-bind:style="`
          width: ${carouselWidth}px;
          transform: translate3d(${currentOffset}px, 0, 0);
          transition: ${!dragging ? transitionStyle : 'none'};
        `"
      >
        <slot></slot>
      </div>
    </div>
    <navigation v-if="navigationEnabled"></navigation>
    <pagination v-if="paginationEnabled && pageCount > 0"></pagination>
  </div>
</template>
 
<script>
  import autoplay from "./mixins/autoplay"
  import debounce from "./utils/debounce"
  import Navigation from "./Navigation.vue"
  import Pagination from "./Pagination.vue"
 
  export default {
    name: "carousel",
    components: {
      Navigation,
      Pagination,
    },
    data() {
      return {
        browserWidth: null,
        carouselWidth: null,
        currentPage: 0,
        dragOffset: 0,
        dragStartX: 0,
        dragStartY: 0,
        offset: 0,
        slideWidth: null,
        dragging: false,
        endTime: 0,
        momemtum: 0,
        refreshRate: 16,
        isTouch: typeof window !== "undefined" && ("ontouchstart" in window)
      }
    },
    mixins: [
      autoplay
    ],
    props: {
      /**
       * Flag to activate dragging with mouse
       * False by default
       */
      mouseDrag: {
        type: Boolean,
        default: false
      },
      /**
       * Slide transition easing
       * Any valid CSS transition easing accepted
       */
      easing: {
        type: String,
        default: "ease",
      },
      /**
       * Minimum distance for the swipe to trigger
       * a slide advance
       */
      minSwipeDistance: {
        type: Number,
        default: 5,
      },
      /**
       * Flag to render the navigation component
       * (next/prev buttons)
       */
      navigationEnabled: {
        type: Boolean,
        default: false,
      },
      /**
       * The fill color of the active pagination dot
       * Any valid CSS color is accepted
       */
      paginationActiveColor: {
        type: String,
        default: "#000000",
      },
      /**
       * The fill color of pagination dots
       * Any valid CSS color is accepted
       */
      paginationColor: {
        type: String,
        default: "#efefef",
      },
      /**
       * Flag to render pagination component
       */
      paginationEnabled: {
        type: Boolean,
        default: true,
      },
      /**
       * The padding inside each pagination dot
       * Pixel values are accepted
       */
      paginationPadding: {
        type: Number,
        default: 10,
      },
      /**
       * The size of each pagination dot
       * Pixel values are accepted
       */
      paginationSize: {
        type: Number,
        default: 10,
      },
      /**
       * Maximum number of slides displayed on each page
       */
      perPage: {
        type: Number,
        default: 2,
      },
      /**
       * Configure the number of visible slides with a particular browser width.
       * This will be an array of arrays, ex. [[320, 2], [1199, 4]]
       * Formatted as [x, y] where x=browser width, and y=number of slides displayed.
       * ex. [1199, 4] means if (window <= 1199) then show 4 slides per page
       */
      perPageCustom: {
        type: Array,
      },
      /**
       * Scroll per page, not per item
       */
      scrollPerPage: {
        type: Boolean,
        default: false,
      },
      /**
       * Slide transition speed
       * Number of milliseconds accepted
       */
      speed: E{
        type: Number,
        default: 500,
      },
      /**
       * Resistance coefficient on the edge
       */
      resistanceCoef: {
        type: Number,
      I  default: 20
      }
    },
    computed: {
      /**
       * @return {Boolean} Can the slider move forward?
       */
      canAdvanceForward() {
        return (this.currentPage < (this.pageCount - 1))
      },
      /**
       * @return {Boolean} Can the slider move backward?
       */
      canAdvanceBackward() {
        return (this.currentPage > 0)
      },
      /**
       * Number of slides to display per page in the current context.
       * This is constant unless responsive perPage option is set.
       * @return {Number} The number of slides per page to display
      I */
      currentPerPage() {
        return (!this.perPageCustom || this.$isServer)
        ? this.perPage
        : this.getBreakpointSlidesPerPage(this.perPageCustom, this.browserWidth)
      },
      /**
       * The horizontal distance the inner wrapper is offset while navigating.
       * @return {Number} Pixel value of offset to apply
       */
      currentOffset() {
        return (this.offset + this.dragOffset) * -1
      },
      isHidden() {
        return (this.carouselWidth <= 0)
      },
      /**
       * Calculate the number of pages of slides
       * @return {Number} Number of pages
       */
      pageCount() {
        return Math.ceil(this.slideCount / this.currentPerPage)
      },
      /**
       * Get the number of slides
       * @return {Number} Number of slides
      E */
      slideCount() {
        return (this.$slots && this.$slots.default && this.$slots.default.length) || 0
      },
      transitionStyle() {
        return `${this.speed / 1000}s ${this.easing} transform`
      },
      maxOffset() {
        return (this.slideWidth * this.slideCount) - this.carouselWidth
      }
    },
    methods: {
      /**
       * Increase/decrease the current page value
       * @param  {String} direction (Optional) The direction to advance
       */
      advancePage(direction) {
        if (direction && direction === "backward" && this.canAdvanceBackward) {
          this.goToPage(this.currentPage - 1)
        } else if (
          (
            !direction
            || (direction && direction !== "backward"))
            && this.canAdvanceForward
          ) {
          this.goToPage(this.currentPage + 1)
        }
      },
      /**
       * A mutation observer is used to detect changes to the containing node
       * in order to keep the magnet container in sync with the height its reference node.
       */
      attachMutationObserver() {
        const MutationObserver = window.MutationObserver
         || window.WebKitMutationObserver
         || window.MozMutationObserver
 
        if (MutationObserver) {
          const config = { attributes: true, data: true }
          this.mutationObserver = new MutationObserver(() => {
            this.$nextTick(() => {
              this.computeCarouselWidth()
            })
          })
          if (this.$parent.$el) {
            this.mutationObserver.observe(this.$parent.$el, config)
          }
        }
      },
      /**
       * Calculate the width of each slide
       * @return {Number} Slide width
       */
      calculateSlideWidth() {
        const width = this.carouselWidth
        const perPage = this.currentPerPage
 
        this.slideWidth = width / perPage
        this.setChildSlideWidth(this.slideWidth)
      },
      /**
       * Stop listening to mutation changes
       */
      detachMutationObserver() {
        if (this.mutationObserver) {
          this.mutationObserver.disconnect()
        }
      },
      /**
       * Given a viewport width, find the number of slides to display
       * @param  {Number} width Current viewport width in pixels
       * @return {Number}       Number of slides to display
       */
      getBreakpointSlidesPerPage(breakpointArray, width) {
        const breakpoints = breakpointArray.sort((a, b) => ((a[0] > b[0]) ? -1 : 1))
 
        // Reduce the breakpoints to entries where the width is in range
        // The breakpoint arrays are formatted as [widthToMatch, numberOfSlides]
        const matches = breakpoints.filter(breakpoint => width >= breakpoint[0])
 
        // If there is a match, the result should return only
        //E the slide count from the first matching breakpoint
        const match = matches[0] && matches[0][1]
 
        return match || this.perPage
      },
      /**
       * Get the current browser viewport width
       * @return {Number} Browser"s width in pixels
       */
      getBrowserWidth() {
        this.browserWidth = window.innerWidth
        return this.browserWidth
      },
      /**
       * Get the width of the carousel DOM element
    E   * @return {Number} Width of the carousel in pixels
       */
      getCarouselWidth() {
      I  this.carouselWidth = (this.$el && this.$el.clientWidth) || 0 // Assign globally
        return this.carouselWidth
      },
      /**
       * Set the current page to a specific value
       * This function will only apply the change if the value is within the carousel bounds
       * @param  {Number} page The value of the new page number
       */
      goToPage(page) {
    E    if ((page >= 0) && (page <= this.pageCount)) {
          // update current offset and change the current page
          this.offset = Math.min(this.slideWidth * this.currentPerPage * page, this.maxOffset)
          this.currentPage = page
        }
      },
      /**
       * Trigger actions when mouse is pressed
E       * @param  {Object} e The event object
       */
      /* istanbul ignore next */
      onStart(e) {
        document.addEventListener(
          this.isTouch ? "touchend" : "mouseup",
          this.onEnd, true)
 
        document.addEventListener(
          this.isTouch ? "touchmove" : "mousemove",
          this.onDrag, true)
 
        this.startTime = e.timeStamp
        this.dragging = true
        this.dragStartX = this.isTouch ? e.touches[0].clientX : e.clientX
        this.dragStartY = this.isTouch ? e.touches[0].clientY : e.clientY
      },
      /**
       * Trigger actions when mouse is released
       * @param  {Object} e The event object
       */
      onEnd(e) {
        // compute the momemtum speed
        const eventPosX = this.isTouch ? e.changedTouches[0].clientX : e.clientX
        this.momemtum = (this.dragStartX - eventPosX) / (e.timeStamp - this.startTime)
 
        this.offset += this.dragOffset
        this.dragOffset = 0
        this.dragging = false
 
        this.render()
 
        // clear events listeners
        document.removeEventListener(
          this.isTouch ? "touchend" : "mouseup",
          this.onEnd, true)
        document.removeEventListener(
          this.isTouch ? "touchmove" : "mousemove",
          this.onDrag, true)
      },
      /**
       * Trigger actions when mouse is pressed and then moved (mouse drag)
       * @param  {Object} e The event object
       */
      onDrag(e) {
        const eventPosX = this.isTouch ? e.touches[0].clientX : e.clientX
        const eventPosY = this.isTouch ? e.touches[0].clientY : e.clientY
        const newOffsetX = (this.dragStartX - eventPosX)
        const newOffsetY = (this.dragStartY - eventPosY)
 
        // if it is a touch device, check if we are below the min swipe threshold
        // (if user scroll the page on the component)
        if (this.isTouch && Math.abs(newOffsetX) < Math.abs(newOffsetY)) {
          return
        }
 
        // we are good to prevent the move and handle the translation
        e.preventDefault()
        e.stopImmediatePropagation()
 
        this.dragOffset = newOffsetX
        const nextOffset = this.offset + this.dragOffset
        if (nextOffset < 0) {
          this.dragOffset = -Math.sqrt(-this.resistanceCoef * this.dragOffset)
        } else if (nextOffset > this.maxOffset) {
          this.dragOffset = Math.sqrt(this.resistanceCoef * this.dragOffset)
        }
      },
      onResize() {
        this.computeCarouselWidth()
 
        this.dragging = true // force a dragging to disable animation
        this.render()
        // clear dragging after refresh rate
        setTimeout(() => {
          this.dragging = false
        }, this.refreshRate)
      },
      render() {
        // add extra slides depending on the momemtum speed
        this.offset += Math.max(
                -this.currentPerPage + 1,
                Math.min(Math.round(this.momemtum), this.currentPerPage - 1)
              ) * this.slideWidth
 
        // & snap the new offset on a slide or page if scrollPerPage
        const width = (this.scrollPerPage) ? this.slideWidth * this.currentPerPage : this.slideWidth
        this.offset = width * Math.round(this.offset / width)
  
        // clamp the offset between 0 -> maxOffset
        this.offset = Math.max(0, Math.min(this.offset, this.maxOffset))
 
        // update the current page
        this.currentPage = Math.round((this.offset / this.slideWidth) / this.currentPerPage)
      },
      /**
       * Re-compute the width of the carousel and its slides
       */
      computeCarouselWidth() {
        this.getBrowserWidth()
        this.getCarouselWidth()
        this.calculateSlideWidth()
        this.setCurrentPageInBounds()
      },
      /**
       * Assign widths to child slides within slots
       * @param {Number} width Width to set on slides
       */
      setChildSlideWidth(width) {
        if (this.$slots.default) {
          this.$slots.default.map((child) => {
            const slotChild = child
            if (slotChild && slotChild.child) {
              slotChild.child.width = width
            }
            return slotChild
          })
        }
      },
      /**
       * When the current page exceeds the carousel bounds, reset it to the maximum allowed
       */
      setCurrentPageInBounds() {
        if (!this.canAdvanceForward) {
          const setPage = (this.pageCount - 1)
          this.currentPage = (setPage >= 0) ? setPage : 0
        }
      },
    },
    mounted() {
      if (!this.$isServer) {
        window.addEventListener("resize", debounce(this.onResize, this.refreshRate))
 
        // setup the start event only if touch device or mousedrag activated
        if (this.isTouch || this.mouseDrag) {
          this.$refs["carousel-wrapper"].addEventListener(
            this.isTouch ? "touchstart" : "mousedown",
            this.onStart)
        }
      }
 
      this.attachMutationObserver()
      this.computeCarouselWidth()
    },
    destroyed() {
      if (!this.$isServer) {
        this.detachMutationObserver()
        window.removeEventListener("resize", this.getBrowserWidth)
        this.$refs["carousel-wrapper"].removeEventListener(
          this.isTouch ? "touchstart" : "mousedown",
          this.onStart)
      }
    },
  }
</script>
 
<style scoped>
.carousel {
  width: 100%;
  position: relative;
  overflow: hidden;
}
 
.carousel-inner {
  display: flex;
  flex-direction: row;
  backface-visibility: hidden;
}
</style>