first commit

This commit is contained in:
2024-11-11 18:46:54 +01:00
commit a630d17338
25634 changed files with 4923715 additions and 0 deletions

View File

@@ -0,0 +1,79 @@
/**
* 2007-2019 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2019 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
export default function () {
$(document).ready(function () {
$('.js-attribute-checkbox').change((event) => {
if ($(event.target).is(':checked')) {
if ($(`.token[data-value="${$(event.target).data('value')}"] .close`).length === 0) {
$('#form_step3_attributes').tokenfield(
'createToken',
{value: $(event.target).data('value'), label: $(event.target).data('label')}
);
}
} else {
$(`.token[data-value="${$(event.target).data('value')}"] .close`).click();
}
});
});
$('#form_step3_attributes')
.on('tokenfield:createdtoken', function (e) {
if (!$(`.js-attribute-checkbox[data-value="${e.attrs.value}"]`).is(':checked')) {
$(`.js-attribute-checkbox[data-value="${e.attrs.value}"]`).prop('checked', true);
}
})
.on('tokenfield:removedtoken', function (e) {
if ($(`.js-attribute-checkbox[data-value="${e.attrs.value}"]`).is(':checked')) {
$(`.js-attribute-checkbox[data-value="${e.attrs.value}"]`).prop('checked', false);
}
});
$('input.form-control[counter], textarea.form-control:not(.autoload_rte)[counter]').each(function () {
let counter = $(this).attr('counter');
if (typeof counter === undefined || counter === false) {
return;
}
handleCounter($(this));
$(this).on('input', function () {
handleCounter($(this));
});
function handleCounter(object) {
let counter = $(object).attr('counter');
let counter_type = $(object).attr('counter_type');
let max = $(object).val().length;
$(object).parent().find('span.currentLength').text(max);
if ('recommended' !== counter_type && max > counter) {
$(object).parent().find('span.maxLength').addClass('text-danger');
} else {
$(object).parent().find('span.maxLength').removeClass('text-danger');
}
}
});
}

View File

@@ -0,0 +1,74 @@
/**
* 2007-2019 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2019 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
export default function() {
/**
* scroll right to show radio buttons on the category tree
*/
const scrollCategoryTree = function scrollCategoryTree() {
let $categoryTreeOverflow = $('.category-tree-overflow');
let leftPos = $categoryTreeOverflow.width();
$categoryTreeOverflow.animate({scrollLeft: leftPos}, 200);
};
const treeAction = (treeState) => {
if (treeState === 'expand') {
$('.js-categories-tree ul').show();
$('.more').toggleClass('less');
// scroll right to see the radio buttons
scrollCategoryTree();
} else {
$('.js-categories-tree ul:not(.category-tree)').hide();
$('.less').toggleClass('more');
}
};
$('#categories-tree-expand').on('click', (e) => {
treeAction('expand');
$('#categories-tree-expand').hide();
$('#categories-tree-reduce').show();
});
$('#categories-tree-reduce').on('click', (e) => {
treeAction('collapse');
$('#categories-tree-reduce').hide();
$('#categories-tree-expand').show();
});
// scroll right to see the radio buttons
$('.category-tree-overflow .checkbox').on('click', (e) => {
if (!$(e.target).is('input')) {
// do not scroll if (un)checking some inputs
scrollCategoryTree();
}
});
$('.category-tree-overflow .checkbox label').on('click', (e) => {
if (!$(e.target).is('input')) {
// do not scroll if (un)checking some inputs
scrollCategoryTree();
}
});
}

View File

@@ -0,0 +1,209 @@
var $ = window.$;
export default function() {
$(document).ready(function() {
const $jsCombinationsList = $('.js-combinations-list');
// If we are not on the product page, return
if (0 === $jsCombinationsList.length) {
return;
}
const idsProductAttribute = $jsCombinationsList.data('ids-product-attribute').toString().split(',');
const refreshImagesUrl = $jsCombinationsList
.attr('data-action-refresh-images')
.replace(/form-images\/\d+/, 'form-images/' + $jsCombinationsList.data('id-product'));
const idsCount = idsProductAttribute.length;
const step = 50;
let currentCount = 0;
$.get(refreshImagesUrl).then(function(response) {
if (idsCount !== 0) {
getCombinations(response);
}
});
$('#create-combinations').click(function(event) {
event.preventDefault();
form.send(false, false, generate);
});
const productDropzone = Dropzone.forElement('#product-images-dropzone');
const updateCombinationImages = function() {
const productAttributeIds = $.map(
$('.js-combinations-list .combination'),
(combination) => {
return $(combination).data('index');
}
);
$.get(refreshImagesUrl).then((response) => {
refreshImagesCombination(response, productAttributeIds);
});
};
productDropzone.on('success', updateCombinationImages);
$(document).on('click', '#form .product-combination-image', function() {
const input = $(this).find('input');
const isChecked = input.prop('checked');
input.prop('checked', !isChecked);
$(this).toggleClass('img-highlight', !isChecked);
refreshDefaultImage();
});
$('#product_combination_bulk_impact_on_price_ti, #product_combination_bulk_impact_on_price_te').keyup(function() {
const self = $(this);
const price = priceCalculation.normalizePrice(self.val());
if ('product_combination_bulk_impact_on_price_ti' === self.attr('id')) {
$('#product_combination_bulk_impact_on_price_te').val(priceCalculation.removeCurrentTax(price)).change();
} else {
$('#product_combination_bulk_impact_on_price_ti').val(priceCalculation.addCurrentTax(price)).change();
}
});
const getCombinations = (combinationsImages) => {
let $jsCombinationsBulkForm = $('#combinations-bulk-form');
if (!$jsCombinationsBulkForm.hasClass('inactive')) {
$jsCombinationsBulkForm.addClass('inactive');
}
const $combinationsUrl = getCombinationsUrl();
if ($combinationsUrl === false) {
return;
}
$.get($combinationsUrl).then(function (resp) {
$('#loading-attribute').before(resp);
refreshImagesCombination(combinationsImages, idsProductAttribute.slice(currentCount, currentCount+step));
currentCount += step;
if (currentCount < idsCount) {
getCombinations(combinationsImages);
} else {
activateCombinationsBulk();
}
});
};
/*
* Retrieve URL to get a set of combination forms from data attribute
* Concatenate ids_product_attribute to load from a slice of idsProductAttribute depending of step and last set
*/
const getCombinationsUrl = () => {
const $numbers = idsProductAttribute.slice(currentCount, currentCount+step).join('-');
if ($numbers.length === 0) {
return false;
}
return $jsCombinationsList
.data('combinations-url')
.replace(
':numbers',
$numbers
);
};
});
const activateCombinationsBulk = () => {
let $jsCombinationsBulkForm = $('#combinations-bulk-form');
if ($jsCombinationsBulkForm.hasClass('inactive')) {
$jsCombinationsBulkForm.removeClass('inactive');
$('#loading-attribute').fadeOut(1000).remove();
$('[data-toggle="popover"]').popover();
}
}
const refreshImagesCombination = (combinationsImages, idsProductAttribute) => {
$.each(idsProductAttribute, function (index, value) {
const $combinationElem = $('.combination[data="' + value + '"]');
const $index = $combinationElem.attr('data-index');
let $imagesElem = $combinationElem.find('.images');
let html = '';
if (0 === $imagesElem.length) {
$imagesElem = $('#combination_' + $index + '_id_image_attr');
}
$.each(combinationsImages[value], function(key, image) {
html += `<div class="product-combination-image ${(image.id_image_attr ? 'img-highlight' : '')}">
<input type="checkbox" name="combination_${$index}[id_image_attr][]" value="${image.id}" ${(image.id_image_attr ? 'checked="checked"' : '')}>
<img src="${image.base_image_url}-small_default.${image.format}" alt="" />
</div>`;
});
$imagesElem.html(html);
$combinationElem.fadeIn(1000);
});
refreshDefaultImage();
};
const refreshDefaultImage = () => {
const productCoverImageElem = $('#product-images-dropzone').find('.iscover');
let productDefaultImageUrl = null;
/** get product cover image */
if (productCoverImageElem.length === 1) {
let imgElem = productCoverImageElem.parent().find('.dz-image');
/** Dropzone.js workaround : If this is a fresh upload image, look up for an img, else find a background url */
if (imgElem.find('img').length) {
productDefaultImageUrl = imgElem.find('img').attr('src');
} else {
productDefaultImageUrl = imgElem.css('background-image')
.replace(/^url\(["']?/, '')
.replace(/["']?\)$/, '');
}
}
$.each($('#form .combination-form'), function(key, elem) {
let defaultImageUrl = productDefaultImageUrl;
/** get first selected image */
const defaultImageElem = $(elem).find('.product-combination-image input:checked:first');
if (defaultImageElem.length === 1) {
defaultImageUrl = defaultImageElem.parent().find('img').attr('src');
}
if (defaultImageUrl) {
var img = '<img src="' + defaultImageUrl + '" class="img-responsive" />';
$('#attribute_' + $(elem).attr('data')).find('td.img').html(img);
}
});
};
const generate = () => {
$.ajax({
type: 'POST',
url: $('#form_step3_attributes').attr('data-action'),
data: $('#attributes-generator input.attribute-generator, #form_id_product').serialize(),
beforeSend: function() {
$('#create-combinations, #submit, .btn-submit').attr('disabled', 'disabled');
},
success: function(response) {
refreshTotalCombinations(1, $(response.form).filter('.combination.loaded').length);
$('#accordion_combinations').append(response.form);
displayFieldsManager.refresh();
const url = $('.js-combinations-list').attr('data-action-refresh-images').replace(/form-images\/\d+/, 'form-images/' + $('.js-combinations-list').data('id-product'));
$.get(url)
.then(function(combinationsImages) {
refreshImagesCombination(combinationsImages, response.ids_product_attribute);
});
/** initialize form */
$('input.attribute-generator').remove();
$('#attributes-generator div.token').remove();
$('.js-attribute-checkbox:checked').each(function() {
$(this).prop('checked', false);
});
$('#combinations_thead').fadeIn();
},
complete: function() {
$('#create-combinations, #submit, .btn-submit').removeAttr('disabled');
activateCombinationsBulk();
supplierCombinations.refresh();
warehouseCombinations.refresh();
}
});
};
}

View File

@@ -0,0 +1,69 @@
/**
* 2007-2019 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2019 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
import productHeader from './product-header';
import productSearchAutocomplete from './product-search-autocomplete';
import categoryTree from './category-tree';
import attributes from './attributes';
import bulkCombination from './product-bulk-combinations';
import nestedCategory from './nested-categories';
import combination from './combination';
import Serp from '../app/utils/serp/index';
const $ = window.$;
$(() => {
productHeader();
productSearchAutocomplete();
categoryTree();
attributes();
combination();
bulkCombination().init();
nestedCategory().init();
new Serp(
{
container: '#serp-app',
defaultTitle: '.serp-default-title:input',
watchedTitle: '.serp-watched-title:input',
defaultDescription: '.serp-default-description',
watchedDescription: '.serp-watched-description',
watchedMetaUrl: '.serp-watched-url:input',
},
$('#product_form_preview_btn').data('redirect')
);
// This is the only script for the module page so there is no specific file for it.
$('.modules-list-select').on('change', (e) => {
$('.module-render-container').hide();
$(`.${e.target.value}`).show();
});
$('.modules-list-button').on('click', (e) => {
const target = $(e.target).data('target');
$('.module-selection').show();
$('.modules-list-select').val(target).trigger('change');
return false;
});
});

View File

@@ -0,0 +1,63 @@
/**
* Nested categories management
*/
export default function() {
var nestedCategoriesForm = $('#form_step1_categories');
return {
'init': function() {
if (0 === nestedCategoriesForm.length) {
return;
}
nestedCategoriesForm.categorytree();
this.removeDefaultIfNeeded();
// now we can select default category from nested Categories even if it's not related from a "code" point of view.
nestedCategoriesForm.on('change', 'input.default-category', function updateDefaultCategory() {
var categoryId = $(this).val();
/* we can't select a default category if category is not selected
* that's why we check category first instead of warn user.
*/
var category = nestedCategoriesForm.find('input[value="' + categoryId + '"].category');
var defaultcat = nestedCategoriesForm.find('input[value="' + categoryId + '"].default-category');
if (false === category.is(':checked') && true === defaultcat.is(':checked')) {
category.trigger('click');
}
defaultCategory.check(categoryId);
});
},
'removeDefaultIfNeeded': function() {
/**
* What if we unselect category when it's a default category ?
*/
nestedCategoriesForm.on('change', 'input.category', function removeDefaultCategoryIfNotSelected() {
const findClosestCheckedCategory = function(category) {
const parent = category.closest('ul').parent();
const parentCategory = parent.find('> div > label > input');
if (!parent.is('li')) {
return nestedCategoriesForm.find('input[type="checkbox"]:checked').first()
} else if (parentCategory.prop('checked')) {
return parentCategory;
}
return findClosestCheckedCategory(parent);
};
var categoryId = $(this).val();
var category = nestedCategoriesForm.find('input[value="' + categoryId + '"].category');
var defaultcat = nestedCategoriesForm.find('input[value="' + categoryId + '"].default-category');
if (1 > nestedCategoriesForm.find('input[type="checkbox"]').filter(':checked').length) {
category.prop('checked', true);
} else if (false === category.is(':checked') && true === defaultcat.is(':checked')) {
const newCategory = findClosestCheckedCategory(category);
defaultCategory.check(newCategory.val());
productCategoriesTags.checkDefaultCategory(newCategory.val());
}
});
}
};
}

View File

@@ -0,0 +1,287 @@
/**
* Combination bulk actions management
*/
export default function() {
var bulkForm = $('#bulk-combinations-container');
var deleteCombinationsBtn = $('#delete-combinations');
var applyChangesBtn = $('#apply-on-combinations');
var syncedCollection = $('[data-uniqid]');
var finalPrice = $('#form_step2_price');
var finalPriceIT = $('#form_step2_price_ttc');
var finalPriceBasics = $('#form_step1_price_shortcut');
var finalPriceBasicsIT = $('#form_step1_price_ttc_shortcut');
var impactOnPriceSelector = 'input.attribute_priceTE';
var finalPriceSelector = '.attribute-finalprice span';
return {
'init': function init() {
var that = this;
// stop propagation on buttons
deleteCombinationsBtn.on('click', (event) => {
event.preventDefault();
that.deleteCombinations();
});
applyChangesBtn.on('click', (event) => {
event.preventDefault();
that.applyChangesOnCombinations()
.hideForm()
.resetForm()
.unselectCombinations()
.submitUpdate();
});
/* if final price change with user interaction, combinations should be impacted */
finalPrice.on('blur', () => {
this.syncToPricingTab();
});
finalPriceIT.on('blur', () => {
this.syncToPricingTab();
});
/* if we use final price shortcuts, also combinations should be impacted */
finalPriceBasics.on('blur', () => {
this.syncToPricingTab();
});
finalPriceBasicsIT.on('blur', () => {
this.syncToPricingTab();
});
syncedCollection.on('DOMSubtreeModified', (event) => {
var uniqid = event.target.getAttribute('data-uniqid');
var newValue = event.target.innerText;
var spans = $('[data-uniqid="'+uniqid+'"]');
spans.each( function( index, element ){
if ($(this).text() !== newValue) {
$(this).text(newValue);
}
});
});
// bulk select animation
$('#toggle-all-combinations').on('change', (event) => {
$('#accordion_combinations td:first-child input[type="checkbox"]').each(function() {
$(this).prop('checked', $(event.currentTarget).prop('checked'));
});
});
$(document).on('change', '.js-combination', () => {
if ($('.bulk-action').attr('aria-expanded') === "false" || !$('.js-combination').is(':checked')) {
$('.js-collapse').collapse('toggle');
}
$('span.js-bulk-combinations').text($('input.js-combination:checked').length);
});
},
'getSelectedCombinations': function getSelectedCombinations() {
var combinations = [];
var selectedCombinations = Array.from($('#accordion_combinations td:first-child input[type="checkbox"]:checked'));
selectedCombinations.forEach((combination) => {
var combinationId = combination.getAttribute('data-id');
var combinationIndex = combination.getAttribute('data-index');
combinations.push(new Combination(combinationId, combinationIndex));
});
return combinations;
},
'applyChangesOnCombinations': function applyChangesOnCombinations() {
var values = this.getFormValues();
var combinations = this.getSelectedCombinations();
combinations.forEach((combination) => {
combination.updateForm(values);
combination.syncValues(values);
});
return this;
},
'deleteCombinations': function deleteCombinations() {
var combinations = this.getSelectedCombinations();
var combinationsIds = [];
combinations.forEach((combination) => {
combinationsIds.push(combination.domId);
});
modalConfirmation.create(translate_javascripts['Are you sure to delete this?'], null, {
onContinue: function() {
var deletionURL = $(deleteCombinationsBtn).attr('data');
$.ajax({
type: 'DELETE',
data: {
'attribute-ids': combinationsIds
},
url: deletionURL,
beforeSend: function () {
$('#create-combinations, #apply-on-combinations, #submit, .btn-submit').attr('disabled', 'disabled');
},
success: function(response) {
showSuccessMessage(response.message);
refreshTotalCombinations(-1, combinationsIds.length);
$('span.js-bulk-combinations').text('0');
combinationsIds.forEach((combinationId) => {
var combination = new Combination(combinationId);
combination.removeFromDOM();
});
displayFieldsManager.refresh();
},
error: function(response) {
showErrorMessage(jQuery.parseJSON(response.responseText).message);
},
complete: function () {
$('#create-combinations, #apply-on-combinations, #submit, .btn-submit').removeAttr('disabled');
},
});
}
}).show();
},
'getFormValues': function getFormValues() {
var values = [];
$(bulkForm).find('input').each(function() {
if ($(this).val() !== '' && $(this).attr('id') !== 'product_combination_bulk__token') {
values.push({
'id': $(this).attr('id'),
'value': $(this).val()
});
}
});
return values;
},
'resetForm': function resetForm() {
bulkForm.find('input').val('');
return this;
},
'unselectCombinations': function unselectCombinations() {
// Use of the bulk action button. It has an event listener to unselect all the combinations
$('#toggle-all-combinations').prop('checked', false);
return this;
},
'hideForm': function toggleForm() {
bulkForm.collapse('hide');
return this;
},
'submitUpdate': function submitUpdate() {
var globalProductSubmitButton = $('#form'); // @todo: choose a better identifier
globalProductSubmitButton.submit();
},
'syncToPricingTab': function syncToPricingTab() {
var newPrice = finalPrice.val();
$('tr.combination').toArray().forEach((item) => {
var jQueryRow = $('#'+item.id);
var jQueryFinalPriceEl = jQueryRow.find(finalPriceSelector);
var impactOnPriceEl = jQueryRow.find(impactOnPriceSelector);
var impactOnPrice = impactOnPriceEl.val();
jQueryFinalPriceEl.data('price', newPrice);
// calculate new price
var newFinalPrice = new Number(newPrice) + new Number(impactOnPrice);
jQueryFinalPriceEl.text(ps_round(newFinalPrice, 6));
});
}
};
}
class Combination {
constructor(domId, index) {
this.inputBulkPattern = "product_combination_bulk_";
this.inputPattern = "combination_" + index + "_";
this.domId = domId;
this.appId = 'attribute_' + this.domId;
this.element = $('#' + this.appId);
this.form = $('#combination_form_' + this.domId);
}
isSelected() {
return this.element.checked;
}
removeFromDOM() {
$(this.element).remove();
}
updateForm(values) {
values.forEach((valueObject) => {
var valueId = valueObject.id.substr(this.inputBulkPattern.length);
var $field = $('#'+this.convertInput(valueId));
if ($field.is(':checkbox')) {
$field.prop("checked", !!valueObject.value);
} else {
$field.val(valueObject.value);
}
});
return this.form;
}
/**
* Returns the related input field in legacy form from
* bulk form field
*
* @param bulkInput
* @returns {string}
*/
convertInput(bulkInput) {
var convertedInput = '';
switch (bulkInput) {
case "quantity":
case "reference":
case "minimal_quantity":
case "low_stock_threshold":
case "low_stock_alert":
convertedInput = this.inputPattern + 'attribute_' + bulkInput;
break;
case "cost_price":
convertedInput = this.inputPattern + 'attribute_wholesale_price';
break;
case "date_availability":
convertedInput = this.inputPattern + 'available_date_attribute';
break;
case "impact_on_weight":
convertedInput = this.inputPattern + 'attribute_weight';
break;
case "impact_on_price_te":
convertedInput = this.inputPattern + 'attribute_price';
break;
case "impact_on_price_ti":
convertedInput = this.inputPattern + 'attribute_priceTI';
break;
default:
}
return convertedInput;
}
/**
* Sync values with fast bulk edit form of each combination
*
* @param values
* @returns {bool}
*/
syncValues(values) {
values.forEach((valueObject) => {
var valueId = valueObject.id.substr(this.inputBulkPattern.length);
var value = valueObject.value;
var syncedProperties = [
'quantity',
'impact_on_price_te'
];
if (syncedProperties.indexOf(valueId) !== -1) {
valueId = valueId === 'quantity' ? 'quantity' : 'price';
var input = $(`#attribute_${this.domId} .attribute-${valueId} input`);
input.val(value);
input.change();
}
});
return true;
}
}

View File

@@ -0,0 +1,93 @@
/**
* 2007-2019 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2019 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
const $ = window.$;
export default function() {
const $defaultArrowWidth = 35;
const $arrow = $('.js-arrow');
const $tabs = $('.js-tabs');
const $navTabs = $('.js-nav-tabs');
let $positions;
let $moveTo = 0;
let $tabWidth = 0;
let $navWidth = $defaultArrowWidth;
let $widthWithTabs = 0;
$navTabs.find('li').each((index, item) => {
$navWidth += $(item).width();
});
$navTabs.width($navWidth);
$widthWithTabs = $navWidth + ($defaultArrowWidth * 2);
$navTabs.find('[data-toggle="tab"]').on('click', (e) => {
if (!$(e.target).hasClass('active')) {
$('#form_content > .form-contenttab').removeClass('active');
}
if ($(e.target).attr('href') === '#step1') {
setTimeout(() => {
$('#description_short, #tab_description_short .description-tab').addClass('active');
}, 100);
}
});
$arrow.on('click', (e) => {
if ($arrow.is(':visible')) {
$tabWidth = $navWidth > $navWidth ? $navWidth - $tabs.width() : $tabs.width();
$positions = $navTabs.position();
$moveTo = '-=0';
if ($(e.currentTarget).hasClass('right-arrow')) {
if (($tabWidth - $positions.left) < $navWidth) {
$moveTo = `-=${$tabWidth}`;
}
} else {
if ($positions.left < $defaultArrowWidth) {
$moveTo = `+=${$tabWidth}`;
}
}
$navTabs.animate(
{
left: $moveTo
},
400,
'easeOutQuad',
() => {
if ($(e.currentTarget).hasClass('right-arrow')) {
$('.left-arrow').addClass('visible');
$('.right-arrow').removeClass('visible');
} else {
$('.right-arrow').addClass('visible');
$('.left-arrow').removeClass('visible');
}
}
);
}
});
}

View File

@@ -0,0 +1,130 @@
/**
* 2007-2019 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2019 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
import Bloodhound from 'typeahead.js';
export default function() {
$(document).ready(function() {
$('.autocomplete-search').each(function() {
loadAutocomplete($(this), false);
});
$('.autocomplete-search').on('buildTypeahead', function() {
loadAutocomplete($(this), true);
});
});
function loadAutocomplete(object, reset) {
let autocompleteObject = $(object);
let autocompleteFormId = autocompleteObject.attr('data-formid');
let formId = `#${autocompleteFormId}-data .delete`;
let autocompleteSource = `${autocompleteFormId}_source`;
if (true === reset) {
$('#' + autocompleteFormId).typeahead('destroy');
}
$(document).on('click', formId, (e) => {
e.preventDefault();
window.modalConfirmation.create(window.translate_javascripts['Are you sure to delete this?'], null, {
onContinue: () => {
$(e.target).parents('.media').remove();
// Save current product after its related product has been removed
$('#submit').click();
}
}).show();
});
document[autocompleteSource] = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) {
return obj[autocompleteObject.attr('data-mappingvalue')];
},
remote: {
url: autocompleteObject.attr('data-remoteurl'),
cache: false,
wildcard: '%QUERY',
transform: function(response) {
if (!response) {
return [];
}
return response;
}
}
});
//define typeahead
$('#' + autocompleteFormId).typeahead({
limit: 20,
minLength: 2,
highlight: true,
cache: false,
hint: false,
}, {
display: autocompleteObject.attr('data-mappingname'),
source: document[autocompleteFormId + '_source'],
limit: 30,
templates: {
suggestion: function(item) {
return '<div><img src="' + item.image + '" style="width:50px" /> ' + item.name + '</div>';
}
}
}).bind('typeahead:select', function(e, suggestion) {
//if collection length is up to limit, return
let formIdItem = $(`#${autocompleteFormId}-data li`);
let autocompleteFormLimit = parseInt(autocompleteObject.attr('data-limit'));
if (autocompleteFormLimit !== 0 && formIdItem.length >= autocompleteFormLimit) {
return false;
}
var value = suggestion[autocompleteObject.attr('data-mappingvalue')];
if (suggestion.id_product_attribute) {
value = value + ',' + suggestion.id_product_attribute;
}
let tplcollection = $('#tplcollection-' + autocompleteFormId);
let tplcollectionHtml = tplcollection.html().replace('%s', suggestion[autocompleteObject.attr('data-mappingname')]);
var html = `<li class="media">
<div class="media-left">
<img class="media-object image" src="${suggestion.image}" />
</div>
<div class="media-body media-middle">
${tplcollectionHtml}
</div>
<input type="hidden" name="${autocompleteObject.attr('data-fullname')}[data][]" value="${value}" />
</li>`;
$('#' + autocompleteFormId + '-data').append(html);
}).bind('typeahead:close', function(e) {
$(e.target).val('');
});
}
}