UNPKG

swiper

Version:

Most modern mobile touch slider and framework with hardware accelerated transitions

1,522 lines (1,375 loc) 254 kB
/** * Swiper 5.4.5 * Most modern mobile touch slider and framework with hardware accelerated transitions * http://swiperjs.com * * Copyright 2014-2020 Vladimir Kharlampidi * * Released under the MIT License * * Released on: June 16, 2020 */ import { $, addClass, removeClass, hasClass, toggleClass, attr, removeAttr, data, transform, transition as transition$1, on, off, trigger, transitionEnd as transitionEnd$1, outerWidth, outerHeight, offset, css, each, html, text, is, index, eq, append, prepend, next, nextAll, prev, prevAll, parent, parents, closest, find, children, filter, remove, add, styles } from 'dom7/dist/dom7.modular'; import { window, document as document$1 } from 'ssr-window'; const Methods = { addClass, removeClass, hasClass, toggleClass, attr, removeAttr, data, transform, transition: transition$1, on, off, trigger, transitionEnd: transitionEnd$1, outerWidth, outerHeight, offset, css, each, html, text, is, index, eq, append, prepend, next, nextAll, prev, prevAll, parent, parents, closest, find, children, filter, remove, add, styles, }; Object.keys(Methods).forEach((methodName) => { $.fn[methodName] = $.fn[methodName] || Methods[methodName]; }); const Utils = { deleteProps(obj) { const object = obj; Object.keys(object).forEach((key) => { try { object[key] = null; } catch (e) { // no getter for object } try { delete object[key]; } catch (e) { // something got wrong } }); }, nextTick(callback, delay = 0) { return setTimeout(callback, delay); }, now() { return Date.now(); }, getTranslate(el, axis = 'x') { let matrix; let curTransform; let transformMatrix; const curStyle = window.getComputedStyle(el, null); if (window.WebKitCSSMatrix) { curTransform = curStyle.transform || curStyle.webkitTransform; if (curTransform.split(',').length > 6) { curTransform = curTransform.split(', ').map((a) => a.replace(',', '.')).join(', '); } // Some old versions of Webkit choke when 'none' is passed; pass // empty string instead in this case transformMatrix = new window.WebKitCSSMatrix(curTransform === 'none' ? '' : curTransform); } else { transformMatrix = curStyle.MozTransform || curStyle.OTransform || curStyle.MsTransform || curStyle.msTransform || curStyle.transform || curStyle.getPropertyValue('transform').replace('translate(', 'matrix(1, 0, 0, 1,'); matrix = transformMatrix.toString().split(','); } if (axis === 'x') { // Latest Chrome and webkits Fix if (window.WebKitCSSMatrix) curTransform = transformMatrix.m41; // Crazy IE10 Matrix else if (matrix.length === 16) curTransform = parseFloat(matrix[12]); // Normal Browsers else curTransform = parseFloat(matrix[4]); } if (axis === 'y') { // Latest Chrome and webkits Fix if (window.WebKitCSSMatrix) curTransform = transformMatrix.m42; // Crazy IE10 Matrix else if (matrix.length === 16) curTransform = parseFloat(matrix[13]); // Normal Browsers else curTransform = parseFloat(matrix[5]); } return curTransform || 0; }, parseUrlQuery(url) { const query = {}; let urlToParse = url || window.location.href; let i; let params; let param; let length; if (typeof urlToParse === 'string' && urlToParse.length) { urlToParse = urlToParse.indexOf('?') > -1 ? urlToParse.replace(/\S*\?/, '') : ''; params = urlToParse.split('&').filter((paramsPart) => paramsPart !== ''); length = params.length; for (i = 0; i < length; i += 1) { param = params[i].replace(/#\S+/g, '').split('='); query[decodeURIComponent(param[0])] = typeof param[1] === 'undefined' ? undefined : decodeURIComponent(param[1]) || ''; } } return query; }, isObject(o) { return typeof o === 'object' && o !== null && o.constructor && o.constructor === Object; }, extend(...args) { const to = Object(args[0]); for (let i = 1; i < args.length; i += 1) { const nextSource = args[i]; if (nextSource !== undefined && nextSource !== null) { const keysArray = Object.keys(Object(nextSource)); for (let nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex += 1) { const nextKey = keysArray[nextIndex]; const desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); if (desc !== undefined && desc.enumerable) { if (Utils.isObject(to[nextKey]) && Utils.isObject(nextSource[nextKey])) { Utils.extend(to[nextKey], nextSource[nextKey]); } else if (!Utils.isObject(to[nextKey]) && Utils.isObject(nextSource[nextKey])) { to[nextKey] = {}; Utils.extend(to[nextKey], nextSource[nextKey]); } else { to[nextKey] = nextSource[nextKey]; } } } } } return to; }, }; const Support = (function Support() { return { touch: !!(('ontouchstart' in window) || (window.DocumentTouch && document$1 instanceof window.DocumentTouch)), pointerEvents: !!window.PointerEvent && ('maxTouchPoints' in window.navigator) && window.navigator.maxTouchPoints >= 0, observer: (function checkObserver() { return ('MutationObserver' in window || 'WebkitMutationObserver' in window); }()), passiveListener: (function checkPassiveListener() { let supportsPassive = false; try { const opts = Object.defineProperty({}, 'passive', { // eslint-disable-next-line get() { supportsPassive = true; }, }); window.addEventListener('testPassiveListener', null, opts); } catch (e) { // No support } return supportsPassive; }()), gestures: (function checkGestures() { return 'ongesturestart' in window; }()), }; }()); class SwiperClass { constructor(params = {}) { const self = this; self.params = params; // Events self.eventsListeners = {}; if (self.params && self.params.on) { Object.keys(self.params.on).forEach((eventName) => { self.on(eventName, self.params.on[eventName]); }); } } on(events, handler, priority) { const self = this; if (typeof handler !== 'function') return self; const method = priority ? 'unshift' : 'push'; events.split(' ').forEach((event) => { if (!self.eventsListeners[event]) self.eventsListeners[event] = []; self.eventsListeners[event][method](handler); }); return self; } once(events, handler, priority) { const self = this; if (typeof handler !== 'function') return self; function onceHandler(...args) { self.off(events, onceHandler); if (onceHandler.f7proxy) { delete onceHandler.f7proxy; } handler.apply(self, args); } onceHandler.f7proxy = handler; return self.on(events, onceHandler, priority); } off(events, handler) { const self = this; if (!self.eventsListeners) return self; events.split(' ').forEach((event) => { if (typeof handler === 'undefined') { self.eventsListeners[event] = []; } else if (self.eventsListeners[event] && self.eventsListeners[event].length) { self.eventsListeners[event].forEach((eventHandler, index) => { if (eventHandler === handler || (eventHandler.f7proxy && eventHandler.f7proxy === handler)) { self.eventsListeners[event].splice(index, 1); } }); } }); return self; } emit(...args) { const self = this; if (!self.eventsListeners) return self; let events; let data; let context; if (typeof args[0] === 'string' || Array.isArray(args[0])) { events = args[0]; data = args.slice(1, args.length); context = self; } else { events = args[0].events; data = args[0].data; context = args[0].context || self; } const eventsArray = Array.isArray(events) ? events : events.split(' '); eventsArray.forEach((event) => { if (self.eventsListeners && self.eventsListeners[event]) { const handlers = []; self.eventsListeners[event].forEach((eventHandler) => { handlers.push(eventHandler); }); handlers.forEach((eventHandler) => { eventHandler.apply(context, data); }); } }); return self; } useModulesParams(instanceParams) { const instance = this; if (!instance.modules) return; Object.keys(instance.modules).forEach((moduleName) => { const module = instance.modules[moduleName]; // Extend params if (module.params) { Utils.extend(instanceParams, module.params); } }); } useModules(modulesParams = {}) { const instance = this; if (!instance.modules) return; Object.keys(instance.modules).forEach((moduleName) => { const module = instance.modules[moduleName]; const moduleParams = modulesParams[moduleName] || {}; // Extend instance methods and props if (module.instance) { Object.keys(module.instance).forEach((modulePropName) => { const moduleProp = module.instance[modulePropName]; if (typeof moduleProp === 'function') { instance[modulePropName] = moduleProp.bind(instance); } else { instance[modulePropName] = moduleProp; } }); } // Add event listeners if (module.on && instance.on) { Object.keys(module.on).forEach((moduleEventName) => { instance.on(moduleEventName, module.on[moduleEventName]); }); } // Module create callback if (module.create) { module.create.bind(instance)(moduleParams); } }); } static set components(components) { const Class = this; if (!Class.use) return; Class.use(components); } static installModule(module, ...params) { const Class = this; if (!Class.prototype.modules) Class.prototype.modules = {}; const name = module.name || (`${Object.keys(Class.prototype.modules).length}_${Utils.now()}`); Class.prototype.modules[name] = module; // Prototype if (module.proto) { Object.keys(module.proto).forEach((key) => { Class.prototype[key] = module.proto[key]; }); } // Class if (module.static) { Object.keys(module.static).forEach((key) => { Class[key] = module.static[key]; }); } // Callback if (module.install) { module.install.apply(Class, params); } return Class; } static use(module, ...params) { const Class = this; if (Array.isArray(module)) { module.forEach((m) => Class.installModule(m)); return Class; } return Class.installModule(module, ...params); } } function updateSize () { const swiper = this; let width; let height; const $el = swiper.$el; if (typeof swiper.params.width !== 'undefined') { width = swiper.params.width; } else { width = $el[0].clientWidth; } if (typeof swiper.params.height !== 'undefined') { height = swiper.params.height; } else { height = $el[0].clientHeight; } if ((width === 0 && swiper.isHorizontal()) || (height === 0 && swiper.isVertical())) { return; } // Subtract paddings width = width - parseInt($el.css('padding-left'), 10) - parseInt($el.css('padding-right'), 10); height = height - parseInt($el.css('padding-top'), 10) - parseInt($el.css('padding-bottom'), 10); Utils.extend(swiper, { width, height, size: swiper.isHorizontal() ? width : height, }); } function updateSlides () { const swiper = this; const params = swiper.params; const { $wrapperEl, size: swiperSize, rtlTranslate: rtl, wrongRTL, } = swiper; const isVirtual = swiper.virtual && params.virtual.enabled; const previousSlidesLength = isVirtual ? swiper.virtual.slides.length : swiper.slides.length; const slides = $wrapperEl.children(`.${swiper.params.slideClass}`); const slidesLength = isVirtual ? swiper.virtual.slides.length : slides.length; let snapGrid = []; const slidesGrid = []; const slidesSizesGrid = []; function slidesForMargin(slideIndex) { if (!params.cssMode) return true; if (slideIndex === slides.length - 1) { return false; } return true; } let offsetBefore = params.slidesOffsetBefore; if (typeof offsetBefore === 'function') { offsetBefore = params.slidesOffsetBefore.call(swiper); } let offsetAfter = params.slidesOffsetAfter; if (typeof offsetAfter === 'function') { offsetAfter = params.slidesOffsetAfter.call(swiper); } const previousSnapGridLength = swiper.snapGrid.length; const previousSlidesGridLength = swiper.snapGrid.length; let spaceBetween = params.spaceBetween; let slidePosition = -offsetBefore; let prevSlideSize = 0; let index = 0; if (typeof swiperSize === 'undefined') { return; } if (typeof spaceBetween === 'string' && spaceBetween.indexOf('%') >= 0) { spaceBetween = (parseFloat(spaceBetween.replace('%', '')) / 100) * swiperSize; } swiper.virtualSize = -spaceBetween; // reset margins if (rtl) slides.css({ marginLeft: '', marginTop: '' }); else slides.css({ marginRight: '', marginBottom: '' }); let slidesNumberEvenToRows; if (params.slidesPerColumn > 1) { if (Math.floor(slidesLength / params.slidesPerColumn) === slidesLength / swiper.params.slidesPerColumn) { slidesNumberEvenToRows = slidesLength; } else { slidesNumberEvenToRows = Math.ceil(slidesLength / params.slidesPerColumn) * params.slidesPerColumn; } if (params.slidesPerView !== 'auto' && params.slidesPerColumnFill === 'row') { slidesNumberEvenToRows = Math.max(slidesNumberEvenToRows, params.slidesPerView * params.slidesPerColumn); } } // Calc slides let slideSize; const slidesPerColumn = params.slidesPerColumn; const slidesPerRow = slidesNumberEvenToRows / slidesPerColumn; const numFullColumns = Math.floor(slidesLength / params.slidesPerColumn); for (let i = 0; i < slidesLength; i += 1) { slideSize = 0; const slide = slides.eq(i); if (params.slidesPerColumn > 1) { // Set slides order let newSlideOrderIndex; let column; let row; if (params.slidesPerColumnFill === 'row' && params.slidesPerGroup > 1) { const groupIndex = Math.floor(i / (params.slidesPerGroup * params.slidesPerColumn)); const slideIndexInGroup = i - params.slidesPerColumn * params.slidesPerGroup * groupIndex; const columnsInGroup = groupIndex === 0 ? params.slidesPerGroup : Math.min(Math.ceil((slidesLength - groupIndex * slidesPerColumn * params.slidesPerGroup) / slidesPerColumn), params.slidesPerGroup); row = Math.floor(slideIndexInGroup / columnsInGroup); column = (slideIndexInGroup - row * columnsInGroup) + groupIndex * params.slidesPerGroup; newSlideOrderIndex = column + ((row * slidesNumberEvenToRows) / slidesPerColumn); slide .css({ '-webkit-box-ordinal-group': newSlideOrderIndex, '-moz-box-ordinal-group': newSlideOrderIndex, '-ms-flex-order': newSlideOrderIndex, '-webkit-order': newSlideOrderIndex, order: newSlideOrderIndex, }); } else if (params.slidesPerColumnFill === 'column') { column = Math.floor(i / slidesPerColumn); row = i - (column * slidesPerColumn); if (column > numFullColumns || (column === numFullColumns && row === slidesPerColumn - 1)) { row += 1; if (row >= slidesPerColumn) { row = 0; column += 1; } } } else { row = Math.floor(i / slidesPerRow); column = i - (row * slidesPerRow); } slide.css( `margin-${swiper.isHorizontal() ? 'top' : 'left'}`, (row !== 0 && params.spaceBetween) && (`${params.spaceBetween}px`) ); } if (slide.css('display') === 'none') continue; // eslint-disable-line if (params.slidesPerView === 'auto') { const slideStyles = window.getComputedStyle(slide[0], null); const currentTransform = slide[0].style.transform; const currentWebKitTransform = slide[0].style.webkitTransform; if (currentTransform) { slide[0].style.transform = 'none'; } if (currentWebKitTransform) { slide[0].style.webkitTransform = 'none'; } if (params.roundLengths) { slideSize = swiper.isHorizontal() ? slide.outerWidth(true) : slide.outerHeight(true); } else { // eslint-disable-next-line if (swiper.isHorizontal()) { const width = parseFloat(slideStyles.getPropertyValue('width')); const paddingLeft = parseFloat(slideStyles.getPropertyValue('padding-left')); const paddingRight = parseFloat(slideStyles.getPropertyValue('padding-right')); const marginLeft = parseFloat(slideStyles.getPropertyValue('margin-left')); const marginRight = parseFloat(slideStyles.getPropertyValue('margin-right')); const boxSizing = slideStyles.getPropertyValue('box-sizing'); if (boxSizing && boxSizing === 'border-box') { slideSize = width + marginLeft + marginRight; } else { slideSize = width + paddingLeft + paddingRight + marginLeft + marginRight; } } else { const height = parseFloat(slideStyles.getPropertyValue('height')); const paddingTop = parseFloat(slideStyles.getPropertyValue('padding-top')); const paddingBottom = parseFloat(slideStyles.getPropertyValue('padding-bottom')); const marginTop = parseFloat(slideStyles.getPropertyValue('margin-top')); const marginBottom = parseFloat(slideStyles.getPropertyValue('margin-bottom')); const boxSizing = slideStyles.getPropertyValue('box-sizing'); if (boxSizing && boxSizing === 'border-box') { slideSize = height + marginTop + marginBottom; } else { slideSize = height + paddingTop + paddingBottom + marginTop + marginBottom; } } } if (currentTransform) { slide[0].style.transform = currentTransform; } if (currentWebKitTransform) { slide[0].style.webkitTransform = currentWebKitTransform; } if (params.roundLengths) slideSize = Math.floor(slideSize); } else { slideSize = (swiperSize - ((params.slidesPerView - 1) * spaceBetween)) / params.slidesPerView; if (params.roundLengths) slideSize = Math.floor(slideSize); if (slides[i]) { if (swiper.isHorizontal()) { slides[i].style.width = `${slideSize}px`; } else { slides[i].style.height = `${slideSize}px`; } } } if (slides[i]) { slides[i].swiperSlideSize = slideSize; } slidesSizesGrid.push(slideSize); if (params.centeredSlides) { slidePosition = slidePosition + (slideSize / 2) + (prevSlideSize / 2) + spaceBetween; if (prevSlideSize === 0 && i !== 0) slidePosition = slidePosition - (swiperSize / 2) - spaceBetween; if (i === 0) slidePosition = slidePosition - (swiperSize / 2) - spaceBetween; if (Math.abs(slidePosition) < 1 / 1000) slidePosition = 0; if (params.roundLengths) slidePosition = Math.floor(slidePosition); if ((index) % params.slidesPerGroup === 0) snapGrid.push(slidePosition); slidesGrid.push(slidePosition); } else { if (params.roundLengths) slidePosition = Math.floor(slidePosition); if ((index - Math.min(swiper.params.slidesPerGroupSkip, index)) % swiper.params.slidesPerGroup === 0) snapGrid.push(slidePosition); slidesGrid.push(slidePosition); slidePosition = slidePosition + slideSize + spaceBetween; } swiper.virtualSize += slideSize + spaceBetween; prevSlideSize = slideSize; index += 1; } swiper.virtualSize = Math.max(swiper.virtualSize, swiperSize) + offsetAfter; let newSlidesGrid; if ( rtl && wrongRTL && (params.effect === 'slide' || params.effect === 'coverflow')) { $wrapperEl.css({ width: `${swiper.virtualSize + params.spaceBetween}px` }); } if (params.setWrapperSize) { if (swiper.isHorizontal()) $wrapperEl.css({ width: `${swiper.virtualSize + params.spaceBetween}px` }); else $wrapperEl.css({ height: `${swiper.virtualSize + params.spaceBetween}px` }); } if (params.slidesPerColumn > 1) { swiper.virtualSize = (slideSize + params.spaceBetween) * slidesNumberEvenToRows; swiper.virtualSize = Math.ceil(swiper.virtualSize / params.slidesPerColumn) - params.spaceBetween; if (swiper.isHorizontal()) $wrapperEl.css({ width: `${swiper.virtualSize + params.spaceBetween}px` }); else $wrapperEl.css({ height: `${swiper.virtualSize + params.spaceBetween}px` }); if (params.centeredSlides) { newSlidesGrid = []; for (let i = 0; i < snapGrid.length; i += 1) { let slidesGridItem = snapGrid[i]; if (params.roundLengths) slidesGridItem = Math.floor(slidesGridItem); if (snapGrid[i] < swiper.virtualSize + snapGrid[0]) newSlidesGrid.push(slidesGridItem); } snapGrid = newSlidesGrid; } } // Remove last grid elements depending on width if (!params.centeredSlides) { newSlidesGrid = []; for (let i = 0; i < snapGrid.length; i += 1) { let slidesGridItem = snapGrid[i]; if (params.roundLengths) slidesGridItem = Math.floor(slidesGridItem); if (snapGrid[i] <= swiper.virtualSize - swiperSize) { newSlidesGrid.push(slidesGridItem); } } snapGrid = newSlidesGrid; if (Math.floor(swiper.virtualSize - swiperSize) - Math.floor(snapGrid[snapGrid.length - 1]) > 1) { snapGrid.push(swiper.virtualSize - swiperSize); } } if (snapGrid.length === 0) snapGrid = [0]; if (params.spaceBetween !== 0) { if (swiper.isHorizontal()) { if (rtl) slides.filter(slidesForMargin).css({ marginLeft: `${spaceBetween}px` }); else slides.filter(slidesForMargin).css({ marginRight: `${spaceBetween}px` }); } else slides.filter(slidesForMargin).css({ marginBottom: `${spaceBetween}px` }); } if (params.centeredSlides && params.centeredSlidesBounds) { let allSlidesSize = 0; slidesSizesGrid.forEach((slideSizeValue) => { allSlidesSize += slideSizeValue + (params.spaceBetween ? params.spaceBetween : 0); }); allSlidesSize -= params.spaceBetween; const maxSnap = allSlidesSize - swiperSize; snapGrid = snapGrid.map((snap) => { if (snap < 0) return -offsetBefore; if (snap > maxSnap) return maxSnap + offsetAfter; return snap; }); } if (params.centerInsufficientSlides) { let allSlidesSize = 0; slidesSizesGrid.forEach((slideSizeValue) => { allSlidesSize += slideSizeValue + (params.spaceBetween ? params.spaceBetween : 0); }); allSlidesSize -= params.spaceBetween; if (allSlidesSize < swiperSize) { const allSlidesOffset = (swiperSize - allSlidesSize) / 2; snapGrid.forEach((snap, snapIndex) => { snapGrid[snapIndex] = snap - allSlidesOffset; }); slidesGrid.forEach((snap, snapIndex) => { slidesGrid[snapIndex] = snap + allSlidesOffset; }); } } Utils.extend(swiper, { slides, snapGrid, slidesGrid, slidesSizesGrid, }); if (slidesLength !== previousSlidesLength) { swiper.emit('slidesLengthChange'); } if (snapGrid.length !== previousSnapGridLength) { if (swiper.params.watchOverflow) swiper.checkOverflow(); swiper.emit('snapGridLengthChange'); } if (slidesGrid.length !== previousSlidesGridLength) { swiper.emit('slidesGridLengthChange'); } if (params.watchSlidesProgress || params.watchSlidesVisibility) { swiper.updateSlidesOffset(); } } function updateAutoHeight (speed) { const swiper = this; const activeSlides = []; let newHeight = 0; let i; if (typeof speed === 'number') { swiper.setTransition(speed); } else if (speed === true) { swiper.setTransition(swiper.params.speed); } // Find slides currently in view if (swiper.params.slidesPerView !== 'auto' && swiper.params.slidesPerView > 1) { if (swiper.params.centeredSlides) { swiper.visibleSlides.each((index, slide) => { activeSlides.push(slide); }); } else { for (i = 0; i < Math.ceil(swiper.params.slidesPerView); i += 1) { const index = swiper.activeIndex + i; if (index > swiper.slides.length) break; activeSlides.push(swiper.slides.eq(index)[0]); } } } else { activeSlides.push(swiper.slides.eq(swiper.activeIndex)[0]); } // Find new height from highest slide in view for (i = 0; i < activeSlides.length; i += 1) { if (typeof activeSlides[i] !== 'undefined') { const height = activeSlides[i].offsetHeight; newHeight = height > newHeight ? height : newHeight; } } // Update Height if (newHeight) swiper.$wrapperEl.css('height', `${newHeight}px`); } function updateSlidesOffset () { const swiper = this; const slides = swiper.slides; for (let i = 0; i < slides.length; i += 1) { slides[i].swiperSlideOffset = swiper.isHorizontal() ? slides[i].offsetLeft : slides[i].offsetTop; } } function updateSlidesProgress (translate = (this && this.translate) || 0) { const swiper = this; const params = swiper.params; const { slides, rtlTranslate: rtl } = swiper; if (slides.length === 0) return; if (typeof slides[0].swiperSlideOffset === 'undefined') swiper.updateSlidesOffset(); let offsetCenter = -translate; if (rtl) offsetCenter = translate; // Visible Slides slides.removeClass(params.slideVisibleClass); swiper.visibleSlidesIndexes = []; swiper.visibleSlides = []; for (let i = 0; i < slides.length; i += 1) { const slide = slides[i]; const slideProgress = ( (offsetCenter + (params.centeredSlides ? swiper.minTranslate() : 0)) - slide.swiperSlideOffset ) / (slide.swiperSlideSize + params.spaceBetween); if (params.watchSlidesVisibility || (params.centeredSlides && params.autoHeight)) { const slideBefore = -(offsetCenter - slide.swiperSlideOffset); const slideAfter = slideBefore + swiper.slidesSizesGrid[i]; const isVisible = (slideBefore >= 0 && slideBefore < swiper.size - 1) || (slideAfter > 1 && slideAfter <= swiper.size) || (slideBefore <= 0 && slideAfter >= swiper.size); if (isVisible) { swiper.visibleSlides.push(slide); swiper.visibleSlidesIndexes.push(i); slides.eq(i).addClass(params.slideVisibleClass); } } slide.progress = rtl ? -slideProgress : slideProgress; } swiper.visibleSlides = $(swiper.visibleSlides); } function updateProgress (translate) { const swiper = this; if (typeof translate === 'undefined') { const multiplier = swiper.rtlTranslate ? -1 : 1; // eslint-disable-next-line translate = (swiper && swiper.translate && (swiper.translate * multiplier)) || 0; } const params = swiper.params; const translatesDiff = swiper.maxTranslate() - swiper.minTranslate(); let { progress, isBeginning, isEnd } = swiper; const wasBeginning = isBeginning; const wasEnd = isEnd; if (translatesDiff === 0) { progress = 0; isBeginning = true; isEnd = true; } else { progress = (translate - swiper.minTranslate()) / (translatesDiff); isBeginning = progress <= 0; isEnd = progress >= 1; } Utils.extend(swiper, { progress, isBeginning, isEnd, }); if (params.watchSlidesProgress || params.watchSlidesVisibility || (params.centeredSlides && params.autoHeight)) swiper.updateSlidesProgress(translate); if (isBeginning && !wasBeginning) { swiper.emit('reachBeginning toEdge'); } if (isEnd && !wasEnd) { swiper.emit('reachEnd toEdge'); } if ((wasBeginning && !isBeginning) || (wasEnd && !isEnd)) { swiper.emit('fromEdge'); } swiper.emit('progress', progress); } function updateSlidesClasses () { const swiper = this; const { slides, params, $wrapperEl, activeIndex, realIndex, } = swiper; const isVirtual = swiper.virtual && params.virtual.enabled; slides.removeClass(`${params.slideActiveClass} ${params.slideNextClass} ${params.slidePrevClass} ${params.slideDuplicateActiveClass} ${params.slideDuplicateNextClass} ${params.slideDuplicatePrevClass}`); let activeSlide; if (isVirtual) { activeSlide = swiper.$wrapperEl.find(`.${params.slideClass}[data-swiper-slide-index="${activeIndex}"]`); } else { activeSlide = slides.eq(activeIndex); } // Active classes activeSlide.addClass(params.slideActiveClass); if (params.loop) { // Duplicate to all looped slides if (activeSlide.hasClass(params.slideDuplicateClass)) { $wrapperEl .children(`.${params.slideClass}:not(.${params.slideDuplicateClass})[data-swiper-slide-index="${realIndex}"]`) .addClass(params.slideDuplicateActiveClass); } else { $wrapperEl .children(`.${params.slideClass}.${params.slideDuplicateClass}[data-swiper-slide-index="${realIndex}"]`) .addClass(params.slideDuplicateActiveClass); } } // Next Slide let nextSlide = activeSlide.nextAll(`.${params.slideClass}`).eq(0).addClass(params.slideNextClass); if (params.loop && nextSlide.length === 0) { nextSlide = slides.eq(0); nextSlide.addClass(params.slideNextClass); } // Prev Slide let prevSlide = activeSlide.prevAll(`.${params.slideClass}`).eq(0).addClass(params.slidePrevClass); if (params.loop && prevSlide.length === 0) { prevSlide = slides.eq(-1); prevSlide.addClass(params.slidePrevClass); } if (params.loop) { // Duplicate to all looped slides if (nextSlide.hasClass(params.slideDuplicateClass)) { $wrapperEl .children(`.${params.slideClass}:not(.${params.slideDuplicateClass})[data-swiper-slide-index="${nextSlide.attr('data-swiper-slide-index')}"]`) .addClass(params.slideDuplicateNextClass); } else { $wrapperEl .children(`.${params.slideClass}.${params.slideDuplicateClass}[data-swiper-slide-index="${nextSlide.attr('data-swiper-slide-index')}"]`) .addClass(params.slideDuplicateNextClass); } if (prevSlide.hasClass(params.slideDuplicateClass)) { $wrapperEl .children(`.${params.slideClass}:not(.${params.slideDuplicateClass})[data-swiper-slide-index="${prevSlide.attr('data-swiper-slide-index')}"]`) .addClass(params.slideDuplicatePrevClass); } else { $wrapperEl .children(`.${params.slideClass}.${params.slideDuplicateClass}[data-swiper-slide-index="${prevSlide.attr('data-swiper-slide-index')}"]`) .addClass(params.slideDuplicatePrevClass); } } } function updateActiveIndex (newActiveIndex) { const swiper = this; const translate = swiper.rtlTranslate ? swiper.translate : -swiper.translate; const { slidesGrid, snapGrid, params, activeIndex: previousIndex, realIndex: previousRealIndex, snapIndex: previousSnapIndex, } = swiper; let activeIndex = newActiveIndex; let snapIndex; if (typeof activeIndex === 'undefined') { for (let i = 0; i < slidesGrid.length; i += 1) { if (typeof slidesGrid[i + 1] !== 'undefined') { if (translate >= slidesGrid[i] && translate < slidesGrid[i + 1] - ((slidesGrid[i + 1] - slidesGrid[i]) / 2)) { activeIndex = i; } else if (translate >= slidesGrid[i] && translate < slidesGrid[i + 1]) { activeIndex = i + 1; } } else if (translate >= slidesGrid[i]) { activeIndex = i; } } // Normalize slideIndex if (params.normalizeSlideIndex) { if (activeIndex < 0 || typeof activeIndex === 'undefined') activeIndex = 0; } } if (snapGrid.indexOf(translate) >= 0) { snapIndex = snapGrid.indexOf(translate); } else { const skip = Math.min(params.slidesPerGroupSkip, activeIndex); snapIndex = skip + Math.floor((activeIndex - skip) / params.slidesPerGroup); } if (snapIndex >= snapGrid.length) snapIndex = snapGrid.length - 1; if (activeIndex === previousIndex) { if (snapIndex !== previousSnapIndex) { swiper.snapIndex = snapIndex; swiper.emit('snapIndexChange'); } return; } // Get real index const realIndex = parseInt(swiper.slides.eq(activeIndex).attr('data-swiper-slide-index') || activeIndex, 10); Utils.extend(swiper, { snapIndex, realIndex, previousIndex, activeIndex, }); swiper.emit('activeIndexChange'); swiper.emit('snapIndexChange'); if (previousRealIndex !== realIndex) { swiper.emit('realIndexChange'); } if (swiper.initialized || swiper.params.runCallbacksOnInit) { swiper.emit('slideChange'); } } function updateClickedSlide (e) { const swiper = this; const params = swiper.params; const slide = $(e.target).closest(`.${params.slideClass}`)[0]; let slideFound = false; if (slide) { for (let i = 0; i < swiper.slides.length; i += 1) { if (swiper.slides[i] === slide) slideFound = true; } } if (slide && slideFound) { swiper.clickedSlide = slide; if (swiper.virtual && swiper.params.virtual.enabled) { swiper.clickedIndex = parseInt($(slide).attr('data-swiper-slide-index'), 10); } else { swiper.clickedIndex = $(slide).index(); } } else { swiper.clickedSlide = undefined; swiper.clickedIndex = undefined; return; } if (params.slideToClickedSlide && swiper.clickedIndex !== undefined && swiper.clickedIndex !== swiper.activeIndex) { swiper.slideToClickedSlide(); } } var update = { updateSize, updateSlides, updateAutoHeight, updateSlidesOffset, updateSlidesProgress, updateProgress, updateSlidesClasses, updateActiveIndex, updateClickedSlide, }; function getTranslate (axis = this.isHorizontal() ? 'x' : 'y') { const swiper = this; const { params, rtlTranslate: rtl, translate, $wrapperEl, } = swiper; if (params.virtualTranslate) { return rtl ? -translate : translate; } if (params.cssMode) { return translate; } let currentTranslate = Utils.getTranslate($wrapperEl[0], axis); if (rtl) currentTranslate = -currentTranslate; return currentTranslate || 0; } function setTranslate (translate, byController) { const swiper = this; const { rtlTranslate: rtl, params, $wrapperEl, wrapperEl, progress, } = swiper; let x = 0; let y = 0; const z = 0; if (swiper.isHorizontal()) { x = rtl ? -translate : translate; } else { y = translate; } if (params.roundLengths) { x = Math.floor(x); y = Math.floor(y); } if (params.cssMode) { wrapperEl[swiper.isHorizontal() ? 'scrollLeft' : 'scrollTop'] = swiper.isHorizontal() ? -x : -y; } else if (!params.virtualTranslate) { $wrapperEl.transform(`translate3d(${x}px, ${y}px, ${z}px)`); } swiper.previousTranslate = swiper.translate; swiper.translate = swiper.isHorizontal() ? x : y; // Check if we need to update progress let newProgress; const translatesDiff = swiper.maxTranslate() - swiper.minTranslate(); if (translatesDiff === 0) { newProgress = 0; } else { newProgress = (translate - swiper.minTranslate()) / (translatesDiff); } if (newProgress !== progress) { swiper.updateProgress(translate); } swiper.emit('setTranslate', swiper.translate, byController); } function minTranslate () { return (-this.snapGrid[0]); } function maxTranslate () { return (-this.snapGrid[this.snapGrid.length - 1]); } function translateTo (translate = 0, speed = this.params.speed, runCallbacks = true, translateBounds = true, internal) { const swiper = this; const { params, wrapperEl, } = swiper; if (swiper.animating && params.preventInteractionOnTransition) { return false; } const minTranslate = swiper.minTranslate(); const maxTranslate = swiper.maxTranslate(); let newTranslate; if (translateBounds && translate > minTranslate) newTranslate = minTranslate; else if (translateBounds && translate < maxTranslate) newTranslate = maxTranslate; else newTranslate = translate; // Update progress swiper.updateProgress(newTranslate); if (params.cssMode) { const isH = swiper.isHorizontal(); if (speed === 0) { wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = -newTranslate; } else { // eslint-disable-next-line if (wrapperEl.scrollTo) { wrapperEl.scrollTo({ [isH ? 'left' : 'top']: -newTranslate, behavior: 'smooth', }); } else { wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = -newTranslate; } } return true; } if (speed === 0) { swiper.setTransition(0); swiper.setTranslate(newTranslate); if (runCallbacks) { swiper.emit('beforeTransitionStart', speed, internal); swiper.emit('transitionEnd'); } } else { swiper.setTransition(speed); swiper.setTranslate(newTranslate); if (runCallbacks) { swiper.emit('beforeTransitionStart', speed, internal); swiper.emit('transitionStart'); } if (!swiper.animating) { swiper.animating = true; if (!swiper.onTranslateToWrapperTransitionEnd) { swiper.onTranslateToWrapperTransitionEnd = function transitionEnd(e) { if (!swiper || swiper.destroyed) return; if (e.target !== this) return; swiper.$wrapperEl[0].removeEventListener('transitionend', swiper.onTranslateToWrapperTransitionEnd); swiper.$wrapperEl[0].removeEventListener('webkitTransitionEnd', swiper.onTranslateToWrapperTransitionEnd); swiper.onTranslateToWrapperTransitionEnd = null; delete swiper.onTranslateToWrapperTransitionEnd; if (runCallbacks) { swiper.emit('transitionEnd'); } }; } swiper.$wrapperEl[0].addEventListener('transitionend', swiper.onTranslateToWrapperTransitionEnd); swiper.$wrapperEl[0].addEventListener('webkitTransitionEnd', swiper.onTranslateToWrapperTransitionEnd); } } return true; } var translate = { getTranslate, setTranslate, minTranslate, maxTranslate, translateTo, }; function setTransition (duration, byController) { const swiper = this; if (!swiper.params.cssMode) { swiper.$wrapperEl.transition(duration); } swiper.emit('setTransition', duration, byController); } function transitionStart (runCallbacks = true, direction) { const swiper = this; const { activeIndex, params, previousIndex } = swiper; if (params.cssMode) return; if (params.autoHeight) { swiper.updateAutoHeight(); } let dir = direction; if (!dir) { if (activeIndex > previousIndex) dir = 'next'; else if (activeIndex < previousIndex) dir = 'prev'; else dir = 'reset'; } swiper.emit('transitionStart'); if (runCallbacks && activeIndex !== previousIndex) { if (dir === 'reset') { swiper.emit('slideResetTransitionStart'); return; } swiper.emit('slideChangeTransitionStart'); if (dir === 'next') { swiper.emit('slideNextTransitionStart'); } else { swiper.emit('slidePrevTransitionStart'); } } } function transitionEnd (runCallbacks = true, direction) { const swiper = this; const { activeIndex, previousIndex, params } = swiper; swiper.animating = false; if (params.cssMode) return; swiper.setTransition(0); let dir = direction; if (!dir) { if (activeIndex > previousIndex) dir = 'next'; else if (activeIndex < previousIndex) dir = 'prev'; else dir = 'reset'; } swiper.emit('transitionEnd'); if (runCallbacks && activeIndex !== previousIndex) { if (dir === 'reset') { swiper.emit('slideResetTransitionEnd'); return; } swiper.emit('slideChangeTransitionEnd'); if (dir === 'next') { swiper.emit('slideNextTransitionEnd'); } else { swiper.emit('slidePrevTransitionEnd'); } } } var transition = { setTransition, transitionStart, transitionEnd, }; function slideTo (index = 0, speed = this.params.speed, runCallbacks = true, internal) { const swiper = this; let slideIndex = index; if (slideIndex < 0) slideIndex = 0; const { params, snapGrid, slidesGrid, previousIndex, activeIndex, rtlTranslate: rtl, wrapperEl, } = swiper; if (swiper.animating && params.preventInteractionOnTransition) { return false; } const skip = Math.min(swiper.params.slidesPerGroupSkip, slideIndex); let snapIndex = skip + Math.floor((slideIndex - skip) / swiper.params.slidesPerGroup); if (snapIndex >= snapGrid.length) snapIndex = snapGrid.length - 1; if ((activeIndex || params.initialSlide || 0) === (previousIndex || 0) && runCallbacks) { swiper.emit('beforeSlideChangeStart'); } const translate = -snapGrid[snapIndex]; // Update progress swiper.updateProgress(translate); // Normalize slideIndex if (params.normalizeSlideIndex) { for (let i = 0; i < slidesGrid.length; i += 1) { if (-Math.floor(translate * 100) >= Math.floor(slidesGrid[i] * 100)) { slideIndex = i; } } } // Directions locks if (swiper.initialized && slideIndex !== activeIndex) { if (!swiper.allowSlideNext && translate < swiper.translate && translate < swiper.minTranslate()) { return false; } if (!swiper.allowSlidePrev && translate > swiper.translate && translate > swiper.maxTranslate()) { if ((activeIndex || 0) !== slideIndex) return false; } } let direction; if (slideIndex > activeIndex) direction = 'next'; else if (slideIndex < activeIndex) direction = 'prev'; else direction = 'reset'; // Update Index if ((rtl && -translate === swiper.translate) || (!rtl && translate === swiper.translate)) { swiper.updateActiveIndex(slideIndex); // Update Height if (params.autoHeight) { swiper.updateAutoHeight(); } swiper.updateSlidesClasses(); if (params.effect !== 'slide') { swiper.setTranslate(translate); } if (direction !== 'reset') { swiper.transitionStart(runCallbacks, direction); swiper.transitionEnd(runCallbacks, direction); } return false; } if (params.cssMode) { const isH = swiper.isHorizontal(); let t = -translate; if (rtl) { t = wrapperEl.scrollWidth - wrapperEl.offsetWidth - t; } if (speed === 0) { wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = t; } else { // eslint-disable-next-line if (wrapperEl.scrollTo) { wrapperEl.scrollTo({ [isH ? 'left' : 'top']: t, behavior: 'smooth', }); } else { wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = t; } } return true; } if (speed === 0) { swiper.setTransition(0); swiper.setTranslate(translate); swiper.updateActiveIndex(slideIndex); swiper.updateSlidesClasses(); swiper.emit('beforeTransitionStart', speed, internal); swiper.transitionStart(runCallbacks, direction); swiper.transitionEnd(runCallbacks, direction); } else { swiper.setTransition(speed); swiper.setTranslate(translate); swiper.updateActiveIndex(slideIndex); swiper.updateSlidesClasses(); swiper.emit('beforeTransitionStart', speed, internal); swiper.transitionStart(runCallbacks, direction); if (!swiper.animating) { swiper.animating = true; if (!swiper.onSlideToWrapperTransitionEnd) { swiper.onSlideToWrapperTransitionEnd = function transitionEnd(e) { if (!swiper || swiper.destroyed) return; if (e.target !== this) return; swiper.$wrapperEl[0].removeEventListener('transitionend', swiper.onSlideToWrapperTransitionEnd); swiper.$wrapperEl[0].removeEventListener('webkitTransitionEnd', swiper.onSlideToWrapperTransitionEnd); swiper.onSlideToWrapperTransitionEnd = null; delete swiper.onSlideToWrapperTransitionEnd; swiper.transitionEnd(runCallbacks, direction); }; } swiper.$wrapperEl[0].addEventListener('transitionend', swiper.onSlideToWrapperTransitionEnd); swiper.$wrapperEl[0].addEventListener('webkitTransitionEnd', swiper.onSlideToWrapperTransitionEnd); } } return true; } function slideToLoop (index = 0, speed = this.params.speed, runCallbacks = true, internal) { const swiper = this; let newIndex = index; if (swiper.params.loop) { newIndex += swiper.loopedSlides; } return swiper.slideTo(newIndex, speed, runCallbacks, internal); } /* eslint no-unused-vars: "off" */ function slideNext (speed = this.params.speed, runCallbacks = true, internal) { const swiper = this; const { params, animating } = swiper; const increment = swiper.activeIndex < params.slidesPerGroupSkip ? 1 : params.slidesPerGroup; if (params.loop) { if (animating) return false; swiper.loopFix(); // eslint-disable-next-line swiper._clientLeft = swiper.$wrapperEl[0].clientLeft; } return swiper.slideTo(swiper.activeIndex + increment, speed, runCallbacks, internal); } /* eslint no-unused-vars: "off" */ function slidePrev (speed = this.params.speed, runCallbacks = true, internal) { const swiper = this; const { params, animating, snapGrid, slidesGrid, rtlTranslate, } = swiper; if (params.loop) { if (animating) return false; swiper.loopFix(); // eslint-disable-next-line swiper._clientLeft = swiper.$wrapperEl[0].clientLeft; } const translate = rtlTranslate ? swiper.translate : -swiper.translate; function normalize(val) { if (val < 0) return -Math.floor(Math.abs(val)); return Math.floor(val); } const normalizedTranslate = normalize(translate); const normalizedSnapGrid = snapGrid.map((val) => normalize(val)); const normalizedSlidesGrid = slidesGrid.map((val) => normalize(val)); const currentSnap = snapGrid[normalizedSnapGrid.indexOf(normalizedTranslate)]; let prevSnap = snapGrid[normalizedSnapGrid.indexOf(normalizedTranslate) - 1]; if (typeof prevSnap === 'undefined' && params.cssMode) { snapGrid.forEach((snap) => { if (!prevSnap && normalizedTranslate >= snap) prevSnap = snap; }); } let prevIndex; if (typeof prevSnap !== 'undefined') { prevIndex = slidesGrid.indexOf(prevSnap); if (prevIndex < 0) prevIndex = swiper.activeIndex - 1; } return swiper.slideTo(prevIndex, speed, runCallbacks, internal); } /* eslint no-unused-vars: "off" */ function slideReset (speed = this.params.speed, runCallbacks = true, internal) { const swiper = this; return swiper.slideTo(swiper.activeIndex, speed, runCallbacks, internal); } /* eslint no-unused-vars: "off" */ function slideToClosest (speed = this.params.speed, runCallbacks = true, internal, threshold = 0.5) { const swiper = this; let index = swiper.activeIndex; const skip = Math.min(swiper.params.slidesPerGroupSkip, index); const snapIndex = skip + Math.floor((index - skip) / swiper.params.slidesPerGroup); const translate = swiper.rtlTranslate ? swiper.translate : -swiper.translate; if (translate >= swiper.snapGrid[snapIndex]) { // The current translate is on or after the current snap index, so the choice // is between the current index and the one after it. const currentSnap = swiper.snapGrid[snapIndex]; const nextSnap = swiper.snapGrid[snapIndex + 1]; if ((translate - currentSnap) > (nextSnap - currentSnap) * threshold) { index += swiper.params.slidesPerGroup; } } else { // The current translate is before the current snap index, so the choice // is between the current index and the one before it. const prevSnap = swiper.snapGrid[snapIndex - 1]; const currentSnap = swiper.snapGrid[snapIndex]; if ((translate - prevSnap) <= (currentSnap - prevSnap) * threshold) { index -= swiper.params.slidesPerGroup; } } index = Math.max(index, 0); index = Math.min(index, swiper.slidesGrid.length - 1); return swiper.slideTo(index, speed, runCallbacks, internal); } function slideToClickedSlide () { const swiper = this; const { params, $wrapperEl } = swiper; const slidesPerView = params.slidesPerView === 'auto' ? swiper.slidesPerViewDynamic() : params.slidesPerView; let slideToIndex = swiper.clickedIndex; let realIndex; if (params.loop) { if (swiper.animating) return; realIndex = parseInt($(swiper.clickedSlide).attr('data-swiper-slide-index'), 10); if (params.centeredSlides) { if ( (slideToIndex < swiper.loopedSlides - (slidesPerView / 2)) || (slideToIndex > (swiper.slides.length - swiper.loopedSlides) + (slidesPerView / 2)) ) { swiper.loopFix(); slideToIndex = $wrapperEl .children(`.${params.slideClass}[data-swiper-slide-index="${realIndex}"]:not(.${params.slideDuplicateClass})`) .eq(0) .index(); Utils.nextTick(() => { swiper.slideTo(slideToIndex); }); } else { swiper.slideTo(slideToIndex); } } else if (slideToIndex > swiper.slides.length - slidesPerView) { swiper.loopFix(); slideToIndex = $wrapperEl .children(`.${params.slideClass}[data-swiper-slide-index="${realIndex}"]:not(.${params.slideDuplicateClass})`) .eq(0) .index(); Utils.nextTick(() => { swiper.slideTo(slideToIndex); }); } else { swiper.slideTo(slideToIndex); } } else { swiper.slideTo(slideToIndex); } } var slide = { slideTo, slideToLoop, slideNext, slidePrev, slideReset, slideToClosest, slideToClickedSlide, }; function loopCreate () { const swiper = this; const { params, $wrapperEl } = swiper; // Remove duplicated slides $wrapperEl.children(`