(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["js/productDetail~js/productTile~js/search"],{ /***/ "./cartridges/app_storefront_base/cartridge/client/default/js/product/base.js": /*!************************************************************************************!*\ !*** ./cartridges/app_storefront_base/cartridge/client/default/js/product/base.js ***! \************************************************************************************/ /*! exports provided: default */ /*! ModuleConcatenation bailout: Module uses injected variables ($) */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function($) { /** * Retrieves the relevant pid value * @param {jquery} $el - DOM container for a given add to cart button * @return {string} - value to be used when adding product to cart */ function getPidValue($el) { var pid; if ($('#quickViewModal').hasClass('show') && !$('.product-set').length) { pid = $($el).closest('.modal-content').find('.product-quickview').data('pid'); } else if ($('.product-set-detail').length || $('.product-set').length) { pid = $($el).closest('.product-detail').find('.product-id').text(); } else { pid = $('.product-detail:not(".bundle-item")').data('pid'); } return pid; } /** * Retrieve contextual quantity selector * @param {jquery} $el - DOM container for the relevant quantity * @return {jquery} - quantity selector DOM container */ function getQuantitySelector($el) { return $el && $('.set-items').length ? $($el).closest('.product-detail').find('.quantity-select') : $('.quantity-select'); } /** * Retrieves the value associated with the Quantity pull-down menu * @param {jquery} $el - DOM container for the relevant quantity * @return {string} - value found in the quantity input */ function getQuantitySelected($el) { return getQuantitySelector($el).val(); } /** * Process the attribute values for an attribute that has image swatches * * @param {Object} attr - Attribute * @param {string} attr.id - Attribute ID * @param {Object[]} attr.values - Array of attribute value objects * @param {string} attr.values.value - Attribute coded value * @param {string} attr.values.url - URL to de/select an attribute value of the product * @param {boolean} attr.values.isSelectable - Flag as to whether an attribute value can be * selected. If there is no variant that corresponds to a specific combination of attribute * values, an attribute may be disabled in the Product Detail Page * @param {jQuery} $productContainer - DOM container for a given product */ function processSwatchValues(attr, $productContainer) { attr.values.forEach(function (attrValue) { var $attrValue = $productContainer.find('[data-attr="' + attr.id + '"] [data-attr-value="' + attrValue.value + '"]'); var $swatchAnchor = $attrValue.parent(); if (attrValue.selected) { $attrValue.addClass('selected'); } else { $attrValue.removeClass('selected'); } if (attrValue.url) { $swatchAnchor.attr('href', attrValue.url); } else { $swatchAnchor.removeAttr('href'); } // Disable if not selectable $attrValue.removeClass('selectable unselectable'); $attrValue.addClass(attrValue.selectable ? 'selectable' : 'unselectable'); }); } /** * Process attribute values associated with an attribute that does not have image swatches * * @param {Object} attr - Attribute * @param {string} attr.id - Attribute ID * @param {Object[]} attr.values - Array of attribute value objects * @param {string} attr.values.value - Attribute coded value * @param {string} attr.values.url - URL to de/select an attribute value of the product * @param {boolean} attr.values.isSelectable - Flag as to whether an attribute value can be * selected. If there is no variant that corresponds to a specific combination of attribute * values, an attribute may be disabled in the Product Detail Page * @param {jQuery} $productContainer - DOM container for a given product */ function processNonSwatchValues(attr, $productContainer) { var $attr = '[data-attr="' + attr.id + '"]'; var $defaultOption = $productContainer.find($attr + ' .select-' + attr.id + ' option:first'); $defaultOption.attr('value', attr.resetUrl); attr.values.forEach(function (attrValue) { var $attrValue = $productContainer.find($attr + ' [data-attr-value="' + attrValue.value + '"]'); $attrValue.attr('value', attrValue.url).removeAttr('disabled'); if (!attrValue.selectable) { $attrValue.attr('disabled', true); } }); } /** * Routes the handling of attribute processing depending on whether the attribute has image * swatches or not * * @param {Object} attrs - Attribute * @param {string} attr.id - Attribute ID * @param {jQuery} $productContainer - DOM element for a given product */ function updateAttrs(attrs, $productContainer) { // Currently, the only attribute type that has image swatches is Color. var attrsWithSwatches = ['color']; attrs.forEach(function (attr) { if (attrsWithSwatches.indexOf(attr.id) > -1) { processSwatchValues(attr, $productContainer); } else { processNonSwatchValues(attr, $productContainer); } }); } /** * Updates the availability status in the Product Detail Page * * @param {Object} response - Ajax response object after an * attribute value has been [de]selected * @param {jQuery} $productContainer - DOM element for a given product */ function updateAvailability(response, $productContainer) { var availabilityValue = ''; var availabilityMessages = response.product.availability.messages; if (!response.product.readyToOrder) { availabilityValue = '
' + response.resources.info_selectforstock + '
'; } else { availabilityMessages.forEach(function (message) { availabilityValue += '
' + message + '
'; }); } $($productContainer).trigger('product:updateAvailability', { product: response.product, $productContainer: $productContainer, message: availabilityValue, resources: response.resources }); } /** * Generates html for promotions section * * @param {array} promotions - list of promotions * @return {string} - Compiled HTML */ function getPromotionsHtml(promotions) { if (!promotions) { return ''; } var html = ''; promotions.forEach(function (promotion) { html += '
' + promotion.calloutMsg + '
'; }); return html; } /** * Generates html for product attributes section * * @param {array} attributes - list of attributes * @return {string} - Compiled HTML */ function getAttributesHtml(attributes) { if (!attributes) { return ''; } var html = ''; attributes.forEach(function (attributeGroup) { if (attributeGroup.ID === 'mainAttributes') { attributeGroup.attributes.forEach(function (attribute) { html += '
' + attribute.label + ': ' + attribute.value + '
'; }); } }); return html; } /** * @typedef UpdatedOptionValue * @type Object * @property {string} id - Option value ID for look up * @property {string} url - Updated option value selection URL */ /** * @typedef OptionSelectionResponse * @type Object * @property {string} priceHtml - Updated price HTML code * @property {Object} options - Updated Options * @property {string} options.id - Option ID * @property {UpdatedOptionValue[]} options.values - Option values */ /** * Updates DOM using post-option selection Ajax response * * @param {OptionSelectionResponse} options - Ajax response options from selecting a product option * @param {jQuery} $productContainer - DOM element for current product */ function updateOptions(options, $productContainer) { options.forEach(function (option) { var $optionEl = $productContainer.find('.product-option[data-option-id*="' + option.id + '"]'); option.values.forEach(function (value) { var valueEl = $optionEl.find('option[data-value-id*="' + value.id + '"]'); valueEl.val(value.url); }); }); } /** * Parses JSON from Ajax call made whenever an attribute value is [de]selected * @param {Object} response - response from Ajax call * @param {Object} response.product - Product object * @param {string} response.product.id - Product ID * @param {Object[]} response.product.variationAttributes - Product attributes * @param {Object[]} response.product.images - Product images * @param {boolean} response.product.hasRequiredAttrsSelected - Flag as to whether all required * attributes have been selected. Used partially to * determine whether the Add to Cart button can be enabled * @param {jQuery} $productContainer - DOM element for a given product. */ function handleVariantResponse(response, $productContainer) { var isChoiceOfBonusProducts = $productContainer.parents('.choose-bonus-product-dialog').length > 0; var isVaraint; if (response.product.variationAttributes) { updateAttrs(response.product.variationAttributes, $productContainer); isVaraint = response.product.productType === 'variant'; if (isChoiceOfBonusProducts && isVaraint) { $productContainer.parent('.bonus-product-item').data('pid', response.product.id); $productContainer.parent('.bonus-product-item').data('ready-to-order', response.product.readyToOrder); } } // Update primary images var primaryImageUrls = response.product.images; primaryImageUrls.large.forEach(function (imageUrl, idx) { $productContainer.find('.primary-images').find('img').eq(idx).attr('src', imageUrl.url); }); // Update pricing if (!isChoiceOfBonusProducts) { var $priceSelector = $('.prices .price', $productContainer).length ? $('.prices .price', $productContainer) : $('.prices .price'); $priceSelector.replaceWith(response.product.price.html); } // Update promotions $('.promotions').empty().html(getPromotionsHtml(response.product.promotions)); updateAvailability(response, $productContainer); if (isChoiceOfBonusProducts) { var $selectButton = $productContainer.find('.select-bonus-product'); $selectButton.trigger('bonusproduct:updateSelectButton', { product: response.product, $productContainer: $productContainer }); } else { // Enable "Add to Cart" button if all required attributes have been selected $('button.add-to-cart, button.add-to-cart-global, button.update-cart-product-global').trigger('product:updateAddToCart', { product: response.product, $productContainer: $productContainer }).trigger('product:statusUpdate', response.product); } // Update attributes $productContainer.find('.main-attributes').empty().html(getAttributesHtml(response.product.attributes)); } /** * @typespec UpdatedQuantity * @type Object * @property {boolean} selected - Whether the quantity has been selected * @property {string} value - The number of products to purchase * @property {string} url - Compiled URL that specifies variation attributes, product ID, options, * etc. */ /** * Updates the quantity DOM elements post Ajax call * @param {UpdatedQuantity[]} quantities - * @param {jQuery} $productContainer - DOM container for a given product */ function updateQuantities(quantities, $productContainer) { if (!($productContainer.parent('.bonus-product-item').length > 0)) { var optionsHtml = quantities.map(function (quantity) { var selected = quantity.selected ? ' selected ' : ''; return ''; }).join(''); getQuantitySelector($productContainer).empty().html(optionsHtml); } } /** * updates the product view when a product attribute is selected or deselected or when * changing quantity * @param {string} selectedValueUrl - the Url for the selected variation value * @param {jQuery} $productContainer - DOM element for current product */ function attributeSelect(selectedValueUrl, $productContainer) { if (selectedValueUrl) { $('body').trigger('product:beforeAttributeSelect', { url: selectedValueUrl, container: $productContainer }); $.ajax({ url: selectedValueUrl, method: 'GET', success: function success(data) { handleVariantResponse(data, $productContainer); updateOptions(data.product.options, $productContainer); updateQuantities(data.product.quantities, $productContainer); $('body').trigger('product:afterAttributeSelect', { data: data, container: $productContainer }); $.spinner().stop(); }, error: function error() { $.spinner().stop(); } }); } } /** * Retrieves url to use when adding a product to the cart * * @return {string} - The provided URL to use when adding a product to the cart */ function getAddToCartUrl() { return $('.add-to-cart-url').val(); } /** * Parses the html for a modal window * @param {string} html - representing the body and footer of the modal window * * @return {Object} - Object with properties body and footer. */ function parseHtml(html) { var $html = $('
').append($.parseHTML(html)); var body = $html.find('.choice-of-bonus-product'); var footer = $html.find('.modal-footer').children(); return { body: body, footer: footer }; } /** * Retrieves url to use when adding a product to the cart * * @param {Object} data - data object used to fill in dynamic portions of the html */ function chooseBonusProducts(data) { $('.modal-body').spinner().start(); if ($('#chooseBonusProductModal').length !== 0) { $('#chooseBonusProductModal').remove(); } var bonusUrl; if (data.bonusChoiceRuleBased) { bonusUrl = data.showProductsUrlRuleBased; } else { bonusUrl = data.showProductsUrlListBased; } var htmlString = '' + ''; $('body').append(htmlString); $('.modal-body').spinner().start(); $.ajax({ url: bonusUrl, method: 'GET', dataType: 'html', success: function success(html) { var parsedHtml = parseHtml(html); $('#chooseBonusProductModal .modal-body').empty(); $('#chooseBonusProductModal .modal-body').html(parsedHtml.body); $('#chooseBonusProductModal .modal-footer').html(parsedHtml.footer); $('#chooseBonusProductModal').modal('show'); $.spinner().stop(); }, error: function error() { $.spinner().stop(); } }); } /** * Updates the Mini-Cart quantity value after the customer has pressed the "Add to Cart" button * @param {string} response - ajax response from clicking the add to cart button */ function handlePostCartAdd(response) { $('.minicart').trigger('count:update', response); var messageType = response.error ? 'alert-danger' : 'alert-success'; // show add to cart toast if (response.newBonusDiscountLineItem && Object.keys(response.newBonusDiscountLineItem).length !== 0) { chooseBonusProducts(response.newBonusDiscountLineItem); } else { if ($('.add-to-cart-messages').length === 0) { $('body').append('
'); } $('.add-to-cart-messages').append(''); setTimeout(function () { $('.add-to-basket-alert').remove(); }, 5000); } } /** * Retrieves the bundle product item ID's for the Controller to replace bundle master product * items with their selected variants * * @return {string[]} - List of selected bundle product item ID's */ function getChildProducts() { var childProducts = []; $('.bundle-item').each(function () { childProducts.push({ pid: $(this).find('.product-id').text(), quantity: parseInt($(this).find('label.quantity').data('quantity'), 10) }); }); return childProducts.length ? JSON.stringify(childProducts) : []; } /** * Retrieve product options * * @param {jQuery} $productContainer - DOM element for current product * @return {string} - Product options and their selected values */ function getOptions($productContainer) { var options = $productContainer.find('.product-option').map(function () { var $elOption = $(this).find('.options-select'); var urlValue = $elOption.val(); var selectedValueId = $elOption.find('option[value="' + urlValue + '"]').data('value-id'); return { optionId: $(this).data('option-id'), selectedValueId: selectedValueId }; }).toArray(); return JSON.stringify(options); } /* harmony default export */ __webpack_exports__["default"] = ({ attributeSelect: attributeSelect, methods: { editBonusProducts: function editBonusProducts(data) { chooseBonusProducts(data); } }, colorAttribute: function colorAttribute() { $(document).on('click', '[data-attr="color"] a', function (e) { e.preventDefault(); if ($(this).attr('disabled')) { return; } var $productContainer = $(this).closest('.set-item'); if (!$productContainer.length) { $productContainer = $(this).closest('.product-detail'); } attributeSelect(e.currentTarget.href, $productContainer); }); }, selectAttribute: function selectAttribute() { $(document).on('change', 'select[class*="select-"], .options-select', function (e) { e.preventDefault(); var $productContainer = $(this).closest('.set-item'); if (!$productContainer.length) { $productContainer = $(this).closest('.product-detail'); } attributeSelect(e.currentTarget.value, $productContainer); }); }, availability: function availability() { $(document).on('change', '.quantity-select', function (e) { e.preventDefault(); var $productContainer = $(this).closest('.product-detail'); if (!$productContainer.length) { $productContainer = $(this).closest('.modal-content').find('.product-quickview'); } if ($('.bundle-items', $productContainer).length === 0) { attributeSelect($(e.currentTarget).find('option:selected').data('url'), $productContainer); } }); }, addToCart: function addToCart() { $(document).on('click', 'button.add-to-cart, button.add-to-cart-global', function () { var addToCartUrl; var pid; var pidsObj; var setPids; $('body').trigger('product:beforeAddToCart', this); if ($('.set-items').length && $(this).hasClass('add-to-cart-global')) { setPids = []; $('.product-detail').each(function () { if (!$(this).hasClass('product-set-detail')) { setPids.push({ pid: $(this).find('.product-id').text(), qty: $(this).find('.quantity-select').val(), options: getOptions($(this)) }); } }); pidsObj = JSON.stringify(setPids); } pid = getPidValue($(this)); var $productContainer = $(this).closest('.product-detail'); if (!$productContainer.length) { $productContainer = $(this).closest('.quick-view-dialog').find('.product-detail'); } addToCartUrl = getAddToCartUrl(); var form = { pid: pid, pidsObj: pidsObj, childProducts: getChildProducts(), quantity: getQuantitySelected($(this)) }; if (!$('.bundle-item').length) { form.options = getOptions($productContainer); } $(this).trigger('updateAddToCartFormData', form); if (addToCartUrl) { $.ajax({ url: addToCartUrl, method: 'POST', data: form, success: function success(data) { handlePostCartAdd(data); $('body').trigger('product:afterAddToCart', data); $.spinner().stop(); }, error: function error() { $.spinner().stop(); } }); } }); }, selectBonusProduct: function selectBonusProduct() { $(document).on('click', '.select-bonus-product', function () { var $choiceOfBonusProduct = $(this).parents('.choice-of-bonus-product'); var pid = $(this).data('pid'); var maxPids = $('.choose-bonus-product-dialog').data('total-qty'); var submittedQty = parseInt($(this).parents('.choice-of-bonus-product').find('.bonus-quantity-select').val(), 10); var totalQty = 0; $.each($('#chooseBonusProductModal .selected-bonus-products .selected-pid'), function () { totalQty += $(this).data('qty'); }); totalQty += submittedQty; var optionID = $(this).parents('.choice-of-bonus-product').find('.product-option').data('option-id'); var valueId = $(this).parents('.choice-of-bonus-product').find('.options-select option:selected').data('valueId'); if (totalQty <= maxPids) { var selectedBonusProductHtml = '' + '
' + '
' + $choiceOfBonusProduct.find('.product-name').html() + '
' + '
' + '
'; $('#chooseBonusProductModal .selected-bonus-products').append(selectedBonusProductHtml); $('.pre-cart-products').html(totalQty); $('.selected-bonus-products .bonus-summary').removeClass('alert-danger'); } else { $('.selected-bonus-products .bonus-summary').addClass('alert-danger'); } }); }, removeBonusProduct: function removeBonusProduct() { $(document).on('click', '.selected-pid', function () { $(this).remove(); var $selected = $('#chooseBonusProductModal .selected-bonus-products .selected-pid'); var count = 0; if ($selected.length) { $selected.each(function () { count += parseInt($(this).data('qty'), 10); }); } $('.pre-cart-products').html(count); $('.selected-bonus-products .bonus-summary').removeClass('alert-danger'); }); }, enableBonusProductSelection: function enableBonusProductSelection() { $('body').on('bonusproduct:updateSelectButton', function (e, response) { $('button.select-bonus-product', response.$productContainer).attr('disabled', !response.product.readyToOrder || !response.product.available); var pid = response.product.id; $('button.select-bonus-product').data('pid', pid); }); }, showMoreBonusProducts: function showMoreBonusProducts() { $(document).on('click', '.show-more-bonus-products', function () { var url = $(this).data('url'); $('.modal-content').spinner().start(); $.ajax({ url: url, method: 'GET', success: function success(html) { var parsedHtml = parseHtml(html); $('.modal-body').append(parsedHtml.body); $('.show-more-bonus-products:first').remove(); $('.modal-content').spinner().stop(); }, error: function error() { $('.modal-content').spinner().stop(); } }); }); }, addBonusProductsToCart: function addBonusProductsToCart() { $(document).on('click', '.add-bonus-products', function () { var $readyToOrderBonusProducts = $('.choose-bonus-product-dialog .selected-pid'); var queryString = '?pids='; var url = $('.choose-bonus-product-dialog').data('addtocarturl'); var pidsObject = { bonusProducts: [] }; $.each($readyToOrderBonusProducts, function () { var qtyOption = parseInt($(this).data('qty'), 10); var option = null; if (qtyOption > 0) { if ($(this).data('optionid') && $(this).data('option-selected-value')) { option = {}; option.optionId = $(this).data('optionid'); option.productId = $(this).data('pid'); option.selectedValueId = $(this).data('option-selected-value'); } pidsObject.bonusProducts.push({ pid: $(this).data('pid'), qty: qtyOption, options: [option] }); pidsObject.totalQty = parseInt($('.pre-cart-products').html(), 10); } }); queryString += JSON.stringify(pidsObject); queryString = queryString + '&uuid=' + $('.choose-bonus-product-dialog').data('uuid'); queryString = queryString + '&pliuuid=' + $('.choose-bonus-product-dialog').data('pliuuid'); $.spinner().start(); $.ajax({ url: url + queryString, method: 'POST', success: function success(data) { $.spinner().stop(); if (data.error) { $('.error-choice-of-bonus-products').html(data.errorMessage); } else { $('.configure-bonus-product-attributes').html(data); $('.bonus-products-step2').removeClass('hidden-xl-down'); $('#chooseBonusProductModal').modal('hide'); if ($('.add-to-cart-messages').length === 0) { $('body').append('
'); } $('.minicart-quantity').html(data.totalQty); $('.add-to-cart-messages').append(''); setTimeout(function () { $('.add-to-basket-alert').remove(); if ($('.cart-page').length) { location.reload(); } }, 3000); } }, error: function error() { $.spinner().stop(); } }); }); }, getPidValue: getPidValue, getQuantitySelected: getQuantitySelected }); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js"))) /***/ }), /***/ "./cartridges/app_tfg/cartridge/client/default/js/components/tooltip.js": /*!******************************************************************************************!*\ !*** ./cartridges/app_tfg/cartridge/client/default/js/components/tooltip.js + 1 modules ***! \******************************************************************************************/ /*! exports provided: default */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/tippy.js/node_modules/popper.js/dist/esm/popper.js (<- Module uses injected variables (global)) */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXTERNAL MODULE: ./node_modules/tippy.js/node_modules/popper.js/dist/esm/popper.js var esm_popper = __webpack_require__("./node_modules/tippy.js/node_modules/popper.js/dist/esm/popper.js"); // CONCATENATED MODULE: ./node_modules/tippy.js/esm/index.all.js /**! * tippy.js v4.0.3 * (c) 2017-2019 atomiks * MIT License */ var css = ".tippy-iOS{cursor:pointer!important}.tippy-notransition{transition:none}.tippy-popper{transition-timing-function:cubic-bezier(.165,.84,.44,1);max-width:calc(100% - 10px);pointer-events:none;outline:0}.tippy-popper[x-placement^=top] .tippy-backdrop{border-radius:40% 40% 0 0}.tippy-popper[x-placement^=top] .tippy-roundarrow{bottom:-8px;-webkit-transform-origin:50% 0;transform-origin:50% 0}.tippy-popper[x-placement^=top] .tippy-roundarrow svg{position:absolute;left:0;-webkit-transform:rotate(180deg);transform:rotate(180deg)}.tippy-popper[x-placement^=top] .tippy-arrow{border-top:8px solid #333;border-right:8px solid transparent;border-left:8px solid transparent;bottom:-7px;margin:0 6px;-webkit-transform-origin:50% 0;transform-origin:50% 0}.tippy-popper[x-placement^=top] .tippy-backdrop{-webkit-transform-origin:0 25%;transform-origin:0 25%}.tippy-popper[x-placement^=top] .tippy-backdrop[data-state=visible]{-webkit-transform:scale(1) translate(-50%,-55%);transform:scale(1) translate(-50%,-55%)}.tippy-popper[x-placement^=top] .tippy-backdrop[data-state=hidden]{-webkit-transform:scale(.2) translate(-50%,-45%);transform:scale(.2) translate(-50%,-45%);opacity:0}.tippy-popper[x-placement^=top] [data-animation=shift-toward][data-state=visible]{-webkit-transform:translateY(-10px);transform:translateY(-10px)}.tippy-popper[x-placement^=top] [data-animation=shift-toward][data-state=hidden]{opacity:0;-webkit-transform:translateY(-20px);transform:translateY(-20px)}.tippy-popper[x-placement^=top] [data-animation=perspective]{-webkit-transform-origin:bottom;transform-origin:bottom}.tippy-popper[x-placement^=top] [data-animation=perspective][data-state=visible]{-webkit-transform:perspective(700px) translateY(-10px) rotateX(0);transform:perspective(700px) translateY(-10px) rotateX(0)}.tippy-popper[x-placement^=top] [data-animation=perspective][data-state=hidden]{opacity:0;-webkit-transform:perspective(700px) translateY(0) rotateX(60deg);transform:perspective(700px) translateY(0) rotateX(60deg)}.tippy-popper[x-placement^=top] [data-animation=fade][data-state=visible]{-webkit-transform:translateY(-10px);transform:translateY(-10px)}.tippy-popper[x-placement^=top] [data-animation=fade][data-state=hidden]{opacity:0;-webkit-transform:translateY(-10px);transform:translateY(-10px)}.tippy-popper[x-placement^=top] [data-animation=shift-away][data-state=visible]{-webkit-transform:translateY(-10px);transform:translateY(-10px)}.tippy-popper[x-placement^=top] [data-animation=shift-away][data-state=hidden]{opacity:0;-webkit-transform:translateY(0);transform:translateY(0)}.tippy-popper[x-placement^=top] [data-animation=scale]{-webkit-transform-origin:bottom;transform-origin:bottom}.tippy-popper[x-placement^=top] [data-animation=scale][data-state=visible]{-webkit-transform:translateY(-10px) scale(1);transform:translateY(-10px) scale(1)}.tippy-popper[x-placement^=top] [data-animation=scale][data-state=hidden]{opacity:0;-webkit-transform:translateY(-10px) scale(.5);transform:translateY(-10px) scale(.5)}.tippy-popper[x-placement^=bottom] .tippy-backdrop{border-radius:0 0 30% 30%}.tippy-popper[x-placement^=bottom] .tippy-roundarrow{top:-8px;-webkit-transform-origin:50% 100%;transform-origin:50% 100%}.tippy-popper[x-placement^=bottom] .tippy-roundarrow svg{position:absolute;left:0;-webkit-transform:rotate(0);transform:rotate(0)}.tippy-popper[x-placement^=bottom] .tippy-arrow{border-bottom:8px solid #333;border-right:8px solid transparent;border-left:8px solid transparent;top:-7px;margin:0 6px;-webkit-transform-origin:50% 100%;transform-origin:50% 100%}.tippy-popper[x-placement^=bottom] .tippy-backdrop{-webkit-transform-origin:0 -50%;transform-origin:0 -50%}.tippy-popper[x-placement^=bottom] .tippy-backdrop[data-state=visible]{-webkit-transform:scale(1) translate(-50%,-45%);transform:scale(1) translate(-50%,-45%)}.tippy-popper[x-placement^=bottom] .tippy-backdrop[data-state=hidden]{-webkit-transform:scale(.2) translate(-50%);transform:scale(.2) translate(-50%);opacity:0}.tippy-popper[x-placement^=bottom] [data-animation=shift-toward][data-state=visible]{-webkit-transform:translateY(10px);transform:translateY(10px)}.tippy-popper[x-placement^=bottom] [data-animation=shift-toward][data-state=hidden]{opacity:0;-webkit-transform:translateY(20px);transform:translateY(20px)}.tippy-popper[x-placement^=bottom] [data-animation=perspective]{-webkit-transform-origin:top;transform-origin:top}.tippy-popper[x-placement^=bottom] [data-animation=perspective][data-state=visible]{-webkit-transform:perspective(700px) translateY(10px) rotateX(0);transform:perspective(700px) translateY(10px) rotateX(0)}.tippy-popper[x-placement^=bottom] [data-animation=perspective][data-state=hidden]{opacity:0;-webkit-transform:perspective(700px) translateY(0) rotateX(-60deg);transform:perspective(700px) translateY(0) rotateX(-60deg)}.tippy-popper[x-placement^=bottom] [data-animation=fade][data-state=visible]{-webkit-transform:translateY(10px);transform:translateY(10px)}.tippy-popper[x-placement^=bottom] [data-animation=fade][data-state=hidden]{opacity:0;-webkit-transform:translateY(10px);transform:translateY(10px)}.tippy-popper[x-placement^=bottom] [data-animation=shift-away][data-state=visible]{-webkit-transform:translateY(10px);transform:translateY(10px)}.tippy-popper[x-placement^=bottom] [data-animation=shift-away][data-state=hidden]{opacity:0;-webkit-transform:translateY(0);transform:translateY(0)}.tippy-popper[x-placement^=bottom] [data-animation=scale]{-webkit-transform-origin:top;transform-origin:top}.tippy-popper[x-placement^=bottom] [data-animation=scale][data-state=visible]{-webkit-transform:translateY(10px) scale(1);transform:translateY(10px) scale(1)}.tippy-popper[x-placement^=bottom] [data-animation=scale][data-state=hidden]{opacity:0;-webkit-transform:translateY(10px) scale(.5);transform:translateY(10px) scale(.5)}.tippy-popper[x-placement^=left] .tippy-backdrop{border-radius:50% 0 0 50%}.tippy-popper[x-placement^=left] .tippy-roundarrow{right:-16px;-webkit-transform-origin:33.33333333% 50%;transform-origin:33.33333333% 50%}.tippy-popper[x-placement^=left] .tippy-roundarrow svg{position:absolute;left:0;-webkit-transform:rotate(90deg);transform:rotate(90deg)}.tippy-popper[x-placement^=left] .tippy-arrow{border-left:8px solid #333;border-top:8px solid transparent;border-bottom:8px solid transparent;right:-7px;margin:3px 0;-webkit-transform-origin:0 50%;transform-origin:0 50%}.tippy-popper[x-placement^=left] .tippy-backdrop{-webkit-transform-origin:50% 0;transform-origin:50% 0}.tippy-popper[x-placement^=left] .tippy-backdrop[data-state=visible]{-webkit-transform:scale(1) translate(-50%,-50%);transform:scale(1) translate(-50%,-50%)}.tippy-popper[x-placement^=left] .tippy-backdrop[data-state=hidden]{-webkit-transform:scale(.2) translate(-75%,-50%);transform:scale(.2) translate(-75%,-50%);opacity:0}.tippy-popper[x-placement^=left] [data-animation=shift-toward][data-state=visible]{-webkit-transform:translateX(-10px);transform:translateX(-10px)}.tippy-popper[x-placement^=left] [data-animation=shift-toward][data-state=hidden]{opacity:0;-webkit-transform:translateX(-20px);transform:translateX(-20px)}.tippy-popper[x-placement^=left] [data-animation=perspective]{-webkit-transform-origin:right;transform-origin:right}.tippy-popper[x-placement^=left] [data-animation=perspective][data-state=visible]{-webkit-transform:perspective(700px) translateX(-10px) rotateY(0);transform:perspective(700px) translateX(-10px) rotateY(0)}.tippy-popper[x-placement^=left] [data-animation=perspective][data-state=hidden]{opacity:0;-webkit-transform:perspective(700px) translateX(0) rotateY(-60deg);transform:perspective(700px) translateX(0) rotateY(-60deg)}.tippy-popper[x-placement^=left] [data-animation=fade][data-state=visible]{-webkit-transform:translateX(-10px);transform:translateX(-10px)}.tippy-popper[x-placement^=left] [data-animation=fade][data-state=hidden]{opacity:0;-webkit-transform:translateX(-10px);transform:translateX(-10px)}.tippy-popper[x-placement^=left] [data-animation=shift-away][data-state=visible]{-webkit-transform:translateX(-10px);transform:translateX(-10px)}.tippy-popper[x-placement^=left] [data-animation=shift-away][data-state=hidden]{opacity:0;-webkit-transform:translateX(0);transform:translateX(0)}.tippy-popper[x-placement^=left] [data-animation=scale]{-webkit-transform-origin:right;transform-origin:right}.tippy-popper[x-placement^=left] [data-animation=scale][data-state=visible]{-webkit-transform:translateX(-10px) scale(1);transform:translateX(-10px) scale(1)}.tippy-popper[x-placement^=left] [data-animation=scale][data-state=hidden]{opacity:0;-webkit-transform:translateX(-10px) scale(.5);transform:translateX(-10px) scale(.5)}.tippy-popper[x-placement^=right] .tippy-backdrop{border-radius:0 50% 50% 0}.tippy-popper[x-placement^=right] .tippy-roundarrow{left:-16px;-webkit-transform-origin:66.66666666% 50%;transform-origin:66.66666666% 50%}.tippy-popper[x-placement^=right] .tippy-roundarrow svg{position:absolute;left:0;-webkit-transform:rotate(-90deg);transform:rotate(-90deg)}.tippy-popper[x-placement^=right] .tippy-arrow{border-right:8px solid #333;border-top:8px solid transparent;border-bottom:8px solid transparent;left:-7px;margin:3px 0;-webkit-transform-origin:100% 50%;transform-origin:100% 50%}.tippy-popper[x-placement^=right] .tippy-backdrop{-webkit-transform-origin:-50% 0;transform-origin:-50% 0}.tippy-popper[x-placement^=right] .tippy-backdrop[data-state=visible]{-webkit-transform:scale(1) translate(-50%,-50%);transform:scale(1) translate(-50%,-50%)}.tippy-popper[x-placement^=right] .tippy-backdrop[data-state=hidden]{-webkit-transform:scale(.2) translate(-25%,-50%);transform:scale(.2) translate(-25%,-50%);opacity:0}.tippy-popper[x-placement^=right] [data-animation=shift-toward][data-state=visible]{-webkit-transform:translateX(10px);transform:translateX(10px)}.tippy-popper[x-placement^=right] [data-animation=shift-toward][data-state=hidden]{opacity:0;-webkit-transform:translateX(20px);transform:translateX(20px)}.tippy-popper[x-placement^=right] [data-animation=perspective]{-webkit-transform-origin:left;transform-origin:left}.tippy-popper[x-placement^=right] [data-animation=perspective][data-state=visible]{-webkit-transform:perspective(700px) translateX(10px) rotateY(0);transform:perspective(700px) translateX(10px) rotateY(0)}.tippy-popper[x-placement^=right] [data-animation=perspective][data-state=hidden]{opacity:0;-webkit-transform:perspective(700px) translateX(0) rotateY(60deg);transform:perspective(700px) translateX(0) rotateY(60deg)}.tippy-popper[x-placement^=right] [data-animation=fade][data-state=visible]{-webkit-transform:translateX(10px);transform:translateX(10px)}.tippy-popper[x-placement^=right] [data-animation=fade][data-state=hidden]{opacity:0;-webkit-transform:translateX(10px);transform:translateX(10px)}.tippy-popper[x-placement^=right] [data-animation=shift-away][data-state=visible]{-webkit-transform:translateX(10px);transform:translateX(10px)}.tippy-popper[x-placement^=right] [data-animation=shift-away][data-state=hidden]{opacity:0;-webkit-transform:translateX(0);transform:translateX(0)}.tippy-popper[x-placement^=right] [data-animation=scale]{-webkit-transform-origin:left;transform-origin:left}.tippy-popper[x-placement^=right] [data-animation=scale][data-state=visible]{-webkit-transform:translateX(10px) scale(1);transform:translateX(10px) scale(1)}.tippy-popper[x-placement^=right] [data-animation=scale][data-state=hidden]{opacity:0;-webkit-transform:translateX(10px) scale(.5);transform:translateX(10px) scale(.5)}.tippy-tooltip{position:relative;color:#fff;border-radius:4px;font-size:.9rem;padding:.3rem .6rem;line-height:1.4;text-align:center;will-change:transform;background-color:#333}.tippy-tooltip[data-size=small]{padding:.2rem .4rem;font-size:.75rem}.tippy-tooltip[data-size=large]{padding:.4rem .8rem;font-size:1rem}.tippy-tooltip[data-animatefill]{overflow:hidden;background-color:transparent}.tippy-tooltip[data-interactive],.tippy-tooltip[data-interactive] path{pointer-events:auto}.tippy-tooltip[data-inertia][data-state=visible]{transition-timing-function:cubic-bezier(.54,1.5,.38,1.11)}.tippy-tooltip[data-inertia][data-state=hidden]{transition-timing-function:ease}.tippy-arrow,.tippy-roundarrow{position:absolute;width:0;height:0}.tippy-roundarrow{width:24px;height:8px;fill:#333;pointer-events:none}.tippy-backdrop{position:absolute;will-change:transform;background-color:#333;border-radius:50%;width:calc(110% + 2rem);left:50%;top:50%;z-index:-1;transition:all cubic-bezier(.46,.1,.52,.98);-webkit-backface-visibility:hidden;backface-visibility:hidden}.tippy-backdrop:after{content:\"\";float:left;padding-top:100%}.tippy-backdrop+.tippy-content{transition-property:opacity;will-change:opacity}.tippy-backdrop+.tippy-content[data-state=visible]{opacity:1}.tippy-backdrop+.tippy-content[data-state=hidden]{opacity:0}"; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var version = "4.0.3"; var isBrowser = typeof window !== 'undefined'; var ua = isBrowser && navigator.userAgent; var isIE = /MSIE |Trident\//.test(ua); var isUCBrowser = /UCBrowser\//.test(ua); var isIOS = isBrowser && /iPhone|iPad|iPod/.test(navigator.platform) && !window.MSStream; var Defaults = { a11y: true, allowHTML: true, animateFill: true, animation: 'shift-away', appendTo: function appendTo() { return document.body; }, aria: 'describedby', arrow: false, arrowType: 'sharp', boundary: 'scrollParent', content: '', delay: [0, 20], distance: 10, duration: [325, 275], flip: true, flipBehavior: 'flip', flipOnUpdate: false, followCursor: false, hideOnClick: true, ignoreAttributes: false, inertia: false, interactive: false, interactiveBorder: 2, interactiveDebounce: 0, lazy: true, maxWidth: 350, multiple: false, offset: 0, onHidden: function onHidden() {}, onHide: function onHide() {}, onMount: function onMount() {}, onShow: function onShow() {}, onShown: function onShown() {}, placement: 'top', popperOptions: {}, role: 'tooltip', showOnInit: false, size: 'regular', sticky: false, target: '', theme: 'dark', touch: true, touchHold: false, trigger: 'mouseenter focus', updateDuration: 0, wait: null, zIndex: 9999 /** * If the set() method encounters one of these, the popperInstance must be * recreated */ }; var POPPER_INSTANCE_DEPENDENCIES = ['arrow', 'arrowType', 'boundary', 'distance', 'flip', 'flipBehavior', 'flipOnUpdate', 'offset', 'placement', 'popperOptions']; var Selectors = { POPPER: '.tippy-popper', TOOLTIP: '.tippy-tooltip', CONTENT: '.tippy-content', BACKDROP: '.tippy-backdrop', ARROW: '.tippy-arrow', ROUND_ARROW: '.tippy-roundarrow' }; var elementProto = isBrowser ? Element.prototype : {}; var matches = elementProto.matches || elementProto.matchesSelector || elementProto.webkitMatchesSelector || elementProto.mozMatchesSelector || elementProto.msMatchesSelector; /** * Ponyfill for Array.from - converts iterable values to an array * @param {ArrayLike} value * @return {any[]} */ function arrayFrom(value) { return [].slice.call(value); } /** * Ponyfill for Element.prototype.closest * @param {Element} element * @param {String} parentSelector * @return {Element} */ function closest(element, parentSelector) { return (elementProto.closest || function (selector) { var el = this; while (el) { if (matches.call(el, selector)) return el; el = el.parentElement; } }).call(element, parentSelector); } /** * Works like Element.prototype.closest, but uses a callback instead * @param {Element} element * @param {Function} callback * @return {Element} */ function closestCallback(element, callback) { while (element) { if (callback(element)) return element; element = element.parentElement; } } /** * Determines if a value is a "bare" virtual element (before mutations done * by `polyfillElementPrototypeProperties()`). JSDOM elements show up as * [object Object], we can check if the value is "element-like" if it has * `addEventListener` * @param {any} value * @return {Boolean} */ function isBareVirtualElement(value) { return {}.toString.call(value) === '[object Object]' && !value.addEventListener; } /** * Safe .hasOwnProperty check, for prototype-less objects * @param {Object} obj * @param {String} key * @return {Boolean} */ function index_all_hasOwnProperty(obj, key) { return {}.hasOwnProperty.call(obj, key); } /** * Returns an array of elements based on the value * @param {any} value * @return {Array} */ function getArrayOfElements(value) { if (isSingular(value)) { return [value]; } if (value instanceof NodeList) { return arrayFrom(value); } if (Array.isArray(value)) { return value; } try { return arrayFrom(document.querySelectorAll(value)); } catch (e) { return []; } } /** * Returns a value at a given index depending on if it's an array or number * @param {any} value * @param {Number} index * @param {any} defaultValue */ function getValue(value, index, defaultValue) { if (Array.isArray(value)) { var v = value[index]; return v == null ? defaultValue : v; } return value; } /** * Debounce utility * @param {Function} fn * @param {Number} ms */ function debounce(fn, ms) { var timeoutId; return function () { var _this = this, _arguments = arguments; clearTimeout(timeoutId); timeoutId = setTimeout(function () { return fn.apply(_this, _arguments); }, ms); }; } /** * Prevents errors from being thrown while accessing nested modifier objects * in `popperOptions` * @param {Object} obj * @param {String} key * @return {Object|undefined} */ function getModifier(obj, key) { return obj && obj.modifiers && obj.modifiers[key]; } /** * Determines if an array or string includes a value * @param {Array|String} a * @param {any} b * @return {Boolean} */ function includes(a, b) { return a.indexOf(b) > -1; } /** * Determines if the value is singular-like * @param {any} value * @return {Boolean} */ function isSingular(value) { return !!value && value.isVirtual || value instanceof Element; } /** * Tricking bundlers, linters, and minifiers * @return {String} */ function innerHTML() { return 'innerHTML'; } /** * Evaluates a function if one, or returns the value * @param {any} value * @param {any[]} args * @return {Boolean} */ function evaluateValue(value, args) { return typeof value === 'function' ? value.apply(null, args) : value; } /** * Sets a popperInstance `flip` modifier's enabled state * @param {Object[]} modifiers * @param {any} value */ function setFlipModifierEnabled(modifiers, value) { modifiers.filter(function (m) { return m.name === 'flip'; })[0].enabled = value; } /** * Returns a new `div` element * @return {HTMLDivElement} */ function div() { return document.createElement('div'); } /** * Sets the innerHTML of an element while tricking linters & minifiers * @param {HTMLElement} el * @param {Element|String} html */ function setInnerHTML(el, html) { el[innerHTML()] = html instanceof Element ? html[innerHTML()] : html; } /** * Sets the content of a tooltip * @param {HTMLElement} contentEl * @param {Object} props */ function setContent(contentEl, props) { if (props.content instanceof Element) { setInnerHTML(contentEl, ''); contentEl.appendChild(props.content); } else { contentEl[props.allowHTML ? 'innerHTML' : 'textContent'] = props.content; } } /** * Returns the child elements of a popper element * @param {HTMLElement} popper * @return {Object} */ function getChildren(popper) { return { tooltip: popper.querySelector(Selectors.TOOLTIP), backdrop: popper.querySelector(Selectors.BACKDROP), content: popper.querySelector(Selectors.CONTENT), arrow: popper.querySelector(Selectors.ARROW) || popper.querySelector(Selectors.ROUND_ARROW) }; } /** * Adds `data-inertia` attribute * @param {HTMLElement} tooltip */ function addInertia(tooltip) { tooltip.setAttribute('data-inertia', ''); } /** * Removes `data-inertia` attribute * @param {HTMLElement} tooltip */ function removeInertia(tooltip) { tooltip.removeAttribute('data-inertia'); } /** * Creates an arrow element and returns it * @return {HTMLDivElement} */ function createArrowElement(arrowType) { var arrow = div(); if (arrowType === 'round') { arrow.className = 'tippy-roundarrow'; setInnerHTML(arrow, ''); } else { arrow.className = 'tippy-arrow'; } return arrow; } /** * Creates a backdrop element and returns it * @return {HTMLDivElement} */ function createBackdropElement() { var backdrop = div(); backdrop.className = 'tippy-backdrop'; backdrop.setAttribute('data-state', 'hidden'); return backdrop; } /** * Adds interactive-related attributes * @param {HTMLElement} popper * @param {HTMLElement} tooltip */ function addInteractive(popper, tooltip) { popper.setAttribute('tabindex', '-1'); tooltip.setAttribute('data-interactive', ''); } /** * Removes interactive-related attributes * @param {HTMLElement} popper * @param {HTMLElement} tooltip */ function removeInteractive(popper, tooltip) { popper.removeAttribute('tabindex'); tooltip.removeAttribute('data-interactive'); } /** * Applies a transition duration to a list of elements * @param {Array} els * @param {Number} value */ function applyTransitionDuration(els, value) { els.forEach(function (el) { if (el) { el.style.transitionDuration = "".concat(value, "ms"); } }); } /** * Add/remove transitionend listener from tooltip * @param {Element} tooltip * @param {String} action * @param {Function} listener */ function toggleTransitionEndListener(tooltip, action, listener) { // UC Browser hasn't adopted the `transitionend` event despite supporting // unprefixed transitions... var eventName = isUCBrowser && document.body.style.WebkitTransition !== undefined ? 'webkitTransitionEnd' : 'transitionend'; tooltip[action + 'EventListener'](eventName, listener); } /** * Returns the popper's placement, ignoring shifting (top-start, etc) * @param {Element} popper * @return {String} */ function getPopperPlacement(popper) { var fullPlacement = popper.getAttribute('x-placement'); return fullPlacement ? fullPlacement.split('-')[0] : ''; } /** * Sets the visibility state to elements so they can begin to transition * @param {Array} els * @param {String} state */ function setVisibilityState(els, state) { els.forEach(function (el) { if (el) { el.setAttribute('data-state', state); } }); } /** * Triggers reflow * @param {Element} popper */ function reflow(popper) { void popper.offsetHeight; } /** * Adds/removes theme from tooltip's classList * @param {HTMLDivElement} tooltip * @param {String} action * @param {String} theme */ function toggleTheme(tooltip, action, theme) { theme.split(' ').forEach(function (themeName) { tooltip.classList[action](themeName + '-theme'); }); } /** * Constructs the popper element and returns it * @param {Number} id * @param {Object} props * @return {HTMLDivElement} */ function createPopperElement(id, props) { var popper = div(); popper.className = 'tippy-popper'; popper.id = "tippy-".concat(id); popper.style.zIndex = props.zIndex; if (props.role) { popper.setAttribute('role', props.role); } var tooltip = div(); tooltip.className = 'tippy-tooltip'; tooltip.style.maxWidth = props.maxWidth + (typeof props.maxWidth === 'number' ? 'px' : ''); tooltip.setAttribute('data-size', props.size); tooltip.setAttribute('data-animation', props.animation); tooltip.setAttribute('data-state', 'hidden'); toggleTheme(tooltip, 'add', props.theme); var content = div(); content.className = 'tippy-content'; content.setAttribute('data-state', 'hidden'); if (props.interactive) { addInteractive(popper, tooltip); } if (props.arrow) { tooltip.appendChild(createArrowElement(props.arrowType)); } if (props.animateFill) { tooltip.appendChild(createBackdropElement()); tooltip.setAttribute('data-animatefill', ''); } if (props.inertia) { addInertia(tooltip); } setContent(content, props); tooltip.appendChild(content); popper.appendChild(tooltip); return popper; } /** * Updates the popper element based on the new props * @param {HTMLDivElement} popper * @param {Object} prevProps * @param {Object} nextProps */ function updatePopperElement(popper, prevProps, nextProps) { var _getChildren = getChildren(popper), tooltip = _getChildren.tooltip, content = _getChildren.content, backdrop = _getChildren.backdrop, arrow = _getChildren.arrow; popper.style.zIndex = nextProps.zIndex; tooltip.setAttribute('data-size', nextProps.size); tooltip.setAttribute('data-animation', nextProps.animation); tooltip.style.maxWidth = nextProps.maxWidth + (typeof nextProps.maxWidth === 'number' ? 'px' : ''); if (nextProps.role) { popper.setAttribute('role', nextProps.role); } else { popper.removeAttribute('role'); } if (prevProps.content !== nextProps.content) { setContent(content, nextProps); } // animateFill if (!prevProps.animateFill && nextProps.animateFill) { tooltip.appendChild(createBackdropElement()); tooltip.setAttribute('data-animatefill', ''); } else if (prevProps.animateFill && !nextProps.animateFill) { tooltip.removeChild(backdrop); tooltip.removeAttribute('data-animatefill'); } // arrow if (!prevProps.arrow && nextProps.arrow) { tooltip.appendChild(createArrowElement(nextProps.arrowType)); } else if (prevProps.arrow && !nextProps.arrow) { tooltip.removeChild(arrow); } // arrowType if (prevProps.arrow && nextProps.arrow && prevProps.arrowType !== nextProps.arrowType) { tooltip.replaceChild(createArrowElement(nextProps.arrowType), arrow); } // interactive if (!prevProps.interactive && nextProps.interactive) { addInteractive(popper, tooltip); } else if (prevProps.interactive && !nextProps.interactive) { removeInteractive(popper, tooltip); } // inertia if (!prevProps.inertia && nextProps.inertia) { addInertia(tooltip); } else if (prevProps.inertia && !nextProps.inertia) { removeInertia(tooltip); } // theme if (prevProps.theme !== nextProps.theme) { toggleTheme(tooltip, 'remove', prevProps.theme); toggleTheme(tooltip, 'add', nextProps.theme); } } /** * Runs the callback after the popper's position has been updated * update() is debounced with Promise.resolve() or setTimeout() * scheduleUpdate() is update() wrapped in requestAnimationFrame() * @param {Popper} popperInstance * @param {Function} callback */ function afterPopperPositionUpdates(popperInstance, callback) { var popper = popperInstance.popper, options = popperInstance.options; var onCreate = options.onCreate, onUpdate = options.onUpdate; options.onCreate = options.onUpdate = function (data) { reflow(popper); callback(); onUpdate(data); options.onCreate = onCreate; options.onUpdate = onUpdate; }; } /** * Hides all visible poppers on the document * @param {Object} options */ function hideAll() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, checkHideOnClick = _ref.checkHideOnClick, exclude = _ref.exclude, duration = _ref.duration; arrayFrom(document.querySelectorAll(Selectors.POPPER)).forEach(function (popper) { var instance = popper._tippy; if (instance && (checkHideOnClick ? instance.props.hideOnClick === true : true) && (!exclude || popper !== exclude.popper)) { instance.hide(duration); } }); } /** * Determines if the mouse cursor is outside of the popper's interactive border * region * @param {String} popperPlacement * @param {ClientRect} popperRect * @param {MouseEvent} event * @param {Object} props * @return {Boolean} */ function isCursorOutsideInteractiveBorder(popperPlacement, popperRect, event, props) { if (!popperPlacement) { return true; } var x = event.clientX, y = event.clientY; var interactiveBorder = props.interactiveBorder, distance = props.distance; var exceedsTop = popperRect.top - y > (popperPlacement === 'top' ? interactiveBorder + distance : interactiveBorder); var exceedsBottom = y - popperRect.bottom > (popperPlacement === 'bottom' ? interactiveBorder + distance : interactiveBorder); var exceedsLeft = popperRect.left - x > (popperPlacement === 'left' ? interactiveBorder + distance : interactiveBorder); var exceedsRight = x - popperRect.right > (popperPlacement === 'right' ? interactiveBorder + distance : interactiveBorder); return exceedsTop || exceedsBottom || exceedsLeft || exceedsRight; } /** * Returns the distance offset, taking into account the default offset due to * the transform: translate() rule (10px) in CSS * @param {Number} distance * @return {String} */ function getOffsetDistanceInPx(distance) { return -(distance - 10) + 'px'; } var PASSIVE = { passive: true }; var PADDING = 3; var isUsingTouch = false; function onDocumentTouch() { if (isUsingTouch) { return; } isUsingTouch = true; if (isIOS) { document.body.classList.add('tippy-iOS'); } if (window.performance) { document.addEventListener('mousemove', onDocumentMouseMove); } } var lastMouseMoveTime = 0; function onDocumentMouseMove() { var now = performance.now(); // Chrome 60+ is 1 mousemove per animation frame, use 20ms time difference if (now - lastMouseMoveTime < 20) { isUsingTouch = false; document.removeEventListener('mousemove', onDocumentMouseMove); if (!isIOS) { document.body.classList.remove('tippy-iOS'); } } lastMouseMoveTime = now; } function onDocumentClick(_ref) { var target = _ref.target; // Simulated events dispatched on the document if (!(target instanceof Element)) { return hideAll(); } // Clicked on an interactive popper var popper = closest(target, Selectors.POPPER); if (popper && popper._tippy && popper._tippy.props.interactive) { return; } // Clicked on a reference var reference = closestCallback(target, function (el) { return el._tippy && el._tippy.reference === el; }); if (reference) { var instance = reference._tippy; var isClickTrigger = includes(instance.props.trigger, 'click'); if (isUsingTouch || isClickTrigger) { return hideAll({ exclude: instance, checkHideOnClick: true }); } if (instance.props.hideOnClick !== true || isClickTrigger) { return; } instance.clearDelayTimeouts(); } hideAll({ checkHideOnClick: true }); } function onWindowBlur() { var _document = document, activeElement = _document.activeElement; if (activeElement && activeElement.blur && activeElement._tippy) { activeElement.blur(); } } /** * Adds the needed global event listeners */ function bindGlobalEventListeners() { document.addEventListener('click', onDocumentClick, true); document.addEventListener('touchstart', onDocumentTouch, PASSIVE); window.addEventListener('blur', onWindowBlur); } var keys = Object.keys(Defaults); /** * Determines if an element can receive focus * @param {Element|Object} el * @return {Boolean} */ function canReceiveFocus(el) { return el instanceof Element ? matches.call(el, 'a[href],area[href],button,details,input,textarea,select,iframe,[tabindex]') && !el.hasAttribute('disabled') : true; } /** * Returns an object of optional props from data-tippy-* attributes * @param {Element|Object} reference * @return {Object} */ function getDataAttributeOptions(reference) { return keys.reduce(function (acc, key) { var valueAsString = (reference.getAttribute("data-tippy-".concat(key)) || '').trim(); if (!valueAsString) { return acc; } if (key === 'content') { acc[key] = valueAsString; } else { try { acc[key] = JSON.parse(valueAsString); } catch (e) { acc[key] = valueAsString; } } return acc; }, {}); } /** * Polyfills the virtual reference (plain object) with Element.prototype props * Mutating because DOM elements are mutated, adds `_tippy` property * @param {Object} virtualReference */ function polyfillElementPrototypeProperties(virtualReference) { var polyfills = { isVirtual: true, attributes: virtualReference.attributes || {}, setAttribute: function setAttribute(key, value) { virtualReference.attributes[key] = value; }, getAttribute: function getAttribute(key) { return virtualReference.attributes[key]; }, removeAttribute: function removeAttribute(key) { delete virtualReference.attributes[key]; }, hasAttribute: function hasAttribute(key) { return key in virtualReference.attributes; }, addEventListener: function addEventListener() {}, removeEventListener: function removeEventListener() {}, classList: { classNames: {}, add: function add(key) { virtualReference.classList.classNames[key] = true; }, remove: function remove(key) { delete virtualReference.classList.classNames[key]; }, contains: function contains(key) { return key in virtualReference.classList.classNames; } } }; for (var key in polyfills) { virtualReference[key] = polyfills[key]; } } /** * Evaluates the props object by merging data attributes and * disabling conflicting options where necessary * @param {Element} reference * @param {Object} props * @return {Object} */ function evaluateProps(reference, props) { var out = _extends({}, props, { content: evaluateValue(props.content, [reference]) }, props.ignoreAttributes ? {} : getDataAttributeOptions(reference)); if (out.arrow || isUCBrowser) { out.animateFill = false; } return out; } /** * Validates an object of options with the valid default props object * @param {Object} options * @param {Object} defaults */ function validateOptions() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var defaults = arguments.length > 1 ? arguments[1] : undefined; Object.keys(options).forEach(function (option) { if (!index_all_hasOwnProperty(defaults, option)) { throw new Error("[tippy]: `".concat(option, "` is not a valid option")); } }); } var idCounter = 1; /** * Creates and returns a Tippy object. We're using a closure pattern instead of * a class so that the exposed object API is clean without private members * prefixed with `_`. * @param {Element} reference * @param {Object} collectionProps * @return {Object} instance */ function createTippy(reference, collectionProps) { var props = evaluateProps(reference, collectionProps); // If the reference shouldn't have multiple tippys, return null early if (!props.multiple && reference._tippy) { return null; } /* ======================= 🔒 Private members 🔒 ======================= */ // The last trigger event object that caused the tippy to show var lastTriggerEvent = {}; // The last mousemove event object created by the document mousemove event var lastMouseMoveEvent = null; // Timeout created by the show delay var showTimeoutId = 0; // Timeout created by the hide delay var hideTimeoutId = 0; // Flag to determine if the tippy is preparing to show due to the show timeout var isPreparingToShow = false; // The current `transitionend` callback reference var transitionEndListener = function transitionEndListener() {}; // Array of event listeners currently attached to the reference element var listeners = []; // Private onMouseMove handler reference, debounced or not var debouncedOnMouseMove = props.interactiveDebounce > 0 ? debounce(onMouseMove, props.interactiveDebounce) : onMouseMove; // Node the tippy is currently appended to var parentNode = null; /* ======================= 🔑 Public members 🔑 ======================= */ // id used for the `aria-describedby` / `aria-labelledby` attribute var id = idCounter++; // Popper element reference var popper = createPopperElement(id, props); // Prevent a tippy with a delay from hiding if the cursor left then returned // before it started hiding popper.addEventListener('mouseenter', function (event) { if (instance.props.interactive && instance.state.isVisible && lastTriggerEvent.type === 'mouseenter') { prepareShow(event); } }); popper.addEventListener('mouseleave', function () { if (instance.props.interactive && lastTriggerEvent.type === 'mouseenter') { document.addEventListener('mousemove', debouncedOnMouseMove); } }); // Popper element children: { arrow, backdrop, content, tooltip } var popperChildren = getChildren(popper); // The state of the tippy var state = { // If the tippy is currently enabled isEnabled: true, // show() invoked, not currently transitioning out isVisible: false, // If the tippy has been destroyed isDestroyed: false, // If the tippy is on the DOM (transitioning out or in) isMounted: false, // show() transition finished isShown: false // Popper.js instance for the tippy is lazily created }; var popperInstance = null; // 🌟 tippy instance var instance = { // properties id: id, reference: reference, popper: popper, popperChildren: popperChildren, popperInstance: popperInstance, props: props, state: state, // methods clearDelayTimeouts: clearDelayTimeouts, set: set, setContent: setContent$$1, show: show, hide: hide, enable: enable, disable: disable, destroy: destroy }; addTriggersToReference(); if (!props.lazy) { createPopperInstance(); instance.popperInstance.disableEventListeners(); } if (props.showOnInit) { prepareShow(); } // Ensure the reference element can receive focus (and is not a delegate) if (props.a11y && !props.target && !canReceiveFocus(reference)) { reference.setAttribute('tabindex', '0'); } // Install shortcuts reference._tippy = instance; popper._tippy = instance; return instance; /* ======================= 🔒 Private methods 🔒 ======================= */ /** * Positions the virtual reference near the mouse cursor */ function positionVirtualReferenceNearCursor(event) { var _lastMouseMoveEvent = lastMouseMoveEvent = event, clientX = _lastMouseMoveEvent.clientX, clientY = _lastMouseMoveEvent.clientY; if (!instance.popperInstance) { return; } // Ensure virtual reference is padded to prevent tooltip from // overflowing. Maybe Popper.js issue? var placement = getPopperPlacement(instance.popper); var padding = instance.popperChildren.arrow ? PADDING + 16 : PADDING; var isVerticalPlacement = includes(['top', 'bottom'], placement); var isHorizontalPlacement = includes(['left', 'right'], placement); // Top / left boundary var x = isVerticalPlacement ? Math.max(padding, clientX) : clientX; var y = isHorizontalPlacement ? Math.max(padding, clientY) : clientY; // Bottom / right boundary if (isVerticalPlacement && x > padding) { x = Math.min(clientX, window.innerWidth - padding); } if (isHorizontalPlacement && y > padding) { y = Math.min(clientY, window.innerHeight - padding); } var rect = instance.reference.getBoundingClientRect(); var followCursor = instance.props.followCursor; var isHorizontal = followCursor === 'horizontal'; var isVertical = followCursor === 'vertical'; instance.popperInstance.reference = { getBoundingClientRect: function getBoundingClientRect() { return { width: 0, height: 0, top: isHorizontal ? rect.top : y, bottom: isHorizontal ? rect.bottom : y, left: isVertical ? rect.left : x, right: isVertical ? rect.right : x }; }, clientWidth: 0, clientHeight: 0 }; instance.popperInstance.scheduleUpdate(); if (followCursor === 'initial' && instance.state.isVisible) { removeFollowCursorListener(); } } /** * Creates the tippy instance for a delegate when it's been triggered */ function createDelegateChildTippy(event) { var targetEl = closest(event.target, instance.props.target); if (targetEl && !targetEl._tippy) { createTippy(targetEl, _extends({}, instance.props, { content: evaluateValue(collectionProps.content, [targetEl]), appendTo: collectionProps.appendTo, target: '', showOnInit: true })); prepareShow(event); } } /** * Setup before show() is invoked (delays, etc.) */ function prepareShow(event) { clearDelayTimeouts(); if (instance.state.isVisible) { return; } // Is a delegate, create an instance for the child target if (instance.props.target) { return createDelegateChildTippy(event); } isPreparingToShow = true; if (instance.props.wait) { return instance.props.wait(instance, event); } // If the tooltip has a delay, we need to be listening to the mousemove as // soon as the trigger event is fired, so that it's in the correct position // upon mount. // Edge case: if the tooltip is still mounted, but then prepareShow() is // called, it causes a jump. if (hasFollowCursorBehavior() && !instance.state.isMounted) { document.addEventListener('mousemove', positionVirtualReferenceNearCursor); } var delay = getValue(instance.props.delay, 0, Defaults.delay); if (delay) { showTimeoutId = setTimeout(function () { show(); }, delay); } else { show(); } } /** * Setup before hide() is invoked (delays, etc.) */ function prepareHide() { clearDelayTimeouts(); if (!instance.state.isVisible) { return removeFollowCursorListener(); } isPreparingToShow = false; var delay = getValue(instance.props.delay, 1, Defaults.delay); if (delay) { hideTimeoutId = setTimeout(function () { if (instance.state.isVisible) { hide(); } }, delay); } else { hide(); } } /** * Removes the follow cursor listener */ function removeFollowCursorListener() { document.removeEventListener('mousemove', positionVirtualReferenceNearCursor); lastMouseMoveEvent = null; } /** * Cleans up old listeners */ function cleanupOldMouseListeners() { document.body.removeEventListener('mouseleave', prepareHide); document.removeEventListener('mousemove', debouncedOnMouseMove); } /** * Event listener invoked upon trigger */ function onTrigger(event) { if (!instance.state.isEnabled || isEventListenerStopped(event)) { return; } if (!instance.state.isVisible) { lastTriggerEvent = event; // Use the `mouseenter` event as a "mock" mousemove event for touch // devices if (isUsingTouch && includes(event.type, 'mouse')) { lastMouseMoveEvent = event; } } // Toggle show/hide when clicking click-triggered tooltips if (event.type === 'click' && instance.props.hideOnClick !== false && instance.state.isVisible) { prepareHide(); } else { prepareShow(event); } } /** * Event listener used for interactive tooltips to detect when they should * hide */ function onMouseMove(event) { var referenceTheCursorIsOver = closestCallback(event.target, function (el) { return el._tippy; }); var isCursorOverPopper = closest(event.target, Selectors.POPPER) === instance.popper; var isCursorOverReference = referenceTheCursorIsOver === instance.reference; if (isCursorOverPopper || isCursorOverReference) { return; } if (isCursorOutsideInteractiveBorder(getPopperPlacement(instance.popper), instance.popper.getBoundingClientRect(), event, instance.props)) { cleanupOldMouseListeners(); prepareHide(); } } /** * Event listener invoked upon mouseleave */ function onMouseLeave(event) { if (isEventListenerStopped(event)) { return; } if (instance.props.interactive) { document.body.addEventListener('mouseleave', prepareHide); document.addEventListener('mousemove', debouncedOnMouseMove); return; } prepareHide(); } /** * Event listener invoked upon blur */ function onBlur(event) { if (event.target !== instance.reference) { return; } if (instance.props.interactive && event.relatedTarget && instance.popper.contains(event.relatedTarget)) { return; } prepareHide(); } /** * Event listener invoked when a child target is triggered */ function onDelegateShow(event) { if (closest(event.target, instance.props.target)) { prepareShow(event); } } /** * Event listener invoked when a child target should hide */ function onDelegateHide(event) { if (closest(event.target, instance.props.target)) { prepareHide(); } } /** * Determines if an event listener should stop further execution due to the * `touchHold` option */ function isEventListenerStopped(event) { var supportsTouch = 'ontouchstart' in window; var isTouchEvent = includes(event.type, 'touch'); var touchHold = instance.props.touchHold; return supportsTouch && isUsingTouch && touchHold && !isTouchEvent || isUsingTouch && !touchHold && isTouchEvent; } /** * Creates the popper instance for the instance */ function createPopperInstance() { var popperOptions = instance.props.popperOptions; var _instance$popperChild = instance.popperChildren, tooltip = _instance$popperChild.tooltip, arrow = _instance$popperChild.arrow; instance.popperInstance = new esm_popper["default"](instance.reference, instance.popper, _extends({ placement: instance.props.placement }, popperOptions, { modifiers: _extends({}, popperOptions ? popperOptions.modifiers : {}, { preventOverflow: _extends({ boundariesElement: instance.props.boundary, padding: PADDING }, getModifier(popperOptions, 'preventOverflow')), arrow: _extends({ element: arrow, enabled: !!arrow }, getModifier(popperOptions, 'arrow')), flip: _extends({ enabled: instance.props.flip, // The tooltip is offset by 10px from the popper in CSS, // we need to account for its distance padding: instance.props.distance + PADDING, behavior: instance.props.flipBehavior }, getModifier(popperOptions, 'flip')), offset: _extends({ offset: instance.props.offset }, getModifier(popperOptions, 'offset')) }), onUpdate: function onUpdate(data) { if (instance.props.flip && !instance.props.flipOnUpdate) { if (data.flipped) { instance.popperInstance.options.placement = data.placement; } setFlipModifierEnabled(instance.popperInstance.modifiers, false); } var styles = tooltip.style; styles.top = ''; styles.bottom = ''; styles.left = ''; styles.right = ''; styles[getPopperPlacement(instance.popper)] = getOffsetDistanceInPx(instance.props.distance); if (popperOptions.onUpdate) { popperOptions.onUpdate(data); } } })); } /** * Mounts the tooltip to the DOM, callback to show tooltip is run **after** * popper's position has updated */ function mount(callback) { var shouldEnableListeners = !hasFollowCursorBehavior() && !(instance.props.followCursor === 'initial' && isUsingTouch); if (!instance.popperInstance) { createPopperInstance(); if (!shouldEnableListeners) { instance.popperInstance.disableEventListeners(); } } else { if (!hasFollowCursorBehavior()) { instance.popperInstance.scheduleUpdate(); if (shouldEnableListeners) { instance.popperInstance.enableEventListeners(); } } setFlipModifierEnabled(instance.popperInstance.modifiers, instance.props.flip); } // If the instance previously had followCursor behavior, it will be // positioned incorrectly if triggered by `focus` afterwards. // Update the reference back to the real DOM element instance.popperInstance.reference = instance.reference; var arrow = instance.popperChildren.arrow; if (hasFollowCursorBehavior()) { if (arrow) { arrow.style.margin = '0'; } var delay = getValue(instance.props.delay, 0, Defaults.delay); if (lastTriggerEvent.type) { positionVirtualReferenceNearCursor(delay && lastMouseMoveEvent ? lastMouseMoveEvent : lastTriggerEvent); } } else if (arrow) { arrow.style.margin = ''; } afterPopperPositionUpdates(instance.popperInstance, callback); var appendTo = instance.props.appendTo; parentNode = appendTo === 'parent' ? instance.reference.parentNode : evaluateValue(appendTo, [instance.reference]); if (!parentNode.contains(instance.popper)) { parentNode.appendChild(instance.popper); instance.props.onMount(instance); instance.state.isMounted = true; } } /** * Determines if the instance is in `followCursor` mode */ function hasFollowCursorBehavior() { return instance.props.followCursor && !isUsingTouch && lastTriggerEvent.type !== 'focus'; } /** * Updates the tooltip's position on each animation frame + timeout */ function makeSticky() { applyTransitionDuration([instance.popper], isIE ? 0 : instance.props.updateDuration); var updatePosition = function updatePosition() { if (instance.popperInstance) { instance.popperInstance.scheduleUpdate(); } if (instance.state.isMounted) { requestAnimationFrame(updatePosition); } else { applyTransitionDuration([instance.popper], 0); } }; updatePosition(); } /** * Invokes a callback once the tooltip has fully transitioned out */ function onTransitionedOut(duration, callback) { onTransitionEnd(duration, function () { if (!instance.state.isVisible && parentNode && parentNode.contains(instance.popper)) { callback(); } }); } /** * Invokes a callback once the tooltip has fully transitioned in */ function onTransitionedIn(duration, callback) { onTransitionEnd(duration, callback); } /** * Invokes a callback once the tooltip's CSS transition ends */ function onTransitionEnd(duration, callback) { // Make callback synchronous if duration is 0 if (duration === 0) { return callback(); } var tooltip = instance.popperChildren.tooltip; var listener = function listener(e) { if (e.target === tooltip) { toggleTransitionEndListener(tooltip, 'remove', listener); callback(); } }; toggleTransitionEndListener(tooltip, 'remove', transitionEndListener); toggleTransitionEndListener(tooltip, 'add', listener); transitionEndListener = listener; } /** * Adds an event listener to the reference and stores it in `listeners` */ function on(eventType, handler) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; instance.reference.addEventListener(eventType, handler, options); listeners.push({ eventType: eventType, handler: handler, options: options }); } /** * Adds event listeners to the reference based on the `trigger` prop */ function addTriggersToReference() { if (instance.props.touchHold && !instance.props.target) { on('touchstart', onTrigger, PASSIVE); on('touchend', onMouseLeave, PASSIVE); } instance.props.trigger.trim().split(' ').forEach(function (eventType) { if (eventType === 'manual') { return; } if (!instance.props.target) { on(eventType, onTrigger); switch (eventType) { case 'mouseenter': on('mouseleave', onMouseLeave); break; case 'focus': on(isIE ? 'focusout' : 'blur', onBlur); break; } } else { switch (eventType) { case 'mouseenter': on('mouseover', onDelegateShow); on('mouseout', onDelegateHide); break; case 'focus': on('focusin', onDelegateShow); on('focusout', onDelegateHide); break; case 'click': on(eventType, onDelegateShow); break; } } }); } /** * Removes event listeners from the reference */ function removeTriggersFromReference() { listeners.forEach(function (_ref) { var eventType = _ref.eventType, handler = _ref.handler, options = _ref.options; instance.reference.removeEventListener(eventType, handler, options); }); listeners = []; } /** * Returns inner elements used in show/hide methods */ function getInnerElements() { return [instance.popperChildren.tooltip, instance.popperChildren.backdrop, instance.popperChildren.content]; } /* ======================= 🔑 Public methods 🔑 ======================= */ /** * Enables the instance to allow it to show or hide */ function enable() { instance.state.isEnabled = true; } /** * Disables the instance to disallow it to show or hide */ function disable() { instance.state.isEnabled = false; } /** * Clears pending timeouts related to the `delay` prop if any */ function clearDelayTimeouts() { clearTimeout(showTimeoutId); clearTimeout(hideTimeoutId); } /** * Sets new props for the instance and redraws the tooltip */ function set() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; validateOptions(options, Defaults); var prevProps = instance.props; var nextProps = evaluateProps(instance.reference, _extends({}, instance.props, options, { ignoreAttributes: true })); nextProps.ignoreAttributes = index_all_hasOwnProperty(options, 'ignoreAttributes') ? options.ignoreAttributes : prevProps.ignoreAttributes; instance.props = nextProps; if (index_all_hasOwnProperty(options, 'trigger') || index_all_hasOwnProperty(options, 'touchHold')) { removeTriggersFromReference(); addTriggersToReference(); } if (index_all_hasOwnProperty(options, 'interactiveDebounce')) { cleanupOldMouseListeners(); debouncedOnMouseMove = debounce(onMouseMove, options.interactiveDebounce); } updatePopperElement(instance.popper, prevProps, nextProps); instance.popperChildren = getChildren(instance.popper); if (instance.popperInstance) { instance.popperInstance.update(); if (POPPER_INSTANCE_DEPENDENCIES.some(function (prop) { return index_all_hasOwnProperty(options, prop); })) { instance.popperInstance.destroy(); createPopperInstance(); if (!instance.state.isVisible) { instance.popperInstance.disableEventListeners(); } if (instance.props.followCursor && lastMouseMoveEvent) { positionVirtualReferenceNearCursor(lastMouseMoveEvent); } } } } /** * Shortcut for .set({ content: newContent }) */ function setContent$$1(content) { set({ content: content }); } /** * Shows the tooltip */ function show() { var duration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getValue(instance.props.duration, 0, Defaults.duration[0]); if (instance.state.isDestroyed || !instance.state.isEnabled || isUsingTouch && !instance.props.touch) { return; } // Destroy tooltip if the reference element is no longer on the DOM if (!instance.reference.isVirtual && !document.documentElement.contains(instance.reference)) { return destroy(); } // Do not show tooltip if the reference element has a `disabled` attribute if (instance.reference.hasAttribute('disabled')) { return; } if (instance.props.onShow(instance) === false) { return; } instance.popper.style.visibility = 'visible'; instance.state.isVisible = true; if (instance.props.interactive) { instance.reference.classList.add('tippy-active'); } // Prevent a transition if the popper is at the opposite placement applyTransitionDuration([instance.popper, instance.popperChildren.tooltip, instance.popperChildren.backdrop], 0); mount(function () { if (!instance.state.isVisible) { return; } // Arrow will sometimes not be positioned correctly. Force another update if (!hasFollowCursorBehavior()) { instance.popperInstance.update(); } // Allow followCursor: 'initial' on touch devices if (isUsingTouch && instance.props.followCursor === 'initial') { positionVirtualReferenceNearCursor(lastMouseMoveEvent); } applyTransitionDuration([instance.popper], props.updateDuration); applyTransitionDuration(getInnerElements(), duration); if (instance.popperChildren.backdrop) { instance.popperChildren.content.style.transitionDelay = Math.round(duration / 12) + 'ms'; } if (instance.props.sticky) { makeSticky(); } setVisibilityState(getInnerElements(), 'visible'); onTransitionedIn(duration, function () { instance.popperChildren.tooltip.classList.add('tippy-notransition'); if (instance.props.aria) { instance.reference.setAttribute("aria-".concat(instance.props.aria), instance.popper.id); } instance.props.onShown(instance); instance.state.isShown = true; }); }); } /** * Hides the tooltip */ function hide() { var duration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getValue(instance.props.duration, 1, Defaults.duration[1]); if (instance.state.isDestroyed || !instance.state.isEnabled) { return; } if (instance.props.onHide(instance) === false) { return; } instance.popperChildren.tooltip.classList.remove('tippy-notransition'); if (instance.props.interactive) { instance.reference.classList.remove('tippy-active'); } instance.popper.style.visibility = 'hidden'; instance.state.isVisible = false; instance.state.isShown = false; applyTransitionDuration(getInnerElements(), duration); setVisibilityState(getInnerElements(), 'hidden'); onTransitionedOut(duration, function () { if (!isPreparingToShow) { removeFollowCursorListener(); } if (instance.props.aria) { instance.reference.removeAttribute("aria-".concat(instance.props.aria)); } instance.popperInstance.disableEventListeners(); instance.popperInstance.options.placement = instance.props.placement; parentNode.removeChild(instance.popper); instance.props.onHidden(instance); instance.state.isMounted = false; }); } /** * Destroys the tooltip */ function destroy(destroyTargetInstances) { if (instance.state.isDestroyed) { return; } // If the popper is currently mounted to the DOM, we want to ensure it gets // hidden and unmounted instantly upon destruction if (instance.state.isMounted) { hide(0); } removeTriggersFromReference(); delete instance.reference._tippy; if (instance.props.target && destroyTargetInstances) { arrayFrom(instance.reference.querySelectorAll(instance.props.target)).forEach(function (child) { if (child._tippy) { child._tippy.destroy(); } }); } if (instance.popperInstance) { instance.popperInstance.destroy(); } instance.state.isDestroyed = true; } } /** * Groups an array of instances by taking control of their props during * certain lifecycles. * @param {Object[]} targets * @param {Object} options */ function group(instances) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$delay = _ref.delay, delay = _ref$delay === void 0 ? instances[0].props.delay : _ref$delay, _ref$duration = _ref.duration, duration = _ref$duration === void 0 ? 0 : _ref$duration; var isAnyTippyOpen = false; instances.forEach(function (instance) { instance._originalProps = { duration: instance.props.duration, onHide: instance.props.onHide, onShow: instance.props.onShow, onShown: instance.props.onShown }; }); function setIsAnyTippyOpen(value) { isAnyTippyOpen = value; updateInstances(); } function onShow(instance) { instance._originalProps.onShow(instance); instances.forEach(function (instance) { instance.set({ duration: duration }); instance.hide(); }); setIsAnyTippyOpen(true); } function onHide(instance) { instance._originalProps.onHide(instance); setIsAnyTippyOpen(false); } function onShown(instance) { instance._originalProps.onShown(instance); instance.set({ duration: instance._originalProps.duration }); } function updateInstances() { instances.forEach(function (instance) { instance.set({ onShow: onShow, onShown: onShown, onHide: onHide, delay: isAnyTippyOpen ? [0, Array.isArray(delay) ? delay[1] : delay] : delay, duration: isAnyTippyOpen ? duration : instance._originalProps.duration }); }); } updateInstances(); } var globalEventListenersBound = false; /** * Exported module * @param {String|Element|Element[]|NodeList|Object} targets * @param {Object} options * @return {Object} */ function tippy(targets, options) { validateOptions(options, Defaults); if (!globalEventListenersBound) { bindGlobalEventListeners(); globalEventListenersBound = true; } var props = _extends({}, Defaults, options); // If they are specifying a virtual positioning reference, we need to polyfill // some native DOM props if (isBareVirtualElement(targets)) { polyfillElementPrototypeProperties(targets); } var instances = getArrayOfElements(targets).reduce(function (acc, reference) { var instance = reference && createTippy(reference, props); if (instance) { acc.push(instance); } return acc; }, []); return isSingular(targets) ? instances[0] : instances; } /** * Static props */ tippy.version = version; tippy.defaults = Defaults; /** * Static methods */ tippy.setDefaults = function (partialDefaults) { Object.keys(partialDefaults).forEach(function (key) { Defaults[key] = partialDefaults[key]; }); }; tippy.hideAll = hideAll; tippy.group = group; /** * Auto-init tooltips for elements with a `data-tippy="..."` attribute */ function autoInit() { arrayFrom(document.querySelectorAll('[data-tippy]')).forEach(function (el) { var content = el.getAttribute('data-tippy'); if (content) { tippy(el, { content: content }); } }); } if (isBrowser) { setTimeout(autoInit); } /** * Injects a string of CSS styles to a style node in * @param {String} css */ function injectCSS(css) { if (isBrowser) { var style = document.createElement('style'); style.type = 'text/css'; style.textContent = css; var head = document.head; var firstChild = head.firstChild; if (firstChild) { head.insertBefore(style, firstChild); } else { head.appendChild(style); } } } injectCSS(css); /* harmony default export */ var index_all = (tippy); //# sourceMappingURL=index.all.js.map // CONCATENATED MODULE: ./cartridges/app_tfg/cartridge/client/default/js/components/tooltip.js const DEFAULTS = { arrow: true, animation: 'fade', appendTo: 'parent', placement: 'top', interactive: true, theme: 'light-border', maxWidth: 240 }; const getOptions = options => Object.assign({}, DEFAULTS, options || {}); const initTooltip = (selector, options) => { index_all(selector, getOptions(options)); }; /* harmony default export */ var components_tooltip = __webpack_exports__["default"] = ((selector, options) => { initTooltip(selector, options); }); /***/ }), /***/ "./cartridges/app_tfg/cartridge/client/default/js/product/base.js": /*!************************************************************************!*\ !*** ./cartridges/app_tfg/cartridge/client/default/js/product/base.js ***! \************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js"); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ~base */ "./cartridges/app_storefront_base/cartridge/client/default/js/product/base.js"); /* harmony import */ var _util_domutils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/domutils */ "./cartridges/app_tfg/cartridge/client/default/js/util/domutils.js"); /* harmony import */ var _util_fetchutils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/fetchutils */ "./cartridges/app_tfg/cartridge/client/default/js/util/fetchutils.js"); /* harmony import */ var _components_sizeConversions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../components/sizeConversions */ "./cartridges/app_tfg/cartridge/client/default/js/components/sizeConversions.js"); /* harmony import */ var _components_stickyHeaderScroll__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../components/stickyHeaderScroll */ "./cartridges/app_tfg/cartridge/client/default/js/components/stickyHeaderScroll.js"); /* harmony import */ var _components_flyoutUnderHeader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../components/flyoutUnderHeader */ "./cartridges/app_tfg/cartridge/client/default/js/components/flyoutUnderHeader.js"); /* eslint-disable import/no-named-as-default */ // eslint-disable-line import/named const CONSTANTS = { ADD_NOTIFICATION_DISPLAY_TIME: 5000 }; const CLASSES = { ATTRIBUTE_HAS_ERROR: 'product-detail__attribute--error' }; const SELECTORS = { DETAILS: '.product-detail', VARIANT_DETAILS: '.product-detail__details-row', SET_DETAILS: '.set-item', ATTRIBUTES_CONTAINER: '.product-detail__attributes', ATTRIBUTE: '.product-detail__attribute', ATTRIBUTE_VALUE: '.product-detail__attribute__value', ATTRIBUTE_ERROR: '.product-detail__attribute__error', ATTRIBUTE_DROPDOWN: '.product-detail__attribute__dropdown', ADD_TO_BASKET_NOTIFICATION: '.product-detail__add-to-cart__notification', ADD_TO_WISHLIST_NOTIFICATION: '.product-detail__add-to-wishlist__notification', get SELECTED_ATTRIBUTE_VALUE() { return `${this.ATTRIBUTE_VALUE}--current`; } }; const getDetailsContainer = child => { let productContainer = child.closest(SELECTORS.SET_DETAILS); if (!productContainer) { productContainer = child.closest(SELECTORS.VARIANT_DETAILS); } if (!productContainer) { productContainer = child.closest(SELECTORS.DETAILS); } return productContainer; }; const handleAttributeChange = async el => { const container = getDetailsContainer(el); let isActiveATBMsg; let index; const $element = jquery__WEBPACK_IMPORTED_MODULE_0___default()(el); // eslint-disable-next-line jquery/no-closest const parent = $element.closest('.set-item'); if (parent.length > 0) { // eslint-disable-next-line jquery/no-find const sameClassElements = jquery__WEBPACK_IMPORTED_MODULE_0___default()('body').find('.set-item'); index = sameClassElements.index(parent); } if (index) { isActiveATBMsg = document.querySelectorAll('.add-to-bag-msg') && document.querySelectorAll('.add-to-bag-msg')[index].classList.contains('active'); } else { isActiveATBMsg = document.querySelector('.add-to-bag-msg') && document.querySelector('.add-to-bag-msg').classList.contains('active'); } document.dispatchEvent(new CustomEvent('product:beforeAttributeSelect')); // eslint-disable-next-line jquery/no-text const _ref = await Object(_util_fetchutils__WEBPACK_IMPORTED_MODULE_3__["loadContent"])(el, el.value, { pview: container.dataset.pview || 'pdp' }), content = _ref.content; const tempContainer = document.createElement('div'); tempContainer.innerHTML = content; let detailsOnly = ''; if (tempContainer.querySelector(SELECTORS.VARIANT_DETAILS)) { detailsOnly = tempContainer.querySelector(SELECTORS.VARIANT_DETAILS).outerHTML; container.outerHTML = detailsOnly; } if (tempContainer.querySelector(SELECTORS.DETAILS) && detailsOnly === '') { detailsOnly = tempContainer.querySelector(SELECTORS.DETAILS).outerHTML; container.outerHTML = detailsOnly; } // eslint-disable-next-line no-undef if (typeof PayPalSDK !== 'undefined') { // eslint-disable-next-line no-undef PayPalSDK.Messages().render(); } Object(_components_sizeConversions__WEBPACK_IMPORTED_MODULE_4__["default"])(); _base__WEBPACK_IMPORTED_MODULE_1__["default"].selectVariationPrompt(); document.dispatchEvent(new CustomEvent('product:afterAttributeSelect')); const ispreorder = el.getAttribute('data-ispreorder'); const preorderDisplayMessage = el.getAttribute('data-preordemessage'); const deliveryAccordion = document.querySelector('.product-detail__accordion__product-details-delivery-returns'); const preOrderMessage = document.querySelector('.pre-order__message'); if (deliveryAccordion) { if (ispreorder === 'true') { preOrderMessage.innerHTML = preorderDisplayMessage; if (deliveryAccordion.classList.contains('d-none')) { deliveryAccordion.classList.remove('d-none'); } } else if (!deliveryAccordion.classList.contains('d-none')) { deliveryAccordion.classList.add('d-none'); } } // eslint-disable-next-line jquery/no-class if (!Object(_util_domutils__WEBPACK_IMPORTED_MODULE_2__["isLG"])()) { // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('body,html').removeClass('overflow-text'); } Object(_components_stickyHeaderScroll__WEBPACK_IMPORTED_MODULE_5__["default"])(); const isSizeEL = el && el.classList.contains('select-dropdown__list-item'); if (isSizeEL || isActiveATBMsg && el.dataset.attr === 'color') { if (index >= 0) { // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('.add-to-bag-msg').eq(index).addClass('active'); } else { // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('.add-to-bag-msg').addClass('active'); } } // eslint-disable-next-line jquery/no-class const isNotify = el && el.querySelector('#notify-btn'); if (isNotify) { // eslint-disable-next-line jquery/no-class if (index >= 0) { // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('.add-to-bag-msg').eq(index).removeClass('active'); } else { // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('.add-to-bag-msg').removeClass('active'); } if (index >= 0) { // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('.continuity-flyout__pane').removeClass('show'); // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('.continuity-flyout__pane').eq(index).addClass('show'); } else { // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('.continuity-flyout__pane').addClass('show'); } } jquery__WEBPACK_IMPORTED_MODULE_0___default()('.sizeguidelabel .close-icon, #sizeGuideAccordion, .continuity-flyout__close').on('click', () => { // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('.select-dropdown__list,.select-dropdown__button').removeClass('active'); // eslint-disable-next-line jquery/no-class if (!Object(_util_domutils__WEBPACK_IMPORTED_MODULE_2__["isLG"])()) { // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('body,html').removeClass('overflow-text'); } }); }; const handleErrorField = data => { data.forEach(attrObj => { const attrContainer = document.querySelector(`${SELECTORS.ATTRIBUTE}--${attrObj.id}`); if (attrContainer) { const attrErrorContainer = attrContainer.querySelector(SELECTORS.ATTRIBUTE_ERROR); attrContainer.classList.add(CLASSES.ATTRIBUTE_HAS_ERROR); if (attrErrorContainer) { attrErrorContainer.innerHTML = attrObj.message; } } }); }; const handleErrorFieldForMultipleFields = (data, attributeContainer) => { data.forEach(attrObj => { const attrContainer = attributeContainer.find(`${SELECTORS.ATTRIBUTE}--${attrObj.id}`); const attrErrorContainer = attrContainer.find(SELECTORS.ATTRIBUTE_ERROR); attrContainer.addClass(CLASSES.ATTRIBUTE_HAS_ERROR); if (attrErrorContainer) { attrErrorContainer.html(attrObj.message); } }); }; _base__WEBPACK_IMPORTED_MODULE_1__["default"].colorAttribute = () => {}; _base__WEBPACK_IMPORTED_MODULE_1__["default"].selectAttribute = () => { Object(_util_domutils__WEBPACK_IMPORTED_MODULE_2__["onEvent"])(document, 'click', SELECTORS.ATTRIBUTE_VALUE, async e => { e.preventDefault(); const value = e.delegateTarget; if (value.dataset.action) { handleAttributeChange(value); } }); Object(_util_domutils__WEBPACK_IMPORTED_MODULE_2__["onEvent"])(document, 'change', SELECTORS.ATTRIBUTE_DROPDOWN, async e => { const dropdown = e.delegateTarget; if (dropdown.value) { handleAttributeChange(dropdown); } }); }; _base__WEBPACK_IMPORTED_MODULE_1__["default"].appendAttributeValuesToAddRequest = () => { jquery__WEBPACK_IMPORTED_MODULE_0___default()(document).on('updateAddToCartFormData', (e, form) => { const selectedValues = document.querySelectorAll(SELECTORS.SELECTED_ATTRIBUTE_VALUE); const selectedValuesMap = Array.from(selectedValues).reduce((map, attrValue) => Object.assign(map, { [attrValue.dataset.attr]: attrValue.dataset.value }), {}); form.selectedValues = JSON.stringify(selectedValuesMap); }); }; _base__WEBPACK_IMPORTED_MODULE_1__["default"].handlePostCartAdd = () => { // eslint-disable-next-line no-unused-vars let lastClickedButton = null; jquery__WEBPACK_IMPORTED_MODULE_0___default()(document).on('updateAddToCartFormData', (e, data) => { if (!data.error) { lastClickedButton = e.target; } }).on('product:afterAddToCart', (e, data) => { const $button = jquery__WEBPACK_IMPORTED_MODULE_0___default()(lastClickedButton); // eslint-disable-next-line jquery/no-closest const parent = $button.closest('.set-item'); if (parent.length > 0) { parent.find('.add-to-bag-msg').removeClass('active'); } else { // eslint-disable-next-line jquery/no-class jquery__WEBPACK_IMPORTED_MODULE_0___default()('.add-to-bag-msg').removeClass('active'); } if (data && !data.error) { // eslint-disable-next-line jquery/no-find, jquery/no-parents let notification = $button.parents(SELECTORS.DETAILS).find(SELECTORS.ADD_TO_BASKET_NOTIFICATION); if (notification.length > 1) { // eslint-disable-next-line jquery/no-find, jquery/no-parents notification = $button.parents(SELECTORS.SET_DETAILS).find(SELECTORS.ADD_TO_BASKET_NOTIFICATION); } if (notification) { notification.removeClass('d-none'); setTimeout(() => { notification.addClass('d-none'); }, CONSTANTS.ADD_NOTIFICATION_DISPLAY_TIME); } } if (data && data.attributeErrors) { // eslint-disable-next-line jquery/no-parents let attributeContainer = $button.parents(SELECTORS.DETAILS); if (attributeContainer.length > 1) { // eslint-disable-next-line jquery/no-parents attributeContainer = $button.parents(SELECTORS.SET_DETAILS); handleErrorFieldForMultipleFields(data.attributeErrors, attributeContainer); } else { handleErrorField(data.attributeErrors); } } }); }; _base__WEBPACK_IMPORTED_MODULE_1__["default"].handlePostWishlistAdd = () => { document.addEventListener('product:addedToWishlist', () => { const notification = document.querySelector(SELECTORS.ADD_TO_WISHLIST_NOTIFICATION); if (notification) { notification.classList.remove('d-none'); setTimeout(() => { notification.classList.add('d-none'); }, CONSTANTS.ADD_NOTIFICATION_DISPLAY_TIME); } }); }; _base__WEBPACK_IMPORTED_MODULE_1__["default"].styleFlyouts = () => { const toggleOpenedClass = add => { const container = document.querySelector(SELECTORS.DETAILS); if (container) { container.classList.toggle('flyout-open', !!add); } }; document.addEventListener(_components_flyoutUnderHeader__WEBPACK_IMPORTED_MODULE_6__["EVENTS"].FLYOUT_OPEN, toggleOpenedClass.bind(null, true)); document.addEventListener(_components_flyoutUnderHeader__WEBPACK_IMPORTED_MODULE_6__["EVENTS"].FLYOUT_CLOSE, toggleOpenedClass.bind(null, false)); }; _base__WEBPACK_IMPORTED_MODULE_1__["default"].selectVariationPrompt = () => { const attributeContainer = document.querySelector(SELECTORS.ATTRIBUTES_CONTAINER); if (attributeContainer && attributeContainer.dataset.attributeErrors) { const data = Object(_util_domutils__WEBPACK_IMPORTED_MODULE_2__["getJSONData"])(attributeContainer, 'attributeErrors'); if (Object.keys(data).length > 0) { handleErrorField(data); } } }; _base__WEBPACK_IMPORTED_MODULE_1__["default"].initSizeConversions = _components_sizeConversions__WEBPACK_IMPORTED_MODULE_4__["default"]; /* harmony default export */ __webpack_exports__["default"] = (_base__WEBPACK_IMPORTED_MODULE_1__["default"]); /***/ }), /***/ "./cartridges/app_tfg/cartridge/client/default/js/product/components/attributes.js": /*!*****************************************************************************************!*\ !*** ./cartridges/app_tfg/cartridge/client/default/js/product/components/attributes.js ***! \*****************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _components_tooltip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../components/tooltip */ "./cartridges/app_tfg/cartridge/client/default/js/components/tooltip.js"); const SELECTORS = { ATTRIBUTE_TOOLTIP: '.product-detail__attribute__value[data-tippy-content]' }; /* harmony default export */ __webpack_exports__["default"] = (() => { Object(_components_tooltip__WEBPACK_IMPORTED_MODULE_0__["default"])(SELECTORS.ATTRIBUTE_TOOLTIP); }); /***/ }), /***/ "./cartridges/app_tfg/cartridge/client/default/js/product/components/imageCarousel.js": /*!********************************************************************************************!*\ !*** ./cartridges/app_tfg/cartridge/client/default/js/product/components/imageCarousel.js ***! \********************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js"); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _util_domutils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../util/domutils */ "./cartridges/app_tfg/cartridge/client/default/js/util/domutils.js"); /* harmony import */ var _thirdParty_bootstrap_carouselSwipe__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../thirdParty/bootstrap/carouselSwipe */ "./cartridges/app_tfg/cartridge/client/default/js/thirdParty/bootstrap/carouselSwipe.js"); /* harmony import */ var _imageGallery__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./imageGallery */ "./cartridges/app_tfg/cartridge/client/default/js/product/components/imageGallery.js"); const GLOBALS = { CAROUSELS: [] }; const CLASSES = { CAROUSEL: 'carousel' }; const SELECTORS = { CAROUSEL_CONTAINER: '.primary-images__carousel', QUICKVIEW_MODAL: '#quickViewModal' }; const clearCarousel = carouselElement => { if (GLOBALS.CAROUSELS.length) { const currentCarousel = GLOBALS.CAROUSELS.find(carousel => carousel === carouselElement); const currentCarouselIndex = GLOBALS.CAROUSELS.findIndex(carousel => carousel === carouselElement); if (currentCarousel) { currentCarousel.classList.remove(CLASSES.CAROUSEL); jquery__WEBPACK_IMPORTED_MODULE_0___default()(currentCarousel).carousel('dispose'); GLOBALS.CAROUSELS.splice(currentCarouselIndex, 1); } } }; const disableCarousel = carouselElement => { carouselElement.dataset.swipeDisabled = 'true'; }; const enableCarousel = carouselElement => { carouselElement.dataset.swipeDisabled = 'false'; }; const initQuickviewCleanup = carouselElement => { const quickViewModal = document.querySelector(SELECTORS.QUICKVIEW_MODAL); if (quickViewModal) { jquery__WEBPACK_IMPORTED_MODULE_0___default()(quickViewModal).on('hidden.bs.modal', clearCarousel.bind(null, carouselElement)); } }; const initCarousel = carouselElement => { carouselElement.classList.add(CLASSES.CAROUSEL); GLOBALS.CAROUSELS.push(jquery__WEBPACK_IMPORTED_MODULE_0___default()(carouselElement).carousel({ interval: false })[0]); Object(_util_domutils__WEBPACK_IMPORTED_MODULE_1__["addUniqueEventListener"])(document, 'product:beforeAttributeSelect', clearCarousel.bind(null, carouselElement)); Object(_util_domutils__WEBPACK_IMPORTED_MODULE_1__["addUniqueEventListener"])(document, _imageGallery__WEBPACK_IMPORTED_MODULE_3__["EVENTS"].PINCH_ZOOM_START, disableCarousel.bind(null, carouselElement)); Object(_util_domutils__WEBPACK_IMPORTED_MODULE_1__["addUniqueEventListener"])(document, _imageGallery__WEBPACK_IMPORTED_MODULE_3__["EVENTS"].PINCH_ZOOM_END, enableCarousel.bind(null, carouselElement)); jquery__WEBPACK_IMPORTED_MODULE_0___default()(carouselElement).on('slid.bs.carousel', () => { _imageGallery__WEBPACK_IMPORTED_MODULE_3__["GLOBALS"].PINCH_ZOOM.forEach(pinchZoomObj => { pinchZoomObj.update({ type: 'resize' }); }); }); initQuickviewCleanup(carouselElement); }; /* harmony default export */ __webpack_exports__["default"] = (forceCarousel => { const isProductSet = document.querySelector('.product-set-detail') !== null; const carousels = Array.from(document.querySelectorAll(SELECTORS.CAROUSEL_CONTAINER)); carousels.forEach(carousel => { if (!Object(_util_domutils__WEBPACK_IMPORTED_MODULE_1__["isLG"])() || forceCarousel || isProductSet) { initCarousel(carousel); Object(_thirdParty_bootstrap_carouselSwipe__WEBPACK_IMPORTED_MODULE_2__["default"])(carousel, {}); } else { clearCarousel(carousel); } }); }); /***/ }), /***/ "./cartridges/app_tfg/cartridge/client/default/js/product/components/imageGallery.js": /*!*******************************************************************************************************!*\ !*** ./cartridges/app_tfg/cartridge/client/default/js/product/components/imageGallery.js + 5 modules ***! \*******************************************************************************************************/ /*! exports provided: GLOBALS, EVENTS, PDP_GALLERY_EVENTS, initImageGallery */ /*! ModuleConcatenation bailout: Cannot concat with ./cartridges/app_tfg/cartridge/client/default/js/product/components/videoPlayer.js because of ./cartridges/app_tfg/cartridge/client/default/js/product/detail.js */ /*! ModuleConcatenation bailout: Cannot concat with ./cartridges/app_tfg/cartridge/client/default/js/util/domutils.js */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, "GLOBALS", function() { return /* binding */ GLOBALS; }); __webpack_require__.d(__webpack_exports__, "EVENTS", function() { return /* binding */ EVENTS; }); __webpack_require__.d(__webpack_exports__, "PDP_GALLERY_EVENTS", function() { return /* binding */ PDP_GALLERY_EVENTS; }); __webpack_require__.d(__webpack_exports__, "initImageGallery", function() { return /* binding */ initImageGallery; }); // CONCATENATED MODULE: ./node_modules/lightgallery/lightgallery.es5.js /*! * lightgallery | 2.7.1 | January 11th 2023 * http://www.lightgalleryjs.com/ * Copyright (c) 2020 Sachin Neravath; * @license GPLv3 */ /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } /** * List of lightGallery events * All events should be documented here * Below interfaces are used to build the website documentations * */ var lGEvents = { afterAppendSlide: 'lgAfterAppendSlide', init: 'lgInit', hasVideo: 'lgHasVideo', containerResize: 'lgContainerResize', updateSlides: 'lgUpdateSlides', afterAppendSubHtml: 'lgAfterAppendSubHtml', beforeOpen: 'lgBeforeOpen', afterOpen: 'lgAfterOpen', slideItemLoad: 'lgSlideItemLoad', beforeSlide: 'lgBeforeSlide', afterSlide: 'lgAfterSlide', posterClick: 'lgPosterClick', dragStart: 'lgDragStart', dragMove: 'lgDragMove', dragEnd: 'lgDragEnd', beforeNextSlide: 'lgBeforeNextSlide', beforePrevSlide: 'lgBeforePrevSlide', beforeClose: 'lgBeforeClose', afterClose: 'lgAfterClose', rotateLeft: 'lgRotateLeft', rotateRight: 'lgRotateRight', flipHorizontal: 'lgFlipHorizontal', flipVertical: 'lgFlipVertical', autoplay: 'lgAutoplay', autoplayStart: 'lgAutoplayStart', autoplayStop: 'lgAutoplayStop', }; var lightGalleryCoreSettings = { mode: 'lg-slide', easing: 'ease', speed: 400, licenseKey: '0000-0000-000-0000', height: '100%', width: '100%', addClass: '', startClass: 'lg-start-zoom', backdropDuration: 300, container: '', startAnimationDuration: 400, zoomFromOrigin: true, hideBarsDelay: 0, showBarsAfter: 10000, slideDelay: 0, supportLegacyBrowser: true, allowMediaOverlap: false, videoMaxSize: '1280-720', loadYouTubePoster: true, defaultCaptionHeight: 0, ariaLabelledby: '', ariaDescribedby: '', resetScrollPosition: true, hideScrollbar: false, closable: true, swipeToClose: true, closeOnTap: true, showCloseIcon: true, showMaximizeIcon: false, loop: true, escKey: true, keyPress: true, trapFocus: true, controls: true, slideEndAnimation: true, hideControlOnEnd: false, mousewheel: false, getCaptionFromTitleOrAlt: true, appendSubHtmlTo: '.lg-sub-html', subHtmlSelectorRelative: false, preload: 2, numberOfSlideItemsInDom: 10, selector: '', selectWithin: '', nextHtml: '', prevHtml: '', index: 0, iframeWidth: '100%', iframeHeight: '100%', iframeMaxWidth: '100%', iframeMaxHeight: '100%', download: true, counter: true, appendCounterTo: '.lg-toolbar', swipeThreshold: 50, enableSwipe: true, enableDrag: true, dynamic: false, dynamicEl: [], extraProps: [], exThumbImage: '', isMobile: undefined, mobileSettings: { controls: false, showCloseIcon: false, download: false, }, plugins: [], strings: { closeGallery: 'Close gallery', toggleMaximize: 'Toggle maximize', previousSlide: 'Previous slide', nextSlide: 'Next slide', download: 'Download', playVideo: 'Play video', }, }; function initLgPolyfills() { (function () { if (typeof window.CustomEvent === 'function') return false; function CustomEvent(event, params) { params = params || { bubbles: false, cancelable: false, detail: null, }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; } window.CustomEvent = CustomEvent; })(); (function () { if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector; } })(); } var lgQuery = /** @class */ (function () { function lgQuery(selector) { this.cssVenderPrefixes = [ 'TransitionDuration', 'TransitionTimingFunction', 'Transform', 'Transition', ]; this.selector = this._getSelector(selector); this.firstElement = this._getFirstEl(); return this; } lgQuery.generateUUID = function () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; return v.toString(16); }); }; lgQuery.prototype._getSelector = function (selector, context) { if (context === void 0) { context = document; } if (typeof selector !== 'string') { return selector; } context = context || document; var fl = selector.substring(0, 1); if (fl === '#') { return context.querySelector(selector); } else { return context.querySelectorAll(selector); } }; lgQuery.prototype._each = function (func) { if (!this.selector) { return this; } if (this.selector.length !== undefined) { [].forEach.call(this.selector, func); } else { func(this.selector, 0); } return this; }; lgQuery.prototype._setCssVendorPrefix = function (el, cssProperty, value) { // prettier-ignore var property = cssProperty.replace(/-([a-z])/gi, function (s, group1) { return group1.toUpperCase(); }); if (this.cssVenderPrefixes.indexOf(property) !== -1) { el.style[property.charAt(0).toLowerCase() + property.slice(1)] = value; el.style['webkit' + property] = value; el.style['moz' + property] = value; el.style['ms' + property] = value; el.style['o' + property] = value; } else { el.style[property] = value; } }; lgQuery.prototype._getFirstEl = function () { if (this.selector && this.selector.length !== undefined) { return this.selector[0]; } else { return this.selector; } }; lgQuery.prototype.isEventMatched = function (event, eventName) { var eventNamespace = eventName.split('.'); return event .split('.') .filter(function (e) { return e; }) .every(function (e) { return eventNamespace.indexOf(e) !== -1; }); }; lgQuery.prototype.attr = function (attr, value) { if (value === undefined) { if (!this.firstElement) { return ''; } return this.firstElement.getAttribute(attr); } this._each(function (el) { el.setAttribute(attr, value); }); return this; }; lgQuery.prototype.find = function (selector) { return $LG(this._getSelector(selector, this.selector)); }; lgQuery.prototype.first = function () { if (this.selector && this.selector.length !== undefined) { return $LG(this.selector[0]); } else { return $LG(this.selector); } }; lgQuery.prototype.eq = function (index) { return $LG(this.selector[index]); }; lgQuery.prototype.parent = function () { return $LG(this.selector.parentElement); }; lgQuery.prototype.get = function () { return this._getFirstEl(); }; lgQuery.prototype.removeAttr = function (attributes) { var attrs = attributes.split(' '); this._each(function (el) { attrs.forEach(function (attr) { return el.removeAttribute(attr); }); }); return this; }; lgQuery.prototype.wrap = function (className) { if (!this.firstElement) { return this; } var wrapper = document.createElement('div'); wrapper.className = className; this.firstElement.parentNode.insertBefore(wrapper, this.firstElement); this.firstElement.parentNode.removeChild(this.firstElement); wrapper.appendChild(this.firstElement); return this; }; lgQuery.prototype.addClass = function (classNames) { if (classNames === void 0) { classNames = ''; } this._each(function (el) { // IE doesn't support multiple arguments classNames.split(' ').forEach(function (className) { if (className) { el.classList.add(className); } }); }); return this; }; lgQuery.prototype.removeClass = function (classNames) { this._each(function (el) { // IE doesn't support multiple arguments classNames.split(' ').forEach(function (className) { if (className) { el.classList.remove(className); } }); }); return this; }; lgQuery.prototype.hasClass = function (className) { if (!this.firstElement) { return false; } return this.firstElement.classList.contains(className); }; lgQuery.prototype.hasAttribute = function (attribute) { if (!this.firstElement) { return false; } return this.firstElement.hasAttribute(attribute); }; lgQuery.prototype.toggleClass = function (className) { if (!this.firstElement) { return this; } if (this.hasClass(className)) { this.removeClass(className); } else { this.addClass(className); } return this; }; lgQuery.prototype.css = function (property, value) { var _this = this; this._each(function (el) { _this._setCssVendorPrefix(el, property, value); }); return this; }; // Need to pass separate namespaces for separate elements lgQuery.prototype.on = function (events, listener) { var _this = this; if (!this.selector) { return this; } events.split(' ').forEach(function (event) { if (!Array.isArray(lgQuery.eventListeners[event])) { lgQuery.eventListeners[event] = []; } lgQuery.eventListeners[event].push(listener); _this.selector.addEventListener(event.split('.')[0], listener); }); return this; }; // @todo - test this lgQuery.prototype.once = function (event, listener) { var _this = this; this.on(event, function () { _this.off(event); listener(event); }); return this; }; lgQuery.prototype.off = function (event) { var _this = this; if (!this.selector) { return this; } Object.keys(lgQuery.eventListeners).forEach(function (eventName) { if (_this.isEventMatched(event, eventName)) { lgQuery.eventListeners[eventName].forEach(function (listener) { _this.selector.removeEventListener(eventName.split('.')[0], listener); }); lgQuery.eventListeners[eventName] = []; } }); return this; }; lgQuery.prototype.trigger = function (event, detail) { if (!this.firstElement) { return this; } var customEvent = new CustomEvent(event.split('.')[0], { detail: detail || null, }); this.firstElement.dispatchEvent(customEvent); return this; }; // Does not support IE lgQuery.prototype.load = function (url) { var _this = this; fetch(url) .then(function (res) { return res.text(); }) .then(function (html) { _this.selector.innerHTML = html; }); return this; }; lgQuery.prototype.html = function (html) { if (html === undefined) { if (!this.firstElement) { return ''; } return this.firstElement.innerHTML; } this._each(function (el) { el.innerHTML = html; }); return this; }; lgQuery.prototype.append = function (html) { this._each(function (el) { if (typeof html === 'string') { el.insertAdjacentHTML('beforeend', html); } else { el.appendChild(html); } }); return this; }; lgQuery.prototype.prepend = function (html) { this._each(function (el) { el.insertAdjacentHTML('afterbegin', html); }); return this; }; lgQuery.prototype.remove = function () { this._each(function (el) { el.parentNode.removeChild(el); }); return this; }; lgQuery.prototype.empty = function () { this._each(function (el) { el.innerHTML = ''; }); return this; }; lgQuery.prototype.scrollTop = function (scrollTop) { if (scrollTop !== undefined) { document.body.scrollTop = scrollTop; document.documentElement.scrollTop = scrollTop; return this; } else { return (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0); } }; lgQuery.prototype.scrollLeft = function (scrollLeft) { if (scrollLeft !== undefined) { document.body.scrollLeft = scrollLeft; document.documentElement.scrollLeft = scrollLeft; return this; } else { return (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0); } }; lgQuery.prototype.offset = function () { if (!this.firstElement) { return { left: 0, top: 0, }; } var rect = this.firstElement.getBoundingClientRect(); var bodyMarginLeft = $LG('body').style().marginLeft; // Minus body margin - https://stackoverflow.com/questions/30711548/is-getboundingclientrect-left-returning-a-wrong-value return { left: rect.left - parseFloat(bodyMarginLeft) + this.scrollLeft(), top: rect.top + this.scrollTop(), }; }; lgQuery.prototype.style = function () { if (!this.firstElement) { return {}; } return (this.firstElement.currentStyle || window.getComputedStyle(this.firstElement)); }; // Width without padding and border even if box-sizing is used. lgQuery.prototype.width = function () { var style = this.style(); return (this.firstElement.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight)); }; // Height without padding and border even if box-sizing is used. lgQuery.prototype.height = function () { var style = this.style(); return (this.firstElement.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom)); }; lgQuery.eventListeners = {}; return lgQuery; }()); function $LG(selector) { initLgPolyfills(); return new lgQuery(selector); } var defaultDynamicOptions = [ 'src', 'sources', 'subHtml', 'subHtmlUrl', 'html', 'video', 'poster', 'slideName', 'responsive', 'srcset', 'sizes', 'iframe', 'downloadUrl', 'download', 'width', 'facebookShareUrl', 'tweetText', 'iframeTitle', 'twitterShareUrl', 'pinterestShareUrl', 'pinterestText', 'fbHtml', 'disqusIdentifier', 'disqusUrl', ]; // Convert html data-attribute to camalcase function convertToData(attr) { // FInd a way for lgsize if (attr === 'href') { return 'src'; } attr = attr.replace('data-', ''); attr = attr.charAt(0).toLowerCase() + attr.slice(1); attr = attr.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); }); return attr; } var utils = { /** * get possible width and height from the lgSize attribute. Used for ZoomFromOrigin option */ getSize: function (el, container, spacing, defaultLgSize) { if (spacing === void 0) { spacing = 0; } var LGel = $LG(el); var lgSize = LGel.attr('data-lg-size') || defaultLgSize; if (!lgSize) { return; } var isResponsiveSizes = lgSize.split(','); // if at-least two viewport sizes are available if (isResponsiveSizes[1]) { var wWidth = window.innerWidth; for (var i = 0; i < isResponsiveSizes.length; i++) { var size_1 = isResponsiveSizes[i]; var responsiveWidth = parseInt(size_1.split('-')[2], 10); if (responsiveWidth > wWidth) { lgSize = size_1; break; } // take last item as last option if (i === isResponsiveSizes.length - 1) { lgSize = size_1; } } } var size = lgSize.split('-'); var width = parseInt(size[0], 10); var height = parseInt(size[1], 10); var cWidth = container.width(); var cHeight = container.height() - spacing; var maxWidth = Math.min(cWidth, width); var maxHeight = Math.min(cHeight, height); var ratio = Math.min(maxWidth / width, maxHeight / height); return { width: width * ratio, height: height * ratio }; }, /** * @desc Get transform value based on the imageSize. Used for ZoomFromOrigin option * @param {jQuery Element} * @returns {String} Transform CSS string */ getTransform: function (el, container, top, bottom, imageSize) { if (!imageSize) { return; } var LGel = $LG(el).find('img').first(); if (!LGel.get()) { return; } var containerRect = container.get().getBoundingClientRect(); var wWidth = containerRect.width; // using innerWidth to include mobile safari bottom bar var wHeight = container.height() - (top + bottom); var elWidth = LGel.width(); var elHeight = LGel.height(); var elStyle = LGel.style(); var x = (wWidth - elWidth) / 2 - LGel.offset().left + (parseFloat(elStyle.paddingLeft) || 0) + (parseFloat(elStyle.borderLeft) || 0) + $LG(window).scrollLeft() + containerRect.left; var y = (wHeight - elHeight) / 2 - LGel.offset().top + (parseFloat(elStyle.paddingTop) || 0) + (parseFloat(elStyle.borderTop) || 0) + $LG(window).scrollTop() + top; var scX = elWidth / imageSize.width; var scY = elHeight / imageSize.height; var transform = 'translate3d(' + (x *= -1) + 'px, ' + (y *= -1) + 'px, 0) scale3d(' + scX + ', ' + scY + ', 1)'; return transform; }, getIframeMarkup: function (iframeWidth, iframeHeight, iframeMaxWidth, iframeMaxHeight, src, iframeTitle) { var title = iframeTitle ? 'title="' + iframeTitle + '"' : ''; return "
\n \n
"; }, getImgMarkup: function (index, src, altAttr, srcset, sizes, sources) { var srcsetAttr = srcset ? "srcset=\"" + srcset + "\"" : ''; var sizesAttr = sizes ? "sizes=\"" + sizes + "\"" : ''; var imgMarkup = ""; var sourceTag = ''; if (sources) { var sourceObj = typeof sources === 'string' ? JSON.parse(sources) : sources; sourceTag = sourceObj.map(function (source) { var attrs = ''; Object.keys(source).forEach(function (key) { // Do not remove the first space as it is required to separate the attributes attrs += " " + key + "=\"" + source[key] + "\""; }); return ""; }); } return "" + sourceTag + imgMarkup; }, // Get src from responsive src getResponsiveSrc: function (srcItms) { var rsWidth = []; var rsSrc = []; var src = ''; for (var i = 0; i < srcItms.length; i++) { var _src = srcItms[i].split(' '); // Manage empty space if (_src[0] === '') { _src.splice(0, 1); } rsSrc.push(_src[0]); rsWidth.push(_src[1]); } var wWidth = window.innerWidth; for (var j = 0; j < rsWidth.length; j++) { if (parseInt(rsWidth[j], 10) > wWidth) { src = rsSrc[j]; break; } } return src; }, isImageLoaded: function (img) { if (!img) return false; // During the onload event, IE correctly identifies any images that // weren’t downloaded as not complete. Others should too. Gecko-based // browsers act like NS4 in that they report this incorrectly. if (!img.complete) { return false; } // However, they do have two very useful properties: naturalWidth and // naturalHeight. These give the true size of the image. If it failed // to load, either of these should be zero. if (img.naturalWidth === 0) { return false; } // No other way of checking: assume it’s ok. return true; }, getVideoPosterMarkup: function (_poster, dummyImg, videoContStyle, playVideoString, _isVideo) { var videoClass = ''; if (_isVideo && _isVideo.youtube) { videoClass = 'lg-has-youtube'; } else if (_isVideo && _isVideo.vimeo) { videoClass = 'lg-has-vimeo'; } else { videoClass = 'lg-has-html5'; } return "
\n
\n \n " + playVideoString + "\n \n \n \n \n \n \n \n
\n " + (dummyImg || '') + "\n \n
"; }, getFocusableElements: function (container) { var elements = container.querySelectorAll('a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type="text"]:not([disabled]), input[type="radio"]:not([disabled]), input[type="checkbox"]:not([disabled]), select:not([disabled])'); var visibleElements = [].filter.call(elements, function (element) { var style = window.getComputedStyle(element); return style.display !== 'none' && style.visibility !== 'hidden'; }); return visibleElements; }, /** * @desc Create dynamic elements array from gallery items when dynamic option is false * It helps to avoid frequent DOM interaction * and avoid multiple checks for dynamic elments * * @returns {Array} dynamicEl */ getDynamicOptions: function (items, extraProps, getCaptionFromTitleOrAlt, exThumbImage) { var dynamicElements = []; var availableDynamicOptions = __spreadArrays(defaultDynamicOptions, extraProps); [].forEach.call(items, function (item) { var dynamicEl = {}; for (var i = 0; i < item.attributes.length; i++) { var attr = item.attributes[i]; if (attr.specified) { var dynamicAttr = convertToData(attr.name); var label = ''; if (availableDynamicOptions.indexOf(dynamicAttr) > -1) { label = dynamicAttr; } if (label) { dynamicEl[label] = attr.value; } } } var currentItem = $LG(item); var alt = currentItem.find('img').first().attr('alt'); var title = currentItem.attr('title'); var thumb = exThumbImage ? currentItem.attr(exThumbImage) : currentItem.find('img').first().attr('src'); dynamicEl.thumb = thumb; if (getCaptionFromTitleOrAlt && !dynamicEl.subHtml) { dynamicEl.subHtml = title || alt || ''; } dynamicEl.alt = alt || title || ''; dynamicElements.push(dynamicEl); }); return dynamicElements; }, isMobile: function () { return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); }, /** * @desc Check the given src is video * @param {String} src * @return {Object} video type * Ex:{ youtube : ["//www.youtube.com/watch?v=c0asJgSyxcY", "c0asJgSyxcY"] } * * @todo - this information can be moved to dynamicEl to avoid frequent calls */ isVideo: function (src, isHTML5VIdeo, index) { if (!src) { if (isHTML5VIdeo) { return { html5: true, }; } else { console.error('lightGallery :- data-src is not provided on slide item ' + (index + 1) + '. Please make sure the selector property is properly configured. More info - https://www.lightgalleryjs.com/demos/html-markup/'); return; } } var youtube = src.match(/\/\/(?:www\.)?youtu(?:\.be|be\.com|be-nocookie\.com)\/(?:watch\?v=|embed\/)?([a-z0-9\-\_\%]+)([\&|?][\S]*)*/i); var vimeo = src.match(/\/\/(?:www\.)?(?:player\.)?vimeo.com\/(?:video\/)?([0-9a-z\-_]+)(.*)?/i); var wistia = src.match(/https?:\/\/(.+)?(wistia\.com|wi\.st)\/(medias|embed)\/([0-9a-z\-_]+)(.*)/); if (youtube) { return { youtube: youtube, }; } else if (vimeo) { return { vimeo: vimeo, }; } else if (wistia) { return { wistia: wistia, }; } }, }; // @ref - https://stackoverflow.com/questions/3971841/how-to-resize-images-proportionally-keeping-the-aspect-ratio // @ref - https://2ality.com/2017/04/setting-up-multi-platform-packages.html // Unique id for each gallery var lgId = 0; var LightGallery = /** @class */ (function () { function LightGallery(element, options) { this.lgOpened = false; this.index = 0; // lightGallery modules this.plugins = []; // false when lightGallery load first slide content; this.lGalleryOn = false; // True when a slide animation is in progress this.lgBusy = false; this.currentItemsInDom = []; // Scroll top value before lightGallery is opened this.prevScrollTop = 0; this.bodyPaddingRight = 0; this.isDummyImageRemoved = false; this.dragOrSwipeEnabled = false; this.mediaContainerPosition = { top: 0, bottom: 0, }; if (!element) { return this; } lgId++; this.lgId = lgId; this.el = element; this.LGel = $LG(element); this.generateSettings(options); this.buildModules(); // When using dynamic mode, ensure dynamicEl is an array if (this.settings.dynamic && this.settings.dynamicEl !== undefined && !Array.isArray(this.settings.dynamicEl)) { throw 'When using dynamic mode, you must also define dynamicEl as an Array.'; } this.galleryItems = this.getItems(); this.normalizeSettings(); // Gallery items this.init(); this.validateLicense(); return this; } LightGallery.prototype.generateSettings = function (options) { // lightGallery settings this.settings = __assign(__assign({}, lightGalleryCoreSettings), options); if (this.settings.isMobile && typeof this.settings.isMobile === 'function' ? this.settings.isMobile() : utils.isMobile()) { var mobileSettings = __assign(__assign({}, this.settings.mobileSettings), this.settings.mobileSettings); this.settings = __assign(__assign({}, this.settings), mobileSettings); } }; LightGallery.prototype.normalizeSettings = function () { if (this.settings.slideEndAnimation) { this.settings.hideControlOnEnd = false; } if (!this.settings.closable) { this.settings.swipeToClose = false; } // And reset it on close to get the correct value next time this.zoomFromOrigin = this.settings.zoomFromOrigin; // At the moment, Zoom from image doesn't support dynamic options // @todo add zoomFromOrigin support for dynamic images if (this.settings.dynamic) { this.zoomFromOrigin = false; } if (!this.settings.container) { this.settings.container = document.body; } // settings.preload should not be grater than $item.length this.settings.preload = Math.min(this.settings.preload, this.galleryItems.length); }; LightGallery.prototype.init = function () { var _this = this; this.addSlideVideoInfo(this.galleryItems); this.buildStructure(); this.LGel.trigger(lGEvents.init, { instance: this, }); if (this.settings.keyPress) { this.keyPress(); } setTimeout(function () { _this.enableDrag(); _this.enableSwipe(); _this.triggerPosterClick(); }, 50); this.arrow(); if (this.settings.mousewheel) { this.mousewheel(); } if (!this.settings.dynamic) { this.openGalleryOnItemClick(); } }; LightGallery.prototype.openGalleryOnItemClick = function () { var _this = this; var _loop_1 = function (index) { var element = this_1.items[index]; var $element = $LG(element); // Using different namespace for click because click event should not unbind if selector is same object('this') // @todo manage all event listners - should have namespace that represent element var uuid = lgQuery.generateUUID(); $element .attr('data-lg-id', uuid) .on("click.lgcustom-item-" + uuid, function (e) { e.preventDefault(); var currentItemIndex = _this.settings.index || index; _this.openGallery(currentItemIndex, element); }); }; var this_1 = this; // Using for loop instead of using bubbling as the items can be any html element. for (var index = 0; index < this.items.length; index++) { _loop_1(index); } }; /** * Module constructor * Modules are build incrementally. * Gallery should be opened only once all the modules are initialized. * use moduleBuildTimeout to make sure this */ LightGallery.prototype.buildModules = function () { var _this = this; this.settings.plugins.forEach(function (plugin) { _this.plugins.push(new plugin(_this, $LG)); }); }; LightGallery.prototype.validateLicense = function () { if (!this.settings.licenseKey) { console.error('Please provide a valid license key'); } else if (this.settings.licenseKey === '0000-0000-000-0000') { console.warn("lightGallery: " + this.settings.licenseKey + " license key is not valid for production use"); } }; LightGallery.prototype.getSlideItem = function (index) { return $LG(this.getSlideItemId(index)); }; LightGallery.prototype.getSlideItemId = function (index) { return "#lg-item-" + this.lgId + "-" + index; }; LightGallery.prototype.getIdName = function (id) { return id + "-" + this.lgId; }; LightGallery.prototype.getElementById = function (id) { return $LG("#" + this.getIdName(id)); }; LightGallery.prototype.manageSingleSlideClassName = function () { if (this.galleryItems.length < 2) { this.outer.addClass('lg-single-item'); } else { this.outer.removeClass('lg-single-item'); } }; LightGallery.prototype.buildStructure = function () { var _this = this; var container = this.$container && this.$container.get(); if (container) { return; } var controls = ''; var subHtmlCont = ''; // Create controls if (this.settings.controls) { controls = "\n "; } if (this.settings.appendSubHtmlTo !== '.lg-item') { subHtmlCont = '
'; } var addClasses = ''; if (this.settings.allowMediaOverlap) { // Do not remove space before last single quote addClasses += 'lg-media-overlap '; } var ariaLabelledby = this.settings.ariaLabelledby ? 'aria-labelledby="' + this.settings.ariaLabelledby + '"' : ''; var ariaDescribedby = this.settings.ariaDescribedby ? 'aria-describedby="' + this.settings.ariaDescribedby + '"' : ''; var containerClassName = "lg-container " + this.settings.addClass + " " + (document.body !== this.settings.container ? 'lg-inline' : ''); var closeIcon = this.settings.closable && this.settings.showCloseIcon ? "" : ''; var maximizeIcon = this.settings.showMaximizeIcon ? "" : ''; var template = "\n
\n
\n\n
\n\n
\n
\n
\n " + controls + "\n
\n
\n " + maximizeIcon + "\n " + closeIcon + "\n
\n " + (this.settings.appendSubHtmlTo === '.lg-outer' ? subHtmlCont : '') + "\n
\n " + (this.settings.appendSubHtmlTo === '.lg-sub-html' ? subHtmlCont : '') + "\n
\n
\n
\n "; $LG(this.settings.container).append(template); if (document.body !== this.settings.container) { $LG(this.settings.container).css('position', 'relative'); } this.outer = this.getElementById('lg-outer'); this.$lgComponents = this.getElementById('lg-components'); this.$backdrop = this.getElementById('lg-backdrop'); this.$container = this.getElementById('lg-container'); this.$inner = this.getElementById('lg-inner'); this.$content = this.getElementById('lg-content'); this.$toolbar = this.getElementById('lg-toolbar'); this.$backdrop.css('transition-duration', this.settings.backdropDuration + 'ms'); var outerClassNames = this.settings.mode + " "; this.manageSingleSlideClassName(); if (this.settings.enableDrag) { outerClassNames += 'lg-grab '; } this.outer.addClass(outerClassNames); this.$inner.css('transition-timing-function', this.settings.easing); this.$inner.css('transition-duration', this.settings.speed + 'ms'); if (this.settings.download) { this.$toolbar.append(""); } this.counter(); $LG(window).on("resize.lg.global" + this.lgId + " orientationchange.lg.global" + this.lgId, function () { _this.refreshOnResize(); }); this.hideBars(); this.manageCloseGallery(); this.toggleMaximize(); this.initModules(); }; LightGallery.prototype.refreshOnResize = function () { if (this.lgOpened) { var currentGalleryItem = this.galleryItems[this.index]; var __slideVideoInfo = currentGalleryItem.__slideVideoInfo; this.mediaContainerPosition = this.getMediaContainerPosition(); var _a = this.mediaContainerPosition, top_1 = _a.top, bottom = _a.bottom; this.currentImageSize = utils.getSize(this.items[this.index], this.outer, top_1 + bottom, __slideVideoInfo && this.settings.videoMaxSize); if (__slideVideoInfo) { this.resizeVideoSlide(this.index, this.currentImageSize); } if (this.zoomFromOrigin && !this.isDummyImageRemoved) { var imgStyle = this.getDummyImgStyles(this.currentImageSize); this.outer .find('.lg-current .lg-dummy-img') .first() .attr('style', imgStyle); } this.LGel.trigger(lGEvents.containerResize); } }; LightGallery.prototype.resizeVideoSlide = function (index, imageSize) { var lgVideoStyle = this.getVideoContStyle(imageSize); var currentSlide = this.getSlideItem(index); currentSlide.find('.lg-video-cont').attr('style', lgVideoStyle); }; /** * Update slides dynamically. * Add, edit or delete slides dynamically when lightGallery is opened. * Modify the current gallery items and pass it via updateSlides method * @note * - Do not mutate existing lightGallery items directly. * - Always pass new list of gallery items * - You need to take care of thumbnails outside the gallery if any * - user this method only if you want to update slides when the gallery is opened. Otherwise, use `refresh()` method. * @param items Gallery items * @param index After the update operation, which slide gallery should navigate to * @category lGPublicMethods * @example * const plugin = lightGallery(); * * // Adding slides dynamically * let galleryItems = [ * // Access existing lightGallery items * // galleryItems are automatically generated internally from the gallery HTML markup * // or directly from galleryItems when dynamic gallery is used * ...plugin.galleryItems, * ...[ * { * src: 'img/img-1.png', * thumb: 'img/thumb1.png', * }, * ], * ]; * plugin.updateSlides( * galleryItems, * plugin.index, * ); * * * // Remove slides dynamically * galleryItems = JSON.parse( * JSON.stringify(updateSlideInstance.galleryItems), * ); * galleryItems.shift(); * updateSlideInstance.updateSlides(galleryItems, 1); * @see Demo */ LightGallery.prototype.updateSlides = function (items, index) { if (this.index > items.length - 1) { this.index = items.length - 1; } if (items.length === 1) { this.index = 0; } if (!items.length) { this.closeGallery(); return; } var currentSrc = this.galleryItems[index].src; this.galleryItems = items; this.updateControls(); this.$inner.empty(); this.currentItemsInDom = []; var _index = 0; // Find the current index based on source value of the slide this.galleryItems.some(function (galleryItem, itemIndex) { if (galleryItem.src === currentSrc) { _index = itemIndex; return true; } return false; }); this.currentItemsInDom = this.organizeSlideItems(_index, -1); this.loadContent(_index, true); this.getSlideItem(_index).addClass('lg-current'); this.index = _index; this.updateCurrentCounter(_index); this.LGel.trigger(lGEvents.updateSlides); }; // Get gallery items based on multiple conditions LightGallery.prototype.getItems = function () { // Gallery items this.items = []; if (!this.settings.dynamic) { if (this.settings.selector === 'this') { this.items.push(this.el); } else if (this.settings.selector) { if (typeof this.settings.selector === 'string') { if (this.settings.selectWithin) { var selectWithin = $LG(this.settings.selectWithin); this.items = selectWithin .find(this.settings.selector) .get(); } else { this.items = this.el.querySelectorAll(this.settings.selector); } } else { this.items = this.settings.selector; } } else { this.items = this.el.children; } return utils.getDynamicOptions(this.items, this.settings.extraProps, this.settings.getCaptionFromTitleOrAlt, this.settings.exThumbImage); } else { return this.settings.dynamicEl || []; } }; LightGallery.prototype.shouldHideScrollbar = function () { return (this.settings.hideScrollbar && document.body === this.settings.container); }; LightGallery.prototype.hideScrollbar = function () { if (!this.shouldHideScrollbar()) { return; } this.bodyPaddingRight = parseFloat($LG('body').style().paddingRight); var bodyRect = document.documentElement.getBoundingClientRect(); var scrollbarWidth = window.innerWidth - bodyRect.width; $LG(document.body).css('padding-right', scrollbarWidth + this.bodyPaddingRight + 'px'); $LG(document.body).addClass('lg-overlay-open'); }; LightGallery.prototype.resetScrollBar = function () { if (!this.shouldHideScrollbar()) { return; } $LG(document.body).css('padding-right', this.bodyPaddingRight + 'px'); $LG(document.body).removeClass('lg-overlay-open'); }; /** * Open lightGallery. * Open gallery with specific slide by passing index of the slide as parameter. * @category lGPublicMethods * @param {Number} index - index of the slide * @param {HTMLElement} element - Which image lightGallery should zoom from * * @example * const $dynamicGallery = document.getElementById('dynamic-gallery-demo'); * const dynamicGallery = lightGallery($dynamicGallery, { * dynamic: true, * dynamicEl: [ * { * src: 'img/1.jpg', * thumb: 'img/thumb-1.jpg', * subHtml: '

Image 1 title

Image 1 descriptions.

', * }, * ... * ], * }); * $dynamicGallery.addEventListener('click', function () { * // Starts with third item.(Optional). * // This is useful if you want use dynamic mode with * // custom thumbnails (thumbnails outside gallery), * dynamicGallery.openGallery(2); * }); * */ LightGallery.prototype.openGallery = function (index, element) { var _this = this; if (index === void 0) { index = this.settings.index; } // prevent accidental double execution if (this.lgOpened) return; this.lgOpened = true; this.outer.removeClass('lg-hide-items'); this.hideScrollbar(); // Add display block, but still has opacity 0 this.$container.addClass('lg-show'); var itemsToBeInsertedToDom = this.getItemsToBeInsertedToDom(index, index); this.currentItemsInDom = itemsToBeInsertedToDom; var items = ''; itemsToBeInsertedToDom.forEach(function (item) { items = items + ("
"); }); this.$inner.append(items); this.addHtml(index); var transform = ''; this.mediaContainerPosition = this.getMediaContainerPosition(); var _a = this.mediaContainerPosition, top = _a.top, bottom = _a.bottom; if (!this.settings.allowMediaOverlap) { this.setMediaContainerPosition(top, bottom); } var __slideVideoInfo = this.galleryItems[index].__slideVideoInfo; if (this.zoomFromOrigin && element) { this.currentImageSize = utils.getSize(element, this.outer, top + bottom, __slideVideoInfo && this.settings.videoMaxSize); transform = utils.getTransform(element, this.outer, top, bottom, this.currentImageSize); } if (!this.zoomFromOrigin || !transform) { this.outer.addClass(this.settings.startClass); this.getSlideItem(index).removeClass('lg-complete'); } var timeout = this.settings.zoomFromOrigin ? 100 : this.settings.backdropDuration; setTimeout(function () { _this.outer.addClass('lg-components-open'); }, timeout); this.index = index; this.LGel.trigger(lGEvents.beforeOpen); // add class lg-current to remove initial transition this.getSlideItem(index).addClass('lg-current'); this.lGalleryOn = false; // Store the current scroll top value to scroll back after closing the gallery.. this.prevScrollTop = $LG(window).scrollTop(); setTimeout(function () { // Need to check both zoomFromOrigin and transform values as we need to set set the // default opening animation if user missed to add the lg-size attribute if (_this.zoomFromOrigin && transform) { var currentSlide_1 = _this.getSlideItem(index); currentSlide_1.css('transform', transform); setTimeout(function () { currentSlide_1 .addClass('lg-start-progress lg-start-end-progress') .css('transition-duration', _this.settings.startAnimationDuration + 'ms'); _this.outer.addClass('lg-zoom-from-image'); }); setTimeout(function () { currentSlide_1.css('transform', 'translate3d(0, 0, 0)'); }, 100); } setTimeout(function () { _this.$backdrop.addClass('in'); _this.$container.addClass('lg-show-in'); }, 10); setTimeout(function () { if (_this.settings.trapFocus && document.body === _this.settings.container) { _this.trapFocus(); } }, _this.settings.backdropDuration + 50); // lg-visible class resets gallery opacity to 1 if (!_this.zoomFromOrigin || !transform) { setTimeout(function () { _this.outer.addClass('lg-visible'); }, _this.settings.backdropDuration); } // initiate slide function _this.slide(index, false, false, false); _this.LGel.trigger(lGEvents.afterOpen); }); if (document.body === this.settings.container) { $LG('html').addClass('lg-on'); } }; /** * Note - Changing the position of the media on every slide transition creates a flickering effect. * Therefore, The height of the caption is calculated dynamically, only once based on the first slide caption. * if you have dynamic captions for each media, * you can provide an appropriate height for the captions via allowMediaOverlap option */ LightGallery.prototype.getMediaContainerPosition = function () { if (this.settings.allowMediaOverlap) { return { top: 0, bottom: 0, }; } var top = this.$toolbar.get().clientHeight || 0; var subHtml = this.outer.find('.lg-components .lg-sub-html').get(); var captionHeight = this.settings.defaultCaptionHeight || (subHtml && subHtml.clientHeight) || 0; var thumbContainer = this.outer.find('.lg-thumb-outer').get(); var thumbHeight = thumbContainer ? thumbContainer.clientHeight : 0; var bottom = thumbHeight + captionHeight; return { top: top, bottom: bottom, }; }; LightGallery.prototype.setMediaContainerPosition = function (top, bottom) { if (top === void 0) { top = 0; } if (bottom === void 0) { bottom = 0; } this.$content.css('top', top + 'px').css('bottom', bottom + 'px'); }; LightGallery.prototype.hideBars = function () { var _this = this; // Hide controllers if mouse doesn't move for some period setTimeout(function () { _this.outer.removeClass('lg-hide-items'); if (_this.settings.hideBarsDelay > 0) { _this.outer.on('mousemove.lg click.lg touchstart.lg', function () { _this.outer.removeClass('lg-hide-items'); clearTimeout(_this.hideBarTimeout); // Timeout will be cleared on each slide movement also _this.hideBarTimeout = setTimeout(function () { _this.outer.addClass('lg-hide-items'); }, _this.settings.hideBarsDelay); }); _this.outer.trigger('mousemove.lg'); } }, this.settings.showBarsAfter); }; LightGallery.prototype.initPictureFill = function ($img) { if (this.settings.supportLegacyBrowser) { try { picturefill({ elements: [$img.get()], }); } catch (e) { console.warn('lightGallery :- If you want srcset or picture tag to be supported for older browser please include picturefil javascript library in your document.'); } } }; /** * @desc Create image counter * Ex: 1/10 */ LightGallery.prototype.counter = function () { if (this.settings.counter) { var counterHtml = "
\n " + (this.index + 1) + " /\n " + this.galleryItems.length + "
"; this.outer.find(this.settings.appendCounterTo).append(counterHtml); } }; /** * @desc add sub-html into the slide * @param {Number} index - index of the slide */ LightGallery.prototype.addHtml = function (index) { var subHtml; var subHtmlUrl; if (this.galleryItems[index].subHtmlUrl) { subHtmlUrl = this.galleryItems[index].subHtmlUrl; } else { subHtml = this.galleryItems[index].subHtml; } if (!subHtmlUrl) { if (subHtml) { // get first letter of sub-html // if first letter starts with . or # get the html form the jQuery object var fL = subHtml.substring(0, 1); if (fL === '.' || fL === '#') { if (this.settings.subHtmlSelectorRelative && !this.settings.dynamic) { subHtml = $LG(this.items) .eq(index) .find(subHtml) .first() .html(); } else { subHtml = $LG(subHtml).first().html(); } } } else { subHtml = ''; } } if (this.settings.appendSubHtmlTo !== '.lg-item') { if (subHtmlUrl) { this.outer.find('.lg-sub-html').load(subHtmlUrl); } else { this.outer.find('.lg-sub-html').html(subHtml); } } else { var currentSlide = $LG(this.getSlideItemId(index)); if (subHtmlUrl) { currentSlide.load(subHtmlUrl); } else { currentSlide.append("
" + subHtml + "
"); } } // Add lg-empty-html class if title doesn't exist if (typeof subHtml !== 'undefined' && subHtml !== null) { if (subHtml === '') { this.outer .find(this.settings.appendSubHtmlTo) .addClass('lg-empty-html'); } else { this.outer .find(this.settings.appendSubHtmlTo) .removeClass('lg-empty-html'); } } this.LGel.trigger(lGEvents.afterAppendSubHtml, { index: index, }); }; /** * @desc Preload slides * @param {Number} index - index of the slide * @todo preload not working for the first slide, Also, should work for the first and last slide as well */ LightGallery.prototype.preload = function (index) { for (var i = 1; i <= this.settings.preload; i++) { if (i >= this.galleryItems.length - index) { break; } this.loadContent(index + i, false); } for (var j = 1; j <= this.settings.preload; j++) { if (index - j < 0) { break; } this.loadContent(index - j, false); } }; LightGallery.prototype.getDummyImgStyles = function (imageSize) { if (!imageSize) return ''; return "width:" + imageSize.width + "px;\n margin-left: -" + imageSize.width / 2 + "px;\n margin-top: -" + imageSize.height / 2 + "px;\n height:" + imageSize.height + "px"; }; LightGallery.prototype.getVideoContStyle = function (imageSize) { if (!imageSize) return ''; return "width:" + imageSize.width + "px;\n height:" + imageSize.height + "px"; }; LightGallery.prototype.getDummyImageContent = function ($currentSlide, index, alt) { var $currentItem; if (!this.settings.dynamic) { $currentItem = $LG(this.items).eq(index); } if ($currentItem) { var _dummyImgSrc = void 0; if (!this.settings.exThumbImage) { _dummyImgSrc = $currentItem.find('img').first().attr('src'); } else { _dummyImgSrc = $currentItem.attr(this.settings.exThumbImage); } if (!_dummyImgSrc) return ''; var imgStyle = this.getDummyImgStyles(this.currentImageSize); var dummyImgContent = ""; $currentSlide.addClass('lg-first-slide'); this.outer.addClass('lg-first-slide-loading'); return dummyImgContent; } return ''; }; LightGallery.prototype.setImgMarkup = function (src, $currentSlide, index) { var currentGalleryItem = this.galleryItems[index]; var alt = currentGalleryItem.alt, srcset = currentGalleryItem.srcset, sizes = currentGalleryItem.sizes, sources = currentGalleryItem.sources; // Use the thumbnail as dummy image which will be resized to actual image size and // displayed on top of actual image var imgContent = ''; var altAttr = alt ? 'alt="' + alt + '"' : ''; if (this.isFirstSlideWithZoomAnimation()) { imgContent = this.getDummyImageContent($currentSlide, index, altAttr); } else { imgContent = utils.getImgMarkup(index, src, altAttr, srcset, sizes, sources); } var imgMarkup = " " + imgContent + ""; $currentSlide.prepend(imgMarkup); }; LightGallery.prototype.onSlideObjectLoad = function ($slide, isHTML5VideoWithoutPoster, onLoad, onError) { var mediaObject = $slide.find('.lg-object').first(); if (utils.isImageLoaded(mediaObject.get()) || isHTML5VideoWithoutPoster) { onLoad(); } else { mediaObject.on('load.lg error.lg', function () { onLoad && onLoad(); }); mediaObject.on('error.lg', function () { onError && onError(); }); } }; /** * * @param $el Current slide item * @param index * @param delay Delay is 0 except first time * @param speed Speed is same as delay, except it is 0 if gallery is opened via hash plugin * @param isFirstSlide */ LightGallery.prototype.onLgObjectLoad = function (currentSlide, index, delay, speed, isFirstSlide, isHTML5VideoWithoutPoster) { var _this = this; this.onSlideObjectLoad(currentSlide, isHTML5VideoWithoutPoster, function () { _this.triggerSlideItemLoad(currentSlide, index, delay, speed, isFirstSlide); }, function () { currentSlide.addClass('lg-complete lg-complete_'); currentSlide.html('Oops... Failed to load content...'); }); }; LightGallery.prototype.triggerSlideItemLoad = function ($currentSlide, index, delay, speed, isFirstSlide) { var _this = this; var currentGalleryItem = this.galleryItems[index]; // Adding delay for video slides without poster for better performance and user experience // Videos should start playing once once the gallery is completely loaded var _speed = isFirstSlide && this.getSlideType(currentGalleryItem) === 'video' && !currentGalleryItem.poster ? speed : 0; setTimeout(function () { $currentSlide.addClass('lg-complete lg-complete_'); _this.LGel.trigger(lGEvents.slideItemLoad, { index: index, delay: delay || 0, isFirstSlide: isFirstSlide, }); }, _speed); }; LightGallery.prototype.isFirstSlideWithZoomAnimation = function () { return !!(!this.lGalleryOn && this.zoomFromOrigin && this.currentImageSize); }; // Add video slideInfo LightGallery.prototype.addSlideVideoInfo = function (items) { var _this = this; items.forEach(function (element, index) { element.__slideVideoInfo = utils.isVideo(element.src, !!element.video, index); if (element.__slideVideoInfo && _this.settings.loadYouTubePoster && !element.poster && element.__slideVideoInfo.youtube) { element.poster = "//img.youtube.com/vi/" + element.__slideVideoInfo.youtube[1] + "/maxresdefault.jpg"; } }); }; /** * Load slide content into slide. * This is used to load content into slides that is not visible too * @param {Number} index - index of the slide. * @param {Boolean} rec - if true call loadcontent() function again. */ LightGallery.prototype.loadContent = function (index, rec) { var _this = this; var currentGalleryItem = this.galleryItems[index]; var $currentSlide = $LG(this.getSlideItemId(index)); var poster = currentGalleryItem.poster, srcset = currentGalleryItem.srcset, sizes = currentGalleryItem.sizes, sources = currentGalleryItem.sources; var src = currentGalleryItem.src; var video = currentGalleryItem.video; var _html5Video = video && typeof video === 'string' ? JSON.parse(video) : video; if (currentGalleryItem.responsive) { var srcDyItms = currentGalleryItem.responsive.split(','); src = utils.getResponsiveSrc(srcDyItms) || src; } var videoInfo = currentGalleryItem.__slideVideoInfo; var lgVideoStyle = ''; var iframe = !!currentGalleryItem.iframe; var isFirstSlide = !this.lGalleryOn; // delay for adding complete class. it is 0 except first time. var delay = 0; if (isFirstSlide) { if (this.zoomFromOrigin && this.currentImageSize) { delay = this.settings.startAnimationDuration + 10; } else { delay = this.settings.backdropDuration + 10; } } if (!$currentSlide.hasClass('lg-loaded')) { if (videoInfo) { var _a = this.mediaContainerPosition, top_2 = _a.top, bottom = _a.bottom; var videoSize = utils.getSize(this.items[index], this.outer, top_2 + bottom, videoInfo && this.settings.videoMaxSize); lgVideoStyle = this.getVideoContStyle(videoSize); } if (iframe) { var markup = utils.getIframeMarkup(this.settings.iframeWidth, this.settings.iframeHeight, this.settings.iframeMaxWidth, this.settings.iframeMaxHeight, src, currentGalleryItem.iframeTitle); $currentSlide.prepend(markup); } else if (poster) { var dummyImg = ''; var hasStartAnimation = isFirstSlide && this.zoomFromOrigin && this.currentImageSize; if (hasStartAnimation) { dummyImg = this.getDummyImageContent($currentSlide, index, ''); } var markup = utils.getVideoPosterMarkup(poster, dummyImg || '', lgVideoStyle, this.settings.strings['playVideo'], videoInfo); $currentSlide.prepend(markup); } else if (videoInfo) { var markup = "
"; $currentSlide.prepend(markup); } else { this.setImgMarkup(src, $currentSlide, index); if (srcset || sources) { var $img = $currentSlide.find('.lg-object'); this.initPictureFill($img); } } if (poster || videoInfo) { this.LGel.trigger(lGEvents.hasVideo, { index: index, src: src, html5Video: _html5Video, hasPoster: !!poster, }); } this.LGel.trigger(lGEvents.afterAppendSlide, { index: index }); if (this.lGalleryOn && this.settings.appendSubHtmlTo === '.lg-item') { this.addHtml(index); } } // For first time add some delay for displaying the start animation. var _speed = 0; // Do not change the delay value because it is required for zoom plugin. // If gallery opened from direct url (hash) speed value should be 0 if (delay && !$LG(document.body).hasClass('lg-from-hash')) { _speed = delay; } // Only for first slide and zoomFromOrigin is enabled if (this.isFirstSlideWithZoomAnimation()) { setTimeout(function () { $currentSlide .removeClass('lg-start-end-progress lg-start-progress') .removeAttr('style'); }, this.settings.startAnimationDuration + 100); if (!$currentSlide.hasClass('lg-loaded')) { setTimeout(function () { if (_this.getSlideType(currentGalleryItem) === 'image') { var alt = currentGalleryItem.alt; var altAttr = alt ? 'alt="' + alt + '"' : ''; $currentSlide .find('.lg-img-wrap') .append(utils.getImgMarkup(index, src, altAttr, srcset, sizes, currentGalleryItem.sources)); if (srcset || sources) { var $img = $currentSlide.find('.lg-object'); _this.initPictureFill($img); } } if (_this.getSlideType(currentGalleryItem) === 'image' || (_this.getSlideType(currentGalleryItem) === 'video' && poster)) { _this.onLgObjectLoad($currentSlide, index, delay, _speed, true, false); // load remaining slides once the slide is completely loaded _this.onSlideObjectLoad($currentSlide, !!(videoInfo && videoInfo.html5 && !poster), function () { _this.loadContentOnFirstSlideLoad(index, $currentSlide, _speed); }, function () { _this.loadContentOnFirstSlideLoad(index, $currentSlide, _speed); }); } }, this.settings.startAnimationDuration + 100); } } // SLide content has been added to dom $currentSlide.addClass('lg-loaded'); if (!this.isFirstSlideWithZoomAnimation() || (this.getSlideType(currentGalleryItem) === 'video' && !poster)) { this.onLgObjectLoad($currentSlide, index, delay, _speed, isFirstSlide, !!(videoInfo && videoInfo.html5 && !poster)); } // When gallery is opened once content is loaded (second time) need to add lg-complete class for css styling if ((!this.zoomFromOrigin || !this.currentImageSize) && $currentSlide.hasClass('lg-complete_') && !this.lGalleryOn) { setTimeout(function () { $currentSlide.addClass('lg-complete'); }, this.settings.backdropDuration); } // Content loaded // Need to set lGalleryOn before calling preload function this.lGalleryOn = true; if (rec === true) { if (!$currentSlide.hasClass('lg-complete_')) { $currentSlide .find('.lg-object') .first() .on('load.lg error.lg', function () { _this.preload(index); }); } else { this.preload(index); } } }; /** * @desc Remove dummy image content and load next slides * Called only for the first time if zoomFromOrigin animation is enabled * @param index * @param $currentSlide * @param speed */ LightGallery.prototype.loadContentOnFirstSlideLoad = function (index, $currentSlide, speed) { var _this = this; setTimeout(function () { $currentSlide.find('.lg-dummy-img').remove(); $currentSlide.removeClass('lg-first-slide'); _this.outer.removeClass('lg-first-slide-loading'); _this.isDummyImageRemoved = true; _this.preload(index); }, speed + 300); }; LightGallery.prototype.getItemsToBeInsertedToDom = function (index, prevIndex, numberOfItems) { var _this = this; if (numberOfItems === void 0) { numberOfItems = 0; } var itemsToBeInsertedToDom = []; // Minimum 2 items should be there var possibleNumberOfItems = Math.max(numberOfItems, 3); possibleNumberOfItems = Math.min(possibleNumberOfItems, this.galleryItems.length); var prevIndexItem = "lg-item-" + this.lgId + "-" + prevIndex; if (this.galleryItems.length <= 3) { this.galleryItems.forEach(function (_element, index) { itemsToBeInsertedToDom.push("lg-item-" + _this.lgId + "-" + index); }); return itemsToBeInsertedToDom; } if (index < (this.galleryItems.length - 1) / 2) { for (var idx = index; idx > index - possibleNumberOfItems / 2 && idx >= 0; idx--) { itemsToBeInsertedToDom.push("lg-item-" + this.lgId + "-" + idx); } var numberOfExistingItems = itemsToBeInsertedToDom.length; for (var idx = 0; idx < possibleNumberOfItems - numberOfExistingItems; idx++) { itemsToBeInsertedToDom.push("lg-item-" + this.lgId + "-" + (index + idx + 1)); } } else { for (var idx = index; idx <= this.galleryItems.length - 1 && idx < index + possibleNumberOfItems / 2; idx++) { itemsToBeInsertedToDom.push("lg-item-" + this.lgId + "-" + idx); } var numberOfExistingItems = itemsToBeInsertedToDom.length; for (var idx = 0; idx < possibleNumberOfItems - numberOfExistingItems; idx++) { itemsToBeInsertedToDom.push("lg-item-" + this.lgId + "-" + (index - idx - 1)); } } if (this.settings.loop) { if (index === this.galleryItems.length - 1) { itemsToBeInsertedToDom.push("lg-item-" + this.lgId + "-" + 0); } else if (index === 0) { itemsToBeInsertedToDom.push("lg-item-" + this.lgId + "-" + (this.galleryItems.length - 1)); } } if (itemsToBeInsertedToDom.indexOf(prevIndexItem) === -1) { itemsToBeInsertedToDom.push("lg-item-" + this.lgId + "-" + prevIndex); } return itemsToBeInsertedToDom; }; LightGallery.prototype.organizeSlideItems = function (index, prevIndex) { var _this = this; var itemsToBeInsertedToDom = this.getItemsToBeInsertedToDom(index, prevIndex, this.settings.numberOfSlideItemsInDom); itemsToBeInsertedToDom.forEach(function (item) { if (_this.currentItemsInDom.indexOf(item) === -1) { _this.$inner.append("
"); } }); this.currentItemsInDom.forEach(function (item) { if (itemsToBeInsertedToDom.indexOf(item) === -1) { $LG("#" + item).remove(); } }); return itemsToBeInsertedToDom; }; /** * Get previous index of the slide */ LightGallery.prototype.getPreviousSlideIndex = function () { var prevIndex = 0; try { var currentItemId = this.outer .find('.lg-current') .first() .attr('id'); prevIndex = parseInt(currentItemId.split('-')[3]) || 0; } catch (error) { prevIndex = 0; } return prevIndex; }; LightGallery.prototype.setDownloadValue = function (index) { if (this.settings.download) { var currentGalleryItem = this.galleryItems[index]; var hideDownloadBtn = currentGalleryItem.downloadUrl === false || currentGalleryItem.downloadUrl === 'false'; if (hideDownloadBtn) { this.outer.addClass('lg-hide-download'); } else { var $download = this.getElementById('lg-download'); this.outer.removeClass('lg-hide-download'); $download.attr('href', currentGalleryItem.downloadUrl || currentGalleryItem.src); if (currentGalleryItem.download) { $download.attr('download', currentGalleryItem.download); } } } }; LightGallery.prototype.makeSlideAnimation = function (direction, currentSlideItem, previousSlideItem) { var _this = this; if (this.lGalleryOn) { previousSlideItem.addClass('lg-slide-progress'); } setTimeout(function () { // remove all transitions _this.outer.addClass('lg-no-trans'); _this.outer .find('.lg-item') .removeClass('lg-prev-slide lg-next-slide'); if (direction === 'prev') { //prevslide currentSlideItem.addClass('lg-prev-slide'); previousSlideItem.addClass('lg-next-slide'); } else { // next slide currentSlideItem.addClass('lg-next-slide'); previousSlideItem.addClass('lg-prev-slide'); } // give 50 ms for browser to add/remove class setTimeout(function () { _this.outer.find('.lg-item').removeClass('lg-current'); currentSlideItem.addClass('lg-current'); // reset all transitions _this.outer.removeClass('lg-no-trans'); }, 50); }, this.lGalleryOn ? this.settings.slideDelay : 0); }; /** * Goto a specific slide. * @param {Number} index - index of the slide * @param {Boolean} fromTouch - true if slide function called via touch event or mouse drag * @param {Boolean} fromThumb - true if slide function called via thumbnail click * @param {String} direction - Direction of the slide(next/prev) * @category lGPublicMethods * @example * const plugin = lightGallery(); * // to go to 3rd slide * plugin.slide(2); * */ LightGallery.prototype.slide = function (index, fromTouch, fromThumb, direction) { var _this = this; var prevIndex = this.getPreviousSlideIndex(); this.currentItemsInDom = this.organizeSlideItems(index, prevIndex); // Prevent multiple call, Required for hsh plugin if (this.lGalleryOn && prevIndex === index) { return; } var numberOfGalleryItems = this.galleryItems.length; if (!this.lgBusy) { if (this.settings.counter) { this.updateCurrentCounter(index); } var currentSlideItem = this.getSlideItem(index); var previousSlideItem_1 = this.getSlideItem(prevIndex); var currentGalleryItem = this.galleryItems[index]; var videoInfo = currentGalleryItem.__slideVideoInfo; this.outer.attr('data-lg-slide-type', this.getSlideType(currentGalleryItem)); this.setDownloadValue(index); if (videoInfo) { var _a = this.mediaContainerPosition, top_3 = _a.top, bottom = _a.bottom; var videoSize = utils.getSize(this.items[index], this.outer, top_3 + bottom, videoInfo && this.settings.videoMaxSize); this.resizeVideoSlide(index, videoSize); } this.LGel.trigger(lGEvents.beforeSlide, { prevIndex: prevIndex, index: index, fromTouch: !!fromTouch, fromThumb: !!fromThumb, }); this.lgBusy = true; clearTimeout(this.hideBarTimeout); this.arrowDisable(index); if (!direction) { if (index < prevIndex) { direction = 'prev'; } else if (index > prevIndex) { direction = 'next'; } } if (!fromTouch) { this.makeSlideAnimation(direction, currentSlideItem, previousSlideItem_1); } else { this.outer .find('.lg-item') .removeClass('lg-prev-slide lg-current lg-next-slide'); var touchPrev = void 0; var touchNext = void 0; if (numberOfGalleryItems > 2) { touchPrev = index - 1; touchNext = index + 1; if (index === 0 && prevIndex === numberOfGalleryItems - 1) { // next slide touchNext = 0; touchPrev = numberOfGalleryItems - 1; } else if (index === numberOfGalleryItems - 1 && prevIndex === 0) { // prev slide touchNext = 0; touchPrev = numberOfGalleryItems - 1; } } else { touchPrev = 0; touchNext = 1; } if (direction === 'prev') { this.getSlideItem(touchNext).addClass('lg-next-slide'); } else { this.getSlideItem(touchPrev).addClass('lg-prev-slide'); } currentSlideItem.addClass('lg-current'); } // Do not put load content in set timeout as it needs to load immediately when the gallery is opened if (!this.lGalleryOn) { this.loadContent(index, true); } else { setTimeout(function () { _this.loadContent(index, true); // Add title if this.settings.appendSubHtmlTo === lg-sub-html if (_this.settings.appendSubHtmlTo !== '.lg-item') { _this.addHtml(index); } }, this.settings.speed + 50 + (fromTouch ? 0 : this.settings.slideDelay)); } setTimeout(function () { _this.lgBusy = false; previousSlideItem_1.removeClass('lg-slide-progress'); _this.LGel.trigger(lGEvents.afterSlide, { prevIndex: prevIndex, index: index, fromTouch: fromTouch, fromThumb: fromThumb, }); }, (this.lGalleryOn ? this.settings.speed + 100 : 100) + (fromTouch ? 0 : this.settings.slideDelay)); } this.index = index; }; LightGallery.prototype.updateCurrentCounter = function (index) { this.getElementById('lg-counter-current').html(index + 1 + ''); }; LightGallery.prototype.updateCounterTotal = function () { this.getElementById('lg-counter-all').html(this.galleryItems.length + ''); }; LightGallery.prototype.getSlideType = function (item) { if (item.__slideVideoInfo) { return 'video'; } else if (item.iframe) { return 'iframe'; } else { return 'image'; } }; LightGallery.prototype.touchMove = function (startCoords, endCoords, e) { var distanceX = endCoords.pageX - startCoords.pageX; var distanceY = endCoords.pageY - startCoords.pageY; var allowSwipe = false; if (this.swipeDirection) { allowSwipe = true; } else { if (Math.abs(distanceX) > 15) { this.swipeDirection = 'horizontal'; allowSwipe = true; } else if (Math.abs(distanceY) > 15) { this.swipeDirection = 'vertical'; allowSwipe = true; } } if (!allowSwipe) { return; } var $currentSlide = this.getSlideItem(this.index); if (this.swipeDirection === 'horizontal') { e === null || e === void 0 ? void 0 : e.preventDefault(); // reset opacity and transition duration this.outer.addClass('lg-dragging'); // move current slide this.setTranslate($currentSlide, distanceX, 0); // move next and prev slide with current slide var width = $currentSlide.get().offsetWidth; var slideWidthAmount = (width * 15) / 100; var gutter = slideWidthAmount - Math.abs((distanceX * 10) / 100); this.setTranslate(this.outer.find('.lg-prev-slide').first(), -width + distanceX - gutter, 0); this.setTranslate(this.outer.find('.lg-next-slide').first(), width + distanceX + gutter, 0); } else if (this.swipeDirection === 'vertical') { if (this.settings.swipeToClose) { e === null || e === void 0 ? void 0 : e.preventDefault(); this.$container.addClass('lg-dragging-vertical'); var opacity = 1 - Math.abs(distanceY) / window.innerHeight; this.$backdrop.css('opacity', opacity); var scale = 1 - Math.abs(distanceY) / (window.innerWidth * 2); this.setTranslate($currentSlide, 0, distanceY, scale, scale); if (Math.abs(distanceY) > 100) { this.outer .addClass('lg-hide-items') .removeClass('lg-components-open'); } } } }; LightGallery.prototype.touchEnd = function (endCoords, startCoords, event) { var _this = this; var distance; // keep slide animation for any mode while dragg/swipe if (this.settings.mode !== 'lg-slide') { this.outer.addClass('lg-slide'); } // set transition duration setTimeout(function () { _this.$container.removeClass('lg-dragging-vertical'); _this.outer .removeClass('lg-dragging lg-hide-items') .addClass('lg-components-open'); var triggerClick = true; if (_this.swipeDirection === 'horizontal') { distance = endCoords.pageX - startCoords.pageX; var distanceAbs = Math.abs(endCoords.pageX - startCoords.pageX); if (distance < 0 && distanceAbs > _this.settings.swipeThreshold) { _this.goToNextSlide(true); triggerClick = false; } else if (distance > 0 && distanceAbs > _this.settings.swipeThreshold) { _this.goToPrevSlide(true); triggerClick = false; } } else if (_this.swipeDirection === 'vertical') { distance = Math.abs(endCoords.pageY - startCoords.pageY); if (_this.settings.closable && _this.settings.swipeToClose && distance > 100) { _this.closeGallery(); return; } else { _this.$backdrop.css('opacity', 1); } } _this.outer.find('.lg-item').removeAttr('style'); if (triggerClick && Math.abs(endCoords.pageX - startCoords.pageX) < 5) { // Trigger click if distance is less than 5 pix var target = $LG(event.target); if (_this.isPosterElement(target)) { _this.LGel.trigger(lGEvents.posterClick); } } _this.swipeDirection = undefined; }); // remove slide class once drag/swipe is completed if mode is not slide setTimeout(function () { if (!_this.outer.hasClass('lg-dragging') && _this.settings.mode !== 'lg-slide') { _this.outer.removeClass('lg-slide'); } }, this.settings.speed + 100); }; LightGallery.prototype.enableSwipe = function () { var _this = this; var startCoords = {}; var endCoords = {}; var isMoved = false; var isSwiping = false; if (this.settings.enableSwipe) { this.$inner.on('touchstart.lg', function (e) { _this.dragOrSwipeEnabled = true; var $item = _this.getSlideItem(_this.index); if (($LG(e.target).hasClass('lg-item') || $item.get().contains(e.target)) && !_this.outer.hasClass('lg-zoomed') && !_this.lgBusy && e.touches.length === 1) { isSwiping = true; _this.touchAction = 'swipe'; _this.manageSwipeClass(); startCoords = { pageX: e.touches[0].pageX, pageY: e.touches[0].pageY, }; } }); this.$inner.on('touchmove.lg', function (e) { if (isSwiping && _this.touchAction === 'swipe' && e.touches.length === 1) { endCoords = { pageX: e.touches[0].pageX, pageY: e.touches[0].pageY, }; _this.touchMove(startCoords, endCoords, e); isMoved = true; } }); this.$inner.on('touchend.lg', function (event) { if (_this.touchAction === 'swipe') { if (isMoved) { isMoved = false; _this.touchEnd(endCoords, startCoords, event); } else if (isSwiping) { var target = $LG(event.target); if (_this.isPosterElement(target)) { _this.LGel.trigger(lGEvents.posterClick); } } _this.touchAction = undefined; isSwiping = false; } }); } }; LightGallery.prototype.enableDrag = function () { var _this = this; var startCoords = {}; var endCoords = {}; var isDraging = false; var isMoved = false; if (this.settings.enableDrag) { this.outer.on('mousedown.lg', function (e) { _this.dragOrSwipeEnabled = true; var $item = _this.getSlideItem(_this.index); if ($LG(e.target).hasClass('lg-item') || $item.get().contains(e.target)) { if (!_this.outer.hasClass('lg-zoomed') && !_this.lgBusy) { e.preventDefault(); if (!_this.lgBusy) { _this.manageSwipeClass(); startCoords = { pageX: e.pageX, pageY: e.pageY, }; isDraging = true; // ** Fix for webkit cursor issue https://code.google.com/p/chromium/issues/detail?id=26723 _this.outer.get().scrollLeft += 1; _this.outer.get().scrollLeft -= 1; // * _this.outer .removeClass('lg-grab') .addClass('lg-grabbing'); _this.LGel.trigger(lGEvents.dragStart); } } } }); $LG(window).on("mousemove.lg.global" + this.lgId, function (e) { if (isDraging && _this.lgOpened) { isMoved = true; endCoords = { pageX: e.pageX, pageY: e.pageY, }; _this.touchMove(startCoords, endCoords); _this.LGel.trigger(lGEvents.dragMove); } }); $LG(window).on("mouseup.lg.global" + this.lgId, function (event) { if (!_this.lgOpened) { return; } var target = $LG(event.target); if (isMoved) { isMoved = false; _this.touchEnd(endCoords, startCoords, event); _this.LGel.trigger(lGEvents.dragEnd); } else if (_this.isPosterElement(target)) { _this.LGel.trigger(lGEvents.posterClick); } // Prevent execution on click if (isDraging) { isDraging = false; _this.outer.removeClass('lg-grabbing').addClass('lg-grab'); } }); } }; LightGallery.prototype.triggerPosterClick = function () { var _this = this; this.$inner.on('click.lg', function (event) { if (!_this.dragOrSwipeEnabled && _this.isPosterElement($LG(event.target))) { _this.LGel.trigger(lGEvents.posterClick); } }); }; LightGallery.prototype.manageSwipeClass = function () { var _touchNext = this.index + 1; var _touchPrev = this.index - 1; if (this.settings.loop && this.galleryItems.length > 2) { if (this.index === 0) { _touchPrev = this.galleryItems.length - 1; } else if (this.index === this.galleryItems.length - 1) { _touchNext = 0; } } this.outer.find('.lg-item').removeClass('lg-next-slide lg-prev-slide'); if (_touchPrev > -1) { this.getSlideItem(_touchPrev).addClass('lg-prev-slide'); } this.getSlideItem(_touchNext).addClass('lg-next-slide'); }; /** * Go to next slide * @param {Boolean} fromTouch - true if slide function called via touch event * @category lGPublicMethods * @example * const plugin = lightGallery(); * plugin.goToNextSlide(); * @see Demo */ LightGallery.prototype.goToNextSlide = function (fromTouch) { var _this = this; var _loop = this.settings.loop; if (fromTouch && this.galleryItems.length < 3) { _loop = false; } if (!this.lgBusy) { if (this.index + 1 < this.galleryItems.length) { this.index++; this.LGel.trigger(lGEvents.beforeNextSlide, { index: this.index, }); this.slide(this.index, !!fromTouch, false, 'next'); } else { if (_loop) { this.index = 0; this.LGel.trigger(lGEvents.beforeNextSlide, { index: this.index, }); this.slide(this.index, !!fromTouch, false, 'next'); } else if (this.settings.slideEndAnimation && !fromTouch) { this.outer.addClass('lg-right-end'); setTimeout(function () { _this.outer.removeClass('lg-right-end'); }, 400); } } } }; /** * Go to previous slides * @param {Boolean} fromTouch - true if slide function called via touch event * @category lGPublicMethods * @example * const plugin = lightGallery({}); * plugin.goToPrevSlide(); * @see Demo * */ LightGallery.prototype.goToPrevSlide = function (fromTouch) { var _this = this; var _loop = this.settings.loop; if (fromTouch && this.galleryItems.length < 3) { _loop = false; } if (!this.lgBusy) { if (this.index > 0) { this.index--; this.LGel.trigger(lGEvents.beforePrevSlide, { index: this.index, fromTouch: fromTouch, }); this.slide(this.index, !!fromTouch, false, 'prev'); } else { if (_loop) { this.index = this.galleryItems.length - 1; this.LGel.trigger(lGEvents.beforePrevSlide, { index: this.index, fromTouch: fromTouch, }); this.slide(this.index, !!fromTouch, false, 'prev'); } else if (this.settings.slideEndAnimation && !fromTouch) { this.outer.addClass('lg-left-end'); setTimeout(function () { _this.outer.removeClass('lg-left-end'); }, 400); } } } }; LightGallery.prototype.keyPress = function () { var _this = this; $LG(window).on("keydown.lg.global" + this.lgId, function (e) { if (_this.lgOpened && _this.settings.escKey === true && e.keyCode === 27) { e.preventDefault(); if (_this.settings.allowMediaOverlap && _this.outer.hasClass('lg-can-toggle') && _this.outer.hasClass('lg-components-open')) { _this.outer.removeClass('lg-components-open'); } else { _this.closeGallery(); } } if (_this.lgOpened && _this.galleryItems.length > 1) { if (e.keyCode === 37) { e.preventDefault(); _this.goToPrevSlide(); } if (e.keyCode === 39) { e.preventDefault(); _this.goToNextSlide(); } } }); }; LightGallery.prototype.arrow = function () { var _this = this; this.getElementById('lg-prev').on('click.lg', function () { _this.goToPrevSlide(); }); this.getElementById('lg-next').on('click.lg', function () { _this.goToNextSlide(); }); }; LightGallery.prototype.arrowDisable = function (index) { // Disable arrows if settings.hideControlOnEnd is true if (!this.settings.loop && this.settings.hideControlOnEnd) { var $prev = this.getElementById('lg-prev'); var $next = this.getElementById('lg-next'); if (index + 1 === this.galleryItems.length) { $next.attr('disabled', 'disabled').addClass('disabled'); } else { $next.removeAttr('disabled').removeClass('disabled'); } if (index === 0) { $prev.attr('disabled', 'disabled').addClass('disabled'); } else { $prev.removeAttr('disabled').removeClass('disabled'); } } }; LightGallery.prototype.setTranslate = function ($el, xValue, yValue, scaleX, scaleY) { if (scaleX === void 0) { scaleX = 1; } if (scaleY === void 0) { scaleY = 1; } $el.css('transform', 'translate3d(' + xValue + 'px, ' + yValue + 'px, 0px) scale3d(' + scaleX + ', ' + scaleY + ', 1)'); }; LightGallery.prototype.mousewheel = function () { var _this = this; var lastCall = 0; this.outer.on('wheel.lg', function (e) { if (!e.deltaY || _this.galleryItems.length < 2) { return; } e.preventDefault(); var now = new Date().getTime(); if (now - lastCall < 1000) { return; } lastCall = now; if (e.deltaY > 0) { _this.goToNextSlide(); } else if (e.deltaY < 0) { _this.goToPrevSlide(); } }); }; LightGallery.prototype.isSlideElement = function (target) { return (target.hasClass('lg-outer') || target.hasClass('lg-item') || target.hasClass('lg-img-wrap')); }; LightGallery.prototype.isPosterElement = function (target) { var playButton = this.getSlideItem(this.index) .find('.lg-video-play-button') .get(); return (target.hasClass('lg-video-poster') || target.hasClass('lg-video-play-button') || (playButton && playButton.contains(target.get()))); }; /** * Maximize minimize inline gallery. * @category lGPublicMethods */ LightGallery.prototype.toggleMaximize = function () { var _this = this; this.getElementById('lg-maximize').on('click.lg', function () { _this.$container.toggleClass('lg-inline'); _this.refreshOnResize(); }); }; LightGallery.prototype.invalidateItems = function () { for (var index = 0; index < this.items.length; index++) { var element = this.items[index]; var $element = $LG(element); $element.off("click.lgcustom-item-" + $element.attr('data-lg-id')); } }; LightGallery.prototype.trapFocus = function () { var _this = this; this.$container.get().focus({ preventScroll: true, }); $LG(window).on("keydown.lg.global" + this.lgId, function (e) { if (!_this.lgOpened) { return; } var isTabPressed = e.key === 'Tab' || e.keyCode === 9; if (!isTabPressed) { return; } var focusableEls = utils.getFocusableElements(_this.$container.get()); var firstFocusableEl = focusableEls[0]; var lastFocusableEl = focusableEls[focusableEls.length - 1]; if (e.shiftKey) { if (document.activeElement === firstFocusableEl) { lastFocusableEl.focus(); e.preventDefault(); } } else { if (document.activeElement === lastFocusableEl) { firstFocusableEl.focus(); e.preventDefault(); } } }); }; LightGallery.prototype.manageCloseGallery = function () { var _this = this; if (!this.settings.closable) return; var mousedown = false; this.getElementById('lg-close').on('click.lg', function () { _this.closeGallery(); }); if (this.settings.closeOnTap) { // If you drag the slide and release outside gallery gets close on chrome // for preventing this check mousedown and mouseup happened on .lg-item or lg-outer this.outer.on('mousedown.lg', function (e) { var target = $LG(e.target); if (_this.isSlideElement(target)) { mousedown = true; } else { mousedown = false; } }); this.outer.on('mousemove.lg', function () { mousedown = false; }); this.outer.on('mouseup.lg', function (e) { var target = $LG(e.target); if (_this.isSlideElement(target) && mousedown) { if (!_this.outer.hasClass('lg-dragging')) { _this.closeGallery(); } } }); } }; /** * Close lightGallery if it is opened. * * @description If closable is false in the settings, you need to pass true via closeGallery method to force close gallery * @return returns the estimated time to close gallery completely including the close animation duration * @category lGPublicMethods * @example * const plugin = lightGallery(); * plugin.closeGallery(); * */ LightGallery.prototype.closeGallery = function (force) { var _this = this; if (!this.lgOpened || (!this.settings.closable && !force)) { return 0; } this.LGel.trigger(lGEvents.beforeClose); if (this.settings.resetScrollPosition && !this.settings.hideScrollbar) { $LG(window).scrollTop(this.prevScrollTop); } var currentItem = this.items[this.index]; var transform; if (this.zoomFromOrigin && currentItem) { var _a = this.mediaContainerPosition, top_4 = _a.top, bottom = _a.bottom; var _b = this.galleryItems[this.index], __slideVideoInfo = _b.__slideVideoInfo, poster = _b.poster; var imageSize = utils.getSize(currentItem, this.outer, top_4 + bottom, __slideVideoInfo && poster && this.settings.videoMaxSize); transform = utils.getTransform(currentItem, this.outer, top_4, bottom, imageSize); } if (this.zoomFromOrigin && transform) { this.outer.addClass('lg-closing lg-zoom-from-image'); this.getSlideItem(this.index) .addClass('lg-start-end-progress') .css('transition-duration', this.settings.startAnimationDuration + 'ms') .css('transform', transform); } else { this.outer.addClass('lg-hide-items'); // lg-zoom-from-image is used for setting the opacity to 1 if zoomFromOrigin is true // If the closing item doesn't have the lg-size attribute, remove this class to avoid the closing css conflicts this.outer.removeClass('lg-zoom-from-image'); } // Unbind all events added by lightGallery // @todo //this.$el.off('.lg.tm'); this.destroyModules(); this.lGalleryOn = false; this.isDummyImageRemoved = false; this.zoomFromOrigin = this.settings.zoomFromOrigin; clearTimeout(this.hideBarTimeout); this.hideBarTimeout = false; $LG('html').removeClass('lg-on'); this.outer.removeClass('lg-visible lg-components-open'); // Resetting opacity to 0 isd required as vertical swipe to close function adds inline opacity. this.$backdrop.removeClass('in').css('opacity', 0); var removeTimeout = this.zoomFromOrigin && transform ? Math.max(this.settings.startAnimationDuration, this.settings.backdropDuration) : this.settings.backdropDuration; this.$container.removeClass('lg-show-in'); // Once the closign animation is completed and gallery is invisible setTimeout(function () { if (_this.zoomFromOrigin && transform) { _this.outer.removeClass('lg-zoom-from-image'); } _this.$container.removeClass('lg-show'); // Reset scrollbar _this.resetScrollBar(); // Need to remove inline opacity as it is used in the stylesheet as well _this.$backdrop .removeAttr('style') .css('transition-duration', _this.settings.backdropDuration + 'ms'); _this.outer.removeClass("lg-closing " + _this.settings.startClass); _this.getSlideItem(_this.index).removeClass('lg-start-end-progress'); _this.$inner.empty(); if (_this.lgOpened) { _this.LGel.trigger(lGEvents.afterClose, { instance: _this, }); } if (_this.$container.get()) { _this.$container.get().blur(); } _this.lgOpened = false; }, removeTimeout + 100); return removeTimeout + 100; }; LightGallery.prototype.initModules = function () { this.plugins.forEach(function (module) { try { module.init(); } catch (err) { console.warn("lightGallery:- make sure lightGallery module is properly initiated"); } }); }; LightGallery.prototype.destroyModules = function (destroy) { this.plugins.forEach(function (module) { try { if (destroy) { module.destroy(); } else { module.closeGallery && module.closeGallery(); } } catch (err) { console.warn("lightGallery:- make sure lightGallery module is properly destroyed"); } }); }; /** * Refresh lightGallery with new set of children. * * @description This is useful to update the gallery when the child elements are changed without calling destroy method. * * If you are using dynamic mode, you can pass the modified array of dynamicEl as the first parameter to refresh the dynamic gallery * @see Demo * @category lGPublicMethods * @example * const plugin = lightGallery(); * // Delete or add children, then call * plugin.refresh(); * */ LightGallery.prototype.refresh = function (galleryItems) { if (!this.settings.dynamic) { this.invalidateItems(); } if (galleryItems) { this.galleryItems = galleryItems; } else { this.galleryItems = this.getItems(); } this.updateControls(); this.openGalleryOnItemClick(); this.LGel.trigger(lGEvents.updateSlides); }; LightGallery.prototype.updateControls = function () { this.addSlideVideoInfo(this.galleryItems); this.updateCounterTotal(); this.manageSingleSlideClassName(); }; LightGallery.prototype.destroyGallery = function () { this.destroyModules(true); if (!this.settings.dynamic) { this.invalidateItems(); } $LG(window).off(".lg.global" + this.lgId); this.LGel.off('.lg'); this.$container.remove(); }; /** * Destroy lightGallery. * Destroy lightGallery and its plugin instances completely * * @description This method also calls CloseGallery function internally. Returns the time takes to completely close and destroy the instance. * In case if you want to re-initialize lightGallery right after destroying it, initialize it only once the destroy process is completed. * You can use refresh method most of the times. * @category lGPublicMethods * @example * const plugin = lightGallery(); * plugin.destroy(); * */ LightGallery.prototype.destroy = function () { var closeTimeout = this.closeGallery(true); if (closeTimeout) { setTimeout(this.destroyGallery.bind(this), closeTimeout); } else { this.destroyGallery(); } return closeTimeout; }; return LightGallery; }()); function lightGallery(el, options) { return new LightGallery(el, options); } /* harmony default export */ var lightgallery_es5 = (lightGallery); //# sourceMappingURL=lightgallery.es5.js.map // CONCATENATED MODULE: ./node_modules/lightgallery/plugins/thumbnail/lg-thumbnail.es5.js /*! * lightgallery | 2.7.1 | January 11th 2023 * http://www.lightgalleryjs.com/ * Copyright (c) 2020 Sachin Neravath; * @license GPLv3 */ /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var lg_thumbnail_es5_assign = function() { lg_thumbnail_es5_assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return lg_thumbnail_es5_assign.apply(this, arguments); }; var thumbnailsSettings = { thumbnail: true, animateThumb: true, currentPagerPosition: 'middle', alignThumbnails: 'middle', thumbWidth: 100, thumbHeight: '80px', thumbMargin: 5, appendThumbnailsTo: '.lg-components', toggleThumb: false, enableThumbDrag: true, enableThumbSwipe: true, thumbnailSwipeThreshold: 10, loadYouTubeThumbnail: true, youTubeThumbSize: 1, thumbnailPluginStrings: { toggleThumbnails: 'Toggle thumbnails', }, }; /** * List of lightGallery events * All events should be documented here * Below interfaces are used to build the website documentations * */ var lg_thumbnail_es5_lGEvents = { afterAppendSlide: 'lgAfterAppendSlide', init: 'lgInit', hasVideo: 'lgHasVideo', containerResize: 'lgContainerResize', updateSlides: 'lgUpdateSlides', afterAppendSubHtml: 'lgAfterAppendSubHtml', beforeOpen: 'lgBeforeOpen', afterOpen: 'lgAfterOpen', slideItemLoad: 'lgSlideItemLoad', beforeSlide: 'lgBeforeSlide', afterSlide: 'lgAfterSlide', posterClick: 'lgPosterClick', dragStart: 'lgDragStart', dragMove: 'lgDragMove', dragEnd: 'lgDragEnd', beforeNextSlide: 'lgBeforeNextSlide', beforePrevSlide: 'lgBeforePrevSlide', beforeClose: 'lgBeforeClose', afterClose: 'lgAfterClose', rotateLeft: 'lgRotateLeft', rotateRight: 'lgRotateRight', flipHorizontal: 'lgFlipHorizontal', flipVertical: 'lgFlipVertical', autoplay: 'lgAutoplay', autoplayStart: 'lgAutoplayStart', autoplayStop: 'lgAutoplayStop', }; var Thumbnail = /** @class */ (function () { function Thumbnail(instance, $LG) { this.thumbOuterWidth = 0; this.thumbTotalWidth = 0; this.translateX = 0; this.thumbClickable = false; // get lightGallery core plugin instance this.core = instance; this.$LG = $LG; return this; } Thumbnail.prototype.init = function () { // extend module default settings with lightGallery core settings this.settings = lg_thumbnail_es5_assign(lg_thumbnail_es5_assign({}, thumbnailsSettings), this.core.settings); this.thumbOuterWidth = 0; this.thumbTotalWidth = this.core.galleryItems.length * (this.settings.thumbWidth + this.settings.thumbMargin); // Thumbnail animation value this.translateX = 0; this.setAnimateThumbStyles(); if (!this.core.settings.allowMediaOverlap) { this.settings.toggleThumb = false; } if (this.settings.thumbnail) { this.build(); if (this.settings.animateThumb) { if (this.settings.enableThumbDrag) { this.enableThumbDrag(); } if (this.settings.enableThumbSwipe) { this.enableThumbSwipe(); } this.thumbClickable = false; } else { this.thumbClickable = true; } this.toggleThumbBar(); this.thumbKeyPress(); } }; Thumbnail.prototype.build = function () { var _this = this; this.setThumbMarkup(); this.manageActiveClassOnSlideChange(); this.$lgThumb.first().on('click.lg touchend.lg', function (e) { var $target = _this.$LG(e.target); if (!$target.hasAttribute('data-lg-item-id')) { return; } setTimeout(function () { // In IE9 and bellow touch does not support // Go to slide if browser does not support css transitions if (_this.thumbClickable && !_this.core.lgBusy) { var index = parseInt($target.attr('data-lg-item-id')); _this.core.slide(index, false, true, false); } }, 50); }); this.core.LGel.on(lg_thumbnail_es5_lGEvents.beforeSlide + ".thumb", function (event) { var index = event.detail.index; _this.animateThumb(index); }); this.core.LGel.on(lg_thumbnail_es5_lGEvents.beforeOpen + ".thumb", function () { _this.thumbOuterWidth = _this.core.outer.get().offsetWidth; }); this.core.LGel.on(lg_thumbnail_es5_lGEvents.updateSlides + ".thumb", function () { _this.rebuildThumbnails(); }); this.core.LGel.on(lg_thumbnail_es5_lGEvents.containerResize + ".thumb", function () { if (!_this.core.lgOpened) return; setTimeout(function () { _this.thumbOuterWidth = _this.core.outer.get().offsetWidth; _this.animateThumb(_this.core.index); _this.thumbOuterWidth = _this.core.outer.get().offsetWidth; }, 50); }); }; Thumbnail.prototype.setThumbMarkup = function () { var thumbOuterClassNames = 'lg-thumb-outer '; if (this.settings.alignThumbnails) { thumbOuterClassNames += "lg-thumb-align-" + this.settings.alignThumbnails; } var html = "
\n
\n
\n
"; this.core.outer.addClass('lg-has-thumb'); if (this.settings.appendThumbnailsTo === '.lg-components') { this.core.$lgComponents.append(html); } else { this.core.outer.append(html); } this.$thumbOuter = this.core.outer.find('.lg-thumb-outer').first(); this.$lgThumb = this.core.outer.find('.lg-thumb').first(); if (this.settings.animateThumb) { this.core.outer .find('.lg-thumb') .css('transition-duration', this.core.settings.speed + 'ms') .css('width', this.thumbTotalWidth + 'px') .css('position', 'relative'); } this.setThumbItemHtml(this.core.galleryItems); }; Thumbnail.prototype.enableThumbDrag = function () { var _this = this; var thumbDragUtils = { cords: { startX: 0, endX: 0, }, isMoved: false, newTranslateX: 0, startTime: new Date(), endTime: new Date(), touchMoveTime: 0, }; var isDragging = false; this.$thumbOuter.addClass('lg-grab'); this.core.outer .find('.lg-thumb') .first() .on('mousedown.lg.thumb', function (e) { if (_this.thumbTotalWidth > _this.thumbOuterWidth) { // execute only on .lg-object e.preventDefault(); thumbDragUtils.cords.startX = e.pageX; thumbDragUtils.startTime = new Date(); _this.thumbClickable = false; isDragging = true; // ** Fix for webkit cursor issue https://code.google.com/p/chromium/issues/detail?id=26723 _this.core.outer.get().scrollLeft += 1; _this.core.outer.get().scrollLeft -= 1; // * _this.$thumbOuter .removeClass('lg-grab') .addClass('lg-grabbing'); } }); this.$LG(window).on("mousemove.lg.thumb.global" + this.core.lgId, function (e) { if (!_this.core.lgOpened) return; if (isDragging) { thumbDragUtils.cords.endX = e.pageX; thumbDragUtils = _this.onThumbTouchMove(thumbDragUtils); } }); this.$LG(window).on("mouseup.lg.thumb.global" + this.core.lgId, function () { if (!_this.core.lgOpened) return; if (thumbDragUtils.isMoved) { thumbDragUtils = _this.onThumbTouchEnd(thumbDragUtils); } else { _this.thumbClickable = true; } if (isDragging) { isDragging = false; _this.$thumbOuter.removeClass('lg-grabbing').addClass('lg-grab'); } }); }; Thumbnail.prototype.enableThumbSwipe = function () { var _this = this; var thumbDragUtils = { cords: { startX: 0, endX: 0, }, isMoved: false, newTranslateX: 0, startTime: new Date(), endTime: new Date(), touchMoveTime: 0, }; this.$lgThumb.on('touchstart.lg', function (e) { if (_this.thumbTotalWidth > _this.thumbOuterWidth) { e.preventDefault(); thumbDragUtils.cords.startX = e.targetTouches[0].pageX; _this.thumbClickable = false; thumbDragUtils.startTime = new Date(); } }); this.$lgThumb.on('touchmove.lg', function (e) { if (_this.thumbTotalWidth > _this.thumbOuterWidth) { e.preventDefault(); thumbDragUtils.cords.endX = e.targetTouches[0].pageX; thumbDragUtils = _this.onThumbTouchMove(thumbDragUtils); } }); this.$lgThumb.on('touchend.lg', function () { if (thumbDragUtils.isMoved) { thumbDragUtils = _this.onThumbTouchEnd(thumbDragUtils); } else { _this.thumbClickable = true; } }); }; // Rebuild thumbnails Thumbnail.prototype.rebuildThumbnails = function () { var _this = this; // Remove transitions this.$thumbOuter.addClass('lg-rebuilding-thumbnails'); setTimeout(function () { _this.thumbTotalWidth = _this.core.galleryItems.length * (_this.settings.thumbWidth + _this.settings.thumbMargin); _this.$lgThumb.css('width', _this.thumbTotalWidth + 'px'); _this.$lgThumb.empty(); _this.setThumbItemHtml(_this.core.galleryItems); _this.animateThumb(_this.core.index); }, 50); setTimeout(function () { _this.$thumbOuter.removeClass('lg-rebuilding-thumbnails'); }, 200); }; // @ts-check Thumbnail.prototype.setTranslate = function (value) { this.$lgThumb.css('transform', 'translate3d(-' + value + 'px, 0px, 0px)'); }; Thumbnail.prototype.getPossibleTransformX = function (left) { if (left > this.thumbTotalWidth - this.thumbOuterWidth) { left = this.thumbTotalWidth - this.thumbOuterWidth; } if (left < 0) { left = 0; } return left; }; Thumbnail.prototype.animateThumb = function (index) { this.$lgThumb.css('transition-duration', this.core.settings.speed + 'ms'); if (this.settings.animateThumb) { var position = 0; switch (this.settings.currentPagerPosition) { case 'left': position = 0; break; case 'middle': position = this.thumbOuterWidth / 2 - this.settings.thumbWidth / 2; break; case 'right': position = this.thumbOuterWidth - this.settings.thumbWidth; } this.translateX = (this.settings.thumbWidth + this.settings.thumbMargin) * index - 1 - position; if (this.translateX > this.thumbTotalWidth - this.thumbOuterWidth) { this.translateX = this.thumbTotalWidth - this.thumbOuterWidth; } if (this.translateX < 0) { this.translateX = 0; } this.setTranslate(this.translateX); } }; Thumbnail.prototype.onThumbTouchMove = function (thumbDragUtils) { thumbDragUtils.newTranslateX = this.translateX; thumbDragUtils.isMoved = true; thumbDragUtils.touchMoveTime = new Date().valueOf(); thumbDragUtils.newTranslateX -= thumbDragUtils.cords.endX - thumbDragUtils.cords.startX; thumbDragUtils.newTranslateX = this.getPossibleTransformX(thumbDragUtils.newTranslateX); // move current slide this.setTranslate(thumbDragUtils.newTranslateX); this.$thumbOuter.addClass('lg-dragging'); return thumbDragUtils; }; Thumbnail.prototype.onThumbTouchEnd = function (thumbDragUtils) { thumbDragUtils.isMoved = false; thumbDragUtils.endTime = new Date(); this.$thumbOuter.removeClass('lg-dragging'); var touchDuration = thumbDragUtils.endTime.valueOf() - thumbDragUtils.startTime.valueOf(); var distanceXnew = thumbDragUtils.cords.endX - thumbDragUtils.cords.startX; var speedX = Math.abs(distanceXnew) / touchDuration; // Some magical numbers // Can be improved if (speedX > 0.15 && thumbDragUtils.endTime.valueOf() - thumbDragUtils.touchMoveTime < 30) { speedX += 1; if (speedX > 2) { speedX += 1; } speedX = speedX + speedX * (Math.abs(distanceXnew) / this.thumbOuterWidth); this.$lgThumb.css('transition-duration', Math.min(speedX - 1, 2) + 'settings'); distanceXnew = distanceXnew * speedX; this.translateX = this.getPossibleTransformX(this.translateX - distanceXnew); this.setTranslate(this.translateX); } else { this.translateX = thumbDragUtils.newTranslateX; } if (Math.abs(thumbDragUtils.cords.endX - thumbDragUtils.cords.startX) < this.settings.thumbnailSwipeThreshold) { this.thumbClickable = true; } return thumbDragUtils; }; Thumbnail.prototype.getThumbHtml = function (thumb, index) { var slideVideoInfo = this.core.galleryItems[index].__slideVideoInfo || {}; var thumbImg; if (slideVideoInfo.youtube) { if (this.settings.loadYouTubeThumbnail) { thumbImg = '//img.youtube.com/vi/' + slideVideoInfo.youtube[1] + '/' + this.settings.youTubeThumbSize + '.jpg'; } else { thumbImg = thumb; } } else { thumbImg = thumb; } return "
\n \n
"; }; Thumbnail.prototype.getThumbItemHtml = function (items) { var thumbList = ''; for (var i = 0; i < items.length; i++) { thumbList += this.getThumbHtml(items[i].thumb, i); } return thumbList; }; Thumbnail.prototype.setThumbItemHtml = function (items) { var thumbList = this.getThumbItemHtml(items); this.$lgThumb.html(thumbList); }; Thumbnail.prototype.setAnimateThumbStyles = function () { if (this.settings.animateThumb) { this.core.outer.addClass('lg-animate-thumb'); } }; // Manage thumbnail active calss Thumbnail.prototype.manageActiveClassOnSlideChange = function () { var _this = this; // manage active class for thumbnail this.core.LGel.on(lg_thumbnail_es5_lGEvents.beforeSlide + ".thumb", function (event) { var $thumb = _this.core.outer.find('.lg-thumb-item'); var index = event.detail.index; $thumb.removeClass('active'); $thumb.eq(index).addClass('active'); }); }; // Toggle thumbnail bar Thumbnail.prototype.toggleThumbBar = function () { var _this = this; if (this.settings.toggleThumb) { this.core.outer.addClass('lg-can-toggle'); this.core.$toolbar.append(''); this.core.outer .find('.lg-toggle-thumb') .first() .on('click.lg', function () { _this.core.outer.toggleClass('lg-components-open'); }); } }; Thumbnail.prototype.thumbKeyPress = function () { var _this = this; this.$LG(window).on("keydown.lg.thumb.global" + this.core.lgId, function (e) { if (!_this.core.lgOpened || !_this.settings.toggleThumb) return; if (e.keyCode === 38) { e.preventDefault(); _this.core.outer.addClass('lg-components-open'); } else if (e.keyCode === 40) { e.preventDefault(); _this.core.outer.removeClass('lg-components-open'); } }); }; Thumbnail.prototype.destroy = function () { if (this.settings.thumbnail) { this.$LG(window).off(".lg.thumb.global" + this.core.lgId); this.core.LGel.off('.lg.thumb'); this.core.LGel.off('.thumb'); this.$thumbOuter.remove(); this.core.outer.removeClass('lg-has-thumb'); } }; return Thumbnail; }()); /* harmony default export */ var lg_thumbnail_es5 = (Thumbnail); //# sourceMappingURL=lg-thumbnail.es5.js.map // CONCATENATED MODULE: ./node_modules/lightgallery/plugins/video/lg-video.es5.js /*! * lightgallery | 2.7.1 | January 11th 2023 * http://www.lightgalleryjs.com/ * Copyright (c) 2020 Sachin Neravath; * @license GPLv3 */ /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var lg_video_es5_assign = function() { lg_video_es5_assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return lg_video_es5_assign.apply(this, arguments); }; var videoSettings = { autoplayFirstVideo: true, youTubePlayerParams: false, vimeoPlayerParams: false, wistiaPlayerParams: false, gotoNextSlideOnVideoEnd: true, autoplayVideoOnSlide: false, videojs: false, videojsTheme: '', videojsOptions: {}, }; /** * List of lightGallery events * All events should be documented here * Below interfaces are used to build the website documentations * */ var lg_video_es5_lGEvents = { afterAppendSlide: 'lgAfterAppendSlide', init: 'lgInit', hasVideo: 'lgHasVideo', containerResize: 'lgContainerResize', updateSlides: 'lgUpdateSlides', afterAppendSubHtml: 'lgAfterAppendSubHtml', beforeOpen: 'lgBeforeOpen', afterOpen: 'lgAfterOpen', slideItemLoad: 'lgSlideItemLoad', beforeSlide: 'lgBeforeSlide', afterSlide: 'lgAfterSlide', posterClick: 'lgPosterClick', dragStart: 'lgDragStart', dragMove: 'lgDragMove', dragEnd: 'lgDragEnd', beforeNextSlide: 'lgBeforeNextSlide', beforePrevSlide: 'lgBeforePrevSlide', beforeClose: 'lgBeforeClose', afterClose: 'lgAfterClose', rotateLeft: 'lgRotateLeft', rotateRight: 'lgRotateRight', flipHorizontal: 'lgFlipHorizontal', flipVertical: 'lgFlipVertical', autoplay: 'lgAutoplay', autoplayStart: 'lgAutoplayStart', autoplayStop: 'lgAutoplayStop', }; var param = function (obj) { return Object.keys(obj) .map(function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]); }) .join('&'); }; var paramsToObject = function (url) { var paramas = url .slice(1) .split('&') .map(function (p) { return p.split('='); }) .reduce(function (obj, pair) { var _a = pair.map(decodeURIComponent), key = _a[0], value = _a[1]; obj[key] = value; return obj; }, {}); return paramas; }; var getYouTubeParams = function (videoInfo, youTubePlayerParamsSettings) { if (!videoInfo.youtube) return ''; var slideUrlParams = videoInfo.youtube[2] ? paramsToObject(videoInfo.youtube[2]) : ''; // For youtube first params gets priority if duplicates found var defaultYouTubePlayerParams = { wmode: 'opaque', autoplay: 0, mute: 1, enablejsapi: 1, }; var playerParamsSettings = youTubePlayerParamsSettings || {}; var youTubePlayerParams = lg_video_es5_assign(lg_video_es5_assign(lg_video_es5_assign({}, defaultYouTubePlayerParams), playerParamsSettings), slideUrlParams); var youTubeParams = "?" + param(youTubePlayerParams); return youTubeParams; }; var isYouTubeNoCookie = function (url) { return url.includes('youtube-nocookie.com'); }; var getVimeoURLParams = function (defaultParams, videoInfo) { if (!videoInfo || !videoInfo.vimeo) return ''; var urlParams = videoInfo.vimeo[2] || ''; var defaultPlayerParams = defaultParams && Object.keys(defaultParams).length !== 0 ? '&' + param(defaultParams) : ''; // Support private video var urlWithHash = videoInfo.vimeo[0].split('/').pop() || ''; var urlWithHashWithParams = urlWithHash.split('?')[0] || ''; var hash = urlWithHashWithParams.split('#')[0]; var isPrivate = videoInfo.vimeo[1] !== hash; if (isPrivate) { urlParams = urlParams.replace("/" + hash, ''); } urlParams = urlParams[0] == '?' ? '&' + urlParams.slice(1) : urlParams || ''; // For vimeo last params gets priority if duplicates found var vimeoPlayerParams = "?autoplay=0&muted=1" + (isPrivate ? "&h=" + hash : '') + defaultPlayerParams + urlParams; return vimeoPlayerParams; }; /** * Video module for lightGallery * Supports HTML5, YouTube, Vimeo, wistia videos * * * @ref Wistia * https://wistia.com/support/integrations/wordpress(How to get url) * https://wistia.com/support/developers/embed-options#using-embed-options * https://wistia.com/support/developers/player-api * https://wistia.com/support/developers/construct-an-embed-code * http://jsfiddle.net/xvnm7xLm/ * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video * https://wistia.com/support/embed-and-share/sharing-videos * https://private-sharing.wistia.com/medias/mwhrulrucj * * @ref Youtube * https://developers.google.com/youtube/player_parameters#enablejsapi * https://developers.google.com/youtube/iframe_api_reference * https://developer.chrome.com/blog/autoplay/#iframe-delegation * * @ref Vimeo * https://stackoverflow.com/questions/10488943/easy-way-to-get-vimeo-id-from-a-vimeo-url * https://vimeo.zendesk.com/hc/en-us/articles/360000121668-Starting-playback-at-a-specific-timecode * https://vimeo.zendesk.com/hc/en-us/articles/360001494447-Using-Player-Parameters */ var Video = /** @class */ (function () { function Video(instance) { // get lightGallery core plugin instance this.core = instance; this.settings = lg_video_es5_assign(lg_video_es5_assign({}, videoSettings), this.core.settings); return this; } Video.prototype.init = function () { var _this = this; /** * Event triggered when video url found without poster * Append video HTML * Play if autoplayFirstVideo is true */ this.core.LGel.on(lg_video_es5_lGEvents.hasVideo + ".video", this.onHasVideo.bind(this)); this.core.LGel.on(lg_video_es5_lGEvents.posterClick + ".video", function () { var $el = _this.core.getSlideItem(_this.core.index); _this.loadVideoOnPosterClick($el); }); this.core.LGel.on(lg_video_es5_lGEvents.slideItemLoad + ".video", this.onSlideItemLoad.bind(this)); // @desc fired immediately before each slide transition. this.core.LGel.on(lg_video_es5_lGEvents.beforeSlide + ".video", this.onBeforeSlide.bind(this)); // @desc fired immediately after each slide transition. this.core.LGel.on(lg_video_es5_lGEvents.afterSlide + ".video", this.onAfterSlide.bind(this)); }; /** * @desc Event triggered when a slide is completely loaded * * @param {Event} event - lightGalley custom event */ Video.prototype.onSlideItemLoad = function (event) { var _this = this; var _a = event.detail, isFirstSlide = _a.isFirstSlide, index = _a.index; // Should check the active slide as well as user may have moved to different slide before the first slide is loaded if (this.settings.autoplayFirstVideo && isFirstSlide && index === this.core.index) { // Delay is just for the transition effect on video load setTimeout(function () { _this.loadAndPlayVideo(index); }, 200); } // Should not call on first slide. should check only if the slide is active if (!isFirstSlide && this.settings.autoplayVideoOnSlide && index === this.core.index) { this.loadAndPlayVideo(index); } }; /** * @desc Event triggered when video url or poster found * Append video HTML is poster is not given * Play if autoplayFirstVideo is true * * @param {Event} event - Javascript Event object. */ Video.prototype.onHasVideo = function (event) { var _a = event.detail, index = _a.index, src = _a.src, html5Video = _a.html5Video, hasPoster = _a.hasPoster; if (!hasPoster) { // All functions are called separately if poster exist in loadVideoOnPosterClick function this.appendVideos(this.core.getSlideItem(index), { src: src, addClass: 'lg-object', index: index, html5Video: html5Video, }); // Automatically navigate to next slide once video reaches the end. this.gotoNextSlideOnVideoEnd(src, index); } }; /** * @desc fired immediately before each slide transition. * Pause the previous video * Hide the download button if the slide contains YouTube, Vimeo, or Wistia videos. * * @param {Event} event - Javascript Event object. * @param {number} prevIndex - Previous index of the slide. * @param {number} index - Current index of the slide */ Video.prototype.onBeforeSlide = function (event) { if (this.core.lGalleryOn) { var prevIndex = event.detail.prevIndex; this.pauseVideo(prevIndex); } }; /** * @desc fired immediately after each slide transition. * Play video if autoplayVideoOnSlide option is enabled. * * @param {Event} event - Javascript Event object. * @param {number} prevIndex - Previous index of the slide. * @param {number} index - Current index of the slide * @todo should check on onSlideLoad as well if video is not loaded on after slide */ Video.prototype.onAfterSlide = function (event) { var _this = this; var _a = event.detail, index = _a.index, prevIndex = _a.prevIndex; // Do not call on first slide var $slide = this.core.getSlideItem(index); if (this.settings.autoplayVideoOnSlide && index !== prevIndex) { if ($slide.hasClass('lg-complete')) { setTimeout(function () { _this.loadAndPlayVideo(index); }, 100); } } }; Video.prototype.loadAndPlayVideo = function (index) { var $slide = this.core.getSlideItem(index); var currentGalleryItem = this.core.galleryItems[index]; if (currentGalleryItem.poster) { this.loadVideoOnPosterClick($slide, true); } else { this.playVideo(index); } }; /** * Play HTML5, Youtube, Vimeo or Wistia videos in a particular slide. * @param {number} index - Index of the slide */ Video.prototype.playVideo = function (index) { this.controlVideo(index, 'play'); }; /** * Pause HTML5, Youtube, Vimeo or Wistia videos in a particular slide. * @param {number} index - Index of the slide */ Video.prototype.pauseVideo = function (index) { this.controlVideo(index, 'pause'); }; Video.prototype.getVideoHtml = function (src, addClass, index, html5Video) { var video = ''; var videoInfo = this.core.galleryItems[index] .__slideVideoInfo || {}; var currentGalleryItem = this.core.galleryItems[index]; var videoTitle = currentGalleryItem.title || currentGalleryItem.alt; videoTitle = videoTitle ? 'title="' + videoTitle + '"' : ''; var commonIframeProps = "allowtransparency=\"true\"\n frameborder=\"0\"\n scrolling=\"no\"\n allowfullscreen\n mozallowfullscreen\n webkitallowfullscreen\n oallowfullscreen\n msallowfullscreen"; if (videoInfo.youtube) { var videoId = 'lg-youtube' + index; var youTubeParams = getYouTubeParams(videoInfo, this.settings.youTubePlayerParams); var isYouTubeNoCookieURL = isYouTubeNoCookie(src); var youtubeURL = isYouTubeNoCookieURL ? '//www.youtube-nocookie.com/' : '//www.youtube.com/'; video = ""; } else if (videoInfo.vimeo) { var videoId = 'lg-vimeo' + index; var playerParams = getVimeoURLParams(this.settings.vimeoPlayerParams, videoInfo); video = ""; } else if (videoInfo.wistia) { var wistiaId = 'lg-wistia' + index; var playerParams = param(this.settings.wistiaPlayerParams); playerParams = playerParams ? '?' + playerParams : ''; video = ""; } else if (videoInfo.html5) { var html5VideoMarkup = ''; for (var i = 0; i < html5Video.source.length; i++) { html5VideoMarkup += ""; } if (html5Video.tracks) { var _loop_1 = function (i) { var trackAttributes = ''; var track = html5Video.tracks[i]; Object.keys(track || {}).forEach(function (key) { trackAttributes += key + "=\"" + track[key] + "\" "; }); html5VideoMarkup += ""; }; for (var i = 0; i < html5Video.tracks.length; i++) { _loop_1(i); } } var html5VideoAttrs_1 = ''; var videoAttributes_1 = html5Video.attributes || {}; Object.keys(videoAttributes_1 || {}).forEach(function (key) { html5VideoAttrs_1 += key + "=\"" + videoAttributes_1[key] + "\" "; }); video = ""; } return video; }; /** * @desc - Append videos to the slide * * @param {HTMLElement} el - slide element * @param {Object} videoParams - Video parameters, Contains src, class, index, htmlVideo */ Video.prototype.appendVideos = function (el, videoParams) { var _a; var videoHtml = this.getVideoHtml(videoParams.src, videoParams.addClass, videoParams.index, videoParams.html5Video); el.find('.lg-video-cont').append(videoHtml); var $videoElement = el.find('.lg-video-object').first(); if (videoParams.html5Video) { $videoElement.on('mousedown.lg.video', function (e) { e.stopPropagation(); }); } if (this.settings.videojs && ((_a = this.core.galleryItems[videoParams.index].__slideVideoInfo) === null || _a === void 0 ? void 0 : _a.html5)) { try { return videojs($videoElement.get(), this.settings.videojsOptions); } catch (e) { console.error('lightGallery:- Make sure you have included videojs'); } } }; Video.prototype.gotoNextSlideOnVideoEnd = function (src, index) { var _this = this; var $videoElement = this.core .getSlideItem(index) .find('.lg-video-object') .first(); var videoInfo = this.core.galleryItems[index].__slideVideoInfo || {}; if (this.settings.gotoNextSlideOnVideoEnd) { if (videoInfo.html5) { $videoElement.on('ended', function () { _this.core.goToNextSlide(); }); } else if (videoInfo.vimeo) { try { // https://github.com/vimeo/player.js/#ended new Vimeo.Player($videoElement.get()).on('ended', function () { _this.core.goToNextSlide(); }); } catch (e) { console.error('lightGallery:- Make sure you have included //github.com/vimeo/player.js'); } } else if (videoInfo.wistia) { try { window._wq = window._wq || []; // @todo Event is gettign triggered multiple times window._wq.push({ id: $videoElement.attr('id'), onReady: function (video) { video.bind('end', function () { _this.core.goToNextSlide(); }); }, }); } catch (e) { console.error('lightGallery:- Make sure you have included //fast.wistia.com/assets/external/E-v1.js'); } } } }; Video.prototype.controlVideo = function (index, action) { var $videoElement = this.core .getSlideItem(index) .find('.lg-video-object') .first(); var videoInfo = this.core.galleryItems[index].__slideVideoInfo || {}; if (!$videoElement.get()) return; if (videoInfo.youtube) { try { $videoElement.get().contentWindow.postMessage("{\"event\":\"command\",\"func\":\"" + action + "Video\",\"args\":\"\"}", '*'); } catch (e) { console.error("lightGallery:- " + e); } } else if (videoInfo.vimeo) { try { new Vimeo.Player($videoElement.get())[action](); } catch (e) { console.error('lightGallery:- Make sure you have included //github.com/vimeo/player.js'); } } else if (videoInfo.html5) { if (this.settings.videojs) { try { videojs($videoElement.get())[action](); } catch (e) { console.error('lightGallery:- Make sure you have included videojs'); } } else { $videoElement.get()[action](); } } else if (videoInfo.wistia) { try { window._wq = window._wq || []; // @todo Find a way to destroy wistia player instance window._wq.push({ id: $videoElement.attr('id'), onReady: function (video) { video[action](); }, }); } catch (e) { console.error('lightGallery:- Make sure you have included //fast.wistia.com/assets/external/E-v1.js'); } } }; Video.prototype.loadVideoOnPosterClick = function ($el, forcePlay) { var _this = this; // check slide has poster if (!$el.hasClass('lg-video-loaded')) { // check already video element present if (!$el.hasClass('lg-has-video')) { $el.addClass('lg-has-video'); var _html = void 0; var _src = this.core.galleryItems[this.core.index].src; var video = this.core.galleryItems[this.core.index].video; if (video) { _html = typeof video === 'string' ? JSON.parse(video) : video; } var videoJsPlayer_1 = this.appendVideos($el, { src: _src, addClass: '', index: this.core.index, html5Video: _html, }); this.gotoNextSlideOnVideoEnd(_src, this.core.index); var $tempImg = $el.find('.lg-object').first().get(); // @todo make sure it is working $el.find('.lg-video-cont').first().append($tempImg); $el.addClass('lg-video-loading'); videoJsPlayer_1 && videoJsPlayer_1.ready(function () { videoJsPlayer_1.on('loadedmetadata', function () { _this.onVideoLoadAfterPosterClick($el, _this.core.index); }); }); $el.find('.lg-video-object') .first() .on('load.lg error.lg loadedmetadata.lg', function () { setTimeout(function () { _this.onVideoLoadAfterPosterClick($el, _this.core.index); }, 50); }); } else { this.playVideo(this.core.index); } } else if (forcePlay) { this.playVideo(this.core.index); } }; Video.prototype.onVideoLoadAfterPosterClick = function ($el, index) { $el.addClass('lg-video-loaded'); this.playVideo(index); }; Video.prototype.destroy = function () { this.core.LGel.off('.lg.video'); this.core.LGel.off('.video'); }; return Video; }()); /* harmony default export */ var lg_video_es5 = (Video); //# sourceMappingURL=lg-video.es5.js.map // CONCATENATED MODULE: ./node_modules/lightgallery/plugins/zoom/lg-zoom.es5.js /*! * lightgallery | 2.7.1 | January 11th 2023 * http://www.lightgalleryjs.com/ * Copyright (c) 2020 Sachin Neravath; * @license GPLv3 */ /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var lg_zoom_es5_assign = function() { lg_zoom_es5_assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return lg_zoom_es5_assign.apply(this, arguments); }; var zoomSettings = { scale: 1, zoom: true, actualSize: true, showZoomInOutIcons: false, actualSizeIcons: { zoomIn: 'lg-zoom-in', zoomOut: 'lg-zoom-out', }, enableZoomAfter: 300, zoomPluginStrings: { zoomIn: 'Zoom in', zoomOut: 'Zoom out', viewActualSize: 'View actual size', }, }; /** * List of lightGallery events * All events should be documented here * Below interfaces are used to build the website documentations * */ var lg_zoom_es5_lGEvents = { afterAppendSlide: 'lgAfterAppendSlide', init: 'lgInit', hasVideo: 'lgHasVideo', containerResize: 'lgContainerResize', updateSlides: 'lgUpdateSlides', afterAppendSubHtml: 'lgAfterAppendSubHtml', beforeOpen: 'lgBeforeOpen', afterOpen: 'lgAfterOpen', slideItemLoad: 'lgSlideItemLoad', beforeSlide: 'lgBeforeSlide', afterSlide: 'lgAfterSlide', posterClick: 'lgPosterClick', dragStart: 'lgDragStart', dragMove: 'lgDragMove', dragEnd: 'lgDragEnd', beforeNextSlide: 'lgBeforeNextSlide', beforePrevSlide: 'lgBeforePrevSlide', beforeClose: 'lgBeforeClose', afterClose: 'lgAfterClose', rotateLeft: 'lgRotateLeft', rotateRight: 'lgRotateRight', flipHorizontal: 'lgFlipHorizontal', flipVertical: 'lgFlipVertical', autoplay: 'lgAutoplay', autoplayStart: 'lgAutoplayStart', autoplayStop: 'lgAutoplayStop', }; var ZOOM_TRANSITION_DURATION = 500; var Zoom = /** @class */ (function () { function Zoom(instance, $LG) { // get lightGallery core plugin instance this.core = instance; this.$LG = $LG; this.settings = lg_zoom_es5_assign(lg_zoom_es5_assign({}, zoomSettings), this.core.settings); return this; } // Append Zoom controls. Actual size, Zoom-in, Zoom-out Zoom.prototype.buildTemplates = function () { var zoomIcons = this.settings.showZoomInOutIcons ? "" : ''; if (this.settings.actualSize) { zoomIcons += ""; } this.core.outer.addClass('lg-use-transition-for-zoom'); this.core.$toolbar.first().append(zoomIcons); }; /** * @desc Enable zoom option only once the image is completely loaded * If zoomFromOrigin is true, Zoom is enabled once the dummy image has been inserted * * Zoom styles are defined under lg-zoomable CSS class. */ Zoom.prototype.enableZoom = function (event) { var _this = this; // delay will be 0 except first time var _speed = this.settings.enableZoomAfter + event.detail.delay; // set _speed value 0 if gallery opened from direct url and if it is first slide if (this.$LG('body').first().hasClass('lg-from-hash') && event.detail.delay) { // will execute only once _speed = 0; } else { // Remove lg-from-hash to enable starting animation. this.$LG('body').first().removeClass('lg-from-hash'); } this.zoomableTimeout = setTimeout(function () { if (!_this.isImageSlide(_this.core.index)) { return; } _this.core.getSlideItem(event.detail.index).addClass('lg-zoomable'); if (event.detail.index === _this.core.index) { _this.setZoomEssentials(); } }, _speed + 30); }; Zoom.prototype.enableZoomOnSlideItemLoad = function () { // Add zoomable class this.core.LGel.on(lg_zoom_es5_lGEvents.slideItemLoad + ".zoom", this.enableZoom.bind(this)); }; Zoom.prototype.getDragCords = function (e) { return { x: e.pageX, y: e.pageY, }; }; Zoom.prototype.getSwipeCords = function (e) { var x = e.touches[0].pageX; var y = e.touches[0].pageY; return { x: x, y: y, }; }; Zoom.prototype.getDragAllowedAxises = function (scale, scaleDiff) { var $image = this.core .getSlideItem(this.core.index) .find('.lg-image') .first() .get(); var height = 0; var width = 0; var rect = $image.getBoundingClientRect(); if (scale) { height = $image.offsetHeight * scale; width = $image.offsetWidth * scale; } else if (scaleDiff) { height = rect.height + scaleDiff * rect.height; width = rect.width + scaleDiff * rect.width; } else { height = rect.height; width = rect.width; } var allowY = height > this.containerRect.height; var allowX = width > this.containerRect.width; return { allowX: allowX, allowY: allowY, }; }; Zoom.prototype.setZoomEssentials = function () { this.containerRect = this.core.$content.get().getBoundingClientRect(); }; /** * @desc Image zoom * Translate the wrap and scale the image to get better user experience * * @param {String} scale - Zoom decrement/increment value */ Zoom.prototype.zoomImage = function (scale, scaleDiff, reposition, resetToMax) { if (Math.abs(scaleDiff) <= 0) return; var offsetX = this.containerRect.width / 2 + this.containerRect.left; var offsetY = this.containerRect.height / 2 + this.containerRect.top + this.scrollTop; var originalX; var originalY; if (scale === 1) { this.positionChanged = false; } var dragAllowedAxises = this.getDragAllowedAxises(0, scaleDiff); var allowY = dragAllowedAxises.allowY, allowX = dragAllowedAxises.allowX; if (this.positionChanged) { originalX = this.left / (this.scale - scaleDiff); originalY = this.top / (this.scale - scaleDiff); this.pageX = offsetX - originalX; this.pageY = offsetY - originalY; this.positionChanged = false; } var possibleSwipeCords = this.getPossibleSwipeDragCords(scaleDiff); var x; var y; var _x = offsetX - this.pageX; var _y = offsetY - this.pageY; if (scale - scaleDiff > 1) { var scaleVal = (scale - scaleDiff) / Math.abs(scaleDiff); _x = (scaleDiff < 0 ? -_x : _x) + this.left * (scaleVal + (scaleDiff < 0 ? -1 : 1)); _y = (scaleDiff < 0 ? -_y : _y) + this.top * (scaleVal + (scaleDiff < 0 ? -1 : 1)); x = _x / scaleVal; y = _y / scaleVal; } else { var scaleVal = (scale - scaleDiff) * scaleDiff; x = _x * scaleVal; y = _y * scaleVal; } if (reposition) { if (allowX) { if (this.isBeyondPossibleLeft(x, possibleSwipeCords.minX)) { x = possibleSwipeCords.minX; } else if (this.isBeyondPossibleRight(x, possibleSwipeCords.maxX)) { x = possibleSwipeCords.maxX; } } else { if (scale > 1) { if (x < possibleSwipeCords.minX) { x = possibleSwipeCords.minX; } else if (x > possibleSwipeCords.maxX) { x = possibleSwipeCords.maxX; } } } // @todo fix this if (allowY) { if (this.isBeyondPossibleTop(y, possibleSwipeCords.minY)) { y = possibleSwipeCords.minY; } else if (this.isBeyondPossibleBottom(y, possibleSwipeCords.maxY)) { y = possibleSwipeCords.maxY; } } else { // If the translate value based on index of beyond the viewport, utilize the available space to prevent image being cut out if (scale > 1) { //If image goes beyond viewport top, use the minim possible translate value if (y < possibleSwipeCords.minY) { y = possibleSwipeCords.minY; } else if (y > possibleSwipeCords.maxY) { y = possibleSwipeCords.maxY; } } } } this.setZoomStyles({ x: x, y: y, scale: scale, }); this.left = x; this.top = y; if (resetToMax) { this.setZoomImageSize(); } }; Zoom.prototype.resetImageTranslate = function (index) { if (!this.isImageSlide(index)) { return; } var $image = this.core.getSlideItem(index).find('.lg-image').first(); this.imageReset = false; $image.removeClass('reset-transition reset-transition-y reset-transition-x'); this.core.outer.removeClass('lg-actual-size'); $image.css('width', 'auto').css('height', 'auto'); setTimeout(function () { $image.removeClass('no-transition'); }, 10); }; Zoom.prototype.setZoomImageSize = function () { var _this = this; var $image = this.core .getSlideItem(this.core.index) .find('.lg-image') .first(); setTimeout(function () { var actualSizeScale = _this.getCurrentImageActualSizeScale(); if (_this.scale >= actualSizeScale) { $image.addClass('no-transition'); _this.imageReset = true; } }, ZOOM_TRANSITION_DURATION); setTimeout(function () { var actualSizeScale = _this.getCurrentImageActualSizeScale(); if (_this.scale >= actualSizeScale) { var dragAllowedAxises = _this.getDragAllowedAxises(_this.scale); $image .css('width', $image.get().naturalWidth + 'px') .css('height', $image.get().naturalHeight + 'px'); _this.core.outer.addClass('lg-actual-size'); if (dragAllowedAxises.allowX && dragAllowedAxises.allowY) { $image.addClass('reset-transition'); } else if (dragAllowedAxises.allowX && !dragAllowedAxises.allowY) { $image.addClass('reset-transition-x'); } else if (!dragAllowedAxises.allowX && dragAllowedAxises.allowY) { $image.addClass('reset-transition-y'); } } }, ZOOM_TRANSITION_DURATION + 50); }; /** * @desc apply scale3d to image and translate to image wrap * @param {style} X,Y and scale */ Zoom.prototype.setZoomStyles = function (style) { var $imageWrap = this.core .getSlideItem(this.core.index) .find('.lg-img-wrap') .first(); var $image = this.core .getSlideItem(this.core.index) .find('.lg-image') .first(); var $dummyImage = this.core.outer .find('.lg-current .lg-dummy-img') .first(); this.scale = style.scale; $image.css('transform', 'scale3d(' + style.scale + ', ' + style.scale + ', 1)'); $dummyImage.css('transform', 'scale3d(' + style.scale + ', ' + style.scale + ', 1)'); var transform = 'translate3d(' + style.x + 'px, ' + style.y + 'px, 0)'; $imageWrap.css('transform', transform); }; /** * @param index - Index of the current slide * @param event - event will be available only if the function is called on clicking/taping the imags */ Zoom.prototype.setActualSize = function (index, event) { var _this = this; var currentItem = this.core.galleryItems[this.core.index]; this.resetImageTranslate(index); setTimeout(function () { // Allow zoom only on image if (!currentItem.src || _this.core.outer.hasClass('lg-first-slide-loading')) { return; } var scale = _this.getCurrentImageActualSizeScale(); var prevScale = _this.scale; if (_this.core.outer.hasClass('lg-zoomed')) { _this.scale = 1; } else { _this.scale = _this.getScale(scale); } _this.setPageCords(event); _this.beginZoom(_this.scale); _this.zoomImage(_this.scale, _this.scale - prevScale, true, true); setTimeout(function () { _this.core.outer.removeClass('lg-grabbing').addClass('lg-grab'); }, 10); }, 50); }; Zoom.prototype.getNaturalWidth = function (index) { var $image = this.core.getSlideItem(index).find('.lg-image').first(); var naturalWidth = this.core.galleryItems[index].width; return naturalWidth ? parseFloat(naturalWidth) : $image.get().naturalWidth; }; Zoom.prototype.getActualSizeScale = function (naturalWidth, width) { var _scale; var scale; if (naturalWidth >= width) { _scale = naturalWidth / width; scale = _scale || 2; } else { scale = 1; } return scale; }; Zoom.prototype.getCurrentImageActualSizeScale = function () { var $image = this.core .getSlideItem(this.core.index) .find('.lg-image') .first(); var width = $image.get().offsetWidth; var naturalWidth = this.getNaturalWidth(this.core.index) || width; return this.getActualSizeScale(naturalWidth, width); }; Zoom.prototype.getPageCords = function (event) { var cords = {}; if (event) { cords.x = event.pageX || event.touches[0].pageX; cords.y = event.pageY || event.touches[0].pageY; } else { var containerRect = this.core.$content .get() .getBoundingClientRect(); cords.x = containerRect.width / 2 + containerRect.left; cords.y = containerRect.height / 2 + this.scrollTop + containerRect.top; } return cords; }; Zoom.prototype.setPageCords = function (event) { var pageCords = this.getPageCords(event); this.pageX = pageCords.x; this.pageY = pageCords.y; }; Zoom.prototype.manageActualPixelClassNames = function () { var $actualSize = this.core.getElementById('lg-actual-size'); $actualSize .removeClass(this.settings.actualSizeIcons.zoomIn) .addClass(this.settings.actualSizeIcons.zoomOut); }; // If true, zoomed - in else zoomed out Zoom.prototype.beginZoom = function (scale) { this.core.outer.removeClass('lg-zoom-drag-transition lg-zoom-dragging'); if (scale > 1) { this.core.outer.addClass('lg-zoomed'); this.manageActualPixelClassNames(); } else { this.resetZoom(); } return scale > 1; }; Zoom.prototype.getScale = function (scale) { var actualSizeScale = this.getCurrentImageActualSizeScale(); if (scale < 1) { scale = 1; } else if (scale > actualSizeScale) { scale = actualSizeScale; } return scale; }; Zoom.prototype.init = function () { var _this = this; if (!this.settings.zoom) { return; } this.buildTemplates(); this.enableZoomOnSlideItemLoad(); var tapped = null; this.core.outer.on('dblclick.lg', function (event) { if (!_this.$LG(event.target).hasClass('lg-image')) { return; } _this.setActualSize(_this.core.index, event); }); this.core.outer.on('touchstart.lg', function (event) { var $target = _this.$LG(event.target); if (event.touches.length === 1 && $target.hasClass('lg-image')) { if (!tapped) { tapped = setTimeout(function () { tapped = null; }, 300); } else { clearTimeout(tapped); tapped = null; event.preventDefault(); _this.setActualSize(_this.core.index, event); } } }); this.core.LGel.on(lg_zoom_es5_lGEvents.containerResize + ".zoom " + lg_zoom_es5_lGEvents.rotateRight + ".zoom " + lg_zoom_es5_lGEvents.rotateLeft + ".zoom " + lg_zoom_es5_lGEvents.flipHorizontal + ".zoom " + lg_zoom_es5_lGEvents.flipVertical + ".zoom", function () { if (!_this.core.lgOpened || !_this.isImageSlide(_this.core.index) || _this.core.touchAction) { return; } var _LGel = _this.core .getSlideItem(_this.core.index) .find('.lg-img-wrap') .first(); _this.top = 0; _this.left = 0; _this.setZoomEssentials(); _this.setZoomSwipeStyles(_LGel, { x: 0, y: 0 }); _this.positionChanged = true; }); // Update zoom on resize and orientationchange this.$LG(window).on("scroll.lg.zoom.global" + this.core.lgId, function () { if (!_this.core.lgOpened) return; _this.scrollTop = _this.$LG(window).scrollTop(); }); this.core.getElementById('lg-zoom-out').on('click.lg', function () { // Allow zoom only on image if (!_this.isImageSlide(_this.core.index)) { return; } var timeout = 0; if (_this.imageReset) { _this.resetImageTranslate(_this.core.index); timeout = 50; } setTimeout(function () { var scale = _this.scale - _this.settings.scale; if (scale < 1) { scale = 1; } _this.beginZoom(scale); _this.zoomImage(scale, -_this.settings.scale, true, true); }, timeout); }); this.core.getElementById('lg-zoom-in').on('click.lg', function () { _this.zoomIn(); }); this.core.getElementById('lg-actual-size').on('click.lg', function () { _this.setActualSize(_this.core.index); }); this.core.LGel.on(lg_zoom_es5_lGEvents.beforeOpen + ".zoom", function () { _this.core.outer.find('.lg-item').removeClass('lg-zoomable'); }); this.core.LGel.on(lg_zoom_es5_lGEvents.afterOpen + ".zoom", function () { _this.scrollTop = _this.$LG(window).scrollTop(); // Set the initial value center _this.pageX = _this.core.outer.width() / 2; _this.pageY = _this.core.outer.height() / 2 + _this.scrollTop; _this.scale = 1; }); // Reset zoom on slide change this.core.LGel.on(lg_zoom_es5_lGEvents.afterSlide + ".zoom", function (event) { var prevIndex = event.detail.prevIndex; _this.scale = 1; _this.positionChanged = false; _this.resetZoom(prevIndex); _this.resetImageTranslate(prevIndex); if (_this.isImageSlide(_this.core.index)) { _this.setZoomEssentials(); } }); // Drag option after zoom this.zoomDrag(); this.pinchZoom(); this.zoomSwipe(); // Store the zoomable timeout value just to clear it while closing this.zoomableTimeout = false; this.positionChanged = false; }; Zoom.prototype.zoomIn = function () { // Allow zoom only on image if (!this.isImageSlide(this.core.index)) { return; } var scale = this.scale + this.settings.scale; scale = this.getScale(scale); this.beginZoom(scale); this.zoomImage(scale, Math.min(this.settings.scale, scale - this.scale), true, true); }; // Reset zoom effect Zoom.prototype.resetZoom = function (index) { this.core.outer.removeClass('lg-zoomed lg-zoom-drag-transition'); var $actualSize = this.core.getElementById('lg-actual-size'); var $item = this.core.getSlideItem(index !== undefined ? index : this.core.index); $actualSize .removeClass(this.settings.actualSizeIcons.zoomOut) .addClass(this.settings.actualSizeIcons.zoomIn); $item.find('.lg-img-wrap').first().removeAttr('style'); $item.find('.lg-image').first().removeAttr('style'); this.scale = 1; this.left = 0; this.top = 0; // Reset pagx pagy values to center this.setPageCords(); }; Zoom.prototype.getTouchDistance = function (e) { return Math.sqrt((e.touches[0].pageX - e.touches[1].pageX) * (e.touches[0].pageX - e.touches[1].pageX) + (e.touches[0].pageY - e.touches[1].pageY) * (e.touches[0].pageY - e.touches[1].pageY)); }; Zoom.prototype.pinchZoom = function () { var _this = this; var startDist = 0; var pinchStarted = false; var initScale = 1; var prevScale = 0; var $item = this.core.getSlideItem(this.core.index); this.core.outer.on('touchstart.lg', function (e) { $item = _this.core.getSlideItem(_this.core.index); if (!_this.isImageSlide(_this.core.index)) { return; } if (e.touches.length === 2) { e.preventDefault(); if (_this.core.outer.hasClass('lg-first-slide-loading')) { return; } initScale = _this.scale || 1; _this.core.outer.removeClass('lg-zoom-drag-transition lg-zoom-dragging'); _this.setPageCords(e); _this.resetImageTranslate(_this.core.index); _this.core.touchAction = 'pinch'; startDist = _this.getTouchDistance(e); } }); this.core.$inner.on('touchmove.lg', function (e) { if (e.touches.length === 2 && _this.core.touchAction === 'pinch' && (_this.$LG(e.target).hasClass('lg-item') || $item.get().contains(e.target))) { e.preventDefault(); var endDist = _this.getTouchDistance(e); var distance = startDist - endDist; if (!pinchStarted && Math.abs(distance) > 5) { pinchStarted = true; } if (pinchStarted) { prevScale = _this.scale; var _scale = Math.max(1, initScale + -distance * 0.02); _this.scale = Math.round((_scale + Number.EPSILON) * 100) / 100; var diff = _this.scale - prevScale; _this.zoomImage(_this.scale, Math.round((diff + Number.EPSILON) * 100) / 100, false, false); } } }); this.core.$inner.on('touchend.lg', function (e) { if (_this.core.touchAction === 'pinch' && (_this.$LG(e.target).hasClass('lg-item') || $item.get().contains(e.target))) { pinchStarted = false; startDist = 0; if (_this.scale <= 1) { _this.resetZoom(); } else { var actualSizeScale = _this.getCurrentImageActualSizeScale(); if (_this.scale >= actualSizeScale) { var scaleDiff = actualSizeScale - _this.scale; if (scaleDiff === 0) { scaleDiff = 0.01; } _this.zoomImage(actualSizeScale, scaleDiff, false, true); } _this.manageActualPixelClassNames(); _this.core.outer.addClass('lg-zoomed'); } _this.core.touchAction = undefined; } }); }; Zoom.prototype.touchendZoom = function (startCoords, endCoords, allowX, allowY, touchDuration) { var distanceXnew = endCoords.x - startCoords.x; var distanceYnew = endCoords.y - startCoords.y; var speedX = Math.abs(distanceXnew) / touchDuration + 1; var speedY = Math.abs(distanceYnew) / touchDuration + 1; if (speedX > 2) { speedX += 1; } if (speedY > 2) { speedY += 1; } distanceXnew = distanceXnew * speedX; distanceYnew = distanceYnew * speedY; var _LGel = this.core .getSlideItem(this.core.index) .find('.lg-img-wrap') .first(); var distance = {}; distance.x = this.left + distanceXnew; distance.y = this.top + distanceYnew; var possibleSwipeCords = this.getPossibleSwipeDragCords(); if (Math.abs(distanceXnew) > 15 || Math.abs(distanceYnew) > 15) { if (allowY) { if (this.isBeyondPossibleTop(distance.y, possibleSwipeCords.minY)) { distance.y = possibleSwipeCords.minY; } else if (this.isBeyondPossibleBottom(distance.y, possibleSwipeCords.maxY)) { distance.y = possibleSwipeCords.maxY; } } if (allowX) { if (this.isBeyondPossibleLeft(distance.x, possibleSwipeCords.minX)) { distance.x = possibleSwipeCords.minX; } else if (this.isBeyondPossibleRight(distance.x, possibleSwipeCords.maxX)) { distance.x = possibleSwipeCords.maxX; } } if (allowY) { this.top = distance.y; } else { distance.y = this.top; } if (allowX) { this.left = distance.x; } else { distance.x = this.left; } this.setZoomSwipeStyles(_LGel, distance); this.positionChanged = true; } }; Zoom.prototype.getZoomSwipeCords = function (startCoords, endCoords, allowX, allowY, possibleSwipeCords) { var distance = {}; if (allowY) { distance.y = this.top + (endCoords.y - startCoords.y); if (this.isBeyondPossibleTop(distance.y, possibleSwipeCords.minY)) { var diffMinY = possibleSwipeCords.minY - distance.y; distance.y = possibleSwipeCords.minY - diffMinY / 6; } else if (this.isBeyondPossibleBottom(distance.y, possibleSwipeCords.maxY)) { var diffMaxY = distance.y - possibleSwipeCords.maxY; distance.y = possibleSwipeCords.maxY + diffMaxY / 6; } } else { distance.y = this.top; } if (allowX) { distance.x = this.left + (endCoords.x - startCoords.x); if (this.isBeyondPossibleLeft(distance.x, possibleSwipeCords.minX)) { var diffMinX = possibleSwipeCords.minX - distance.x; distance.x = possibleSwipeCords.minX - diffMinX / 6; } else if (this.isBeyondPossibleRight(distance.x, possibleSwipeCords.maxX)) { var difMaxX = distance.x - possibleSwipeCords.maxX; distance.x = possibleSwipeCords.maxX + difMaxX / 6; } } else { distance.x = this.left; } return distance; }; Zoom.prototype.isBeyondPossibleLeft = function (x, minX) { return x >= minX; }; Zoom.prototype.isBeyondPossibleRight = function (x, maxX) { return x <= maxX; }; Zoom.prototype.isBeyondPossibleTop = function (y, minY) { return y >= minY; }; Zoom.prototype.isBeyondPossibleBottom = function (y, maxY) { return y <= maxY; }; Zoom.prototype.isImageSlide = function (index) { var currentItem = this.core.galleryItems[index]; return this.core.getSlideType(currentItem) === 'image'; }; Zoom.prototype.getPossibleSwipeDragCords = function (scale) { var $image = this.core .getSlideItem(this.core.index) .find('.lg-image') .first(); var bottom = this.core.mediaContainerPosition.bottom; var imgRect = $image.get().getBoundingClientRect(); var imageHeight = imgRect.height; var imageWidth = imgRect.width; if (scale) { imageHeight = imageHeight + scale * imageHeight; imageWidth = imageWidth + scale * imageWidth; } var minY = (imageHeight - this.containerRect.height) / 2; var maxY = (this.containerRect.height - imageHeight) / 2 + bottom; var minX = (imageWidth - this.containerRect.width) / 2; var maxX = (this.containerRect.width - imageWidth) / 2; var possibleSwipeCords = { minY: minY, maxY: maxY, minX: minX, maxX: maxX, }; return possibleSwipeCords; }; Zoom.prototype.setZoomSwipeStyles = function (LGel, distance) { LGel.css('transform', 'translate3d(' + distance.x + 'px, ' + distance.y + 'px, 0)'); }; Zoom.prototype.zoomSwipe = function () { var _this = this; var startCoords = {}; var endCoords = {}; var isMoved = false; // Allow x direction drag var allowX = false; // Allow Y direction drag var allowY = false; var startTime = new Date(); var endTime = new Date(); var possibleSwipeCords; var _LGel; var $item = this.core.getSlideItem(this.core.index); this.core.$inner.on('touchstart.lg', function (e) { // Allow zoom only on image if (!_this.isImageSlide(_this.core.index)) { return; } $item = _this.core.getSlideItem(_this.core.index); if ((_this.$LG(e.target).hasClass('lg-item') || $item.get().contains(e.target)) && e.touches.length === 1 && _this.core.outer.hasClass('lg-zoomed')) { e.preventDefault(); startTime = new Date(); _this.core.touchAction = 'zoomSwipe'; _LGel = _this.core .getSlideItem(_this.core.index) .find('.lg-img-wrap') .first(); var dragAllowedAxises = _this.getDragAllowedAxises(0); allowY = dragAllowedAxises.allowY; allowX = dragAllowedAxises.allowX; if (allowX || allowY) { startCoords = _this.getSwipeCords(e); } possibleSwipeCords = _this.getPossibleSwipeDragCords(); // reset opacity and transition duration _this.core.outer.addClass('lg-zoom-dragging lg-zoom-drag-transition'); } }); this.core.$inner.on('touchmove.lg', function (e) { if (e.touches.length === 1 && _this.core.touchAction === 'zoomSwipe' && (_this.$LG(e.target).hasClass('lg-item') || $item.get().contains(e.target))) { e.preventDefault(); _this.core.touchAction = 'zoomSwipe'; endCoords = _this.getSwipeCords(e); var distance = _this.getZoomSwipeCords(startCoords, endCoords, allowX, allowY, possibleSwipeCords); if (Math.abs(endCoords.x - startCoords.x) > 15 || Math.abs(endCoords.y - startCoords.y) > 15) { isMoved = true; _this.setZoomSwipeStyles(_LGel, distance); } } }); this.core.$inner.on('touchend.lg', function (e) { if (_this.core.touchAction === 'zoomSwipe' && (_this.$LG(e.target).hasClass('lg-item') || $item.get().contains(e.target))) { e.preventDefault(); _this.core.touchAction = undefined; _this.core.outer.removeClass('lg-zoom-dragging'); if (!isMoved) { return; } isMoved = false; endTime = new Date(); var touchDuration = endTime.valueOf() - startTime.valueOf(); _this.touchendZoom(startCoords, endCoords, allowX, allowY, touchDuration); } }); }; Zoom.prototype.zoomDrag = function () { var _this = this; var startCoords = {}; var endCoords = {}; var isDragging = false; var isMoved = false; // Allow x direction drag var allowX = false; // Allow Y direction drag var allowY = false; var startTime; var endTime; var possibleSwipeCords; var _LGel; this.core.outer.on('mousedown.lg.zoom', function (e) { // Allow zoom only on image if (!_this.isImageSlide(_this.core.index)) { return; } var $item = _this.core.getSlideItem(_this.core.index); if (_this.$LG(e.target).hasClass('lg-item') || $item.get().contains(e.target)) { startTime = new Date(); _LGel = _this.core .getSlideItem(_this.core.index) .find('.lg-img-wrap') .first(); var dragAllowedAxises = _this.getDragAllowedAxises(0); allowY = dragAllowedAxises.allowY; allowX = dragAllowedAxises.allowX; if (_this.core.outer.hasClass('lg-zoomed')) { if (_this.$LG(e.target).hasClass('lg-object') && (allowX || allowY)) { e.preventDefault(); startCoords = _this.getDragCords(e); possibleSwipeCords = _this.getPossibleSwipeDragCords(); isDragging = true; _this.core.outer .removeClass('lg-grab') .addClass('lg-grabbing lg-zoom-drag-transition lg-zoom-dragging'); // reset opacity and transition duration } } } }); this.$LG(window).on("mousemove.lg.zoom.global" + this.core.lgId, function (e) { if (isDragging) { isMoved = true; endCoords = _this.getDragCords(e); var distance = _this.getZoomSwipeCords(startCoords, endCoords, allowX, allowY, possibleSwipeCords); _this.setZoomSwipeStyles(_LGel, distance); } }); this.$LG(window).on("mouseup.lg.zoom.global" + this.core.lgId, function (e) { if (isDragging) { endTime = new Date(); isDragging = false; _this.core.outer.removeClass('lg-zoom-dragging'); // Fix for chrome mouse move on click if (isMoved && (startCoords.x !== endCoords.x || startCoords.y !== endCoords.y)) { endCoords = _this.getDragCords(e); var touchDuration = endTime.valueOf() - startTime.valueOf(); _this.touchendZoom(startCoords, endCoords, allowX, allowY, touchDuration); } isMoved = false; } _this.core.outer.removeClass('lg-grabbing').addClass('lg-grab'); }); }; Zoom.prototype.closeGallery = function () { this.resetZoom(); }; Zoom.prototype.destroy = function () { // Unbind all events added by lightGallery zoom plugin this.$LG(window).off(".lg.zoom.global" + this.core.lgId); this.core.LGel.off('.lg.zoom'); this.core.LGel.off('.zoom'); clearTimeout(this.zoomableTimeout); this.zoomableTimeout = false; }; return Zoom; }()); /* harmony default export */ var lg_zoom_es5 = (Zoom); //# sourceMappingURL=lg-zoom.es5.js.map // CONCATENATED MODULE: ./node_modules/pinch-zoom-js/src/pinch-zoom.js /* PinchZoom.js Copyright (c) Manuel Stofer 2013 - today Author: Manuel Stofer (mst@rtp.ch) Version: 2.3.4 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // polyfills if (typeof Object.assign != 'function') { // Must be writable: true, enumerable: false, configurable: true Object.defineProperty(Object, "assign", { value: function assign(target, varArgs) { // .length of function is 2 if (target == null) { // TypeError if undefined or null throw new TypeError('Cannot convert undefined or null to object'); } var to = Object(target); for (var index = 1; index < arguments.length; index++) { var nextSource = arguments[index]; if (nextSource != null) { // Skip over if undefined or null for (var nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey]; } } } } return to; }, writable: true, configurable: true }); } if (typeof Array.from != 'function') { Array.from = function (object) { return [].slice.call(object); }; } // utils var buildElement = function(str) { // empty string as title argument required by IE and Edge var tmp = document.implementation.createHTMLDocument(''); tmp.body.innerHTML = str; return Array.from(tmp.body.children)[0]; }; var triggerEvent = function(el, name) { var event = document.createEvent('HTMLEvents'); event.initEvent(name, true, false); el.dispatchEvent(event); }; var definePinchZoom = function () { /** * Pinch zoom * @param el * @param options * @constructor */ var PinchZoom = function (el, options) { this.el = el; this.zoomFactor = 1; this.lastScale = 1; this.offset = { x: 0, y: 0 }; this.initialOffset = { x: 0, y: 0, }; this.options = Object.assign({}, this.defaults, options); this.setupMarkup(); this.bindEvents(); this.update(); // The image may already be loaded when PinchZoom is initialized, // and then the load event (which trigger update) will never fire. if (this.isImageLoaded(this.el)) { this.updateAspectRatio(); this.setupOffsets(); } this.enable(); }, sum = function (a, b) { return a + b; }, isCloseTo = function (value, expected) { return value > expected - 0.01 && value < expected + 0.01; }; PinchZoom.prototype = { defaults: { tapZoomFactor: 2, zoomOutFactor: 1.3, animationDuration: 300, maxZoom: 4, minZoom: 0.5, draggableUnzoomed: true, lockDragAxis: false, setOffsetsOnce: false, use2d: true, zoomStartEventName: 'pz_zoomstart', zoomUpdateEventName: 'pz_zoomupdate', zoomEndEventName: 'pz_zoomend', dragStartEventName: 'pz_dragstart', dragUpdateEventName: 'pz_dragupdate', dragEndEventName: 'pz_dragend', doubleTapEventName: 'pz_doubletap', verticalPadding: 0, horizontalPadding: 0, onZoomStart: null, onZoomEnd: null, onZoomUpdate: null, onDragStart: null, onDragEnd: null, onDragUpdate: null, onDoubleTap: null }, /** * Event handler for 'dragstart' * @param event */ handleDragStart: function (event) { triggerEvent(this.el, this.options.dragStartEventName); if(typeof this.options.onDragStart == "function"){ this.options.onDragStart(this, event) } this.stopAnimation(); this.lastDragPosition = false; this.hasInteraction = true; this.handleDrag(event); }, /** * Event handler for 'drag' * @param event */ handleDrag: function (event) { var touch = this.getTouches(event)[0]; this.drag(touch, this.lastDragPosition); this.offset = this.sanitizeOffset(this.offset); this.lastDragPosition = touch; }, handleDragEnd: function () { triggerEvent(this.el, this.options.dragEndEventName); if(typeof this.options.onDragEnd == "function"){ this.options.onDragEnd(this, event) } this.end(); }, /** * Event handler for 'zoomstart' * @param event */ handleZoomStart: function (event) { triggerEvent(this.el, this.options.zoomStartEventName); if(typeof this.options.onZoomStart == "function"){ this.options.onZoomStart(this, event) } this.stopAnimation(); this.lastScale = 1; this.nthZoom = 0; this.lastZoomCenter = false; this.hasInteraction = true; }, /** * Event handler for 'zoom' * @param event */ handleZoom: function (event, newScale) { // a relative scale factor is used var touchCenter = this.getTouchCenter(this.getTouches(event)), scale = newScale / this.lastScale; this.lastScale = newScale; // the first touch events are thrown away since they are not precise this.nthZoom += 1; if (this.nthZoom > 3) { this.scale(scale, touchCenter); this.drag(touchCenter, this.lastZoomCenter); } this.lastZoomCenter = touchCenter; }, handleZoomEnd: function () { triggerEvent(this.el, this.options.zoomEndEventName); if(typeof this.options.onZoomEnd == "function"){ this.options.onZoomEnd(this, event) } this.end(); }, /** * Event handler for 'doubletap' * @param event */ handleDoubleTap: function (event) { var center = this.getTouches(event)[0], zoomFactor = this.zoomFactor > 1 ? 1 : this.options.tapZoomFactor, startZoomFactor = this.zoomFactor, updateProgress = (function (progress) { this.scaleTo(startZoomFactor + progress * (zoomFactor - startZoomFactor), center); }).bind(this); if (this.hasInteraction) { return; } this.isDoubleTap = true; if (startZoomFactor > zoomFactor) { center = this.getCurrentZoomCenter(); } this.animate(this.options.animationDuration, updateProgress, this.swing); triggerEvent(this.el, this.options.doubleTapEventName); if(typeof this.options.onDoubleTap == "function"){ this.options.onDoubleTap(this, event) } }, /** * Compute the initial offset * * the element should be centered in the container upon initialization */ computeInitialOffset: function () { this.initialOffset = { x: -Math.abs(this.el.offsetWidth * this.getInitialZoomFactor() - this.container.offsetWidth) / 2, y: -Math.abs(this.el.offsetHeight * this.getInitialZoomFactor() - this.container.offsetHeight) / 2, }; }, /** * Reset current image offset to that of the initial offset */ resetOffset: function() { this.offset.x = this.initialOffset.x; this.offset.y = this.initialOffset.y; }, /** * Determine if image is loaded */ isImageLoaded: function (el) { if (el.nodeName === 'IMG') { return el.complete && el.naturalHeight !== 0; } else { return Array.from(el.querySelectorAll('img')).every(this.isImageLoaded); } }, setupOffsets: function() { if (this.options.setOffsetsOnce && this._isOffsetsSet) { return; } this._isOffsetsSet = true; this.computeInitialOffset(); this.resetOffset(); }, /** * Max / min values for the offset * @param offset * @return {Object} the sanitized offset */ sanitizeOffset: function (offset) { var elWidth = this.el.offsetWidth * this.getInitialZoomFactor() * this.zoomFactor; var elHeight = this.el.offsetHeight * this.getInitialZoomFactor() * this.zoomFactor; var maxX = elWidth - this.getContainerX() + this.options.horizontalPadding, maxY = elHeight - this.getContainerY() + this.options.verticalPadding, maxOffsetX = Math.max(maxX, 0), maxOffsetY = Math.max(maxY, 0), minOffsetX = Math.min(maxX, 0) - this.options.horizontalPadding, minOffsetY = Math.min(maxY, 0) - this.options.verticalPadding; return { x: Math.min(Math.max(offset.x, minOffsetX), maxOffsetX), y: Math.min(Math.max(offset.y, minOffsetY), maxOffsetY) }; }, /** * Scale to a specific zoom factor (not relative) * @param zoomFactor * @param center */ scaleTo: function (zoomFactor, center) { this.scale(zoomFactor / this.zoomFactor, center); }, /** * Scales the element from specified center * @param scale * @param center */ scale: function (scale, center) { scale = this.scaleZoomFactor(scale); this.addOffset({ x: (scale - 1) * (center.x + this.offset.x), y: (scale - 1) * (center.y + this.offset.y) }); triggerEvent(this.el, this.options.zoomUpdateEventName); if(typeof this.options.onZoomUpdate == "function"){ this.options.onZoomUpdate(this, event) } }, /** * Scales the zoom factor relative to current state * @param scale * @return the actual scale (can differ because of max min zoom factor) */ scaleZoomFactor: function (scale) { var originalZoomFactor = this.zoomFactor; this.zoomFactor *= scale; this.zoomFactor = Math.min(this.options.maxZoom, Math.max(this.zoomFactor, this.options.minZoom)); return this.zoomFactor / originalZoomFactor; }, /** * Determine if the image is in a draggable state * * When the image can be dragged, the drag event is acted upon and cancelled. * When not draggable, the drag event bubbles through this component. * * @return {Boolean} */ canDrag: function () { return this.options.draggableUnzoomed || !isCloseTo(this.zoomFactor, 1); }, /** * Drags the element * @param center * @param lastCenter */ drag: function (center, lastCenter) { if (lastCenter) { if(this.options.lockDragAxis) { // lock scroll to position that was changed the most if(Math.abs(center.x - lastCenter.x) > Math.abs(center.y - lastCenter.y)) { this.addOffset({ x: -(center.x - lastCenter.x), y: 0 }); } else { this.addOffset({ y: -(center.y - lastCenter.y), x: 0 }); } } else { this.addOffset({ y: -(center.y - lastCenter.y), x: -(center.x - lastCenter.x) }); } triggerEvent(this.el, this.options.dragUpdateEventName); if(typeof this.options.onDragUpdate == "function"){ this.options.onDragUpdate(this, event) } } }, /** * Calculates the touch center of multiple touches * @param touches * @return {Object} */ getTouchCenter: function (touches) { return this.getVectorAvg(touches); }, /** * Calculates the average of multiple vectors (x, y values) */ getVectorAvg: function (vectors) { return { x: vectors.map(function (v) { return v.x; }).reduce(sum) / vectors.length, y: vectors.map(function (v) { return v.y; }).reduce(sum) / vectors.length }; }, /** * Adds an offset * @param offset the offset to add * @return return true when the offset change was accepted */ addOffset: function (offset) { this.offset = { x: this.offset.x + offset.x, y: this.offset.y + offset.y }; }, sanitize: function () { if (this.zoomFactor < this.options.zoomOutFactor) { this.zoomOutAnimation(); } else if (this.isInsaneOffset(this.offset)) { this.sanitizeOffsetAnimation(); } }, /** * Checks if the offset is ok with the current zoom factor * @param offset * @return {Boolean} */ isInsaneOffset: function (offset) { var sanitizedOffset = this.sanitizeOffset(offset); return sanitizedOffset.x !== offset.x || sanitizedOffset.y !== offset.y; }, /** * Creates an animation moving to a sane offset */ sanitizeOffsetAnimation: function () { var targetOffset = this.sanitizeOffset(this.offset), startOffset = { x: this.offset.x, y: this.offset.y }, updateProgress = (function (progress) { this.offset.x = startOffset.x + progress * (targetOffset.x - startOffset.x); this.offset.y = startOffset.y + progress * (targetOffset.y - startOffset.y); this.update(); }).bind(this); this.animate( this.options.animationDuration, updateProgress, this.swing ); }, /** * Zooms back to the original position, * (no offset and zoom factor 1) */ zoomOutAnimation: function () { if (this.zoomFactor === 1) { return; } var startZoomFactor = this.zoomFactor, zoomFactor = 1, center = this.getCurrentZoomCenter(), updateProgress = (function (progress) { this.scaleTo(startZoomFactor + progress * (zoomFactor - startZoomFactor), center); }).bind(this); this.animate( this.options.animationDuration, updateProgress, this.swing ); }, /** * Updates the container aspect ratio * * Any previous container height must be cleared before re-measuring the * parent height, since it depends implicitly on the height of any of its children */ updateAspectRatio: function () { this.unsetContainerY(); this.setContainerY(this.container.parentElement.offsetHeight); }, /** * Calculates the initial zoom factor (for the element to fit into the container) * @return {number} the initial zoom factor */ getInitialZoomFactor: function () { var xZoomFactor = this.container.offsetWidth / this.el.offsetWidth; var yZoomFactor = this.container.offsetHeight / this.el.offsetHeight; return Math.min(xZoomFactor, yZoomFactor); }, /** * Calculates the aspect ratio of the element * @return the aspect ratio */ getAspectRatio: function () { return this.el.offsetWidth / this.el.offsetHeight; }, /** * Calculates the virtual zoom center for the current offset and zoom factor * (used for reverse zoom) * @return {Object} the current zoom center */ getCurrentZoomCenter: function () { var offsetLeft = this.offset.x - this.initialOffset.x; var centerX = -1 * this.offset.x - offsetLeft / (1 / this.zoomFactor - 1); var offsetTop = this.offset.y - this.initialOffset.y; var centerY = -1 * this.offset.y - offsetTop / (1 / this.zoomFactor - 1); return { x: centerX, y: centerY }; }, /** * Returns the touches of an event relative to the container offset * @param event * @return array touches */ getTouches: function (event) { var rect = this.container.getBoundingClientRect(); var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; var posTop = rect.top + scrollTop; var posLeft = rect.left + scrollLeft; return Array.prototype.slice.call(event.touches).map(function (touch) { return { x: touch.pageX - posLeft, y: touch.pageY - posTop, }; }); }, /** * Animation loop * does not support simultaneous animations * @param duration * @param framefn * @param timefn * @param callback */ animate: function (duration, framefn, timefn, callback) { var startTime = new Date().getTime(), renderFrame = (function () { if (!this.inAnimation) { return; } var frameTime = new Date().getTime() - startTime, progress = frameTime / duration; if (frameTime >= duration) { framefn(1); if (callback) { callback(); } this.update(); this.stopAnimation(); this.update(); } else { if (timefn) { progress = timefn(progress); } framefn(progress); this.update(); requestAnimationFrame(renderFrame); } }).bind(this); this.inAnimation = true; requestAnimationFrame(renderFrame); }, /** * Stops the animation */ stopAnimation: function () { this.inAnimation = false; }, /** * Swing timing function for animations * @param p * @return {Number} */ swing: function (p) { return -Math.cos(p * Math.PI) / 2 + 0.5; }, getContainerX: function () { return this.container.offsetWidth; }, getContainerY: function () { return this.container.offsetHeight; }, setContainerY: function (y) { return this.container.style.height = y + 'px'; }, unsetContainerY: function () { this.container.style.height = null; }, /** * Creates the expected html structure */ setupMarkup: function () { this.container = buildElement('
'); this.el.parentNode.insertBefore(this.container, this.el); this.container.appendChild(this.el); this.container.style.overflow = 'hidden'; this.container.style.position = 'relative'; this.el.style.webkitTransformOrigin = '0% 0%'; this.el.style.mozTransformOrigin = '0% 0%'; this.el.style.msTransformOrigin = '0% 0%'; this.el.style.oTransformOrigin = '0% 0%'; this.el.style.transformOrigin = '0% 0%'; this.el.style.position = 'absolute'; }, end: function () { this.hasInteraction = false; this.sanitize(); this.update(); }, /** * Binds all required event listeners */ bindEvents: function () { var self = this; detectGestures(this.container, this); window.addEventListener('resize', this.update.bind(this)); Array.from(this.el.querySelectorAll('img')).forEach(function(imgEl) { imgEl.addEventListener('load', self.update.bind(self)); }); if (this.el.nodeName === 'IMG') { this.el.addEventListener('load', this.update.bind(this)); } }, /** * Updates the css values according to the current zoom factor and offset */ update: function (event) { if (this.updatePlaned) { return; } this.updatePlaned = true; window.setTimeout((function () { this.updatePlaned = false; if (event && event.type === 'resize') { this.updateAspectRatio(); this.setupOffsets(); } if (event && event.type === 'load') { this.updateAspectRatio(); this.setupOffsets(); } var zoomFactor = this.getInitialZoomFactor() * this.zoomFactor, offsetX = -this.offset.x / zoomFactor, offsetY = -this.offset.y / zoomFactor, transform3d = 'scale3d(' + zoomFactor + ', ' + zoomFactor + ',1) ' + 'translate3d(' + offsetX + 'px,' + offsetY + 'px,0px)', transform2d = 'scale(' + zoomFactor + ', ' + zoomFactor + ') ' + 'translate(' + offsetX + 'px,' + offsetY + 'px)', removeClone = (function () { if (this.clone) { this.clone.parentNode.removeChild(this.clone); delete this.clone; } }).bind(this); // Scale 3d and translate3d are faster (at least on ios) // but they also reduce the quality. // PinchZoom uses the 3d transformations during interactions // after interactions it falls back to 2d transformations if (!this.options.use2d || this.hasInteraction || this.inAnimation) { this.is3d = true; removeClone(); this.el.style.webkitTransform = transform3d; this.el.style.mozTransform = transform2d; this.el.style.msTransform = transform2d; this.el.style.oTransform = transform2d; this.el.style.transform = transform3d; } else { // When changing from 3d to 2d transform webkit has some glitches. // To avoid this, a copy of the 3d transformed element is displayed in the // foreground while the element is converted from 3d to 2d transform if (this.is3d) { this.clone = this.el.cloneNode(true); this.clone.style.pointerEvents = 'none'; this.container.appendChild(this.clone); window.setTimeout(removeClone, 200); } this.el.style.webkitTransform = transform2d; this.el.style.mozTransform = transform2d; this.el.style.msTransform = transform2d; this.el.style.oTransform = transform2d; this.el.style.transform = transform2d; this.is3d = false; } }).bind(this), 0); }, /** * Enables event handling for gestures */ enable: function() { this.enabled = true; }, /** * Disables event handling for gestures */ disable: function() { this.enabled = false; } }; var detectGestures = function (el, target) { var interaction = null, fingers = 0, lastTouchStart = null, startTouches = null, setInteraction = function (newInteraction, event) { if (interaction !== newInteraction) { if (interaction && !newInteraction) { switch (interaction) { case "zoom": target.handleZoomEnd(event); break; case 'drag': target.handleDragEnd(event); break; } } switch (newInteraction) { case 'zoom': target.handleZoomStart(event); break; case 'drag': target.handleDragStart(event); break; } } interaction = newInteraction; }, updateInteraction = function (event) { if (fingers === 2) { setInteraction('zoom'); } else if (fingers === 1 && target.canDrag()) { setInteraction('drag', event); } else { setInteraction(null, event); } }, targetTouches = function (touches) { return Array.from(touches).map(function (touch) { return { x: touch.pageX, y: touch.pageY }; }); }, getDistance = function (a, b) { var x, y; x = a.x - b.x; y = a.y - b.y; return Math.sqrt(x * x + y * y); }, calculateScale = function (startTouches, endTouches) { var startDistance = getDistance(startTouches[0], startTouches[1]), endDistance = getDistance(endTouches[0], endTouches[1]); return endDistance / startDistance; }, cancelEvent = function (event) { event.stopPropagation(); event.preventDefault(); }, detectDoubleTap = function (event) { var time = (new Date()).getTime(); if (fingers > 1) { lastTouchStart = null; } if (time - lastTouchStart < 300) { cancelEvent(event); target.handleDoubleTap(event); switch (interaction) { case "zoom": target.handleZoomEnd(event); break; case 'drag': target.handleDragEnd(event); break; } } else { target.isDoubleTap = false; } if (fingers === 1) { lastTouchStart = time; } }, firstMove = true; el.addEventListener('touchstart', function (event) { if(target.enabled) { firstMove = true; fingers = event.touches.length; detectDoubleTap(event); } }); el.addEventListener('touchmove', function (event) { if(target.enabled && !target.isDoubleTap) { if (firstMove) { updateInteraction(event); if (interaction) { cancelEvent(event); } startTouches = targetTouches(event.touches); } else { switch (interaction) { case 'zoom': if (startTouches.length == 2 && event.touches.length == 2) { target.handleZoom(event, calculateScale(startTouches, targetTouches(event.touches))); } break; case 'drag': target.handleDrag(event); break; } if (interaction) { cancelEvent(event); target.update(); } } firstMove = false; } }); el.addEventListener('touchend', function (event) { if(target.enabled) { fingers = event.touches.length; updateInteraction(event); } }); }; return PinchZoom; }; var PinchZoom = definePinchZoom(); /* harmony default export */ var pinch_zoom = (PinchZoom); // EXTERNAL MODULE: ./cartridges/app_tfg/cartridge/client/default/js/util/domutils.js + 1 modules var domutils = __webpack_require__("./cartridges/app_tfg/cartridge/client/default/js/util/domutils.js"); // EXTERNAL MODULE: ./cartridges/app_tfg/cartridge/client/default/js/product/components/videoPlayer.js var videoPlayer = __webpack_require__("./cartridges/app_tfg/cartridge/client/default/js/product/components/videoPlayer.js"); // CONCATENATED MODULE: ./cartridges/app_tfg/cartridge/client/default/js/product/components/imageGallery.js /* eslint-disable no-unused-vars */ const GLOBALS = { PINCH_ZOOM: [], PINCH_ZOOM_TOGGLED: false, PLUGIN: null }; const EVENTS = { PINCH_ZOOM_START: 'pinch-zoom:start', PINCH_ZOOM_END: 'pinch-zoom:end' }; const SELECTORS = { GALLERY: '.primary-images__wrapper', IMAGE_WRAPPER: '.primary-images__image-wrapper', TOOLBAR: '.lg-toolbar', SLIDE: '.lg-item', MAIN_IMAGE: '.lg-image' }; const PDP_GALLERY_EVENTS = { OPEN: 'gallery:open' }; const addMouseMoveEvent = image => { if (image) { image.style.top = '0'; image.addEventListener('mousemove', mouseEvent => { const toolbar = document.querySelector(SELECTORS.TOOLBAR); const imgHeight = image.clientHeight; const windowHeight = window.outerHeight; const toolbarHeight = toolbar && toolbar.clientHeight || 0; const mouseY = mouseEvent.clientY - toolbarHeight; const verticalOffsetPercent = mouseY / windowHeight * 100; const imageOffset = imgHeight / 100 * verticalOffsetPercent; const calculatedOffset = Math.min(imgHeight - windowHeight, imageOffset); image.style.top = `-${calculatedOffset}px`; }); image.dataset.scrollInitialized = 'true'; } }; const handleZoomOutVideo = () => { const currentVideoSlide = document.querySelector('.lg-current .lg-video-cont'); if (currentVideoSlide) { document.querySelector('.lg-video-cont').style.height = `${window.innerHeight - document.querySelector('.lg-thumb-outer').offsetHeight}px`; } }; const initGallery = container => { const enableZoomControls = document.querySelector(SELECTORS.GALLERY).dataset.zoomControls; document.querySelectorAll(SELECTORS.IMAGE_WRAPPER).forEach(imageWrapper => { imageWrapper.dataset.width = window.outerWidth; }); // eslint-disable-next-line prefer-const let plugin = lightgallery_es5(container, { plugins: [lg_zoom_es5, lg_thumbnail_es5, lg_video_es5], thumbnail: true, enableDrag: false, download: false, controls: false, actualSize: false, counter: false, autoplayVideoOnSlide: container.dataset.autoplayvideo === 'true', gotoNextSlideOnVideoEnd: container.dataset.gotonextslideonvideoend === 'true', zoomFromOrigin: false, vimeoPlayerParams: { controls: true, loop: container.dataset.playvideoinloop === 'true', autopause: true, autoPlay: container.dataset.autoplayvideo === 'true', responsive: true } }); container.addEventListener('lgBeforeOpen', () => { document.dispatchEvent(new CustomEvent(PDP_GALLERY_EVENTS.OPEN)); }); container.addEventListener('lgAfterOpen', () => { const maincontainer = document.querySelectorAll('.lg-container'); if (maincontainer.length > 1) { maincontainer[0].remove(); } }); container.addEventListener('lgAfterSlide', () => { const zoomIn = document.querySelector('.lg #lg-zoom-in'); if (zoomIn) { zoomIn.classList.remove('inactive'); } }); container.addEventListener('lgSlideItemLoad', () => { handleZoomOutVideo(); const slides = document.querySelectorAll(`${SELECTORS.SLIDE}`); slides.forEach(slide => { const image = slide && slide.querySelector(SELECTORS.MAIN_IMAGE); addMouseMoveEvent(image); }); }); container.addEventListener('lgAfterClose', () => { const videoEle = document.getElementById('product-video'); if (videoEle && !videoEle.classList.contains('d-none')) { const playButton = document.querySelector('.play-button'); if (playButton) { if (playButton.classList.contains('d-none')) { playButton.classList.remove('d-none'); } } } }); if (enableZoomControls === 'true') { container.addEventListener('lgAfterOpen', () => { const thumbnailArea = document.querySelector('.lg-thumb-outer .lg-thumb.group'); const zoomIconsWrapper = document.createElement('div'); const searchIcon = document.createElement('i'); const zoomIcons = { out: document.querySelector('.lg #lg-zoom-out'), in: document.querySelector('.lg #lg-zoom-in') }; zoomIcons.in.classList.remove('lg-icon'); zoomIcons.out.classList.remove('lg-icon'); zoomIcons.in.classList.add('border', 'border-primary', 'font-icon', 'icon-plus', 'text-center', 'mx-4'); zoomIcons.out.classList.add('border', 'border-primary', 'font-icon', 'icon-minus', 'text-center', 'mx-4'); searchIcon.classList.add('lg-zoom-icon', 'font-icon', 'icon-fa-search'); zoomIconsWrapper.classList.add('lg-toolbar-custom'); zoomIconsWrapper.appendChild(zoomIcons.out); zoomIconsWrapper.appendChild(searchIcon); zoomIconsWrapper.appendChild(zoomIcons.in); thumbnailArea.appendChild(zoomIconsWrapper); zoomIcons.in.addEventListener('click', () => { const zoomLevel = document.querySelector('.lg-current .lg-image').dataset.scale; if (zoomLevel > 10) { zoomIcons.in.classList.add('inactive'); } else { zoomIcons.in.classList.remove('inactive'); } }); zoomIcons.out.addEventListener('click', () => { zoomIcons.in.classList.remove('inactive'); }); }); } return plugin; }; const handlePinchZoom = container => { if (!container.dataset.initialized) { const images = container.querySelectorAll('img'); images.forEach(imgElement => { const pinchZoomObj = new pinch_zoom(imgElement, { draggableUnzoomed: false, minZoom: 1, setOffsetsOnce: false, onZoomUpdate: zoomObj => { const zoomStart = zoomObj.zoomFactor > 1 && !GLOBALS.PINCH_ZOOM_TOGGLED; const zoomEnd = zoomObj.zoomFactor <= 1 && GLOBALS.PINCH_ZOOM_TOGGLED; if (zoomStart) { GLOBALS.PINCH_ZOOM_TOGGLED = true; document.dispatchEvent(new CustomEvent(EVENTS.PINCH_ZOOM_START)); } else if (zoomEnd) { GLOBALS.PINCH_ZOOM_TOGGLED = false; document.dispatchEvent(new CustomEvent(EVENTS.PINCH_ZOOM_END)); } } }); GLOBALS.PINCH_ZOOM.push(pinchZoomObj); }); container.dataset.initialized = 'true'; } else if (GLOBALS.PINCH_ZOOM.length > 0) { GLOBALS.PINCH_ZOOM.forEach(pinchZoomObj => { pinchZoomObj.update({ type: 'resize' }); if (pinchZoomObj.el.classList.contains('product-video-slot')) { setTimeout(() => { handleZoomOutVideo(); }, 0); } }); } }; const initImageGallery = () => { const imgObj = document.querySelectorAll('.zoom-image'); const videoButton = document.querySelector('.play-button'); const container = document.querySelector(SELECTORS.GALLERY); let galleryId = container.getAttribute('lg-uid'); const imageWrappers = container.querySelectorAll(SELECTORS.IMAGE_WRAPPER); GLOBALS.PLUGIN = lightgallery_es5(); if (Object(domutils["isLG"])()) { imgObj.forEach(item => { item.addEventListener('click', () => { if (GLOBALS.PLUGIN && GLOBALS.PLUGIN.items) { GLOBALS.PLUGIN.destroy(); galleryId = false; } if (!galleryId) { GLOBALS.PLUGIN = initGallery(container); } }); }); } else if (!Object(domutils["isLG"])() && galleryId && window.lgData && window.lgData[galleryId]) { GLOBALS.PLUGIN.destroy(); } handlePinchZoom(container); if (videoButton) { videoButton.addEventListener('click', () => { if (Object(domutils["isLG"])()) { if (GLOBALS.PLUGIN && GLOBALS.PLUGIN.items) { GLOBALS.PLUGIN.destroy(); } GLOBALS.PLUGIN = initGallery(container); } Object(videoPlayer["default"])(); }); } }; /***/ }), /***/ "./cartridges/app_tfg/cartridge/client/default/js/product/components/videoPlayer.js": /*!******************************************************************************************!*\ !*** ./cartridges/app_tfg/cartridge/client/default/js/product/components/videoPlayer.js ***! \******************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js"); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__); const playButton = document.querySelector('.play-button'); const pauseButton = document.querySelector('.pause-button'); function displayPlayButton() { if (playButton) { if (playButton.classList.contains('d-none')) { playButton.classList.remove('d-none'); } } } function hidePlayButton() { if (playButton) { if (!playButton.classList.contains('d-none')) { playButton.classList.add('d-none'); } } } function displayPauseButton() { if (pauseButton) { if (pauseButton.classList.contains('d-none')) { pauseButton.classList.remove('d-none'); } } } function hidePauseButton() { if (pauseButton) { if (!pauseButton.classList.contains('d-none')) { pauseButton.classList.add('d-none'); } } } function playVideo(isPlayVideo) { const bannerImgElement = document.querySelector('.product-video-slot'); const videoWrapper = document.querySelector('.primary-images__video-wrapper'); const videoEle = document.getElementById('product-video'); const imageCarousel = document.querySelector('.primary-images__carousel'); const container = document.querySelector('.primary-images__wrapper'); const imageElement = document.querySelector('.primary-images__image-wrapper__inner'); const videoElement = document.querySelector('.primary-images__video-wrapper__inner'); let options; if (videoEle) { if (isPlayVideo === 'true') { if (bannerImgElement) { bannerImgElement.classList.add('d-none'); } videoEle.classList.remove('d-none'); hidePlayButton(); } if (imageCarousel.classList.contains('carousel')) { options = { id: videoEle.dataset.videoid, autoplay: videoWrapper.dataset.autoplayvideo === 'true', width: imageElement.offsetWidth, height: imageElement.offsetHeight, muted: true, controls: false, loop: container.dataset.playvideoinloop === 'true', autopause: true, responsive: true }; } else { options = { id: videoEle.dataset.videoid, autoplay: videoWrapper.dataset.autoplayvideo === 'true', width: videoElement.offsetWidth, height: videoElement.offsetHeight, muted: true, controls: false, loop: container.dataset.playvideoinloop === 'true', autopause: true, responsive: true }; } // eslint-disable-next-line no-undef const videoPlayer = new Vimeo.Player(videoEle, options); if (imageCarousel.classList.contains('carousel')) { if (videoWrapper.classList.contains('active') && isPlayVideo === 'true' && !videoEle.classList.contains('d-none')) { hidePlayButton(); hidePauseButton(); videoPlayer.play(); } else { displayPlayButton(); hidePauseButton(); videoPlayer.pause(); } } else if (isPlayVideo === 'true' && !videoEle.classList.contains('d-none')) { hidePlayButton(); hidePauseButton(); videoPlayer.play(); } else { displayPlayButton(); hidePauseButton(); videoPlayer.pause(); } videoPlayer.on('ended', () => { displayPlayButton(); hidePauseButton(); }); return videoPlayer; } return null; } /* harmony default export */ __webpack_exports__["default"] = (() => { const videoWrapper = document.querySelector('.primary-images__video-wrapper'); const carouselControlNext = document.querySelector('.primary-images__carousel .carousel-control-next'); const carouselControlPrev = document.querySelector('.primary-images__carousel .carousel-control-prev'); let thumbPlayBtn = document.querySelector('.pdp-video-thumb-playButton'); const videoEle = document.getElementById('product-video'); const thumbImgs = document.querySelectorAll('.lg-thumb-item'); const imageCarousel = document.querySelector('.primary-images__carousel'); let touchstartY = 0; let touchendY = 0; if (thumbImgs.length > 0 && videoWrapper && videoEle) { if (!thumbPlayBtn) { const videoSlot = +videoWrapper.dataset.videoslot; const thumbBtn = document.createElement('img'); thumbBtn.classList.add('pdp-video-thumb-playButton'); thumbBtn.src = videoWrapper.dataset.thumbBtnSrc; thumbBtn.dataset.lgItemId = videoWrapper.dataset.videoslot; thumbImgs[videoSlot].appendChild(thumbBtn); thumbPlayBtn = thumbBtn; } } if (videoWrapper) { let player; jquery__WEBPACK_IMPORTED_MODULE_0___default()(carouselControlNext).on('click', () => { setTimeout(() => { player = playVideo(videoWrapper.dataset.autoplayvideo); }, 1000); }); jquery__WEBPACK_IMPORTED_MODULE_0___default()(carouselControlPrev).on('click', () => { setTimeout(() => { player = playVideo(videoWrapper.dataset.autoplayvideo); }, 1000); }); jquery__WEBPACK_IMPORTED_MODULE_0___default()(playButton).on('click', () => { setTimeout(() => { player = playVideo('true'); }, 1000); }); jquery__WEBPACK_IMPORTED_MODULE_0___default()(pauseButton).on('click', () => { player = playVideo('false'); }); jquery__WEBPACK_IMPORTED_MODULE_0___default()(thumbPlayBtn).on('click', () => { setTimeout(() => { if (jquery__WEBPACK_IMPORTED_MODULE_0___default()('.lg-video-play-button')) { jquery__WEBPACK_IMPORTED_MODULE_0___default()('.lg-video-play-button').click(); } }, 1500); }); if (videoWrapper.dataset.autoplayvideo) { player = playVideo(videoWrapper.dataset.autoplayvideo); } jquery__WEBPACK_IMPORTED_MODULE_0___default()(document.querySelector('.primary-images__video-link-button')).on('click', () => { setTimeout(() => { player = playVideo(videoWrapper.dataset.autoplayvideo); }, 1000); }); jquery__WEBPACK_IMPORTED_MODULE_0___default()(imageCarousel).on('touchstart', e => { if (imageCarousel.classList.contains('carousel')) { if (videoWrapper.classList.contains('active') && !videoEle.classList.contains('d-none')) { if (playButton) { if (playButton.classList.contains('d-none')) { player.getPaused().then(paused => { if (!paused) { displayPauseButton(); } }); } } } } touchstartY = e.changedTouches[0].screenY; }); jquery__WEBPACK_IMPORTED_MODULE_0___default()(imageCarousel).on('touchend', e => { touchendY = e.changedTouches[0].screenY; if (touchendY !== touchstartY) { if (imageCarousel.classList.contains('carousel')) { if (!videoWrapper.classList.contains('active') && videoEle.classList.contains('d-none')) { setTimeout(() => { player = playVideo('false'); }, 1000); } else { setTimeout(() => { player = playVideo(videoWrapper.dataset.autoplayvideo); }, 1000); } } } }); } }); /***/ }), /***/ "./cartridges/app_tfg/cartridge/client/default/js/thirdParty/bootstrap/carouselSwipe.js": /*!**********************************************************************************************!*\ !*** ./cartridges/app_tfg/cartridge/client/default/js/thirdParty/bootstrap/carouselSwipe.js ***! \**********************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js"); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__); /** * Bootstrap Carousel Swipe v1.1 * * jQuery plugin to enable swipe gestures on Bootstrap 3 carousels. * Examples and documentation: https://github.com/maaaaark/bcSwipe * * Licensed under the MIT license. */ function bcSwipe(carousel, settings) { let config = { threshold: 50 }; if (settings) { config = Object.assign(config, settings); } let stillMoving = false; let start; if ('ontouchstart' in document.documentElement) { carousel.addEventListener('touchstart', onTouchStart, false); } function onTouchStart(e) { if (e.target.dataset.swipeDisabled !== 'true' && e.touches.length === 1) { start = e.touches[0].pageX; stillMoving = true; carousel.addEventListener('touchmove', onTouchMove, false); } } function onTouchMove(e) { if (stillMoving) { const x = e.touches[0].pageX; const difference = start - x; if (Math.abs(difference) >= config.threshold) { cancelTouch(); if (difference > 0) { jquery__WEBPACK_IMPORTED_MODULE_0___default()(carousel).carousel('next'); } else { jquery__WEBPACK_IMPORTED_MODULE_0___default()(carousel).carousel('prev'); } } } } function cancelTouch() { carousel.removeEventListener('touchmove', onTouchMove); start = null; stillMoving = false; } return this; } /* harmony default export */ __webpack_exports__["default"] = ((carousel, settings) => bcSwipe(carousel, settings)); /***/ }), /***/ "./node_modules/tippy.js/node_modules/popper.js/dist/esm/popper.js": /*!*************************************************************************!*\ !*** ./node_modules/tippy.js/node_modules/popper.js/dist/esm/popper.js ***! \*************************************************************************/ /*! exports provided: default */ /*! ModuleConcatenation bailout: Module uses injected variables (global) */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(global) {/**! * @fileOverview Kickass library to create and place poppers near their reference elements. * @version 1.14.7 * @license * Copyright (c) 2016 Federico Zivolo and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'; var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox']; var timeoutDuration = 0; for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) { if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) { timeoutDuration = 1; break; } } function microtaskDebounce(fn) { var called = false; return function () { if (called) { return; } called = true; window.Promise.resolve().then(function () { called = false; fn(); }); }; } function taskDebounce(fn) { var scheduled = false; return function () { if (!scheduled) { scheduled = true; setTimeout(function () { scheduled = false; fn(); }, timeoutDuration); } }; } var supportsMicroTasks = isBrowser && window.Promise; /** * Create a debounced version of a method, that's asynchronously deferred * but called in the minimum time possible. * * @method * @memberof Popper.Utils * @argument {Function} fn * @returns {Function} */ var debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce; /** * Check if the given variable is a function * @method * @memberof Popper.Utils * @argument {Any} functionToCheck - variable to check * @returns {Boolean} answer to: is a function? */ function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } /** * Get CSS computed property of the given element * @method * @memberof Popper.Utils * @argument {Eement} element * @argument {String} property */ function getStyleComputedProperty(element, property) { if (element.nodeType !== 1) { return []; } // NOTE: 1 DOM access here var window = element.ownerDocument.defaultView; var css = window.getComputedStyle(element, null); return property ? css[property] : css; } /** * Returns the parentNode or the host of the element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} parent */ function getParentNode(element) { if (element.nodeName === 'HTML') { return element; } return element.parentNode || element.host; } /** * Returns the scrolling parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} scroll parent */ function getScrollParent(element) { // Return body, `getScroll` will take care to get the correct `scrollTop` from it if (!element) { return document.body; } switch (element.nodeName) { case 'HTML': case 'BODY': return element.ownerDocument.body; case '#document': return element.body; } // Firefox want us to check `-x` and `-y` variations as well var _getStyleComputedProp = getStyleComputedProperty(element), overflow = _getStyleComputedProp.overflow, overflowX = _getStyleComputedProp.overflowX, overflowY = _getStyleComputedProp.overflowY; if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) { return element; } return getScrollParent(getParentNode(element)); } var isIE11 = isBrowser && !!(window.MSInputMethodContext && document.documentMode); var isIE10 = isBrowser && /MSIE 10/.test(navigator.userAgent); /** * Determines if the browser is Internet Explorer * @method * @memberof Popper.Utils * @param {Number} version to check * @returns {Boolean} isIE */ function isIE(version) { if (version === 11) { return isIE11; } if (version === 10) { return isIE10; } return isIE11 || isIE10; } /** * Returns the offset parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} offset parent */ function getOffsetParent(element) { if (!element) { return document.documentElement; } var noOffsetParent = isIE(10) ? document.body : null; // NOTE: 1 DOM access here var offsetParent = element.offsetParent || null; // Skip hidden elements which don't have an offsetParent while (offsetParent === noOffsetParent && element.nextElementSibling) { offsetParent = (element = element.nextElementSibling).offsetParent; } var nodeName = offsetParent && offsetParent.nodeName; if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { return element ? element.ownerDocument.documentElement : document.documentElement; } // .offsetParent will return the closest TH, TD or TABLE in case // no offsetParent is present, I hate this job... if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') { return getOffsetParent(offsetParent); } return offsetParent; } function isOffsetContainer(element) { var nodeName = element.nodeName; if (nodeName === 'BODY') { return false; } return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element; } /** * Finds the root node (document, shadowDOM root) of the given element * @method * @memberof Popper.Utils * @argument {Element} node * @returns {Element} root node */ function getRoot(node) { if (node.parentNode !== null) { return getRoot(node.parentNode); } return node; } /** * Finds the offset parent common to the two provided nodes * @method * @memberof Popper.Utils * @argument {Element} element1 * @argument {Element} element2 * @returns {Element} common offset parent */ function findCommonOffsetParent(element1, element2) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { return document.documentElement; } // Here we make sure to give as "start" the element that comes first in the DOM var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING; var start = order ? element1 : element2; var end = order ? element2 : element1; // Get common ancestor container var range = document.createRange(); range.setStart(start, 0); range.setEnd(end, 0); var commonAncestorContainer = range.commonAncestorContainer; // Both nodes are inside #document if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) { if (isOffsetContainer(commonAncestorContainer)) { return commonAncestorContainer; } return getOffsetParent(commonAncestorContainer); } // one of the nodes is inside shadowDOM, find which one var element1root = getRoot(element1); if (element1root.host) { return findCommonOffsetParent(element1root.host, element2); } else { return findCommonOffsetParent(element1, getRoot(element2).host); } } /** * Gets the scroll value of the given element in the given side (top and left) * @method * @memberof Popper.Utils * @argument {Element} element * @argument {String} side `top` or `left` * @returns {number} amount of scrolled pixels */ function getScroll(element) { var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top'; var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft'; var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { var html = element.ownerDocument.documentElement; var scrollingElement = element.ownerDocument.scrollingElement || html; return scrollingElement[upperSide]; } return element[upperSide]; } /* * Sum or subtract the element scroll values (left and top) from a given rect object * @method * @memberof Popper.Utils * @param {Object} rect - Rect object you want to change * @param {HTMLElement} element - The element from the function reads the scroll values * @param {Boolean} subtract - set to true if you want to subtract the scroll values * @return {Object} rect - The modifier rect object */ function includeScroll(rect, element) { var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); var modifier = subtract ? -1 : 1; rect.top += scrollTop * modifier; rect.bottom += scrollTop * modifier; rect.left += scrollLeft * modifier; rect.right += scrollLeft * modifier; return rect; } /* * Helper to detect borders of a given element * @method * @memberof Popper.Utils * @param {CSSStyleDeclaration} styles * Result of `getStyleComputedProperty` on the given element * @param {String} axis - `x` or `y` * @return {number} borders - The borders size of the given axis */ function getBordersSize(styles, axis) { var sideA = axis === 'x' ? 'Left' : 'Top'; var sideB = sideA === 'Left' ? 'Right' : 'Bottom'; return parseFloat(styles['border' + sideA + 'Width'], 10) + parseFloat(styles['border' + sideB + 'Width'], 10); } function getSize(axis, body, html, computedStyle) { return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE(10) ? parseInt(html['offset' + axis]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')]) : 0); } function getWindowSizes(document) { var body = document.body; var html = document.documentElement; var computedStyle = isIE(10) && getComputedStyle(html); return { height: getSize('Height', body, html, computedStyle), width: getSize('Width', body, html, computedStyle) }; } var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** * Given element offsets, generate an output similar to getBoundingClientRect * @method * @memberof Popper.Utils * @argument {Object} offsets * @returns {Object} ClientRect like output */ function getClientRect(offsets) { return _extends({}, offsets, { right: offsets.left + offsets.width, bottom: offsets.top + offsets.height }); } /** * Get bounding client rect of given element * @method * @memberof Popper.Utils * @param {HTMLElement} element * @return {Object} client rect */ function getBoundingClientRect(element) { var rect = {}; // IE10 10 FIX: Please, don't ask, the element isn't // considered in DOM in some circumstances... // This isn't reproducible in IE10 compatibility mode of IE11 try { if (isIE(10)) { rect = element.getBoundingClientRect(); var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); rect.top += scrollTop; rect.left += scrollLeft; rect.bottom += scrollTop; rect.right += scrollLeft; } else { rect = element.getBoundingClientRect(); } } catch (e) {} var result = { left: rect.left, top: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; // subtract scrollbar size from sizes var sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {}; var width = sizes.width || element.clientWidth || result.right - result.left; var height = sizes.height || element.clientHeight || result.bottom - result.top; var horizScrollbar = element.offsetWidth - width; var vertScrollbar = element.offsetHeight - height; // if an hypothetical scrollbar is detected, we must be sure it's not a `border` // we make this check conditional for performance reasons if (horizScrollbar || vertScrollbar) { var styles = getStyleComputedProperty(element); horizScrollbar -= getBordersSize(styles, 'x'); vertScrollbar -= getBordersSize(styles, 'y'); result.width -= horizScrollbar; result.height -= vertScrollbar; } return getClientRect(result); } function getOffsetRectRelativeToArbitraryNode(children, parent) { var fixedPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var isIE10 = isIE(10); var isHTML = parent.nodeName === 'HTML'; var childrenRect = getBoundingClientRect(children); var parentRect = getBoundingClientRect(parent); var scrollParent = getScrollParent(children); var styles = getStyleComputedProperty(parent); var borderTopWidth = parseFloat(styles.borderTopWidth, 10); var borderLeftWidth = parseFloat(styles.borderLeftWidth, 10); // In cases where the parent is fixed, we must ignore negative scroll in offset calc if (fixedPosition && isHTML) { parentRect.top = Math.max(parentRect.top, 0); parentRect.left = Math.max(parentRect.left, 0); } var offsets = getClientRect({ top: childrenRect.top - parentRect.top - borderTopWidth, left: childrenRect.left - parentRect.left - borderLeftWidth, width: childrenRect.width, height: childrenRect.height }); offsets.marginTop = 0; offsets.marginLeft = 0; // Subtract margins of documentElement in case it's being used as parent // we do this only on HTML because it's the only element that behaves // differently when margins are applied to it. The margins are included in // the box of the documentElement, in the other cases not. if (!isIE10 && isHTML) { var marginTop = parseFloat(styles.marginTop, 10); var marginLeft = parseFloat(styles.marginLeft, 10); offsets.top -= borderTopWidth - marginTop; offsets.bottom -= borderTopWidth - marginTop; offsets.left -= borderLeftWidth - marginLeft; offsets.right -= borderLeftWidth - marginLeft; // Attach marginTop and marginLeft because in some circumstances we may need them offsets.marginTop = marginTop; offsets.marginLeft = marginLeft; } if (isIE10 && !fixedPosition ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') { offsets = includeScroll(offsets, parent); } return offsets; } function getViewportOffsetRectRelativeToArtbitraryNode(element) { var excludeScroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var html = element.ownerDocument.documentElement; var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html); var width = Math.max(html.clientWidth, window.innerWidth || 0); var height = Math.max(html.clientHeight, window.innerHeight || 0); var scrollTop = !excludeScroll ? getScroll(html) : 0; var scrollLeft = !excludeScroll ? getScroll(html, 'left') : 0; var offset = { top: scrollTop - relativeOffset.top + relativeOffset.marginTop, left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft, width: width, height: height }; return getClientRect(offset); } /** * Check if the given element is fixed or is inside a fixed parent * @method * @memberof Popper.Utils * @argument {Element} element * @argument {Element} customContainer * @returns {Boolean} answer to "isFixed?" */ function isFixed(element) { var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { return false; } if (getStyleComputedProperty(element, 'position') === 'fixed') { return true; } var parentNode = getParentNode(element); if (!parentNode) { return false; } return isFixed(parentNode); } /** * Finds the first parent of an element that has a transformed property defined * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} first transformed parent or documentElement */ function getFixedPositionOffsetParent(element) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element || !element.parentElement || isIE()) { return document.documentElement; } var el = element.parentElement; while (el && getStyleComputedProperty(el, 'transform') === 'none') { el = el.parentElement; } return el || document.documentElement; } /** * Computed the boundaries limits and return them * @method * @memberof Popper.Utils * @param {HTMLElement} popper * @param {HTMLElement} reference * @param {number} padding * @param {HTMLElement} boundariesElement - Element used to define the boundaries * @param {Boolean} fixedPosition - Is in fixed position mode * @returns {Object} Coordinates of the boundaries */ function getBoundaries(popper, reference, padding, boundariesElement) { var fixedPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; // NOTE: 1 DOM access here var boundaries = { top: 0, left: 0 }; var offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, reference); // Handle viewport case if (boundariesElement === 'viewport') { boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition); } else { // Handle other cases based on DOM element used as boundaries var boundariesNode = void 0; if (boundariesElement === 'scrollParent') { boundariesNode = getScrollParent(getParentNode(reference)); if (boundariesNode.nodeName === 'BODY') { boundariesNode = popper.ownerDocument.documentElement; } } else if (boundariesElement === 'window') { boundariesNode = popper.ownerDocument.documentElement; } else { boundariesNode = boundariesElement; } var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition); // In case of HTML, we need a different computation if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) { var _getWindowSizes = getWindowSizes(popper.ownerDocument), height = _getWindowSizes.height, width = _getWindowSizes.width; boundaries.top += offsets.top - offsets.marginTop; boundaries.bottom = height + offsets.top; boundaries.left += offsets.left - offsets.marginLeft; boundaries.right = width + offsets.left; } else { // for all the other DOM elements, this one is good boundaries = offsets; } } // Add paddings padding = padding || 0; var isPaddingNumber = typeof padding === 'number'; boundaries.left += isPaddingNumber ? padding : padding.left || 0; boundaries.top += isPaddingNumber ? padding : padding.top || 0; boundaries.right -= isPaddingNumber ? padding : padding.right || 0; boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0; return boundaries; } function getArea(_ref) { var width = _ref.width, height = _ref.height; return width * height; } /** * Utility used to transform the `auto` placement to the placement with more * available space. * @method * @memberof Popper.Utils * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) { var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; if (placement.indexOf('auto') === -1) { return placement; } var boundaries = getBoundaries(popper, reference, padding, boundariesElement); var rects = { top: { width: boundaries.width, height: refRect.top - boundaries.top }, right: { width: boundaries.right - refRect.right, height: boundaries.height }, bottom: { width: boundaries.width, height: boundaries.bottom - refRect.bottom }, left: { width: refRect.left - boundaries.left, height: boundaries.height } }; var sortedAreas = Object.keys(rects).map(function (key) { return _extends({ key: key }, rects[key], { area: getArea(rects[key]) }); }).sort(function (a, b) { return b.area - a.area; }); var filteredAreas = sortedAreas.filter(function (_ref2) { var width = _ref2.width, height = _ref2.height; return width >= popper.clientWidth && height >= popper.clientHeight; }); var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key; var variation = placement.split('-')[1]; return computedPlacement + (variation ? '-' + variation : ''); } /** * Get offsets to the reference element * @method * @memberof Popper.Utils * @param {Object} state * @param {Element} popper - the popper element * @param {Element} reference - the reference element (the popper will be relative to this) * @param {Element} fixedPosition - is in fixed position mode * @returns {Object} An object containing the offsets which will be applied to the popper */ function getReferenceOffsets(state, popper, reference) { var fixedPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var commonOffsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, reference); return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent, fixedPosition); } /** * Get the outer sizes of the given element (offset size + margins) * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Object} object containing width and height properties */ function getOuterSizes(element) { var window = element.ownerDocument.defaultView; var styles = window.getComputedStyle(element); var x = parseFloat(styles.marginTop || 0) + parseFloat(styles.marginBottom || 0); var y = parseFloat(styles.marginLeft || 0) + parseFloat(styles.marginRight || 0); var result = { width: element.offsetWidth + y, height: element.offsetHeight + x }; return result; } /** * Get the opposite placement of the given one * @method * @memberof Popper.Utils * @argument {String} placement * @returns {String} flipped placement */ function getOppositePlacement(placement) { var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; return placement.replace(/left|right|bottom|top/g, function (matched) { return hash[matched]; }); } /** * Get offsets to the popper * @method * @memberof Popper.Utils * @param {Object} position - CSS position the Popper will get applied * @param {HTMLElement} popper - the popper element * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this) * @param {String} placement - one of the valid placement options * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper */ function getPopperOffsets(popper, referenceOffsets, placement) { placement = placement.split('-')[0]; // Get popper node sizes var popperRect = getOuterSizes(popper); // Add position, width and height to our offsets object var popperOffsets = { width: popperRect.width, height: popperRect.height }; // depending by the popper placement we have to compute its offsets slightly differently var isHoriz = ['right', 'left'].indexOf(placement) !== -1; var mainSide = isHoriz ? 'top' : 'left'; var secondarySide = isHoriz ? 'left' : 'top'; var measurement = isHoriz ? 'height' : 'width'; var secondaryMeasurement = !isHoriz ? 'height' : 'width'; popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; if (placement === secondarySide) { popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; } else { popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; } return popperOffsets; } /** * Mimics the `find` method of Array * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function find(arr, check) { // use native find if supported if (Array.prototype.find) { return arr.find(check); } // use `filter` to obtain the same behavior of `find` return arr.filter(check)[0]; } /** * Return the index of the matching object * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function findIndex(arr, prop, value) { // use native findIndex if supported if (Array.prototype.findIndex) { return arr.findIndex(function (cur) { return cur[prop] === value; }); } // use `find` + `indexOf` if `findIndex` isn't supported var match = find(arr, function (obj) { return obj[prop] === value; }); return arr.indexOf(match); } /** * Loop trough the list of modifiers and run them in order, * each of them will then edit the data object. * @method * @memberof Popper.Utils * @param {dataObject} data * @param {Array} modifiers * @param {String} ends - Optional modifier name used as stopper * @returns {dataObject} */ function runModifiers(modifiers, data, ends) { var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); modifiersToRun.forEach(function (modifier) { if (modifier['function']) { // eslint-disable-line dot-notation console.warn('`modifier.function` is deprecated, use `modifier.fn`!'); } var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation if (modifier.enabled && isFunction(fn)) { // Add properties to offsets to make them a complete clientRect object // we do this before each modifier to make sure the previous one doesn't // mess with these values data.offsets.popper = getClientRect(data.offsets.popper); data.offsets.reference = getClientRect(data.offsets.reference); data = fn(data, modifier); } }); return data; } /** * Updates the position of the popper, computing the new offsets and applying * the new style.
* Prefer `scheduleUpdate` over `update` because of performance reasons. * @method * @memberof Popper */ function update() { // if popper is destroyed, don't perform any further update if (this.state.isDestroyed) { return; } var data = { instance: this, styles: {}, arrowStyles: {}, attributes: {}, flipped: false, offsets: {} }; // compute reference element offsets data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference, this.options.positionFixed); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding); // store the computed placement inside `originalPlacement` data.originalPlacement = data.placement; data.positionFixed = this.options.positionFixed; // compute the popper offsets data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement); data.offsets.popper.position = this.options.positionFixed ? 'fixed' : 'absolute'; // run the modifiers data = runModifiers(this.modifiers, data); // the first `update` will call `onCreate` callback // the other ones will call `onUpdate` callback if (!this.state.isCreated) { this.state.isCreated = true; this.options.onCreate(data); } else { this.options.onUpdate(data); } } /** * Helper used to know if the given modifier is enabled. * @method * @memberof Popper.Utils * @returns {Boolean} */ function isModifierEnabled(modifiers, modifierName) { return modifiers.some(function (_ref) { var name = _ref.name, enabled = _ref.enabled; return enabled && name === modifierName; }); } /** * Get the prefixed supported property name * @method * @memberof Popper.Utils * @argument {String} property (camelCase) * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix) */ function getSupportedPropertyName(property) { var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O']; var upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (var i = 0; i < prefixes.length; i++) { var prefix = prefixes[i]; var toCheck = prefix ? '' + prefix + upperProp : property; if (typeof document.body.style[toCheck] !== 'undefined') { return toCheck; } } return null; } /** * Destroys the popper. * @method * @memberof Popper */ function destroy() { this.state.isDestroyed = true; // touch DOM only if `applyStyle` modifier is enabled if (isModifierEnabled(this.modifiers, 'applyStyle')) { this.popper.removeAttribute('x-placement'); this.popper.style.position = ''; this.popper.style.top = ''; this.popper.style.left = ''; this.popper.style.right = ''; this.popper.style.bottom = ''; this.popper.style.willChange = ''; this.popper.style[getSupportedPropertyName('transform')] = ''; } this.disableEventListeners(); // remove the popper if user explicity asked for the deletion on destroy // do not use `remove` because IE11 doesn't support it if (this.options.removeOnDestroy) { this.popper.parentNode.removeChild(this.popper); } return this; } /** * Get the window associated with the element * @argument {Element} element * @returns {Window} */ function getWindow(element) { var ownerDocument = element.ownerDocument; return ownerDocument ? ownerDocument.defaultView : window; } function attachToScrollParents(scrollParent, event, callback, scrollParents) { var isBody = scrollParent.nodeName === 'BODY'; var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent; target.addEventListener(event, callback, { passive: true }); if (!isBody) { attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents); } scrollParents.push(target); } /** * Setup needed event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function setupEventListeners(reference, options, state, updateBound) { // Resize event listener on window state.updateBound = updateBound; getWindow(reference).addEventListener('resize', state.updateBound, { passive: true }); // Scroll event listener on scroll parents var scrollElement = getScrollParent(reference); attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents); state.scrollElement = scrollElement; state.eventsEnabled = true; return state; } /** * It will add resize/scroll events and start recalculating * position of the popper element when they are triggered. * @method * @memberof Popper */ function enableEventListeners() { if (!this.state.eventsEnabled) { this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate); } } /** * Remove event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function removeEventListeners(reference, state) { // Remove resize event listener on window getWindow(reference).removeEventListener('resize', state.updateBound); // Remove scroll event listener on scroll parents state.scrollParents.forEach(function (target) { target.removeEventListener('scroll', state.updateBound); }); // Reset state state.updateBound = null; state.scrollParents = []; state.scrollElement = null; state.eventsEnabled = false; return state; } /** * It will remove resize/scroll events and won't recalculate popper position * when they are triggered. It also won't trigger `onUpdate` callback anymore, * unless you call `update` method manually. * @method * @memberof Popper */ function disableEventListeners() { if (this.state.eventsEnabled) { cancelAnimationFrame(this.scheduleUpdate); this.state = removeEventListeners(this.reference, this.state); } } /** * Tells if a given input is a number * @method * @memberof Popper.Utils * @param {*} input to check * @return {Boolean} */ function isNumeric(n) { return n !== '' && !isNaN(parseFloat(n)) && isFinite(n); } /** * Set the style to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the style to * @argument {Object} styles * Object with a list of properties and values which will be applied to the element */ function setStyles(element, styles) { Object.keys(styles).forEach(function (prop) { var unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; } element.style[prop] = styles[prop] + unit; }); } /** * Set the attributes to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the attributes to * @argument {Object} styles * Object with a list of properties and values which will be applied to the element */ function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { var value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} data.styles - List of style properties - values to apply to popper element * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element * @argument {Object} options - Modifiers configuration and options * @returns {Object} The same data object */ function applyStyle(data) { // any property present in `data.styles` will be applied to the popper, // in this way we can make the 3rd party modifiers add custom styles to it // Be aware, modifiers could override the properties defined in the previous // lines of this modifier! setStyles(data.instance.popper, data.styles); // any property present in `data.attributes` will be applied to the popper, // they will be set as HTML attributes of the element setAttributes(data.instance.popper, data.attributes); // if arrowElement is defined and arrowStyles has some properties if (data.arrowElement && Object.keys(data.arrowStyles).length) { setStyles(data.arrowElement, data.arrowStyles); } return data; } /** * Set the x-placement attribute before everything else because it could be used * to add margins to the popper margins needs to be calculated to get the * correct popper offsets. * @method * @memberof Popper.modifiers * @param {HTMLElement} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as popper * @param {Object} options - Popper.js options */ function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets var referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding); popper.setAttribute('x-placement', placement); // Apply `position` to popper before anything else because // without the position applied we can't guarantee correct computations setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' }); return options; } /** * @function * @memberof Popper.Utils * @argument {Object} data - The data object generated by `update` method * @argument {Boolean} shouldRound - If the offsets should be rounded at all * @returns {Object} The popper's position offsets rounded * * The tale of pixel-perfect positioning. It's still not 100% perfect, but as * good as it can be within reason. * Discussion here: https://github.com/FezVrasta/popper.js/pull/715 * * Low DPI screens cause a popper to be blurry if not using full pixels (Safari * as well on High DPI screens). * * Firefox prefers no rounding for positioning and does not have blurriness on * high DPI screens. * * Only horizontal placement and left/right values need to be considered. */ function getRoundedOffsets(data, shouldRound) { var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var round = Math.round, floor = Math.floor; var noRound = function noRound(v) { return v; }; var referenceWidth = round(reference.width); var popperWidth = round(popper.width); var isVertical = ['left', 'right'].indexOf(data.placement) !== -1; var isVariation = data.placement.indexOf('-') !== -1; var sameWidthParity = referenceWidth % 2 === popperWidth % 2; var bothOddWidth = referenceWidth % 2 === 1 && popperWidth % 2 === 1; var horizontalToInteger = !shouldRound ? noRound : isVertical || isVariation || sameWidthParity ? round : floor; var verticalToInteger = !shouldRound ? noRound : round; return { left: horizontalToInteger(bothOddWidth && !isVariation && shouldRound ? popper.left - 1 : popper.left), top: verticalToInteger(popper.top), bottom: verticalToInteger(popper.bottom), right: horizontalToInteger(popper.right) }; } var isFirefox = isBrowser && /Firefox/i.test(navigator.userAgent); /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeStyle(data, options) { var x = options.x, y = options.y; var popper = data.offsets.popper; // Remove this legacy support in Popper.js v2 var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) { return modifier.name === 'applyStyle'; }).gpuAcceleration; if (legacyGpuAccelerationOption !== undefined) { console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!'); } var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration; var offsetParent = getOffsetParent(data.instance.popper); var offsetParentRect = getBoundingClientRect(offsetParent); // Styles var styles = { position: popper.position }; var offsets = getRoundedOffsets(data, window.devicePixelRatio < 2 || !isFirefox); var sideA = x === 'bottom' ? 'top' : 'bottom'; var sideB = y === 'right' ? 'left' : 'right'; // if gpuAcceleration is set to `true` and transform is supported, // we use `translate3d` to apply the position to the popper we // automatically use the supported prefixed version if needed var prefixedProperty = getSupportedPropertyName('transform'); // now, let's make a step back and look at this code closely (wtf?) // If the content of the popper grows once it's been positioned, it // may happen that the popper gets misplaced because of the new content // overflowing its reference element // To avoid this problem, we provide two options (x and y), which allow // the consumer to define the offset origin. // If we position a popper on top of a reference element, we can set // `x` to `top` to make the popper grow towards its top instead of // its bottom. var left = void 0, top = void 0; if (sideA === 'bottom') { // when offsetParent is the positioning is relative to the bottom of the screen (excluding the scrollbar) // and not the bottom of the html element if (offsetParent.nodeName === 'HTML') { top = -offsetParent.clientHeight + offsets.bottom; } else { top = -offsetParentRect.height + offsets.bottom; } } else { top = offsets.top; } if (sideB === 'right') { if (offsetParent.nodeName === 'HTML') { left = -offsetParent.clientWidth + offsets.right; } else { left = -offsetParentRect.width + offsets.right; } } else { left = offsets.left; } if (gpuAcceleration && prefixedProperty) { styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)'; styles[sideA] = 0; styles[sideB] = 0; styles.willChange = 'transform'; } else { // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties var invertTop = sideA === 'bottom' ? -1 : 1; var invertLeft = sideB === 'right' ? -1 : 1; styles[sideA] = top * invertTop; styles[sideB] = left * invertLeft; styles.willChange = sideA + ', ' + sideB; } // Attributes var attributes = { 'x-placement': data.placement }; // Update `data` attributes, styles and arrowStyles data.attributes = _extends({}, attributes, data.attributes); data.styles = _extends({}, styles, data.styles); data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles); return data; } /** * Helper used to know if the given modifier depends from another one.
* It checks if the needed modifier is listed and enabled. * @method * @memberof Popper.Utils * @param {Array} modifiers - list of modifiers * @param {String} requestingName - name of requesting modifier * @param {String} requestedName - name of requested modifier * @returns {Boolean} */ function isModifierRequired(modifiers, requestingName, requestedName) { var requesting = find(modifiers, function (_ref) { var name = _ref.name; return name === requestingName; }); var isRequired = !!requesting && modifiers.some(function (modifier) { return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order; }); if (!isRequired) { var _requesting = '`' + requestingName + '`'; var requested = '`' + requestedName + '`'; console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!'); } return isRequired; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function arrow(data, options) { var _data$offsets$arrow; // arrow depends on keepTogether in order to work if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) { return data; } var arrowElement = options.element; // if arrowElement is a string, suppose it's a CSS selector if (typeof arrowElement === 'string') { arrowElement = data.instance.popper.querySelector(arrowElement); // if arrowElement is not found, don't run the modifier if (!arrowElement) { return data; } } else { // if the arrowElement isn't a query selector we must check that the // provided DOM node is child of its popper node if (!data.instance.popper.contains(arrowElement)) { console.warn('WARNING: `arrow.element` must be child of its popper element!'); return data; } } var placement = data.placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isVertical = ['left', 'right'].indexOf(placement) !== -1; var len = isVertical ? 'height' : 'width'; var sideCapitalized = isVertical ? 'Top' : 'Left'; var side = sideCapitalized.toLowerCase(); var altSide = isVertical ? 'left' : 'top'; var opSide = isVertical ? 'bottom' : 'right'; var arrowElementSize = getOuterSizes(arrowElement)[len]; // // extends keepTogether behavior making sure the popper and its // reference have enough pixels in conjunction // // top/left side if (reference[opSide] - arrowElementSize < popper[side]) { data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize); } // bottom/right side if (reference[side] + arrowElementSize > popper[opSide]) { data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide]; } data.offsets.popper = getClientRect(data.offsets.popper); // compute center of the popper var center = reference[side] + reference[len] / 2 - arrowElementSize / 2; // Compute the sideValue using the updated popper offsets // take popper margin in account because we don't have this info available var css = getStyleComputedProperty(data.instance.popper); var popperMarginSide = parseFloat(css['margin' + sideCapitalized], 10); var popperBorderSide = parseFloat(css['border' + sideCapitalized + 'Width'], 10); var sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide; // prevent arrowElement from being placed not contiguously to its popper sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0); data.arrowElement = arrowElement; data.offsets.arrow = (_data$offsets$arrow = {}, defineProperty(_data$offsets$arrow, side, Math.round(sideValue)), defineProperty(_data$offsets$arrow, altSide, ''), _data$offsets$arrow); return data; } /** * Get the opposite placement variation of the given one * @method * @memberof Popper.Utils * @argument {String} placement variation * @returns {String} flipped placement variation */ function getOppositeVariation(variation) { if (variation === 'end') { return 'start'; } else if (variation === 'start') { return 'end'; } return variation; } /** * List of accepted placements to use as values of the `placement` option.
* Valid placements are: * - `auto` * - `top` * - `right` * - `bottom` * - `left` * * Each placement can have a variation from this list: * - `-start` * - `-end` * * Variations are interpreted easily if you think of them as the left to right * written languages. Horizontally (`top` and `bottom`), `start` is left and `end` * is right.
* Vertically (`left` and `right`), `start` is top and `end` is bottom. * * Some valid examples are: * - `top-end` (on top of reference, right aligned) * - `right-start` (on right of reference, top aligned) * - `bottom` (on bottom, centered) * - `auto-end` (on the side with more space available, alignment depends by placement) * * @static * @type {Array} * @enum {String} * @readonly * @method placements * @memberof Popper */ var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start']; // Get rid of `auto` `auto-start` and `auto-end` var validPlacements = placements.slice(3); /** * Given an initial placement, returns all the subsequent placements * clockwise (or counter-clockwise). * * @method * @memberof Popper.Utils * @argument {String} placement - A valid placement (it accepts variations) * @argument {Boolean} counter - Set to true to walk the placements counterclockwise * @returns {Array} placements including their variations */ function clockwise(placement) { var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var index = validPlacements.indexOf(placement); var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index)); return counter ? arr.reverse() : arr; } var BEHAVIORS = { FLIP: 'flip', CLOCKWISE: 'clockwise', COUNTERCLOCKWISE: 'counterclockwise' }; /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function flip(data, options) { // if `inner` modifier is enabled, we can't use the `flip` modifier if (isModifierEnabled(data.instance.modifiers, 'inner')) { return data; } if (data.flipped && data.placement === data.originalPlacement) { // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides return data; } var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement, data.positionFixed); var placement = data.placement.split('-')[0]; var placementOpposite = getOppositePlacement(placement); var variation = data.placement.split('-')[1] || ''; var flipOrder = []; switch (options.behavior) { case BEHAVIORS.FLIP: flipOrder = [placement, placementOpposite]; break; case BEHAVIORS.CLOCKWISE: flipOrder = clockwise(placement); break; case BEHAVIORS.COUNTERCLOCKWISE: flipOrder = clockwise(placement, true); break; default: flipOrder = options.behavior; } flipOrder.forEach(function (step, index) { if (placement !== step || flipOrder.length === index + 1) { return data; } placement = data.placement.split('-')[0]; placementOpposite = getOppositePlacement(placement); var popperOffsets = data.offsets.popper; var refOffsets = data.offsets.reference; // using floor because the reference offsets may contain decimals we are not going to consider here var floor = Math.floor; var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom); var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left); var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right); var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top); var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom); var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom; // flip the variation if required var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom); if (overlapsRef || overflowsBoundaries || flippedVariation) { // this boolean to detect any flip loop data.flipped = true; if (overlapsRef || overflowsBoundaries) { placement = flipOrder[index + 1]; } if (flippedVariation) { variation = getOppositeVariation(variation); } data.placement = placement + (variation ? '-' + variation : ''); // this object contains `position`, we want to preserve it along with // any additional property we may add in the future data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement)); data = runModifiers(data.instance.modifiers, data, 'flip'); } }); return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function keepTogether(data) { var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var placement = data.placement.split('-')[0]; var floor = Math.floor; var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var side = isVertical ? 'right' : 'bottom'; var opSide = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; if (popper[side] < floor(reference[opSide])) { data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement]; } if (popper[opSide] > floor(reference[side])) { data.offsets.popper[opSide] = floor(reference[side]); } return data; } /** * Converts a string containing value + unit into a px value number * @function * @memberof {modifiers~offset} * @private * @argument {String} str - Value + unit string * @argument {String} measurement - `height` or `width` * @argument {Object} popperOffsets * @argument {Object} referenceOffsets * @returns {Number|String} * Value in pixels, or original string if no values were extracted */ function toValue(str, measurement, popperOffsets, referenceOffsets) { // separate value from unit var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/); var value = +split[1]; var unit = split[2]; // If it's not a number it's an operator, I guess if (!value) { return str; } if (unit.indexOf('%') === 0) { var element = void 0; switch (unit) { case '%p': element = popperOffsets; break; case '%': case '%r': default: element = referenceOffsets; } var rect = getClientRect(element); return rect[measurement] / 100 * value; } else if (unit === 'vh' || unit === 'vw') { // if is a vh or vw, we calculate the size based on the viewport var size = void 0; if (unit === 'vh') { size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); } else { size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); } return size / 100 * value; } else { // if is an explicit pixel unit, we get rid of the unit and keep the value // if is an implicit unit, it's px, and we return just the value return value; } } /** * Parse an `offset` string to extrapolate `x` and `y` numeric offsets. * @function * @memberof {modifiers~offset} * @private * @argument {String} offset * @argument {Object} popperOffsets * @argument {Object} referenceOffsets * @argument {String} basePlacement * @returns {Array} a two cells array with x and y offsets in numbers */ function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { var offsets = [0, 0]; // Use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1; // Split the offset string to obtain a list of values and operands // The regex addresses values with the plus or minus sign in front (+10, -20, etc) var fragments = offset.split(/(\+|\-)/).map(function (frag) { return frag.trim(); }); // Detect if the offset string contains a pair of values or a single one // they could be separated by comma or space var divider = fragments.indexOf(find(fragments, function (frag) { return frag.search(/,|\s/) !== -1; })); if (fragments[divider] && fragments[divider].indexOf(',') === -1) { console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.'); } // If divider is found, we divide the list of values and operands to divide // them by ofset X and Y. var splitRegex = /\s*,\s*|\s+/; var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments]; // Convert the values with units to absolute pixels to allow our computations ops = ops.map(function (op, index) { // Most of the units rely on the orientation of the popper var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width'; var mergeWithPrevious = false; return op // This aggregates any `+` or `-` sign that aren't considered operators // e.g.: 10 + +5 => [10, +, +5] .reduce(function (a, b) { if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) { a[a.length - 1] = b; mergeWithPrevious = true; return a; } else if (mergeWithPrevious) { a[a.length - 1] += b; mergeWithPrevious = false; return a; } else { return a.concat(b); } }, []) // Here we convert the string values into number values (in px) .map(function (str) { return toValue(str, measurement, popperOffsets, referenceOffsets); }); }); // Loop trough the offsets arrays and execute the operations ops.forEach(function (op, index) { op.forEach(function (frag, index2) { if (isNumeric(frag)) { offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1); } }); }); return offsets; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @argument {Number|String} options.offset=0 * The offset value as described in the modifier description * @returns {Object} The data object, properly modified */ function offset(data, _ref) { var offset = _ref.offset; var placement = data.placement, _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var basePlacement = placement.split('-')[0]; var offsets = void 0; if (isNumeric(+offset)) { offsets = [+offset, 0]; } else { offsets = parseOffset(offset, popper, reference, basePlacement); } if (basePlacement === 'left') { popper.top += offsets[0]; popper.left -= offsets[1]; } else if (basePlacement === 'right') { popper.top += offsets[0]; popper.left += offsets[1]; } else if (basePlacement === 'top') { popper.left += offsets[0]; popper.top -= offsets[1]; } else if (basePlacement === 'bottom') { popper.left += offsets[0]; popper.top += offsets[1]; } data.popper = popper; return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function preventOverflow(data, options) { var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper); // If offsetParent is the reference element, we really want to // go one step up and use the next offsetParent as reference to // avoid to make this modifier completely useless and look like broken if (data.instance.reference === boundariesElement) { boundariesElement = getOffsetParent(boundariesElement); } // NOTE: DOM access here // resets the popper's position so that the document size can be calculated excluding // the size of the popper element itself var transformProp = getSupportedPropertyName('transform'); var popperStyles = data.instance.popper.style; // assignment to help minification var top = popperStyles.top, left = popperStyles.left, transform = popperStyles[transformProp]; popperStyles.top = ''; popperStyles.left = ''; popperStyles[transformProp] = ''; var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement, data.positionFixed); // NOTE: DOM access here // restores the original style properties after the offsets have been computed popperStyles.top = top; popperStyles.left = left; popperStyles[transformProp] = transform; options.boundaries = boundaries; var order = options.priority; var popper = data.offsets.popper; var check = { primary: function primary(placement) { var value = popper[placement]; if (popper[placement] < boundaries[placement] && !options.escapeWithReference) { value = Math.max(popper[placement], boundaries[placement]); } return defineProperty({}, placement, value); }, secondary: function secondary(placement) { var mainSide = placement === 'right' ? 'left' : 'top'; var value = popper[mainSide]; if (popper[placement] > boundaries[placement] && !options.escapeWithReference) { value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height)); } return defineProperty({}, mainSide, value); } }; order.forEach(function (placement) { var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary'; popper = _extends({}, popper, check[side](placement)); }); data.offsets.popper = popper; return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function shift(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var shiftvariation = placement.split('-')[1]; // if shift shiftvariation is specified, run the modifier if (shiftvariation) { var _data$offsets = data.offsets, reference = _data$offsets.reference, popper = _data$offsets.popper; var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1; var side = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; var shiftOffsets = { start: defineProperty({}, side, reference[side]), end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement]) }; data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]); } return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function hide(data) { if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) { return data; } var refRect = data.offsets.reference; var bound = find(data.instance.modifiers, function (modifier) { return modifier.name === 'preventOverflow'; }).boundaries; if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === true) { return data; } data.hide = true; data.attributes['x-out-of-boundaries'] = ''; } else { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === false) { return data; } data.hide = false; data.attributes['x-out-of-boundaries'] = false; } return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function inner(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1; var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1; popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0); data.placement = getOppositePlacement(placement); data.offsets.popper = getClientRect(popper); return data; } /** * Modifier function, each modifier can have a function of this type assigned * to its `fn` property.
* These functions will be called on each update, this means that you must * make sure they are performant enough to avoid performance bottlenecks. * * @function ModifierFn * @argument {dataObject} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {dataObject} The data object, properly modified */ /** * Modifiers are plugins used to alter the behavior of your poppers.
* Popper.js uses a set of 9 modifiers to provide all the basic functionalities * needed by the library. * * Usually you don't want to override the `order`, `fn` and `onLoad` props. * All the other properties are configurations that could be tweaked. * @namespace modifiers */ var modifiers = { /** * Modifier used to shift the popper on the start or end of its reference * element.
* It will read the variation of the `placement` property.
* It can be one either `-end` or `-start`. * @memberof modifiers * @inner */ shift: { /** @prop {number} order=100 - Index used to define the order of execution */ order: 100, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: shift }, /** * The `offset` modifier can shift your popper on both its axis. * * It accepts the following units: * - `px` or unit-less, interpreted as pixels * - `%` or `%r`, percentage relative to the length of the reference element * - `%p`, percentage relative to the length of the popper element * - `vw`, CSS viewport width unit * - `vh`, CSS viewport height unit * * For length is intended the main axis relative to the placement of the popper.
* This means that if the placement is `top` or `bottom`, the length will be the * `width`. In case of `left` or `right`, it will be the `height`. * * You can provide a single value (as `Number` or `String`), or a pair of values * as `String` divided by a comma or one (or more) white spaces.
* The latter is a deprecated method because it leads to confusion and will be * removed in v2.
* Additionally, it accepts additions and subtractions between different units. * Note that multiplications and divisions aren't supported. * * Valid examples are: * ``` * 10 * '10%' * '10, 10' * '10%, 10' * '10 + 10%' * '10 - 5vh + 3%' * '-10px + 5vh, 5px - 6%' * ``` * > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap * > with their reference element, unfortunately, you will have to disable the `flip` modifier. * > You can read more on this at this [issue](https://github.com/FezVrasta/popper.js/issues/373). * * @memberof modifiers * @inner */ offset: { /** @prop {number} order=200 - Index used to define the order of execution */ order: 200, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: offset, /** @prop {Number|String} offset=0 * The offset value as described in the modifier description */ offset: 0 }, /** * Modifier used to prevent the popper from being positioned outside the boundary. * * A scenario exists where the reference itself is not within the boundaries.
* We can say it has "escaped the boundaries" — or just "escaped".
* In this case we need to decide whether the popper should either: * * - detach from the reference and remain "trapped" in the boundaries, or * - if it should ignore the boundary and "escape with its reference" * * When `escapeWithReference` is set to`true` and reference is completely * outside its boundaries, the popper will overflow (or completely leave) * the boundaries in order to remain attached to the edge of the reference. * * @memberof modifiers * @inner */ preventOverflow: { /** @prop {number} order=300 - Index used to define the order of execution */ order: 300, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: preventOverflow, /** * @prop {Array} [priority=['left','right','top','bottom']] * Popper will try to prevent overflow following these priorities by default, * then, it could overflow on the left and on top of the `boundariesElement` */ priority: ['left', 'right', 'top', 'bottom'], /** * @prop {number} padding=5 * Amount of pixel used to define a minimum distance between the boundaries * and the popper. This makes sure the popper always has a little padding * between the edges of its container */ padding: 5, /** * @prop {String|HTMLElement} boundariesElement='scrollParent' * Boundaries used by the modifier. Can be `scrollParent`, `window`, * `viewport` or any DOM element. */ boundariesElement: 'scrollParent' }, /** * Modifier used to make sure the reference and its popper stay near each other * without leaving any gap between the two. Especially useful when the arrow is * enabled and you want to ensure that it points to its reference element. * It cares only about the first axis. You can still have poppers with margin * between the popper and its reference element. * @memberof modifiers * @inner */ keepTogether: { /** @prop {number} order=400 - Index used to define the order of execution */ order: 400, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: keepTogether }, /** * This modifier is used to move the `arrowElement` of the popper to make * sure it is positioned between the reference element and its popper element. * It will read the outer size of the `arrowElement` node to detect how many * pixels of conjunction are needed. * * It has no effect if no `arrowElement` is provided. * @memberof modifiers * @inner */ arrow: { /** @prop {number} order=500 - Index used to define the order of execution */ order: 500, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: arrow, /** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */ element: '[x-arrow]' }, /** * Modifier used to flip the popper's placement when it starts to overlap its * reference element. * * Requires the `preventOverflow` modifier before it in order to work. * * **NOTE:** this modifier will interrupt the current update cycle and will * restart it if it detects the need to flip the placement. * @memberof modifiers * @inner */ flip: { /** @prop {number} order=600 - Index used to define the order of execution */ order: 600, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: flip, /** * @prop {String|Array} behavior='flip' * The behavior used to change the popper's placement. It can be one of * `flip`, `clockwise`, `counterclockwise` or an array with a list of valid * placements (with optional variations) */ behavior: 'flip', /** * @prop {number} padding=5 * The popper will flip if it hits the edges of the `boundariesElement` */ padding: 5, /** * @prop {String|HTMLElement} boundariesElement='viewport' * The element which will define the boundaries of the popper position. * The popper will never be placed outside of the defined boundaries * (except if `keepTogether` is enabled) */ boundariesElement: 'viewport' }, /** * Modifier used to make the popper flow toward the inner of the reference element. * By default, when this modifier is disabled, the popper will be placed outside * the reference element. * @memberof modifiers * @inner */ inner: { /** @prop {number} order=700 - Index used to define the order of execution */ order: 700, /** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */ enabled: false, /** @prop {ModifierFn} */ fn: inner }, /** * Modifier used to hide the popper when its reference element is outside of the * popper boundaries. It will set a `x-out-of-boundaries` attribute which can * be used to hide with a CSS selector the popper when its reference is * out of boundaries. * * Requires the `preventOverflow` modifier before it in order to work. * @memberof modifiers * @inner */ hide: { /** @prop {number} order=800 - Index used to define the order of execution */ order: 800, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: hide }, /** * Computes the style that will be applied to the popper element to gets * properly positioned. * * Note that this modifier will not touch the DOM, it just prepares the styles * so that `applyStyle` modifier can apply it. This separation is useful * in case you need to replace `applyStyle` with a custom implementation. * * This modifier has `850` as `order` value to maintain backward compatibility * with previous versions of Popper.js. Expect the modifiers ordering method * to change in future major versions of the library. * * @memberof modifiers * @inner */ computeStyle: { /** @prop {number} order=850 - Index used to define the order of execution */ order: 850, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: computeStyle, /** * @prop {Boolean} gpuAcceleration=true * If true, it uses the CSS 3D transformation to position the popper. * Otherwise, it will use the `top` and `left` properties */ gpuAcceleration: true, /** * @prop {string} [x='bottom'] * Where to anchor the X axis (`bottom` or `top`). AKA X offset origin. * Change this if your popper should grow in a direction different from `bottom` */ x: 'bottom', /** * @prop {string} [x='left'] * Where to anchor the Y axis (`left` or `right`). AKA Y offset origin. * Change this if your popper should grow in a direction different from `right` */ y: 'right' }, /** * Applies the computed styles to the popper element. * * All the DOM manipulations are limited to this modifier. This is useful in case * you want to integrate Popper.js inside a framework or view library and you * want to delegate all the DOM manipulations to it. * * Note that if you disable this modifier, you must make sure the popper element * has its position set to `absolute` before Popper.js can do its work! * * Just disable this modifier and define your own to achieve the desired effect. * * @memberof modifiers * @inner */ applyStyle: { /** @prop {number} order=900 - Index used to define the order of execution */ order: 900, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: applyStyle, /** @prop {Function} */ onLoad: applyStyleOnLoad, /** * @deprecated since version 1.10.0, the property moved to `computeStyle` modifier * @prop {Boolean} gpuAcceleration=true * If true, it uses the CSS 3D transformation to position the popper. * Otherwise, it will use the `top` and `left` properties */ gpuAcceleration: undefined } }; /** * The `dataObject` is an object containing all the information used by Popper.js. * This object is passed to modifiers and to the `onCreate` and `onUpdate` callbacks. * @name dataObject * @property {Object} data.instance The Popper.js instance * @property {String} data.placement Placement applied to popper * @property {String} data.originalPlacement Placement originally defined on init * @property {Boolean} data.flipped True if popper has been flipped by flip modifier * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier * @property {Object} data.styles Any CSS property defined here will be applied to the popper. It expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow. It expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.boundaries Offsets of the popper boundaries * @property {Object} data.offsets The measurements of popper, reference and arrow elements * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values * @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0 */ /** * Default options provided to Popper.js constructor.
* These can be overridden using the `options` argument of Popper.js.
* To override an option, simply pass an object with the same * structure of the `options` object, as the 3rd argument. For example: * ``` * new Popper(ref, pop, { * modifiers: { * preventOverflow: { enabled: false } * } * }) * ``` * @type {Object} * @static * @memberof Popper */ var Defaults = { /** * Popper's placement. * @prop {Popper.placements} placement='bottom' */ placement: 'bottom', /** * Set this to true if you want popper to position it self in 'fixed' mode * @prop {Boolean} positionFixed=false */ positionFixed: false, /** * Whether events (resize, scroll) are initially enabled. * @prop {Boolean} eventsEnabled=true */ eventsEnabled: true, /** * Set to true if you want to automatically remove the popper when * you call the `destroy` method. * @prop {Boolean} removeOnDestroy=false */ removeOnDestroy: false, /** * Callback called when the popper is created.
* By default, it is set to no-op.
* Access Popper.js instance with `data.instance`. * @prop {onCreate} */ onCreate: function onCreate() {}, /** * Callback called when the popper is updated. This callback is not called * on the initialization/creation of the popper, but only on subsequent * updates.
* By default, it is set to no-op.
* Access Popper.js instance with `data.instance`. * @prop {onUpdate} */ onUpdate: function onUpdate() {}, /** * List of modifiers used to modify the offsets before they are applied to the popper. * They provide most of the functionalities of Popper.js. * @prop {modifiers} */ modifiers: modifiers }; /** * @callback onCreate * @param {dataObject} data */ /** * @callback onUpdate * @param {dataObject} data */ // Utils // Methods var Popper = function () { /** * Creates a new Popper.js instance. * @class Popper * @param {HTMLElement|referenceObject} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as the popper * @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults) * @return {Object} instance - The generated Popper.js instance */ function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, Popper); this.scheduleUpdate = function () { return requestAnimationFrame(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.options = _extends({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference && reference.jquery ? reference[0] : reference; this.popper = popper && popper.jquery ? popper[0] : popper; // Deep merge modifiers options this.options.modifiers = {}; Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); }); // Refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(this.options.modifiers).map(function (name) { return _extends({ name: name }, _this.options.modifiers[name]); }) // sort the modifiers by order .sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; } // We can't use class properties because they don't get listed in the // class prototype and break stuff like Sinon stubs createClass(Popper, [{ key: 'update', value: function update$$1() { return update.call(this); } }, { key: 'destroy', value: function destroy$$1() { return destroy.call(this); } }, { key: 'enableEventListeners', value: function enableEventListeners$$1() { return enableEventListeners.call(this); } }, { key: 'disableEventListeners', value: function disableEventListeners$$1() { return disableEventListeners.call(this); } /** * Schedules an update. It will run on the next UI update available. * @method scheduleUpdate * @memberof Popper */ /** * Collection of utilities useful when writing custom modifiers. * Starting from version 1.7, this method is available only if you * include `popper-utils.js` before `popper.js`. * * **DEPRECATION**: This way to access PopperUtils is deprecated * and will be removed in v2! Use the PopperUtils module directly instead. * Due to the high instability of the methods contained in Utils, we can't * guarantee them to follow semver. Use them at your own risk! * @static * @private * @type {Object} * @deprecated since version 1.8 * @member Utils * @memberof Popper */ }]); return Popper; }(); /** * The `referenceObject` is an object that provides an interface compatible with Popper.js * and lets you use it as replacement of a real DOM node.
* You can use this method to position a popper relatively to a set of coordinates * in case you don't have a DOM node to use as reference. * * ``` * new Popper(referenceObject, popperNode); * ``` * * NB: This feature isn't supported in Internet Explorer 10. * @name referenceObject * @property {Function} data.getBoundingClientRect * A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method. * @property {number} data.clientWidth * An ES6 getter that will return the width of the virtual reference element. * @property {number} data.clientHeight * An ES6 getter that will return the height of the virtual reference element. */ Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils; Popper.placements = placements; Popper.Defaults = Defaults; /* harmony default export */ __webpack_exports__["default"] = (Popper); //# sourceMappingURL=popper.js.map /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) /***/ }) }]); //# sourceMappingURL=search.js.map