Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use JS Standard Style
Marcin Gębala08f3961529a2
diff --git a/.eslintrc.json b/.eslintrc.jsonindex 6c42b9358f..ab4604de6a 100644--- a/.eslintrc.json+++ b/.eslintrc.json@@ -1,19 +1,13 @@{"env": {- "browser": true+ "browser": true,+ "jquery": true},- "extends": ["eslint:recommended", "plugin:react/recommended"],+ "extends": ["standard", "plugin:react/recommended"],"plugins": ["react"],"parser": "babel-eslint","rules": {- "comma-dangle": ["error", "only-multiline"],- "indent": ["error", 2],- "no-trailing-spaces": ["warn"],- "no-undef": ["error"],- "no-unused-vars": ["warn"],- "react/jsx-no-bind": ["error", {"ignoreRefs": true}],"semi": ["error", "always"],- "strict": ["error", "never"],- "quotes": ["warn", "single"]+ "space-before-function-paren": "off"}}\ No newline at end of filediff --git a/package.json b/package.jsonindex 9db18ba886..05c62c2b5d 100644--- a/package.json+++ b/package.json@@ -54,7 +54,10 @@"babel-relay-plugin-loader": "^0.9.0","css-loader": "^0.25.0","eslint": "^3.10.2",+ "eslint-config-standard": "^6.2.1",+ "eslint-plugin-promise": "^3.4.0","eslint-plugin-react": "^6.7.1",+ "eslint-plugin-standard": "^2.0.1","extract-text-webpack-plugin": "^1.0.1","file-loader": "^0.9.0","node-sass": "^3.10.0",diff --git a/saleor/static/js/cart.js b/saleor/static/js/cart.jsdeleted file mode 100644index e69de29bb2..0000000000diff --git a/saleor/static/js/category.js b/saleor/static/js/category.jsindex ffab0a8fbb..e5288144cf 100644--- a/saleor/static/js/category.js+++ b/saleor/static/js/category.js@@ -8,7 +8,6 @@ import ProductFilters from './components/categoryPage/ProductFilters';const categoryPage = document.getElementById('category-page');const categoryData = JSON.parse(categoryPage.getAttribute('data-category'));-class App extends React.Component {static propTypes = {@@ -44,18 +43,18 @@ const RelayApp = Relay.createContainer(App, {}}}- `,- },+ `+ }});const AppRoute = {queries: {viewer: () => Relay.QL`query { viewer }- `,+ `},params: {},- name: 'Viewer',+ name: 'Viewer'};ReactDOM.render(diff --git a/saleor/static/js/components/categoryPage/AttributeInput.js b/saleor/static/js/components/categoryPage/AttributeInput.jsindex c7907f2a8e..dcd3183536 100644--- a/saleor/static/js/components/categoryPage/AttributeInput.js+++ b/saleor/static/js/components/categoryPage/AttributeInput.js@@ -1,8 +1,6 @@import React, { PropTypes } from 'react';-const AttributeInput = ({attribute, checked, onClick, value}) => {-const handleChange = (event) => {const { name, value } = event.target;onClick(name, value);diff --git a/saleor/static/js/components/categoryPage/CategoryFilter.js b/saleor/static/js/components/categoryPage/CategoryFilter.jsindex 88f0b9ab81..1d9805f1d1 100644--- a/saleor/static/js/components/categoryPage/CategoryFilter.js+++ b/saleor/static/js/components/categoryPage/CategoryFilter.js@@ -20,7 +20,7 @@ export default class CategoryFilter extends Component {<a href={parent.url}>See all {parent.name}</a></div>) : (null)}- <ul className={category.parent ? ("childs") : ("childs no-parent")}>+ <ul className={category.parent ? ('childs') : ('childs no-parent')}>{category.children && (category.children.map((child) => {return (<li key={child.pk} className="item">diff --git a/saleor/static/js/components/categoryPage/CategoryPage.js b/saleor/static/js/components/categoryPage/CategoryPage.jsindex 6352c81de0..2651082906 100644--- a/saleor/static/js/components/categoryPage/CategoryPage.js+++ b/saleor/static/js/components/categoryPage/CategoryPage.js@@ -8,16 +8,13 @@ import ProductFilters from './ProductFilters';import ProductList from './ProductList';import SortBy from './SortBy';-const PAGINATE_BY = 20;-const getVarFromQueryString = (key, defaultValue = null) => {let value = queryString.parse(location.search)[key];- return value ? value : defaultValue;+ return value || defaultValue;};-const getAttributesFromQueryString = (exclude) => {// Exclude parameter is used to exclude other query string parameters than// product attribute filters.@@ -39,13 +36,11 @@ const getAttributesFromQueryString = (exclude) => {return attributes;};-const floatOrNull = (value) => {const parsed = parseFloat(value);return isNaN(parsed) ? null : parsed;};-class CategoryPage extends Component {static propTypes = {@@ -111,10 +106,8 @@ class CategoryPage extends Component {urlParams[attributeName] = [valueSlug];}});- const url = Object.keys(urlParams).length ?- '?' + queryString.stringify(urlParams) :- location.href.split('?')[0];- history.pushState({}, null , url);+ const url = Object.keys(urlParams).length ? '?' + queryString.stringify(urlParams) : location.href.split('?')[0];+ history.pushState({}, null, url);}componentDidUpdate() {@@ -181,7 +174,6 @@ class CategoryPage extends Component {}}-export default Relay.createContainer(CategoryPage, {initialVariables: {attributesFilter: getAttributesFromQueryString(['count', 'minPrice', 'maxPrice', 'sortBy']),@@ -211,6 +203,6 @@ export default Relay.createContainer(CategoryPage, {${ProductList.getFragment('products')}}}- `,- },+ `+ }});diff --git a/saleor/static/js/components/categoryPage/PriceFilter.js b/saleor/static/js/components/categoryPage/PriceFilter.jsindex 9d4ea41ba6..5120a2acf3 100644--- a/saleor/static/js/components/categoryPage/PriceFilter.js+++ b/saleor/static/js/components/categoryPage/PriceFilter.js@@ -28,9 +28,9 @@ export default class PriceFilter extends Component {}changeVisibility = () => {- this.setState({- visibility: !this.state.visibility- })+ this.setState({+ visibility: !this.state.visibility+ });}render() {@@ -50,7 +50,7 @@ export default class PriceFilter extends Component {min="0"onKeyUp={this.checkKey}placeholder="min"- ref={input => this.minPriceInput = input}+ ref={input => (this.minPriceInput = input)}type="number"/><span>—</span>@@ -60,7 +60,7 @@ export default class PriceFilter extends Component {min="0"onKeyUp={this.checkKey}placeholder="max"- ref={input => this.maxPriceInput = input}+ ref={input => (this.maxPriceInput = input)}type="number"/><button className="btn" onClick={this.updateFilter}>Update</button>diff --git a/saleor/static/js/components/categoryPage/ProductFilters.js b/saleor/static/js/components/categoryPage/ProductFilters.jsindex 15c00f251e..ec0ab6faf5 100644--- a/saleor/static/js/components/categoryPage/ProductFilters.js+++ b/saleor/static/js/components/categoryPage/ProductFilters.js@@ -3,7 +3,6 @@ import Relay from 'react-relay';import AttributeInput from './AttributeInput';-class ProductFilters extends Component {constructor(props) {@@ -29,7 +28,7 @@ class ProductFilters extends Component {changeVisibility = (target) => {this.setState({- visibility: Object.assign(this.state.visibility, {[target] : !this.state.visibility[target]})+ visibility: Object.assign(this.state.visibility, {[target]: !this.state.visibility[target]})});}@@ -37,9 +36,9 @@ class ProductFilters extends Component {this.props.attributes.map((attribute) => {const attrValue = `${attribute.name}`;this.setState({- visibility: Object.assign(this.state.visibility, {[attrValue] : true})+ visibility: Object.assign(this.state.visibility, {[attrValue]: true})});- })+ });}render() {@@ -57,7 +56,7 @@ class ProductFilters extends Component {<ul id={attribute.name}>{attribute.values.map((value) => {const key = this.getFilterKey(attribute.name, value.slug);- if(visibility[attribute.name] || checkedAttributes.includes(key)) {+ if (visibility[attribute.name] || checkedAttributes.includes(key)) {return (<li key={value.id} className="item"><AttributeInput@@ -68,7 +67,7 @@ class ProductFilters extends Component {/></li>);- }+ }})}</ul></div>@@ -94,6 +93,6 @@ export default Relay.createContainer(ProductFilters, {color}}- `,- },+ `+ }});diff --git a/saleor/static/js/components/categoryPage/ProductItem.js b/saleor/static/js/components/categoryPage/ProductItem.jsindex b507b60d98..3db2f7cf22 100644--- a/saleor/static/js/components/categoryPage/ProductItem.js+++ b/saleor/static/js/components/categoryPage/ProductItem.js@@ -3,7 +3,6 @@ import Relay from 'react-relay';import ProductPrice from './ProductPrice';-class ProductItem extends Component {static propTypes = {@@ -42,6 +41,6 @@ export default Relay.createContainer(ProductItem, {imageUrlurl}- `,- },+ `+ }});diff --git a/saleor/static/js/components/categoryPage/ProductList.js b/saleor/static/js/components/categoryPage/ProductList.jsindex 6605b1449f..6efc2adc4a 100644--- a/saleor/static/js/components/categoryPage/ProductList.js+++ b/saleor/static/js/components/categoryPage/ProductList.js@@ -8,6 +8,7 @@ class ProductList extends Component {static propTypes = {onLoadMore: PropTypes.func.isRequired,products: PropTypes.object,+ setSorting: PropTypes.object};onLoadMore = () => this.props.onLoadMore();@@ -45,6 +46,6 @@ export default Relay.createContainer(ProductList, {hasNextPage}}- `,- },+ `+ }});diff --git a/saleor/static/js/components/categoryPage/ProductPrice.js b/saleor/static/js/components/categoryPage/ProductPrice.jsindex e75397bd01..1f21f18234 100644--- a/saleor/static/js/components/categoryPage/ProductPrice.js+++ b/saleor/static/js/components/categoryPage/ProductPrice.js@@ -1,7 +1,6 @@import React, { PropTypes } from 'react';import Relay from 'react-relay';-const ProductPrice = ({ availability }) => {const { discount, priceRange: { minPrice, maxPrice } } = availability;const isPriceRange = minPrice.gross !== maxPrice.gross;@@ -18,12 +17,10 @@ const ProductPrice = ({ availability }) => {);};-ProductPrice.propTypes = {availability: PropTypes.object.isRequired};-export default Relay.createContainer(ProductPrice, {fragments: {availability: () => Relay.QL`diff --git a/saleor/static/js/components/categoryPage/SortBy.js b/saleor/static/js/components/categoryPage/SortBy.jsindex 6484f60f5c..beb98e394c 100644--- a/saleor/static/js/components/categoryPage/SortBy.js+++ b/saleor/static/js/components/categoryPage/SortBy.js@@ -27,7 +27,7 @@ export default class sortBy extends Component {}render() {- const { sortedValue } = this.props+ const { sortedValue } = this.props;const { visibility } = this.state;return (<div className="sort-by">@@ -41,7 +41,7 @@ export default class sortBy extends Component {</div>) : (<div>- <span>Sort by: <strong>{sortedValue.replace('-','')}</strong></span>+ <span>Sort by: <strong>{sortedValue.replace('-', '')}</strong></span><img src="/static/img/arrow-down-icon.svg" width="15" /></div>)@@ -81,11 +81,11 @@ export default class sortBy extends Component {<span className="-price" onClick={this.setSorting}>descending</span><img className="float-right" src="/static/img/arrow-down-icon.svg" width="15" /></div>- </div>+ </div></li></ul>) : (null)}</div>);}-}\ No newline at end of file+}diff --git a/saleor/static/js/components/variantPicker/AttributeSelectionWidget.js b/saleor/static/js/components/variantPicker/AttributeSelectionWidget.jsindex 11a302d4cf..afe80c1f87 100644--- a/saleor/static/js/components/variantPicker/AttributeSelectionWidget.js+++ b/saleor/static/js/components/variantPicker/AttributeSelectionWidget.js@@ -1,5 +1,4 @@-import React, { Component, PropTypes } from 'react'-+import React, { Component, PropTypes } from 'react';export default class AttributeSelectionWidget extends Component {@@ -10,12 +9,12 @@ export default class AttributeSelectionWidget extends Component {};handleChange = (event) => {- const { name, value } = event.target- this.props.handleChange(name, value)+ const { name, value } = event.target;+ this.props.handleChange(name, value);}render() {- const { attribute: { display, pk, values }, selected } = this.props+ const { attribute: { display, pk, values }, selected } = this.props;return (<div className="form-group product__variant-picker"><label className="control-label"><b>{display}</b></label>@@ -32,10 +31,10 @@ export default class AttributeSelectionWidget extends Component {/>{value.display}</label>- )+ );})}</div></div>- )+ );}}diff --git a/saleor/static/js/components/variantPicker/QuantityInput.js b/saleor/static/js/components/variantPicker/QuantityInput.jsindex 0709bb7457..6f5dcb70ec 100644--- a/saleor/static/js/components/variantPicker/QuantityInput.js+++ b/saleor/static/js/components/variantPicker/QuantityInput.js@@ -1,6 +1,5 @@-import classNames from 'classnames'-import React, { Component, PropTypes } from 'react'-+import classNames from 'classnames';+import React, { Component, PropTypes } from 'react';export default class QuantityInput extends Component {@@ -11,11 +10,11 @@ export default class QuantityInput extends Component {}render() {- const { errors, quantity } = this.props+ const { errors, quantity } = this.props;const formGroupClasses = classNames({'form-group': true,'has-error': errors && !!errors.length- })+ });return (<div className={formGroupClasses}><label className="control-label" htmlFor="id_quantity">Quantity</label>@@ -33,6 +32,6 @@ export default class QuantityInput extends Component {<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 7a8879e8a9..2cbd81fcdd 100644--- a/saleor/static/js/components/variantPicker/VariantPicker.js+++ b/saleor/static/js/components/variantPicker/VariantPicker.js@@ -1,12 +1,11 @@-import _ from 'lodash'-import $ from 'jquery'-import classNames from 'classnames'-import { observer } from 'mobx-react'-import React, { Component, PropTypes } from 'react'--import AttributeSelectionWidget from './AttributeSelectionWidget'-import QuantityInput from './QuantityInput'+import _ from 'lodash';+import $ from 'jquery';+import classNames from 'classnames';+import { observer } from 'mobx-react';+import React, { Component, PropTypes } from 'react';+import AttributeSelectionWidget from './AttributeSelectionWidget';+import QuantityInput from './QuantityInput';@observerexport default class VariantPicker extends Component {@@ -21,23 +20,23 @@ export default class VariantPicker extends Component {}constructor(props) {- super(props)- const { store, variants } = this.props+ super(props);+ const { store, variants } = this.props;- const variant = variants.filter(v => !!Object.keys(v.attributes).length)[0]- const selection = variant ? variant.attributes : {}+ const variant = variants.filter(v => !!Object.keys(v.attributes).length)[0];+ const selection = variant ? variant.attributes : {};this.state = {errors: {},quantity: 1,selection: selection- }- store.setVariant(variant)+ };+ store.setVariant(variant);}handleAddToCart = () => {const { onAddToCartSuccess, onAddToCartError, store } = this.props;- const { quantity } = this.state+ const { quantity } = this.state;if (quantity > 0 && !store.isEmpty) {$.ajax({url: this.props.url,@@ -47,12 +46,12 @@ export default class VariantPicker extends Component {variant: store.variant.id},success: () => {- onAddToCartSuccess()+ onAddToCartSuccess();},error: (response) => {- onAddToCartError(response)+ onAddToCartError(response);}- })+ });}}@@ -60,34 +59,34 @@ export default class VariantPicker extends Component {this.setState({selection: Object.assign({}, this.state.selection, { [attrId]: valueId })}, () => {- this.matchVariantFromSelection()- })+ this.matchVariantFromSelection();+ });}handleQuantityChange = (event) => {- this.setState({quantity: parseInt(event.target.value)})+ this.setState({quantity: parseInt(event.target.value)});}matchVariantFromSelection() {- const { store, variants } = this.props- let matchedVariant = null+ const { store, variants } = this.props;+ let matchedVariant = null;variants.forEach(variant => {if (_.isEqual(this.state.selection, variant.attributes)) {- matchedVariant = variant+ matchedVariant = variant;}- })- store.setVariant(matchedVariant)+ });+ store.setVariant(matchedVariant);}render() {- const { store, variantAttributes } = this.props- const { errors, selection, quantity } = this.state- const disableAddToCart = store.isEmpty+ const { store, variantAttributes } = this.props;+ const { errors, selection, quantity } = this.state;+ const disableAddToCart = store.isEmpty;const addToCartBtnClasses = classNames({'btn primary': true,'disabled': disableAddToCart- })+ });return (<div>@@ -113,6 +112,6 @@ export default class VariantPicker extends Component {</button></div></div>- )+ );}}diff --git a/saleor/static/js/components/variantPicker/VariantPrice.js b/saleor/static/js/components/variantPicker/VariantPrice.jsindex c14e2ca030..520ba79022 100644--- a/saleor/static/js/components/variantPicker/VariantPrice.js+++ b/saleor/static/js/components/variantPicker/VariantPrice.js@@ -1,6 +1,5 @@-import { observer } from 'mobx-react'-import React, { Component, PropTypes } from 'react'-+import { observer } from 'mobx-react';+import React, { Component, PropTypes } from 'react';@observerexport default class VariantPrice extends Component {@@ -11,21 +10,21 @@ export default class VariantPrice extends Component {}render() {- let priceText, priceUndiscountedText, isDiscount- const { availability, store } = this.props- const variant = store.variant- const currency = availability.priceRange.minPrice.currency+ let priceText, priceUndiscountedText, isDiscount;+ const { availability, store } = this.props;+ const variant = store.variant;+ const currency = availability.priceRange.minPrice.currency;if (!store.isEmpty) {// variant price- isDiscount = variant.price !== variant.priceUndiscounted- priceText = `${variant.price} ${currency}`- priceUndiscountedText = `${variant.priceUndiscounted} ${currency}`+ isDiscount = variant.price !== variant.priceUndiscounted;+ priceText = `${variant.price} ${currency}`;+ priceUndiscountedText = `${variant.priceUndiscounted} ${currency}`;} else {// if there's no variant, fall back to product price- const { discount, priceRange, priceRangeUndiscounted } = availability- isDiscount = !!Object.keys(discount).length- priceText = `${priceRange.minPrice.gross} ${currency}`- priceUndiscountedText = `${priceRangeUndiscounted.minPrice.gross} ${currency}`+ const { discount, priceRange, priceRangeUndiscounted } = availability;+ isDiscount = !!Object.keys(discount).length;+ priceText = `${priceRange.minPrice.gross} ${currency}`;+ priceUndiscountedText = `${priceRangeUndiscounted.minPrice.gross} ${currency}`;}return (<h2 itemProp="offers" className="product__info__price" itemScope itemType="http://schema.org/Offer">@@ -34,6 +33,6 @@ export default class VariantPrice extends Component {<small className="product__info__price__undiscounted">{priceUndiscountedText}</small>)}</h2>- )+ );}}diff --git a/saleor/static/js/dashboard.js b/saleor/static/js/dashboard.jsindex 8f23c6ca7d..4f1e6d3dfb 100644--- a/saleor/static/js/dashboard.js+++ b/saleor/static/js/dashboard.js@@ -1,202 +1,201 @@-import Dropzone from 'dropzone'-import $ from 'jquery'-import 'materialize-css/dist/js/materialize'-import 'select2'-import Sortable from 'sortablejs'+import Dropzone from 'dropzone';+import $ from 'jquery';+import 'materialize-css/dist/js/materialize';+import 'select2';+import Sortable from 'sortablejs';-import '../scss/dashboard/dashboard.scss'+import '../scss/dashboard/dashboard.scss';function openModal() {$('.modal-trigger-custom').on('click', function (e) {- var that = this+ let that = this;$.ajax({url: $(this).data('href'),method: 'get',success: function (response) {- var $modal = $($(that).attr('href'))- $modal.html(response)- initSelects()- $modal.modal()+ let $modal = $($(that).attr('href'));+ $modal.html(response);+ initSelects();+ $modal.modal();}- })+ });- e.preventDefault()- })+ e.preventDefault();+ });}$(document).ready(function() {- var tabletScreen = 990- var wideScreen = 1650- var navWidth = '250px'- var $mainNav = $('#main-nav')- var mainNavTop = $mainNav.offset().top- var $menuToggle = $('.menu-toggle')- var $closeMenu = $('#close-menu')- var $openMenu = $('#open-menu')+ let tabletScreen = 990;+ let wideScreen = 1650;+ let navWidth = '250px';+ let $mainNav = $('#main-nav');+ let mainNavTop = $mainNav.offset().top;+ let $closeMenu = $('#close-menu');+ let $openMenu = $('#open-menu');function openMenu(animationSpeed) {$mainNav.animate({'left': navWidth- }, animationSpeed)+ }, animationSpeed);if ($(window).width() < wideScreen && $(window).width() >= tabletScreen) {$('main .container, .subheader .nav-wrapper').animate({'marginLeft': navWidth- }, animationSpeed)+ }, animationSpeed);}- $openMenu.addClass('hide')- $closeMenu.removeClass('hide')+ $openMenu.addClass('hide');+ $closeMenu.removeClass('hide');$(window).scroll(function() {- $mainNav.toggleClass('sticky', $(window).scrollTop() > mainNavTop)- })+ $mainNav.toggleClass('sticky', $(window).scrollTop() > mainNavTop);+ });if ($(window).width() > tabletScreen) {- $.cookie('menu', 'open', { path: '/' })+ $.cookie('menu', 'open', { path: '/' });}}function closeMenu() {$mainNav.animate({'left': '0'- })- $closeMenu.addClass('hide')- $openMenu.removeClass('hide')- $.removeCookie('menu', { path: '/' })+ });+ $closeMenu.addClass('hide');+ $openMenu.removeClass('hide');+ $.removeCookie('menu', { path: '/' });if ($(window).width() < wideScreen) {$('main .container, .subheader .nav-wrapper').css({'margin-left': 'auto'- })+ });}}$openMenu.click(function() {- openMenu(400)- })+ openMenu(400);+ });$closeMenu.click(function() {- closeMenu()- })+ closeMenu();+ });if ($(window).width() <= tabletScreen) {$(window).click(function() {- closeMenu()+ closeMenu();});$openMenu.click(function(event) {- event.stopPropagation();+ event.stopPropagation();});}- if ($.cookie('menu') == 'open') {- openMenu(0)+ if ($.cookie('menu') === 'open') {+ openMenu(0);} else {- closeMenu()+ closeMenu();}- initSelects()- $('.modal').modal()+ initSelects();+ $('.modal').modal();if (isTablet()) {- $('.equal-height-on-med').matchHeight()+ $('.equal-height-on-med').matchHeight();}- var $tabs = $('ul.tabs')+ let $tabs = $('ul.tabs');if ($tabs.length) {$tabs.find('.tab').on('click', function (e) {- window.history.pushState(null, null, e.target.hash)- var tabSelector = $(this).find('a').attr('href')- $('.btn-fab').addClass('btn-fab-hidden')- $(tabSelector + '-btn').removeClass('btn-fab-hidden')- })+ window.history.pushState(null, null, e.target.hash);+ let tabSelector = $(this).find('a').attr('href');+ $('.btn-fab').addClass('btn-fab-hidden');+ $(tabSelector + '-btn').removeClass('btn-fab-hidden');+ });- $tabs.find('a.active').parent().click()+ $tabs.find('a.active').parent().click();}- openModal()- var $messages = $('.message')- var timeout = 0- var offset = 100- var firstMessageOffset = 250+ openModal();+ let $messages = $('.message');+ let timeout = 0;+ let offset = 100;+ let firstMessageOffset = 250;setTimeout(function() {$messages.each(function () {- var that = this+ let that = this;setTimeout(function () {- $(that).removeClass('toast--hidden')- }, timeout + offset)- timeout += 3000+ $(that).removeClass('toast--hidden');+ }, timeout + offset);+ timeout += 3000;setTimeout(function () {- $(that).addClass('toast--hidden')- }, timeout - offset)- })- }, firstMessageOffset)+ $(that).addClass('toast--hidden');+ }, timeout - offset);+ });+ }, firstMessageOffset);$(document).on('submit', '.form-async', function(e) {- var that = this+ let that = this;$.ajax({url: $(that).attr('action'),method: 'post',data: $(that).serialize(),complete: function(response) {if (response.status === 400) {- $(that).parent().html(response.responseText)- initSelects()+ $(that).parent().html(response.responseText);+ initSelects();} else {- $('.modal-close').click()+ $('.modal-close').click();}},success: function(response) {if (response.redirectUrl) {- window.location.href = response.redirectUrl+ window.location.href = response.redirectUrl;} else {- location.reload()+ location.reload();}}- })- e.preventDefault()+ });+ e.preventDefault();}).on('click', '.modal-close', function() {- $('.modal').modal('close')- })+ $('.modal').modal('close');+ });function isTablet() {- return !$('.hide-on-med-only').is(':visible')+ return !$('.hide-on-med-only').is(':visible');}-})+});Dropzone.options.productImageForm = {- paramName: "image",+ paramName: 'image',maxFilesize: 20,- previewsContainer: ".product-gallery",+ previewsContainer: '.product-gallery',thumbnailWidth: 400,thumbnailHeight: 250,- previewTemplate: $("#template").html(),+ previewTemplate: $('#template').html(),clickable: false,init: function() {- var $dropzoneGhost = $('.dropzone-ghost')- var $gallery = $('.product-gallery')+ let $dropzoneGhost = $('.dropzone-ghost');+ let $gallery = $('.product-gallery');this.on('complete', function() {- $dropzoneGhost.remove().appendTo($gallery)+ $dropzoneGhost.remove().appendTo($gallery);}).on('success', function(e, response) {- $(e.previewElement).find('.product-gallery-item-desc').html(e.name)- $(e.previewElement).attr('data-id', response.id)- var editLinkHref = $(e.previewElement).find('.card-action-edit').attr('href')- editLinkHref = editLinkHref.split('/')- editLinkHref[editLinkHref.length - 2] = response.id- $(e.previewElement).find('.card-action-edit').attr('href', editLinkHref.join('/'))- $(e.previewElement).find('.card-action-edit').show()- var deleteLinkHref = $(e.previewElement).find('.card-action-delete').attr('data-href')- deleteLinkHref = deleteLinkHref.split('/')- deleteLinkHref[deleteLinkHref.length - 3] = response.id- $(e.previewElement).find('.card-action-delete').attr('data-href', deleteLinkHref.join('/'))- $(e.previewElement).find('.card-action-delete').show()- $('.no-images').addClass('hide')- openModal()- })+ $(e.previewElement).find('.product-gallery-item-desc').html(e.name);+ $(e.previewElement).attr('data-id', response.id);+ let editLinkHref = $(e.previewElement).find('.card-action-edit').attr('href');+ editLinkHref = editLinkHref.split('/');+ editLinkHref[editLinkHref.length - 2] = response.id;+ $(e.previewElement).find('.card-action-edit').attr('href', editLinkHref.join('/'));+ $(e.previewElement).find('.card-action-edit').show();+ let deleteLinkHref = $(e.previewElement).find('.card-action-delete').attr('data-href');+ deleteLinkHref = deleteLinkHref.split('/');+ deleteLinkHref[deleteLinkHref.length - 3] = response.id;+ $(e.previewElement).find('.card-action-delete').attr('data-href', deleteLinkHref.join('/'));+ $(e.previewElement).find('.card-action-delete').show();+ $('.no-images').addClass('hide');+ openModal();+ });}-}-var el = document.getElementById('product-gallery')+};+let el = document.getElementById('product-gallery');if (el) {Sortable.create(el, {handle: '.sortable__handle',onUpdate: function () {$.ajax({dataType: 'json',- contentType: "application/json",+ contentType: 'application/json',data: JSON.stringify({'order': (function () {- var postData = []+ let postData = [];$(el).find('.product-gallery-item[data-id]').each(function() {- postData.push($(this).data('id'))- })- return postData+ postData.push($(this).data('id'));+ });+ return postData;})()}),headers: {@@ -204,29 +203,29 @@ if (el) {},method: 'post',url: $(el).data('post-url')- })+ });}- })+ });}$('.select-all').on('change', function() {- var $items = $(this).parents('form').find('.switch-actions')+ let $items = $(this).parents('form').find('.switch-actions');if (this.checked) {- $items.prop('checked', true)+ $items.prop('checked', true);} else {- $items.prop('checked', false)+ $items.prop('checked', false);}-})+});$('.switch-actions').on('change', function() {- var $btnChecked = $(this).parents('form').find('.btn-show-when-checked')- var $btnUnchecked = $(this).parents('form').find('.btn-show-when-unchecked')- if($(this).parents('form').find('.switch-actions:checked').length) {- $btnChecked.show()- $btnUnchecked.hide()+ let $btnChecked = $(this).parents('form').find('.btn-show-when-checked');+ let $btnUnchecked = $(this).parents('form').find('.btn-show-when-unchecked');+ if ($(this).parents('form').find('.switch-actions:checked').length) {+ $btnChecked.show();+ $btnUnchecked.hide();} else {- $btnUnchecked.show()- $btnChecked.hide()+ $btnUnchecked.show();+ $btnChecked.hide();}-})+});$('.datepicker').pickadate({format: 'd mmmm yyyy',formatSubmit: 'yyyy-mm-dd',@@ -235,36 +234,36 @@ $('.datepicker').pickadate({onClose: function() {$(document.activeElement).blur();}-})+});function initSelects() {- $('select:not(.browser-default):not([multiple])').material_select()- $('select[multiple]:not(.browser-default)').select2()+ $('select:not(.browser-default):not([multiple])').material_select();+ $('select[multiple]:not(.browser-default)').select2();}// Coupon dynamic forms$(document).ready(() => {- let $voucherTypeInput = $('.body-vouchers [name="type"]')+ let $voucherTypeInput = $('.body-vouchers [name="type"]');if ($voucherTypeInput.length) {- let $discountValueType = $('[name="discount_value_type"]')- let $voucherForms = $('.voucher-form')- let $applyToProduct = $('[name="product-apply_to"]').parents('.input')- let $applyToCategory = $('[name="category-apply_to"]').parents('.input')+ let $discountValueType = $('[name="discount_value_type"]');+ let $voucherForms = $('.voucher-form');+ let $applyToProduct = $('[name="product-apply_to"]').parents('.input');+ let $applyToCategory = $('[name="category-apply_to"]').parents('.input');let onChange = () => {- let discountValueType = $discountValueType.val()- let type = $voucherTypeInput.val()- let hide = discountValueType === 'percentage'- $applyToProduct.toggleClass('hide', hide)- $applyToCategory.toggleClass('hide', hide)+ let discountValueType = $discountValueType.val();+ let type = $voucherTypeInput.val();+ let hide = discountValueType === 'percentage';+ $applyToProduct.toggleClass('hide', hide);+ $applyToCategory.toggleClass('hide', hide);$voucherForms.each((index, form) => {- let $form = $(form)- let hideForm = $form.data('type') !== type- $form.toggleClass('hide', hideForm)- })- }+ let $form = $(form);+ let hideForm = $form.data('type') !== type;+ $form.toggleClass('hide', hideForm);+ });+ };- $discountValueType.on('change', onChange)- $voucherTypeInput.on('change', onChange)- $voucherTypeInput.trigger('change')+ $discountValueType.on('change', onChange);+ $voucherTypeInput.on('change', onChange);+ $voucherTypeInput.trigger('change');}-})+});diff --git a/saleor/static/js/storefront.js b/saleor/static/js/storefront.jsindex 881a2017d3..8653210892 100644--- a/saleor/static/js/storefront.js+++ b/saleor/static/js/storefront.js@@ -1,155 +1,154 @@-import '../scss/storefront/storefront.scss'-import 'jquery.cookie'-import React from 'react'-import ReactDOM from 'react-dom'+import '../scss/storefront/storefront.scss';+import 'jquery.cookie';+import React from 'react';+import ReactDOM from 'react-dom';import Relay from 'react-relay';-import variantPickerStore from './stores/variantPicker'+import variantPickerStore from './stores/variantPicker';-import VariantPicker from './components/variantPicker/VariantPicker'-import VariantPrice from './components/variantPicker/VariantPrice'+import VariantPicker from './components/variantPicker/VariantPicker';+import VariantPrice from './components/variantPicker/VariantPrice';-let csrftoken = $.cookie('csrftoken')+let csrftoken = $.cookie('csrftoken');-function csrfSafeMethod(method) {- return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method)+function csrfSafeMethod (method) {+ return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method);}$.ajaxSetup({- beforeSend: function(xhr, settings) {+ beforeSend: function (xhr, settings) {if (!csrfSafeMethod(settings.type) && !this.crossDomain) {- xhr.setRequestHeader('X-CSRFToken', csrftoken)+ xhr.setRequestHeader('X-CSRFToken', csrftoken);}}-})+});Relay.injectNetworkLayer(new Relay.DefaultNetworkLayer('/graphql/', {credentials: 'same-origin',headers: {- 'X-CSRFToken': csrftoken,- },+ 'X-CSRFToken': csrftoken+ }})-)+);-var getAjaxError = (response) => {- var ajaxError = $.parseJSON(response.responseText).error.quantity- return ajaxError-}+let getAjaxError = (response) => {+ let ajaxError = $.parseJSON(response.responseText).error.quantity;+ return ajaxError;+};// Mobile menu$(document).ready((e) => {- var $toogleIcon = $('.navbar__brand__menu-toggle')- var $mobileNav = $('nav')- var windowWidth = $(window).width()+ let $toogleIcon = $('.navbar__brand__menu-toggle');+ let $mobileNav = $('nav');+ let windowWidth = $(window).width();if (windowWidth < 767) {- $mobileNav.append('<ul class="nav navbar-nav navbar__menu__login"></ul>')+ $mobileNav.append('<ul class="nav navbar-nav navbar__menu__login"></ul>');$('.navbar__login a').appendTo('.navbar__menu__login')- .wrap( '<li class="nav-item login-item"></li>')- .addClass('nav-link')+ .wrap('<li class="nav-item login-item"></li>')+ .addClass('nav-link');}$toogleIcon.click((e) => {- $mobileNav.toggleClass('open')- event.stopPropagation()- })+ $mobileNav.toggleClass('open');+ event.stopPropagation();+ });$(document).click((e) => {- $mobileNav.removeClass('open')- })-})+ $mobileNav.removeClass('open');+ });+});// Mobile search form-var $searchIcon = $('.mobile-search-icon')-var $closeSearchIcon = $('.mobile-close-search')-var $searchForm = $('.navbar__brand__search')+let $searchIcon = $('.mobile-search-icon');+let $closeSearchIcon = $('.mobile-close-search');+let $searchForm = $('.navbar__brand__search');$searchIcon.click((e) => {- $searchForm.animate({left: 0}, {duration: 500})-})+ $searchForm.animate({left: 0}, {duration: 500});+});$closeSearchIcon.click((e) => {- $searchForm.animate({left: '-100vw'}, {duration: 500})-})+ $searchForm.animate({left: '-100vw'}, {duration: 500});+});// Sticky footer-var navbarHeight = $('.navbar').outerHeight(true)-var footerHeight = $('.footer').outerHeight(true)-var windowHeight = $(window).height()-$('.maincontent').css('min-height', windowHeight - navbarHeight - footerHeight)+let navbarHeight = $('.navbar').outerHeight(true);+let footerHeight = $('.footer').outerHeight(true);+let windowHeight = $(window).height();+$('.maincontent').css('min-height', windowHeight - navbarHeight - footerHeight);// New address dropdown-var $addressShow = $('.address_show label')-var $addressHide = $('.address_hide label')-var $addressForm = $('.checkout__new-address')-var $initialValue = $('#address_new_address').prop('checked')+let $addressShow = $('.address_show label');+let $addressHide = $('.address_hide label');+let $addressForm = $('.checkout__new-address');+let $initialValue = $('#address_new_address').prop('checked');$addressShow.click((e) => {- $addressForm.slideDown('slow')-})+ $addressForm.slideDown('slow');+});$addressHide.click((e) => {- $addressForm.slideUp('slow')-})+ $addressForm.slideUp('slow');+});if ($initialValue) {- $addressForm.slideDown(0)+ $addressForm.slideDown(0);} else {- $addressForm.slideUp(0)+ $addressForm.slideUp(0);}// Smart address form$(function() {- const $i18nAddresses = $('.i18n-address')+ const $i18nAddresses = $('.i18n-address');$i18nAddresses.each(function () {- const $form = $(this).closest('form')- const $countryField = $form.find('select[name=country]')- const $previewField = $form.find('input.preview')+ const $form = $(this).closest('form');+ const $countryField = $form.find('select[name=country]');+ const $previewField = $form.find('input.preview');$countryField.on('change', () => {- $previewField.val('on')- $form.submit()- })- })-})-+ $previewField.val('on');+ $form.submit();+ });+ });+});-//Cart dropdown+// Cart dropdown-var summaryLink = '/cart/summary'-var $cartDropdown = $('.cart-dropdown')-var $addToCartError = $('.product__info__form-error')+let summaryLink = '/cart/summary';+let $cartDropdown = $('.cart-dropdown');+let $addToCartError = $('.product__info__form-error');const onAddToCartSuccess = () => {$.get(summaryLink, (data) => {- $cartDropdown.html(data)- $addToCartError.html('')- var newQunatity = $('.cart-dropdown__total').data('quantity')- $('.badge').html(newQunatity).removeClass('hidden-xs-up')- $cartDropdown.addClass('show')- $cartDropdown.find('.container').scrollTop($cartDropdown.find('.container')[0].scrollHeight)+ $cartDropdown.html(data);+ $addToCartError.html('');+ let newQunatity = $('.cart-dropdown__total').data('quantity');+ $('.badge').html(newQunatity).removeClass('hidden-xs-up');+ $cartDropdown.addClass('show');+ $cartDropdown.find('.container').scrollTop($cartDropdown.find('.container')[0].scrollHeight);setTimeout((e) => {- $cartDropdown.removeClass('show')- }, 2500)- })-}+ $cartDropdown.removeClass('show');+ }, 2500);+ });+};const onAddToCartError = (response) => {- $addToCartError.html(getAjaxError(response))-}+ $addToCartError.html(getAjaxError(response));+};$.get(summaryLink, (data) => {- $cartDropdown.html(data)-})+ $cartDropdown.html(data);+});$('.navbar__brand__cart').hover((e) => {- $cartDropdown.addClass('show')+ $cartDropdown.addClass('show');}, (e) => {- $cartDropdown.removeClass('show')-})+ $cartDropdown.removeClass('show');+});$('.product-form button').click((e) => {- e.preventDefault()- var quantity = $('#id_quantity').val()- var variant = $('#id_variant').val()- $.ajax ({+ e.preventDefault();+ let quantity = $('#id_quantity').val();+ let variant = $('#id_variant').val();+ $.ajax({url: $('.product-form').attr('action'),type: 'POST',data: {@@ -157,23 +156,23 @@ $('.product-form button').click((e) => {quantity: quantity},success: () => {- onAddToCartSuccess()+ onAddToCartSuccess();},error: (response) => {- onAddToCartError(response)+ onAddToCartError(response);}- })-})+ });+});// Delivery information-var $deliveryForm = $('.deliveryform')-var crsfToken = $deliveryForm.data('crsf')-var $countrySelect = $('#id_country')-var $newMethod = $('.cart__delivery-info__method')-var $newPrice = $('.cart__delivery-info__price')+let $deliveryForm = $('.deliveryform');+let crsfToken = $deliveryForm.data('crsf');+let $countrySelect = $('#id_country');+let $newMethod = $('.cart__delivery-info__method');+let $newPrice = $('.cart__delivery-info__price');$countrySelect.on('change', (e) => {- var newCountry = $countrySelect.val()+ let newCountry = $countrySelect.val();$.ajax({url: '/cart/shipingoptions/',type: 'POST',@@ -182,37 +181,36 @@ $countrySelect.on('change', (e) => {'country': newCountry},success: (data) => {- $newMethod.empty()- $newPrice.empty()+ $newMethod.empty();+ $newPrice.empty();$.each(data.options, (key, val) => {- $newMethod.append('<p>' + val.shipping_method__name + '</p>')- $newPrice.append('<p>$' + val.price[1] + '</p>')- })+ $newMethod.append('<p>' + val.shipping_method__name + '</p>');+ $newPrice.append('<p>$' + val.price[1] + '</p>');+ });}- })-})+ });+});// Save tab links to URL$('.nav-tabs a').click((e) => {- e.preventDefault()- $(this).tab('show')+ e.preventDefault();+ $(this).tab('show');});$('ul.nav-tabs li a:not(:first)').on('shown.bs.tab', (e) => {- var id = $(e.target).attr('href').substr(1)- window.location.hash = id+ let id = $(e.target).attr('href').substr(1);+ window.location.hash = id;});-var hash = window.location.hash;-$('.nav-tabs a[href="' + hash + '"]').tab('show')-+let hash = window.location.hash;+$('.nav-tabs a[href="' + hash + '"]').tab('show');// Variant Picker-const variantPickerContainer = document.getElementById('variant-picker')-const variantPriceContainer = document.getElementById('variant-price-component')+const variantPickerContainer = document.getElementById('variant-picker');+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(<VariantPickeronAddToCartError={onAddToCartError}@@ -223,7 +221,7 @@ if (variantPickerContainer) {variants={variantPickerData.variants}/>,variantPickerContainer- )+ );if (variantPriceContainer) {ReactDOM.render(@@ -232,52 +230,51 @@ if (variantPickerContainer) {store={variantPickerStore}/>,variantPriceContainer- )+ );}}-// Cart quantity form-var $cartLine = $('.cart__line')-var $total = $('.cart-total')-var $cartBadge = $('.navbar__brand__cart .badge')-var $removeProductSucces = $('.remove-product-alert')-var $closeMsg = $('.close-msg')+let $cartLine = $('.cart__line');+let $total = $('.cart-total');+let $cartBadge = $('.navbar__brand__cart .badge');+let $removeProductSucces = $('.remove-product-alert');+let $closeMsg = $('.close-msg');$cartLine.each(function() {- var $quantityInput = $(this).find('#id_quantity')- var cartFormUrl = $(this).find('.form-cart').attr('action')- var $qunatityError = $(this).find('.cart__line__quantity-error')- var $subtotal = $(this).find('.cart-item-subtotal h3')- var $deleteIcon = $(this).find('.cart-item-delete')+ let $quantityInput = $(this).find('#id_quantity');+ let cartFormUrl = $(this).find('.form-cart').attr('action');+ let $qunatityError = $(this).find('.cart__line__quantity-error');+ let $subtotal = $(this).find('.cart-item-subtotal h3');+ let $deleteIcon = $(this).find('.cart-item-delete');$(this).on('change', $quantityInput, (e) => {- var newQuantity = $quantityInput.val()+ let newQuantity = $quantityInput.val();$.ajax({url: cartFormUrl,method: 'POST',data: {quantity: newQuantity},success: (response) => {- if (newQuantity == 0) {- if (response.cart.numLines == 0) {- $.cookie('alert', 'true', { path: '/cart' })- location.reload()+ if (newQuantity === 0) {+ if (response.cart.numLines === 0) {+ $.cookie('alert', 'true', { path: '/cart' });+ location.reload();} else {- $removeProductSucces.removeClass('hidden-xs-up')- $(this).fadeOut()+ $removeProductSucces.removeClass('hidden-xs-up');+ $(this).fadeOut();}} else {- $subtotal.html(response.subtotal)+ $subtotal.html(response.subtotal);}- $total.html(response.total)- $cartBadge.html(response.cart.numItems)- $qunatityError.html('')- $cartDropdown.load(summaryLink)+ $total.html(response.total);+ $cartBadge.html(response.cart.numItems);+ $qunatityError.html('');+ $cartDropdown.load(summaryLink);},error: (response) => {- $qunatityError.html(getAjaxError(response))+ $qunatityError.html(getAjaxError(response));}- })- })+ });+ });$deleteIcon.on('click', (e) => {$.ajax({url: cartFormUrl,@@ -285,25 +282,25 @@ $cartLine.each(function() {data: {quantity: 0},success: (response) => {if (response.cart.numLines >= 1) {- $(this).fadeOut()- $total.html(response.total)- $cartBadge.html(response.cart.numItems)- $cartDropdown.load(summaryLink)- $removeProductSucces.removeClass('hidden-xs-up')+ $(this).fadeOut();+ $total.html(response.total);+ $cartBadge.html(response.cart.numItems);+ $cartDropdown.load(summaryLink);+ $removeProductSucces.removeClass('hidden-xs-up');} else {- $.cookie('alert', 'true', { path: '/cart' })- location.reload()+ $.cookie('alert', 'true', { path: '/cart' });+ location.reload();}}- })- })-})+ });+ });+});-if ($.cookie('alert') == 'true') {- $removeProductSucces.removeClass('hidden-xs-up')- $.cookie('alert', 'false', { path: '/cart' })+if ($.cookie('alert') === 'true') {+ $removeProductSucces.removeClass('hidden-xs-up');+ $.cookie('alert', 'false', { path: '/cart' });}$closeMsg.on('click', (e) => {- $removeProductSucces.addClass('hidden-xs-up')-})+ $removeProductSucces.addClass('hidden-xs-up');+});diff --git a/saleor/static/js/stores/variantPicker.js b/saleor/static/js/stores/variantPicker.jsindex 2d76cfff2c..7cd1430686 100644--- a/saleor/static/js/stores/variantPicker.js+++ b/saleor/static/js/stores/variantPicker.js@@ -1,17 +1,16 @@-import { autorun, computed, observable } from 'mobx'-+import { computed, observable } from 'mobx';class VariantPickerStore {@observable variant = {}- setVariant(variant) {- this.variant = variant ? variant : {}- }+ setVariant(variant) {+ this.variant = variant || {};+ }@computed get isEmpty() {- return !this.variant.id+ return !this.variant.id;}}-const store = new VariantPickerStore()-export default store+const store = new VariantPickerStore();+export default store;diff --git a/yarn.lock b/yarn.lockindex 5697e70abb..affc4fa05a 100644--- a/yarn.lock+++ b/yarn.lock@@ -1633,6 +1633,14 @@ escope@^3.6.0:esrecurse "^4.1.0"estraverse "^4.1.1"+eslint-config-standard@^6.2.1:+ version "6.2.1"+ resolved "https://registry.yarnpkg.com/eslint-config-standard/-/eslint-config-standard-6.2.1.tgz#d3a68aafc7191639e7ee441e7348739026354292"++eslint-plugin-promise@^3.4.0:+ version "3.4.0"+ resolved "https://registry.yarnpkg.com/eslint-plugin-promise/-/eslint-plugin-promise-3.4.0.tgz#6ba9048c2df57be77d036e0c68918bc9b4fc4195"+eslint-plugin-react@^6.7.1:version "6.8.0"resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-6.8.0.tgz#741ab5438a094532e5ce1bbb935d6832356f492d"@@ -1640,6 +1648,10 @@ eslint-plugin-react@^6.7.1:doctrine "^1.2.2"jsx-ast-utils "^1.3.4"+eslint-plugin-standard@^2.0.1:+ version "2.0.1"+ resolved "https://registry.yarnpkg.com/eslint-plugin-standard/-/eslint-plugin-standard-2.0.1.tgz#3589699ff9c917f2c25f76a916687f641c369ff3"+eslint@^3.10.2:version "3.12.2"resolved "https://registry.yarnpkg.com/eslint/-/eslint-3.12.2.tgz#6be5a9aa29658252abd7f91e9132bab1f26f3c34"