Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
fix codestyling form js files with prettier+
Julian Böhnke19df38e72afb
diff --git a/package.json b/package.jsonindex ab946f144a..be588f572a 100644--- a/package.json+++ b/package.json@@ -103,6 +103,7 @@"build-schema": "python manage.py get_graphql_schema > saleor/graphql/schema.graphql","heroku-postbuild": "npm run build-assets && npm run build-emails","start": "webpack -d --watch",- "build-emails": "mjml --config.beautify false -l skip \"templates/templated_email/source/*.mjml\" -o templates/templated_email/compiled"+ "build-emails": "mjml --config.beautify false -l skip \"templates/templated_email/source/*.mjml\" -o templates/templated_email/compiled",+ "prettier": "prettier --write \"saleor/static/**/*.js\""}}diff --git a/saleor/static/dashboard/js/components/async-form.js b/saleor/static/dashboard/js/components/async-form.jsindex af9c88c876..3139ae23b9 100644--- a/saleor/static/dashboard/js/components/async-form.js+++ b/saleor/static/dashboard/js/components/async-form.js@@ -1,6 +1,6 @@import { initSelects } from './selects';-const onAsyncFormSubmit = (e) => {+const onAsyncFormSubmit = e => {const $target = $(e.currentTarget);let $action = $target.attr('action');const $submitButton = $target.find('button[type=submit][clicked=true]');@@ -12,7 +12,7 @@ const onAsyncFormSubmit = (e) => {url: $action,method: 'POST',data: $target.serialize(),- complete: (response) => {+ complete: response => {// Write HTML if got 400 response, otherwise pretend nothing happenedif (response.status === 400) {$target.parent().html(response.responseText);@@ -21,7 +21,7 @@ const onAsyncFormSubmit = (e) => {$('.modal-close').click();}},- success: (response) => {+ success: response => {if (response.redirectUrl) {window.location.href = response.redirectUrl;} else {@@ -32,7 +32,7 @@ const onAsyncFormSubmit = (e) => {e.preventDefault();};-const onAsyncFormButtonClick = (e) => {+const onAsyncFormButtonClick = e => {const $button = $(e.currentTarget);const $formAsync = $button.parents('.form-async');$('button[type=submit]', $formAsync).removeAttr('clicked');diff --git a/saleor/static/dashboard/js/components/bulk-actions.js b/saleor/static/dashboard/js/components/bulk-actions.jsindex 9f4e439ea8..a87d30e3a7 100644--- a/saleor/static/dashboard/js/components/bulk-actions.js+++ b/saleor/static/dashboard/js/components/bulk-actions.js@@ -3,26 +3,25 @@* Fixes bug when user checks some items, goes to another page, then goes back in browsing history* and some rows are checked but have no .highlight class.*/-function initCheckedRows () {- $('.select-item:checked:not(#select-all-items)')- .each((itemIndex, item) => {- $(item)- .parent()- .parent()- .addClass('highlight');- });- $('.select-item:not(:checked):not(#select-all-items)')- .each((itemIndex, item) => {+function initCheckedRows() {+ $('.select-item:checked:not(#select-all-items)').each((itemIndex, item) => {+ $(item)+ .parent()+ .parent()+ .addClass('highlight');+ });+ $('.select-item:not(:checked):not(#select-all-items)').each(+ (itemIndex, item) => {$(item).parent().parent().removeClass('highlight');- });+ }+ );}-function moveSelectAllCheckbox (bulk, selectAllState) {- const $selectAll = $('#select-all-items')- .parent()[0].innerHTML;+function moveSelectAllCheckbox(bulk, selectAllState) {+ const $selectAll = $('#select-all-items').parent()[0].innerHTML;const $headerContainer = $('thead .bulk-checkbox');const $actionBarContainer = $('.data-table-bulk-actions__select-all');if (bulk) {@@ -32,38 +31,37 @@ function moveSelectAllCheckbox (bulk, selectAllState) {$actionBarContainer.html('');$headerContainer[0].innerHTML = $selectAll;}- $actionBarContainer.find('#select-all-items')- .prop('checked', selectAllState);- $('.select-all')- .on('change', onSelectAll);+ $actionBarContainer.find('#select-all-items').prop('checked', selectAllState);+ $('.select-all').on('change', onSelectAll);}-function onItemSelect (e) {- const count = $('.select-item:checked').length - $('#select-all-items:checked').length;+function onItemSelect(e) {+ const count =+ $('.select-item:checked').length - $('#select-all-items:checked').length;const maxCount = $('.select-item').length - 1;const $target = $(e.currentTarget);- $target.parent()+ $target+ .parent().parent().toggleClass('highlight', $target.checked);updateSelectedItemsText(count === maxCount);}-function onPageInit () {+function onPageInit() {if (document.querySelector('#bulk-action')) {initCheckedRows();updateSelectedItemsText();- $('.select-all')- .on('change', onSelectAll);- $('.select-item')- .on('change', onItemSelect);- $('.data-table-bulk-actions__action-choice a')- .on('click', onSubmit);- $('.data-table-bulk-actions__dropdown-container .dropdown-content a')- .on('click', onSubmit);+ $('.select-all').on('change', onSelectAll);+ $('.select-item').on('change', onItemSelect);+ $('.data-table-bulk-actions__action-choice a').on('click', onSubmit);+ $('.data-table-bulk-actions__dropdown-container .dropdown-content a').on(+ 'click',+ onSubmit+ );}}-function onSelectAll (e) {+function onSelectAll(e) {const $target = $(e.currentTarget);const $targetForm = $target.parents('form');const $items = $targetForm.find('.select-item:not(.select-all)');@@ -73,17 +71,16 @@ function onSelectAll (e) {updateSelectedItemsText($target[0].checked);}-function onSubmit (e) {+function onSubmit(e) {const a = $(e.currentTarget);e.preventDefault();- $('#bulk-action')- .val(a.attr('data-action'));- $('#bulk-actions-form')- .submit();+ $('#bulk-action').val(a.attr('data-action'));+ $('#bulk-actions-form').submit();}-function updateSelectedItemsText (selectAllState) {- const count = $('.select-item:checked').length - $('#select-all-items:checked').length;+function updateSelectedItemsText(selectAllState) {+ const count =+ $('.select-item:checked').length - $('#select-all-items:checked').length;const $counterTextNode = $('.data-table-bulk-actions__selected-items');const $header = $('.data-table-bulk-actions');const counterText = ngettext('item selected', 'items selected', count);diff --git a/saleor/static/dashboard/js/components/datepicker.js b/saleor/static/dashboard/js/components/datepicker.jsindex 9bc14a437d..e7228ca015 100644--- a/saleor/static/dashboard/js/components/datepicker.js+++ b/saleor/static/dashboard/js/components/datepicker.js@@ -21,7 +21,8 @@ $('.datepicker').pickadate({pgettext('Datepicker month', 'September'),pgettext('Datepicker month', 'October'),pgettext('Datepicker month', 'November'),- pgettext('Datepicker month', 'December')],+ pgettext('Datepicker month', 'December')+ ],monthsShort: [pgettext('Datepicker month shortcut', 'Jan'),pgettext('Datepicker month shortcut', 'Feb'),@@ -34,7 +35,8 @@ $('.datepicker').pickadate({pgettext('Datepicker month shortcut', 'Sep'),pgettext('Datepicker month shortcut', 'Oct'),pgettext('Datepicker month shortcut', 'Nov'),- pgettext('Datepicker month shortcut', 'Dec')],+ pgettext('Datepicker month shortcut', 'Dec')+ ],weekdaysFull: [pgettext('Datepicker weekday', 'Sunday'),pgettext('Datepicker weekday', 'Monday'),@@ -42,7 +44,8 @@ $('.datepicker').pickadate({pgettext('Datepicker weekday', 'Wednesday'),pgettext('Datepicker weekday', 'Thursday'),pgettext('Datepicker weekday', 'Friday'),- pgettext('Datepicker weekday', 'Saturday')],+ pgettext('Datepicker weekday', 'Saturday')+ ],weekdaysShort: [pgettext('Datepicker weekday shortcut', 'Sun'),pgettext('Datepicker weekday shortcut', 'Mon'),@@ -50,7 +53,8 @@ $('.datepicker').pickadate({pgettext('Datepicker weekday shortcut', 'Wed'),pgettext('Datepicker weekday shortcut', 'Thu'),pgettext('Datepicker weekday shortcut', 'Fri'),- pgettext('Datepicker weekday shortcut', 'Sat')],+ pgettext('Datepicker weekday shortcut', 'Sat')+ ],// Materialize modifiedweekdaysLetter: [@@ -60,7 +64,8 @@ $('.datepicker').pickadate({pgettext('Wednesday shortcut', 'W'),pgettext('Thursday shortcut', 'T'),pgettext('Friday shortcut', 'F'),- pgettext('Saturday shortcut', 'S')],+ pgettext('Saturday shortcut', 'S')+ ],today: pgettext('Datepicker option', 'Today'),clear: pgettext('Datepicker option', 'Clear'),close: pgettext('Datepicker option', 'Close'),diff --git a/saleor/static/dashboard/js/components/editor.js b/saleor/static/dashboard/js/components/editor.jsindex 586ae7f25b..744a55af0c 100644--- a/saleor/static/dashboard/js/components/editor.js+++ b/saleor/static/dashboard/js/components/editor.js@@ -58,7 +58,10 @@ const editor = new MediumEditor('.rich-text-editor', {},{name: 'image',- aria: pgettext('Rich text editor option', 'Image (converts selected text to an image tag)'),+ aria: pgettext(+ 'Rich text editor option',+ 'Image (converts selected text to an image tag)'+ ),contentDefault: `<img src="${insertPhotoIcon}">`},{diff --git a/saleor/static/dashboard/js/components/filters.js b/saleor/static/dashboard/js/components/filters.jsindex 99e4fedf2c..019bebe979 100644--- a/saleor/static/dashboard/js/components/filters.js+++ b/saleor/static/dashboard/js/components/filters.js@@ -30,7 +30,7 @@ if ($filters.length) {$(window).on('resize', moveFilters);}-$('.collapse-activate').on('click', (e) => {+$('.collapse-activate').on('click', e => {const $collapsibleCard = $('.collapse');if ($collapsibleCard.hasClass('collapsed')) {$collapsibleCard.removeClass('collapsed');diff --git a/saleor/static/dashboard/js/components/google-preview.js b/saleor/static/dashboard/js/components/google-preview.jsindex 3cecc528d9..c3f5453005 100644--- a/saleor/static/dashboard/js/components/google-preview.js+++ b/saleor/static/dashboard/js/components/google-preview.js@@ -9,7 +9,9 @@ const $descriptionMaterialize = $seoDescription.data('materialize');let $description = '';const $descriptionId = $seoDescription.data('bind');if ($descriptionMaterialize) {- const $descriptions = $(`.materialize-textarea[name='${$descriptionMaterialize}']`);+ const $descriptions = $(+ `.materialize-textarea[name='${$descriptionMaterialize}']`+ );// They're two textareas from Medium editor, first one contains HTML-free text$description = $descriptions.not($descriptionId).first();} else {@@ -43,11 +45,19 @@ function updateCharsCount(seoField) {if ($fieldLength < $minRecommendedLength) {$charCountWrapper.addClass('orange-text');$charCountWrapper.removeClass('green-text');- $charCountWrapper.attr('title', gettext('Your input might be a little too short, think of something more descriptive'));+ $charCountWrapper.attr(+ 'title',+ gettext(+ 'Your input might be a little too short, think of something more descriptive'+ )+ );} else {$charCountWrapper.removeClass('orange-text');$charCountWrapper.addClass('green-text');- $charCountWrapper.attr('title', gettext('Your input fits between the recommended lengths'));+ $charCountWrapper.attr(+ 'title',+ gettext('Your input fits between the recommended lengths')+ );}$charCount.text($fieldLength);}@@ -71,7 +81,7 @@ function truncate(text, seoField) {}function updatePlaceholderOnInput(field, seoField, previewField) {- field.on(watchedEvents, (e) => {+ field.on(watchedEvents, e => {const $target = $(e.currentTarget);const $placeholderText = $target.val() || $target.text();seoField.attr('placeholder', truncate($placeholderText, seoField));@@ -85,7 +95,7 @@ function updatePlaceholderOnInput(field, seoField, previewField) {}function updatePreviewOnInput(seoField, previewField) {- seoField.on(watchedEvents, (e) => {+ seoField.on(watchedEvents, e => {const $target = $(e.currentTarget);const $currentText = $target.val();if ($currentText) {@@ -109,8 +119,16 @@ if ($seoTitle.length) {}if ($seoDescription.length) {if ($description) {- setPlaceholderAndPreview($description, $seoDescription, $googleDescriptionPreview);- updatePlaceholderOnInput($description, $seoDescription, $googleDescriptionPreview);+ setPlaceholderAndPreview(+ $description,+ $seoDescription,+ $googleDescriptionPreview+ );+ updatePlaceholderOnInput(+ $description,+ $seoDescription,+ $googleDescriptionPreview+ );}updatePreviewOnInput($seoDescription, $googleDescriptionPreview);updateCharsCount($seoDescription);diff --git a/saleor/static/dashboard/js/components/image-gallery.js b/saleor/static/dashboard/js/components/image-gallery.jsindex 72c7de26a7..6acfa0728a 100644--- a/saleor/static/dashboard/js/components/image-gallery.js+++ b/saleor/static/dashboard/js/components/image-gallery.js@@ -1,7 +1,7 @@// eslint-disable-next-line no-unused-varsimport Dropzone from 'dropzone';-function createLink (link, index, replacement) {+function createLink(link, index, replacement) {const outputLink = link.attr('data-href-template').split('/');outputLink[outputLink.length + index] = replacement;return outputLink.join('/');@@ -18,7 +18,7 @@ $('#product-image-form').dropzone({previewTemplate: $('#template').html(),method: 'POST',clickable: '.dropzone-message',- init: function () {+ init: function() {this.on('success', (e, response) => {const $previewElement = $(e.previewElement);$previewElement.find('.product-gallery-item-desc').html(response.image);diff --git a/saleor/static/dashboard/js/components/load-action.js b/saleor/static/dashboard/js/components/load-action.jsindex 877d3e9ace..630ef895ab 100644--- a/saleor/static/dashboard/js/components/load-action.js+++ b/saleor/static/dashboard/js/components/load-action.js@@ -1,8 +1,8 @@-function disableSubsequentClicks (e) {+function disableSubsequentClicks(e) {e.preventDefault();}-function initLoadAction (e) {+function initLoadAction(e) {$('body').css('cursor', 'progress');$(e.target).on('click', disableSubsequentClicks);}diff --git a/saleor/static/dashboard/js/components/messages.js b/saleor/static/dashboard/js/components/messages.jsindex bdc3677052..3e4488ebd3 100644--- a/saleor/static/dashboard/js/components/messages.js+++ b/saleor/static/dashboard/js/components/messages.js@@ -7,7 +7,7 @@ const firstMessageOffset = 250;// -----if (data) {- Object.keys(data).forEach((key) => {+ Object.keys(data).forEach(key => {Materialize.toast(data[key], 5000);});}diff --git a/saleor/static/dashboard/js/components/misc.js b/saleor/static/dashboard/js/components/misc.jsindex 82a0bbdb1a..a4808819c2 100644--- a/saleor/static/dashboard/js/components/misc.js+++ b/saleor/static/dashboard/js/components/misc.js@@ -23,12 +23,12 @@ initSelects();$('.modal').modal();// Print button-$('.btn-print').click((e) => {+$('.btn-print').click(e => {window.print();});// Clickable rows in dashboard tables-$(document).on('mouseup', 'tr[data-action-go] > td:not(.ignore-link)', (e) => {+$(document).on('mouseup', 'tr[data-action-go] > td:not(.ignore-link)', e => {const $target = $(e.currentTarget);// Ignore selecting textconst selectedText = getSelection().toString();@@ -42,7 +42,7 @@ $(document).on('mouseup', 'tr[data-action-go] > td:not(.ignore-link)', (e) => {// Publish / unpublish lever in detail viewsconst selectors = ['#product-is-published', '#collection-is-published'];selectors.forEach(selector => {- $(selector).on('click', (e) => {+ $(selector).on('click', e => {const form = $(e.currentTarget).closest('#toggle-publish-form');const input = form.find('#toggle-publish-switch')[0];if (e.target === input) {@@ -53,19 +53,20 @@ selectors.forEach(selector => {headers: {'X-CSRFToken': $('[name=csrfmiddlewaretoken]').val()}- }).then(() => {- window.location.reload();- }).catch(() => {- window.location.reload();- });+ })+ .then(() => {+ window.location.reload();+ })+ .catch(() => {+ window.location.reload();+ });}});});// Styleguide sticky right menu-onScroll(() => $('.styleguide__menu').toggleClass('fixed', $(window).scrollTop() > 100));+onScroll(() =>+ $('.styleguide__menu').toggleClass('fixed', $(window).scrollTop() > 100)+);-export {- screenSizes,- svgInjector-};+export { screenSizes, svgInjector };diff --git a/saleor/static/dashboard/js/components/modal.js b/saleor/static/dashboard/js/components/modal.jsindex 7c281e6726..977f4fa04d 100644--- a/saleor/static/dashboard/js/components/modal.js+++ b/saleor/static/dashboard/js/components/modal.js@@ -10,17 +10,15 @@ const focusInputs = [// ------$('body').on('click', '.modal-trigger-custom', (e) => {+$('body').on('click', '.modal-trigger-custom', e => {const target = e.currentTarget;e.preventDefault();$.ajax({url: target.dataset.href,method: 'GET',- success: (response) => {+ success: response => {const $modal = $(target.getAttribute('href'));- $modal- .html(response)- .modal('open');+ $modal.html(response).modal('open');initSelects();const inputs = $modal.find(focusInputs.join(','));@@ -30,7 +28,7 @@ $('body').on('click', '.modal-trigger-custom', (e) => {}// Image checkbox selector- $('.image_select-item-overlay').on('click', (e) => {+ $('.image_select-item-overlay').on('click', e => {const imageId = e.currentTarget.getAttribute('id');const checkbox = document.querySelector('input#' + imageId);const checkboxState = checkbox.getAttribute('checked');@@ -39,7 +37,11 @@ $('body').on('click', '.modal-trigger-custom', (e) => {});// Inject all SVGs from modal- svgInjector.inject(document.querySelectorAll('.modal-content svg[data-src]:not(.injected-svg)'));+ svgInjector.inject(+ document.querySelectorAll(+ '.modal-content svg[data-src]:not(.injected-svg)'+ )+ );}});});diff --git a/saleor/static/dashboard/js/components/search.js b/saleor/static/dashboard/js/components/search.jsindex e4e898bcfc..040eae6a95 100644--- a/saleor/static/dashboard/js/components/search.js+++ b/saleor/static/dashboard/js/components/search.js@@ -1,15 +1,17 @@-function submit (e) {+function submit(e) {e.preventDefault();- $(e.currentTarget).parent().submit();+ $(e.currentTarget)+ .parent()+ .submit();}-function openSearchBar (e) {+function openSearchBar(e) {e.preventDefault();const $target = $(e.currentTarget);$('.search').toggleClass('expanded', !$target.hasClass('expanded'));}-function closeSearchBar (e) {+function closeSearchBar(e) {const $target = $(e.currentTarget);const isExpanded = $target.hasClass('expanded');$('.search').toggleClass('expanded', isExpanded);diff --git a/saleor/static/dashboard/js/components/selects.js b/saleor/static/dashboard/js/components/selects.jsindex f26e6df572..98c1585acd 100644--- a/saleor/static/dashboard/js/components/selects.js+++ b/saleor/static/dashboard/js/components/selects.js@@ -1,8 +1,11 @@import 'select2';-function appendOption ($select, option) {- $select.append($('<option></option>')- .attr('value', option.id).text(option.text));+function appendOption($select, option) {+ $select.append(+ $('<option></option>')+ .attr('value', option.id)+ .text(option.text)+ );}function initSelects() {@@ -14,8 +17,12 @@ function initSelects() {});$variantAttrsSelect.addClass('select2-enabled');- $('select:not(.browser-default):not(.enable-ajax-select2):not([multiple])').material_select();- $('select[multiple]:not(.browser-default):not(.enable-ajax-select2)').select2({width: '100%'});+ $(+ 'select:not(.browser-default):not(.enable-ajax-select2):not([multiple])'+ ).material_select();+ $('select[multiple]:not(.browser-default):not(.enable-ajax-select2)').select2(+ { width: '100%' }+ );$('select.enable-ajax-select2:not(.select2-enabled)').each((i, select) => {const $select = $(select);@@ -23,9 +30,9 @@ function initSelects() {if (initial) {const initialData = initial instanceof Array ? initial : [initial];- const selected = initialData.map((item) => {+ const selected = initialData.map(item => {appendOption($select, item);- return (item.id);+ return item.id;});$select.val(selected);}@@ -42,6 +49,4 @@ function initSelects() {});}-export {- initSelects-};+export { initSelects };diff --git a/saleor/static/dashboard/js/components/side-menu.js b/saleor/static/dashboard/js/components/side-menu.jsindex 8b6bdd5e9e..0deb093585 100644--- a/saleor/static/dashboard/js/components/side-menu.js+++ b/saleor/static/dashboard/js/components/side-menu.js@@ -1,6 +1,6 @@import { onScroll } from './utils';-function toggleMenu (e) {+function toggleMenu(e) {e.preventDefault();$('body').toggleClass('nav-toggled');}@@ -15,7 +15,8 @@ if ($mainNavTop.length) {$toggleMenu.on('click', toggleMenu);if ($mainNavTop.length > 0) {onScroll(() => {- const stickSideMenu = Math.floor($(window).scrollTop()) > Math.ceil(mainNavTop);+ const stickSideMenu =+ Math.floor($(window).scrollTop()) > Math.ceil(mainNavTop);$('body').toggleClass('sticky-nav', stickSideMenu);});}diff --git a/saleor/static/dashboard/js/components/tab.js b/saleor/static/dashboard/js/components/tab.jsindex ff157d42e8..b5bea935d2 100644--- a/saleor/static/dashboard/js/components/tab.js+++ b/saleor/static/dashboard/js/components/tab.js@@ -1,6 +1,6 @@const $tabs = $('ul.tabs');if ($tabs.length) {- $tabs.find('.tab').on('click', (e) => {+ $tabs.find('.tab').on('click', e => {const tabSelector = $(e.currentTarget).find('a').attr('href');@@ -8,7 +8,8 @@ if ($tabs.length) {$(tabSelector + '-btn').removeClass('btn-fab-hidden');});- $tabs.find('a.active')+ $tabs+ .find('a.active').parent().click();}diff --git a/saleor/static/dashboard/js/components/utils.js b/saleor/static/dashboard/js/components/utils.jsindex 61621729c2..7e066041bb 100644--- a/saleor/static/dashboard/js/components/utils.js+++ b/saleor/static/dashboard/js/components/utils.js@@ -2,9 +2,15 @@ import detectPassiveEvents from 'detect-passive-events';import { parse, stringify } from 'qs';function onScroll(func) {- window.addEventListener('scroll', func, detectPassiveEvents.hasSupport ? {- passive: true- } : false);+ window.addEventListener(+ 'scroll',+ func,+ detectPassiveEvents.hasSupport+ ? {+ passive: true+ }+ : false+ );}function createQueryString(currentQs, newData) {@@ -13,7 +19,4 @@ function createQueryString(currentQs, newData) {return `?${data}`;}-export {- onScroll,- createQueryString-};+export { onScroll, createQueryString };diff --git a/saleor/static/dashboard/js/components/vouchers.js b/saleor/static/dashboard/js/components/vouchers.jsindex 9f8a3d3135..02070ac5e6 100644--- a/saleor/static/dashboard/js/components/vouchers.js+++ b/saleor/static/dashboard/js/components/vouchers.js@@ -2,7 +2,7 @@* Handler for voucher type change event. Manages showing options* that are connected to selected voucher type and hiding others.*/-function onVoucherTypeChange (e) {+function onVoucherTypeChange(e) {const $target = $(e.currentTarget);$('.voucher-form').each((index, form) => {const $form = $(form);@@ -14,9 +14,10 @@ function onVoucherTypeChange (e) {* Handler for discount type change event. Shows additional options* if 'percentage' option is selected.*/-function onDiscountTypeChange (e) {+function onDiscountTypeChange(e) {const $target = $(e.currentTarget);- const showOnPercentage = '[name="product-apply_to"], [name="category-apply_to"]';+ const showOnPercentage =+ '[name="product-apply_to"], [name="category-apply_to"]';const $showOnPercentage = $(showOnPercentage).parents('.input');$showOnPercentage.toggleClass('hide', $target.val() === 'percentage');}diff --git a/saleor/static/js/components/address-form.js b/saleor/static/js/components/address-form.jsindex 3d61fd5d44..98f1202ef5 100644--- a/saleor/static/js/components/address-form.js+++ b/saleor/static/js/components/address-form.js@@ -1,7 +1,7 @@-export default $(document).ready((e) => {- $(function () {+export default $(document).ready(e => {+ $(function() {const $i18nAddresses = $('.i18n-address');- $i18nAddresses.each(function () {+ $i18nAddresses.each(function() {const $form = $(this).closest('form');const $countryField = $form.find('select[name=country]');const $previewField = $form.find('input.preview');@@ -16,7 +16,7 @@ export default $(document).ready((e) => {let $deleteAdressIcon = $('.delete-icon');let $deleteAddress = $('.address-delete');- $deleteAdressIcon.on('click', (e) => {+ $deleteAdressIcon.on('click', e => {if ($deleteAddress.hasClass('none')) {$deleteAddress.removeClass('none');$deleteAdressIcons.addClass('none');@@ -25,7 +25,7 @@ export default $(document).ready((e) => {}});- $deleteAddress.find('.cancel').on('click', (e) => {+ $deleteAddress.find('.cancel').on('click', e => {$deleteAddress.addClass('none');$deleteAdressIcons.removeClass('none');});@@ -36,10 +36,10 @@ export default $(document).ready((e) => {let $addressHide = $('.address_hide label');let $addressForm = $('.checkout__new-address');let $initialValue = $('#address_new_address').prop('checked');- $addressShow.click((e) => {+ $addressShow.click(e => {$addressForm.slideDown('slow');});- $addressHide.click((e) => {+ $addressHide.click(e => {$addressForm.slideUp('slow');});if ($initialValue) {diff --git a/saleor/static/js/components/checkout.js b/saleor/static/js/components/checkout.jsindex a02bdd5859..09b3d61778 100644--- a/saleor/static/js/components/checkout.js+++ b/saleor/static/js/components/checkout.js@@ -1,4 +1,4 @@-import {getAjaxError} from './misc';+import { getAjaxError } from './misc';export const summaryLink = $('html').data('checkout-summary-url');export const $checkoutDropdown = $('.checkout-preview-dropdown');@@ -6,39 +6,49 @@ export const $checkoutIcon = $('.checkout__icon');export const $addToCheckoutError = $('.product__info__form-error small');export const $removeProductSuccess = $('.remove-product-alert');-export const onAddToCheckoutError = (response) => {+export const onAddToCheckoutError = response => {$addToCheckoutError.html(getAjaxError(response));};export const onAddToCheckoutSuccess = () => {- $.get(summaryLink, (data) => {+ $.get(summaryLink, data => {$checkoutDropdown.html(data);$addToCheckoutError.html('');var newQunatity = $('.checkout-preview-dropdown__total').data('quantity');- $('.badge').html(newQunatity).removeClass('empty');+ $('.badge')+ .html(newQunatity)+ .removeClass('empty');$checkoutDropdown.addClass('show');$checkoutIcon.addClass('hover');- $checkoutDropdown.find('.checkout-preview-dropdown__list').scrollTop($checkoutDropdown.find('.checkout-preview-dropdown__list')[0].scrollHeight);- setTimeout((e) => {+ $checkoutDropdown+ .find('.checkout-preview-dropdown__list')+ .scrollTop(+ $checkoutDropdown.find('.checkout-preview-dropdown__list')[0]+ .scrollHeight+ );+ setTimeout(e => {$checkoutDropdown.removeClass('show');$checkoutIcon.removeClass('hover');}, 2500);});};-export default $(document).ready((e) => {+export default $(document).ready(e => {// Checkout dropdown- $.get(summaryLink, (data) => {+ $.get(summaryLink, data => {$checkoutDropdown.html(data);});- $('.navbar__brand__checkout').hover((e) => {- $checkoutDropdown.addClass('show');- $checkoutIcon.addClass('hover');- }, (e) => {- $checkoutDropdown.removeClass('show');- $checkoutIcon.removeClass('hover');- });- $('.product-form button').click((e) => {+ $('.navbar__brand__checkout').hover(+ e => {+ $checkoutDropdown.addClass('show');+ $checkoutIcon.addClass('hover');+ },+ e => {+ $checkoutDropdown.removeClass('show');+ $checkoutIcon.removeClass('hover');+ }+ );+ $('.product-form button').click(e => {e.preventDefault();let $target = $(e.target.form);let quantity = $target.find('input[name="quantity"]').val();@@ -53,19 +63,19 @@ export default $(document).ready((e) => {success: () => {onAddToCheckoutSuccess();},- error: (response) => {+ error: response => {onAddToCheckoutError(response);}});});- $('.checkout-preview__clear').click((e) => {+ $('.checkout-preview__clear').click(e => {$.ajax({url: $('.checkout-preview__clear').data('action'),method: 'POST',data: {},- success: (response) => {+ success: response => {$('.badge').html(response.numItems);- $.cookie('alert', 'true', {path: '/checkout'});+ $.cookie('alert', 'true', { path: '/checkout' });location.reload();}});@@ -77,25 +87,29 @@ export default $(document).ready((e) => {let $total = $('.checkout-preview-subtotal');let $checkoutBadge = $('.navbar__brand__checkout .badge');let $closeMsg = $('.close-msg');- $closeMsg.on('click', (e) => {+ $closeMsg.on('click', e => {$removeProductSuccess.addClass('d-none');});- $checkoutLine.each(function () {+ $checkoutLine.each(function() {let $quantityInput = $(this).find('#id_quantity');- let checkoutFormUrl = $(this).find('.form-checkout').attr('action');- let $qunatityError = $(this).find('.checkout-preview__line__quantity-error');+ let checkoutFormUrl = $(this)+ .find('.form-checkout')+ .attr('action');+ let $qunatityError = $(this).find(+ '.checkout-preview__line__quantity-error'+ );let $subtotal = $(this).find('.checkout-preview-item-price p');let $deleteIcon = $(this).find('.checkout-preview-item-delete');- $(this).on('change', $quantityInput, (e) => {+ $(this).on('change', $quantityInput, e => {let newQuantity = $quantityInput.val();$.ajax({url: checkoutFormUrl,method: 'POST',- data: {quantity: newQuantity},- success: (response) => {+ data: { quantity: newQuantity },+ success: response => {if (newQuantity === 0) {if (response.checkout.numLines === 0) {- $.cookie('alert', 'true', {path: '/checkout'});+ $.cookie('alert', 'true', { path: '/checkout' });location.reload();} else {$removeProductSuccess.removeClass('d-none');@@ -109,17 +123,17 @@ export default $(document).ready((e) => {$checkoutDropdown.load(summaryLink);deliveryAjax();},- error: (response) => {+ error: response => {$qunatityError.html(getAjaxError(response));}});});- $deleteIcon.on('click', (e) => {+ $deleteIcon.on('click', e => {$.ajax({url: checkoutFormUrl,method: 'POST',- data: {quantity: 0},- success: (response) => {+ data: { quantity: 0 },+ success: response => {if (response.checkout.numLines >= 1) {$(this).fadeOut();$total.html(response.total);@@ -127,7 +141,7 @@ export default $(document).ready((e) => {$checkoutDropdown.load(summaryLink);$removeProductSuccess.removeClass('d-none');} else {- $.cookie('alert', 'true', {path: '/checkout'});+ $.cookie('alert', 'true', { path: '/checkout' });location.reload();}deliveryAjax();@@ -142,16 +156,16 @@ export default $(document).ready((e) => {let crsfToken = $deliveryForm.data('crsf');let countrySelect = '#id_country';let $checkoutSubtotal = $('.checkout__subtotal');- let deliveryAjax = (e) => {+ let deliveryAjax = e => {let newCountry = $(countrySelect).val();$.ajax({url: $('html').data('shipping-options-url'),type: 'POST',data: {- 'csrfmiddlewaretoken': crsfToken,- 'country': newCountry+ csrfmiddlewaretoken: crsfToken,+ country: newCountry},- success: (data) => {+ success: data => {$checkoutSubtotal.html(data);}});@@ -161,6 +175,6 @@ export default $(document).ready((e) => {if ($.cookie('alert') === 'true') {$removeProductSuccess.removeClass('d-none');- $.cookie('alert', 'false', {path: '/checkout'});+ $.cookie('alert', 'false', { path: '/checkout' });}});diff --git a/saleor/static/js/components/description-json.js b/saleor/static/js/components/description-json.jsindex 853740dd69..9f42ea66d4 100644--- a/saleor/static/js/components/description-json.js+++ b/saleor/static/js/components/description-json.js@@ -8,4 +8,4 @@ export default $(document).ready(e => {const content = draftToHtml(parsed);description.innerHTML = content;}-});\ No newline at end of file+});diff --git a/saleor/static/js/components/footer.js b/saleor/static/js/components/footer.jsindex 057b7a7207..05121e5675 100644--- a/saleor/static/js/components/footer.js+++ b/saleor/static/js/components/footer.js@@ -1,6 +1,9 @@-export default $(document).ready((e) => {+export default $(document).ready(e => {let navbarHeight = $('.navbar').outerHeight(true);let footerHeight = $('.footer').outerHeight(true);let windowHeight = $(window).height();- $('.maincontent').css('min-height', windowHeight - navbarHeight - footerHeight);+ $('.maincontent').css(+ 'min-height',+ windowHeight - navbarHeight - footerHeight+ );});diff --git a/saleor/static/js/components/language-picker.js b/saleor/static/js/components/language-picker.jsindex b07de3a987..6ea913dec5 100644--- a/saleor/static/js/components/language-picker.js+++ b/saleor/static/js/components/language-picker.js@@ -1,7 +1,9 @@-$('.language-pick').on('click', (e) => {+$('.language-pick').on('click', e => {const $option = $(e.currentTarget);const $langCode = $option.data('lang');- const $input = $(`<input name="language" type="hidden" value="${$langCode}">`);+ const $input = $(+ `<input name="language" type="hidden" value="${$langCode}">`+ );const $languagePickerForm = $('#language-picker');$languagePickerForm.append($input);$languagePickerForm.submit();diff --git a/saleor/static/js/components/misc.js b/saleor/static/js/components/misc.jsindex cfd057f1d9..2da8a9b26e 100644--- a/saleor/static/js/components/misc.js+++ b/saleor/static/js/components/misc.js@@ -1,13 +1,13 @@import 'lazysizes';import SVGInjector from 'svg-injector-2';-export const getAjaxError = (response) => {+export const getAjaxError = response => {let ajaxError = $.parseJSON(response.responseText).error.quantity;return ajaxError;};export const csrftoken = $.cookie('csrftoken');-export default $(document).ready((e) => {+export default $(document).ready(e => {function csrfSafeMethod(method) {return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method);}@@ -15,7 +15,7 @@ export default $(document).ready((e) => {new SVGInjector().inject(document.querySelectorAll('svg[data-src]'));$.ajaxSetup({- beforeSend: function (xhr, settings) {+ beforeSend: function(xhr, settings) {if (!csrfSafeMethod(settings.type) && !this.crossDomain) {xhr.setRequestHeader('X-CSRFToken', csrftoken);}@@ -33,7 +33,7 @@ export default $(document).ready((e) => {// Function for update product image heightfunction updateProductImageHeight() {let productImageWidth = $('.product-image').width();- $('.product-image').css({'height': productImageWidth + 'px'});+ $('.product-image').css({ height: productImageWidth + 'px' });}// Update product-image height when window is initializeddiff --git a/saleor/static/js/components/navbar.js b/saleor/static/js/components/navbar.jsindex 5836262d25..5adab6bb59 100644--- a/saleor/static/js/components/navbar.js+++ b/saleor/static/js/components/navbar.js@@ -16,16 +16,15 @@ const renderNavbar = () => {if ($desktopLinks.length) {$searchForm.addClass('search-form--hidden');$mobileNav.append('<ul class="nav navbar-nav navbar__menu__login"></ul>');- $languagePicker.appendTo('.navbar__menu__login')+ $languagePicker+ .appendTo('.navbar__menu__login').wrap('<li class="nav-item login-item"></li>').addClass('nav-link');$desktopLinks.appendTo('.navbar__menu__login').wrap('<li class="nav-item login-item"></li>').addClass('nav-link');- $desktopLinkBar- .find('li')- .remove();+ $desktopLinkBar.find('li').remove();}$languagePickerButton.attr('data-target', '#languagePickerModal');$languagePickerButton.attr('data-toggle', 'modal');@@ -33,7 +32,8 @@ const renderNavbar = () => {const $mobileLinks = $mobileLinkBar.find('a').not('.dropdown-link');if ($mobileLinks.length) {$searchForm.removeClass('search-form--hidden');- $languagePicker.appendTo('.navbar__login ul')+ $languagePicker+ .appendTo('.navbar__login ul').wrap('<li></li>').removeClass('nav-link');$mobileLinks@@ -50,16 +50,11 @@ const renderNavbar = () => {// -----renderNavbar();-$toogleIcon- .on('click', (e) => {- $mobileNav.toggleClass('open');- e.stopPropagation();- });-$(document)- .on('click', () => $mobileNav.removeClass('open'));-$(window)- .on('resize', renderNavbar);-$searchIcon- .on('click', () => $searchForm.removeClass('search-form--hidden'));-$closeSearchIcon- .on('click', () => $searchForm.addClass('search-form--hidden'));+$toogleIcon.on('click', e => {+ $mobileNav.toggleClass('open');+ e.stopPropagation();+});+$(document).on('click', () => $mobileNav.removeClass('open'));+$(window).on('resize', renderNavbar);+$searchIcon.on('click', () => $searchForm.removeClass('search-form--hidden'));+$closeSearchIcon.on('click', () => $searchForm.addClass('search-form--hidden'));diff --git a/saleor/static/js/components/password-input.js b/saleor/static/js/components/password-input.jsindex b3bcab3d3a..03128ed646 100644--- a/saleor/static/js/components/password-input.js+++ b/saleor/static/js/components/password-input.js@@ -1,12 +1,16 @@import passwordIvisible from '../../images/pass-invisible.svg';import passwordVisible from '../../images/pass-visible.svg';-export default $(document).ready((e) => {+export default $(document).ready(e => {let $inputPassword = $('input[type=password]');- $('<img class="passIcon" src=' + passwordIvisible + ' />').insertAfter($inputPassword);+ $('<img class="passIcon" src=' + passwordIvisible + ' />').insertAfter(+ $inputPassword+ );$inputPassword.parent().addClass('relative');- $('.passIcon').on('click', (e) => {- let $input = $(e.target).parent().find('input');+ $('.passIcon').on('click', e => {+ let $input = $(e.target)+ .parent()+ .find('input');if ($input.attr('type') === 'password') {$input.attr('type', 'text');$(e.target).attr('src', passwordVisible);diff --git a/saleor/static/js/components/product-filters.js b/saleor/static/js/components/product-filters.jsindex 7b10308733..10e1ffbff7 100644--- a/saleor/static/js/components/product-filters.js+++ b/saleor/static/js/components/product-filters.js@@ -1,4 +1,4 @@-$('.filters-menu').on('click', (e) => {+$('.filters-menu').on('click', e => {const menuContainer = $('.filters-menu__body');if (menuContainer.hasClass('d-none')) {menuContainer.removeClass('d-none');@@ -7,7 +7,7 @@ $('.filters-menu').on('click', (e) => {}});-$('.filter-section__header').on('click', (event) => {+$('.filter-section__header').on('click', event => {const $target = $(event.currentTarget).parent();if ($target.attr('aria-expanded') === 'true') {$target.attr('aria-expanded', 'false').addClass('filter-section--closed');diff --git a/saleor/static/js/components/sorter.js b/saleor/static/js/components/sorter.jsindex 44c6aacef1..12c2df21c1 100644--- a/saleor/static/js/components/sorter.js+++ b/saleor/static/js/components/sorter.js@@ -1,6 +1,6 @@-export default $(document).ready((e) => {- $(document).ready((e) => {- $('.sort-by button').on('click', (e) => {+export default $(document).ready(e => {+ $(document).ready(e => {+ $('.sort-by button').on('click', e => {const parentContainer = $(e.currentTarget).parent();const list = parentContainer.find('.sort-list');if (list.hasClass('d-none')) {@@ -11,7 +11,7 @@ export default $(document).ready((e) => {parentContainer.find('.click-area').addClass('d-none');}});- $('.sort-by .click-area').on('click', (e) => {+ $('.sort-by .click-area').on('click', e => {$('.sort-by .sort-list').addClass('d-none');$(e.currentTarget).addClass('d-none');});diff --git a/saleor/static/js/components/styleguide.js b/saleor/static/js/components/styleguide.jsindex 8f2e786207..3b3ddaa104 100644--- a/saleor/static/js/components/styleguide.js+++ b/saleor/static/js/components/styleguide.js@@ -1,6 +1,6 @@-export default $(document).ready(function () {+export default $(document).ready(function() {let styleGuideMenu = $('.styleguide__nav');- $(window).scroll(function () {+ $(window).scroll(function() {if ($(this).scrollTop() > 100) {styleGuideMenu.addClass('fixed');} else {diff --git a/saleor/static/js/components/variant-picker.js b/saleor/static/js/components/variant-picker.jsindex f1425ccd53..49a33e4b3d 100644--- a/saleor/static/js/components/variant-picker.js+++ b/saleor/static/js/components/variant-picker.js@@ -5,14 +5,18 @@ import VariantPicker from './variantPicker/VariantPicker';import VariantPrice from './variantPicker/VariantPrice';import variantPickerStore from '../stores/variantPicker';-import {onAddToCheckoutSuccess, onAddToCheckoutError} from './checkout';+import { onAddToCheckoutSuccess, onAddToCheckoutError } from './checkout';-export default $(document).ready((e) => {+export default $(document).ready(e => {const variantPickerContainer = document.getElementById('variant-picker');- const variantPriceContainer = document.getElementById('variant-price-component');+ const variantPriceContainer = document.getElementById(+ 'variant-price-component'+ );if (variantPickerContainer) {- const variantPickerData = JSON.parse(variantPickerContainer.dataset.variantPickerData);+ const variantPickerData = JSON.parse(+ variantPickerContainer.dataset.variantPickerData+ );ReactDOM.render(<VariantPickeronAddToCheckoutError={onAddToCheckoutError}diff --git a/saleor/static/js/components/variantPicker/AttributeSelectionWidget.js b/saleor/static/js/components/variantPicker/AttributeSelectionWidget.jsindex 5fa30c8f9e..9c484c8dfc 100644--- a/saleor/static/js/components/variantPicker/AttributeSelectionWidget.js+++ b/saleor/static/js/components/variantPicker/AttributeSelectionWidget.js@@ -3,7 +3,6 @@ import PropTypes from 'prop-types';import classNames from 'classnames';export default class AttributeSelectionWidget extends Component {-static propTypes = {attribute: PropTypes.object.isRequired,handleChange: PropTypes.func.isRequired,@@ -12,7 +11,7 @@ export default class AttributeSelectionWidget extends Component {handleChange = (attrPk, valuePk) => {this.props.handleChange(attrPk.toString(), valuePk.toString());- }+ };render() {const { attribute, selected } = this.props;@@ -24,17 +23,15 @@ export default class AttributeSelectionWidget extends Component {const active = selected === value.pk.toString();const labelClass = classNames({'btn btn-secondary variant-picker__option': true,- 'active': active+ active: active});return (<labelclassName={labelClass}key={i}- onClick={() => this.handleChange(attribute.pk, value.pk)}>- <input- defaultChecked={active}- name={value.pk}- type="radio"/>+ onClick={() => this.handleChange(attribute.pk, value.pk)}+ >+ <input defaultChecked={active} name={value.pk} type="radio" />{value.name}</label>);diff --git a/saleor/static/js/components/variantPicker/QuantityInput.js b/saleor/static/js/components/variantPicker/QuantityInput.jsindex 7dfeb8b530..4eae24b1ac 100644--- a/saleor/static/js/components/variantPicker/QuantityInput.js+++ b/saleor/static/js/components/variantPicker/QuantityInput.js@@ -3,23 +3,27 @@ import React, { Component } from 'react';import PropTypes from 'prop-types';export default class QuantityInput extends Component {-static propTypes = {errors: PropTypes.array,handleChange: PropTypes.func.isRequired,quantity: PropTypes.number.isRequired- }+ };render() {const { errors, quantity } = this.props;const formGroupClasses = classNames({'form-group': true,'has-error': errors && !!errors.length,- 'product__info__quantity': true+ product__info__quantity: true});return (<div className={formGroupClasses}>- <label className="control-label product__variant-picker__label" htmlFor="id_quantity">{pgettext('Add to cart form field label', 'Quantity')}</label>+ <label+ className="control-label product__variant-picker__label"+ htmlFor="id_quantity"+ >+ {pgettext('Add to cart form field label', 'Quantity')}+ </label><inputclassName="form-control"defaultValue={quantity}@@ -30,9 +34,7 @@ export default class QuantityInput extends Component {onChange={this.props.handleChange}type="number"/>- {errors && (- <span className="help-block">{errors.join(' ')}</span>- )}+ {errors && <span className="help-block">{errors.join(' ')}</span>}</div>);}diff --git a/saleor/static/js/components/variantPicker/VariantPicker.js b/saleor/static/js/components/variantPicker/VariantPicker.jsindex ad1b7d91be..84934d9a10 100644--- a/saleor/static/js/components/variantPicker/VariantPicker.js+++ b/saleor/static/js/components/variantPicker/VariantPicker.js@@ -9,26 +9,28 @@ import AttributeSelectionWidget from './AttributeSelectionWidget';import QuantityInput from './QuantityInput';import * as queryString from 'query-string';-export default observer(class VariantPicker extends Component {- static propTypes = {- onAddToCheckoutError: PropTypes.func.isRequired,- onAddToCheckoutSuccess: PropTypes.func.isRequired,- store: PropTypes.object.isRequired,- url: PropTypes.string.isRequired,- variantAttributes: PropTypes.array.isRequired,- variants: PropTypes.array.isRequired- };-- constructor (props) {- super(props);- const { variants } = this.props;-- const variant = variants.filter(v => !!Object.keys(v.attributes).length)[0];- const params = queryString.parse(location.search);- let selection = {};- if (Object.keys(params).length) {- Object.keys(params)- .some((name) => {+export default observer(+ class VariantPicker extends Component {+ static propTypes = {+ onAddToCheckoutError: PropTypes.func.isRequired,+ onAddToCheckoutSuccess: PropTypes.func.isRequired,+ store: PropTypes.object.isRequired,+ url: PropTypes.string.isRequired,+ variantAttributes: PropTypes.array.isRequired,+ variants: PropTypes.array.isRequired+ };++ constructor(props) {+ super(props);+ const { variants } = this.props;++ const variant = variants.filter(+ v => !!Object.keys(v.attributes).length+ )[0];+ const params = queryString.parse(location.search);+ let selection = {};+ if (Object.keys(params).length) {+ Object.keys(params).some(name => {const valueName = params[name];const attribute = this.matchAttributeBySlug(name);const value = this.matchAttributeValueByName(attribute, valueName);@@ -41,134 +43,156 @@ export default observer(class VariantPicker extends Component {return true;}});- } else if (Object.keys(variant).length) {- selection = variant.attributes;+ } else if (Object.keys(variant).length) {+ selection = variant.attributes;+ }+ this.state = {+ errors: {},+ quantity: 1,+ selection: selection+ };+ this.matchVariantFromSelection();}- this.state = {- errors: {},- quantity: 1,- selection: selection++ checkVariantAvailability = () => {+ const { store } = this.props;+ return store.variant.availability;};- this.matchVariantFromSelection();- }- checkVariantAvailability = () => {- const { store } = this.props;- return store.variant.availability;- };-- handleAddToCheckout = () => {- const { onAddToCheckoutSuccess, onAddToCheckoutError, store } = this.props;- const { quantity } = this.state;- if (quantity > 0 && !store.isEmpty) {- $.ajax({- url: this.props.url,- method: 'post',- data: {- quantity: quantity,- variant: store.variant.id- },- success: () => {- onAddToCheckoutSuccess();+ handleAddToCheckout = () => {+ const {+ onAddToCheckoutSuccess,+ onAddToCheckoutError,+ store+ } = this.props;+ const { quantity } = this.state;+ if (quantity > 0 && !store.isEmpty) {+ $.ajax({+ url: this.props.url,+ method: 'post',+ data: {+ quantity: quantity,+ variant: store.variant.id+ },+ success: () => {+ onAddToCheckoutSuccess();+ },+ error: response => {+ onAddToCheckoutError(response);+ }+ });+ }+ };++ handleAttributeChange = (attrId, valueId) => {+ this.setState(+ {+ selection: Object.assign({}, this.state.selection, {+ [attrId]: valueId+ })},- error: (response) => {- onAddToCheckoutError(response);+ () => {+ this.matchVariantFromSelection();+ let params = {};+ Object.keys(this.state.selection).forEach(attrId => {+ const attribute = this.matchAttribute(attrId);+ const value = this.matchAttributeValue(+ attribute,+ this.state.selection[attrId]+ );+ if (attribute && value) {+ params[attribute.slug] = value.slug;+ }+ });+ history.pushState(null, null, '?' + queryString.stringify(params));+ }+ );+ };++ handleQuantityChange = event => {+ this.setState({ quantity: parseInt(event.target.value) });+ };++ matchAttribute = id => {+ const { variantAttributes } = this.props;+ const match = variantAttributes.filter(+ attribute => attribute.pk.toString() === id+ );+ return match.length > 0 ? match[0] : null;+ };++ matchAttributeBySlug = slug => {+ const { variantAttributes } = this.props;+ const match = variantAttributes.filter(+ attribute => attribute.slug === slug+ );+ return match.length > 0 ? match[0] : null;+ };++ matchAttributeValue = (attribute, id) => {+ const match = attribute.values.filter(+ attribute => attribute.pk.toString() === id+ );+ return match.length > 0 ? match[0] : null;+ };++ matchAttributeValueByName = (attribute, name) => {+ const match = attribute+ ? attribute.values.filter(value => value.slug === name)+ : [];+ return match.length > 0 ? match[0] : null;+ };++ matchVariantFromSelection() {+ const { store, variants } = this.props;+ let matchedVariant = null;+ variants.forEach(variant => {+ if (_.isEqual(this.state.selection, variant.attributes)) {+ matchedVariant = variant;}});+ store.setVariant(matchedVariant);}- };- handleAttributeChange = (attrId, valueId) => {- this.setState({- selection: Object.assign({}, this.state.selection, { [attrId]: valueId })- }, () => {- this.matchVariantFromSelection();- let params = {};- Object.keys(this.state.selection)- .forEach(attrId => {- const attribute = this.matchAttribute(attrId);- const value = this.matchAttributeValue(attribute, this.state.selection[attrId]);- if (attribute && value) {- params[attribute.slug] = value.slug;- }- });- history.pushState(null, null, '?' + queryString.stringify(params));- });- };-- handleQuantityChange = (event) => {- this.setState({ quantity: parseInt(event.target.value) });- };-- matchAttribute = (id) => {- const { variantAttributes } = this.props;- const match = variantAttributes.filter(attribute => attribute.pk.toString() === id);- return match.length > 0 ? match[0] : null;- };-- matchAttributeBySlug = (slug) => {- const { variantAttributes } = this.props;- const match = variantAttributes.filter(attribute => attribute.slug === slug);- return match.length > 0 ? match[0] : null;- };-- matchAttributeValue = (attribute, id) => {- const match = attribute.values.filter(attribute => attribute.pk.toString() === id);- return match.length > 0 ? match[0] : null;- };-- matchAttributeValueByName = (attribute, name) => {- const match = attribute ? attribute.values.filter(value => value.slug === name) : [];- return match.length > 0 ? match[0] : null;- };-- matchVariantFromSelection () {- const { store, variants } = this.props;- let matchedVariant = null;- variants.forEach(variant => {- if (_.isEqual(this.state.selection, variant.attributes)) {- matchedVariant = variant;- }- });- store.setVariant(matchedVariant);- }+ render() {+ const { store, variantAttributes } = this.props;+ const { errors, selection, quantity } = this.state;+ const disableAddToCheckout =+ store.isEmpty || !this.checkVariantAvailability();++ const addToCheckoutBtnClasses = classNames({+ 'btn btn-primary': true,+ disabled: disableAddToCheckout+ });- render () {- const { store, variantAttributes } = this.props;- const { errors, selection, quantity } = this.state;- const disableAddToCheckout = store.isEmpty || !this.checkVariantAvailability();-- const addToCheckoutBtnClasses = classNames({- 'btn btn-primary': true,- 'disabled': disableAddToCheckout- });-- return (- <div>- {variantAttributes.map((attribute, i) =>- <AttributeSelectionWidget- attribute={attribute}- handleChange={this.handleAttributeChange}- key={i}- selected={selection[attribute.pk]}- />- )}- <div className="clearfix">- <QuantityInput- errors={errors.quantity}- handleChange={this.handleQuantityChange}- quantity={quantity}- />- <div className="form-group product__info__button">- <button- className={addToCheckoutBtnClasses}- onClick={this.handleAddToCheckout}- disabled={disableAddToCheckout}>- {pgettext('Product details primary action', 'Add to cart')}- </button>+ return (+ <div>+ {variantAttributes.map((attribute, i) => (+ <AttributeSelectionWidget+ attribute={attribute}+ handleChange={this.handleAttributeChange}+ key={i}+ selected={selection[attribute.pk]}+ />+ ))}+ <div className="clearfix">+ <QuantityInput+ errors={errors.quantity}+ handleChange={this.handleQuantityChange}+ quantity={quantity}+ />+ <div className="form-group product__info__button">+ <button+ className={addToCheckoutBtnClasses}+ onClick={this.handleAddToCheckout}+ disabled={disableAddToCheckout}+ >+ {pgettext('Product details primary action', 'Add to cart')}+ </button>+ </div></div></div>- </div>- );+ );+ }}-});+);diff --git a/saleor/static/js/components/variantPicker/VariantPrice.js b/saleor/static/js/components/variantPicker/VariantPrice.jsindex a45ad285ed..dd11f54eb2 100644--- a/saleor/static/js/components/variantPicker/VariantPrice.js+++ b/saleor/static/js/components/variantPicker/VariantPrice.js@@ -2,70 +2,78 @@ import { observer } from 'mobx-react';import React, { Component } from 'react';import PropTypes from 'prop-types';-export default observer(class VariantPrice extends Component {- static propTypes = {- availability: PropTypes.object.isRequired,- priceDisplay: PropTypes.object.isRequired,- store: PropTypes.object- }+export default observer(+ class VariantPrice extends Component {+ static propTypes = {+ availability: PropTypes.object.isRequired,+ priceDisplay: PropTypes.object.isRequired,+ store: PropTypes.object+ };- render() {- let priceText, priceUndiscountedText, priceLocalCurrency, isDiscount;- const { availability, priceDisplay, store } = this.props;- const { displayGross, handleTaxes } = priceDisplay;- const variant = store.variant;- const taxRate = availability.taxRate;- if (!store.isEmpty) {- // variant price- isDiscount = variant.price.gross !== variant.priceUndiscounted.gross;- if (displayGross) {- priceText = `${variant.price.grossLocalized}`;- priceUndiscountedText = `${variant.priceUndiscounted.grossLocalized}`;- if (variant.priceLocalCurrency) {- priceLocalCurrency = variant.priceLocalCurrency.grossLocalized;- }- } else {- priceText = `${variant.price.netLocalized}`;- priceUndiscountedText = `${variant.priceUndiscounted.netLocalized}`;- if (variant.priceLocalCurrency) {- priceLocalCurrency = variant.priceLocalCurrency.netLocalized;- }- }- } else {- // if there's no variant, fall back to product price- const { discount, priceRange, priceRangeUndiscounted } = availability;- isDiscount = discount && !!Object.keys(discount).length;- if (displayGross) {- priceText = `${priceRange.minPrice.grossLocalized}`;- priceUndiscountedText = `${priceRangeUndiscounted.minPrice.grossLocalized}`;- if (availability.priceRangeLocalCurrency) {- priceLocalCurrency = availability.priceRangeLocalCurrency.minPrice.grossLocalized;+ render() {+ let priceText, priceUndiscountedText, priceLocalCurrency, isDiscount;+ const { availability, priceDisplay, store } = this.props;+ const { displayGross, handleTaxes } = priceDisplay;+ const variant = store.variant;+ const taxRate = availability.taxRate;+ if (!store.isEmpty) {+ // variant price+ isDiscount = variant.price.gross !== variant.priceUndiscounted.gross;+ if (displayGross) {+ priceText = `${variant.price.grossLocalized}`;+ priceUndiscountedText = `${variant.priceUndiscounted.grossLocalized}`;+ if (variant.priceLocalCurrency) {+ priceLocalCurrency = variant.priceLocalCurrency.grossLocalized;+ }+ } else {+ priceText = `${variant.price.netLocalized}`;+ priceUndiscountedText = `${variant.priceUndiscounted.netLocalized}`;+ if (variant.priceLocalCurrency) {+ priceLocalCurrency = variant.priceLocalCurrency.netLocalized;+ }}} else {- priceText = `${priceRange.minPrice.netLocalized}`;- priceUndiscountedText = `${priceRangeUndiscounted.minPrice.netLocalized}`;- if (availability.priceRangeLocalCurrency) {- priceLocalCurrency = availability.priceRangeLocalCurrency.minPrice.netLocalized;+ // if there's no variant, fall back to product price+ const { discount, priceRange, priceRangeUndiscounted } = availability;+ isDiscount = discount && !!Object.keys(discount).length;+ if (displayGross) {+ priceText = `${priceRange.minPrice.grossLocalized}`;+ priceUndiscountedText = `${priceRangeUndiscounted.minPrice.grossLocalized}`;+ if (availability.priceRangeLocalCurrency) {+ priceLocalCurrency =+ availability.priceRangeLocalCurrency.minPrice.grossLocalized;+ }+ } else {+ priceText = `${priceRange.minPrice.netLocalized}`;+ priceUndiscountedText = `${priceRangeUndiscounted.minPrice.netLocalized}`;+ if (availability.priceRangeLocalCurrency) {+ priceLocalCurrency =+ availability.priceRangeLocalCurrency.minPrice.netLocalized;+ }}}+ return (+ <h2 className="product__info__price">+ <span>{priceText} </span>+ {isDiscount && (+ <small className="product__info__price__undiscounted">+ {priceUndiscountedText}+ </small>+ )}+ {priceLocalCurrency && (+ <p>+ <small className="text-info">≈ {priceLocalCurrency}</small>+ </p>+ )}+ {handleTaxes && [+ displayGross ? (+ <small>including {taxRate}% VAT</small>+ ) : (+ <small>excluding {taxRate}% VAT</small>+ )+ ]}+ </h2>+ );}- return (- <h2 className="product__info__price">- <span>{priceText} </span>- {isDiscount && (- <small className="product__info__price__undiscounted">{priceUndiscountedText}</small>- )}- {priceLocalCurrency && (- <p><small className="text-info">≈ {priceLocalCurrency}</small></p>- )}- {handleTaxes && [- displayGross ? (- <small>including {taxRate}% VAT</small>- ) : (- <small>excluding {taxRate}% VAT</small>- )- ]}- </h2>- );}-});+);