Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor JS/JSX code
Patryk Zawadzki42b86bf893a9
diff --git a/.flowconfig b/.flowconfignew file mode 100644index 0000000000..4a58bdcdef--- /dev/null+++ b/.flowconfig@@ -0,0 +1,7 @@+[ignore]++[include]++[libs]++[options]diff --git a/.gitignore b/.gitignoreindex c289cb3101..7e9d92fd0f 100644--- a/.gitignore+++ b/.gitignore@@ -4,6 +4,7 @@!.buildpacks!.coveragerc!.dockerignore+!.flowconfig!.gitignore!.travis**.cssdiff --git a/Gruntfile.js b/Gruntfile.jsindex 8c7dfa0dbb..e2bd3d100e 100644--- a/Gruntfile.js+++ b/Gruntfile.js@@ -82,8 +82,7 @@ module.exports = function(grunt) {options: {map: true,processors: [- require("autoprefixer"),- require("csswring")+ require("autoprefixer")]},prod: {diff --git a/package.json b/package.jsonindex 18781d46ab..74f9281ff5 100644--- a/package.json+++ b/package.json@@ -26,8 +26,10 @@"jquery.cookie": "^1.4.1","materialize-sass-origin": "git+https://github.com/mociepka/materialize-sass-origin.git","modernizr": "^3.2.0",- "react": "^0.14.2",- "react-dom": "^0.14.2",+ "react": "^0.14.3",+ "react-dom": "^0.14.3",+ "react-redux": "~4.0.0",+ "redux": "~3.0.4","select2": "^4.0.0","sortablejs": "^1.4.2","underscore": "^1.8.3"diff --git a/saleor/cart/views.py b/saleor/cart/views.pyindex e56f720047..ec5e5452e7 100755--- a/saleor/cart/views.py+++ b/saleor/cart/views.py@@ -33,9 +33,12 @@ def index(request, product_id=None):if form.is_valid():form.save()if request.is_ajax():- response = {'product_id': line.product.pk,- 'subtotal': currencyfmt(line.get_total().gross,- line.get_total().currency), 'total': 0}+ response = {+ 'product_id': line.product.pk,+ 'subtotal': currencyfmt(+ line.get_total().gross,+ line.get_total().currency),+ 'total': 0}if cart:response['total'] = currencyfmt(cart.get_total().gross, cart.get_total().currency)diff --git a/saleor/static/js_src/components/cart.jsx b/saleor/static/js_src/components/cart.jsxnew file mode 100644index 0000000000..f780d3d925--- /dev/null+++ b/saleor/static/js_src/components/cart.jsx@@ -0,0 +1,198 @@+import React, {Component, findDOMNode} from 'react';+import {connect} from 'react-redux';++export class CartItemAmountOption extends Component {+ render() {+ var value = this.props.value;+ var label = this.props.label ? this.props.label : value;+ return <option value={value}>{label}</option>;+ };+}++class CartItemAmountSelect extends Component {+ constructor() {+ super(...arguments);+ this.state = {+ error: null,+ lastSavedValue: this.props.value,+ renderSelect: false,+ renderSubmit: false,+ result: null,+ sending: false,+ value: this.props.value+ };+ }++ componentDidMount() {+ if (this.state.value < this.props.thresholdValue) {+ this.setState({renderSelect: true});+ }+ }++ change(event) {+ let newValue = event.target.value;+ this.setState({result: null});+ if (newValue != this.props.thresholdValue || !this.state.renderSelect) {+ this.setState({value: newValue});+ }+ if (newValue >= this.props.thresholdValue) {+ this.setState({renderSelect: false});+ }+ if (newValue < this.props.thresholdValue && this.state.renderSelect) {+ this.sendQuantity(newValue);+ }++ if (!this.state.renderSelect && !this.state.sending) {+ this.setState({renderSubmit: true});+ }+ }++ valueChanged() {+ return this.state.lastSavedValue != this.state.value;+ }++ checkKey(event) {+ if (event.key == "Enter" && this.valueChanged()) {+ this.sendQuantityWrapper();+ }+ }++ sendQuantityWrapper() {+ this.sendQuantity(this.refs.inputQuantity.props.value);+ }++ sendQuantity(quantity) {+ this.setState({renderSubmit: false});+ this.setState({sending: true});++ $.ajax({+ url: this.props.url,+ method: "post",+ data: {quantity: quantity},+ complete: () => {+ this.setState({sending: false});+ if (quantity < this.props.thresholdValue) {+ this.setState({renderSelect: true});+ }+ },+ success: (response) => {+ if (!quantity) {+ if (!response.total) {+ location.reload();+ }+ $(findDOMNode(this)).parents("tr").fadeOut(function() {+ $(this).remove();+ });+ }+ if (response.hasOwnProperty('productId')) {+ let {productId, subtotal, total} = response;+ let props = {productId, subtotal};+ this.props.dispatch({type: 'UPDATE_SUBTOTAL', ...props});+ this.props.dispatch({type: 'UPDATE_TOTAL', total});+ }+ this.setState({result: "success", lastSavedValue: quantity});+ setTimeout(() => {+ this.setState({result: null});+ }, 1000);+ },+ error: (response) => {+ this.setState({error: response.error.quantity, result: "error"});+ }+ });+ }++ removeFromCart() {+ this.sendQuantity(0);+ }++ render() {+ let classNames = [this.props.className];+ switch (this.state.result) {+ case ('success'):+ classNames.push('has-success');+ break;+ case ('error'):+ classNames.push('has-error');+ break;+ }+ let classNamesInput = ['input-group', 'cart-item-quantity'];+ if ((!this.state.renderSubmit || !this.valueChanged()) && !(this.state.result == "error")) {+ classNamesInput.push('no-submit');+ }++ let options = this.props.options.map((option) => <CartItemAmountOption key={option} value={option} label={option == this.props.thresholdValue ? `${option} +` : option} />);+ let select = <select onChange={this.change.bind(this)} value={this.state.value} className="form-control cart-item-quantity-select">+ {options}+ </select>;+ let input = <div className={classNamesInput.join(' ')}>+ <input onKeyUp={this.checkKey.bind(this)} onChange={this.change.bind(this)} id="id_quantity" max={this.props.max} min="1" ref="inputQuantity" name="quantity" type="number" alue={this.state.value} />+ <span className="input-group-btn">+ <button onClick={this.sendQuantityWrapper.bind(this)} className="btn btn-info" type="submit">Update</button>+ </span>+ </div>;+ return <div className={classNames.join(' ')}>+ {this.state.renderSelect ? select : input}+ {this.state.sending && !(this.state.result == 'error')? <i className="fa fa-circle-o-notch fa-spin"></i> : ''}+ {this.state.result == 'error' ? <span className="error text-danger">{this.state.error}</span> : ''}+ <button type="submit" className="btn btn-link btn-sm cart-item-remove" onClick={this.removeFromCart.bind(this)}>+ <span className="text-muted">Remove from cart</span>+ </button>+ </div>;+ }+}++function selectQuantities(state) {+ // FIXME: move quantities to store+ return {};+}++export var CartItemAmount = connect(selectQuantities)(CartItemAmountSelect);++let renderSubtotal = ({productId, subtotals}) => {+ let value;+ if (subtotals.hasOwnProperty(productId)) {+ value = subtotals[productId];+ }+ return <span>{value}</span>;+}++function selectSubtotals(state) {+ return {'subtotals': state.subtotals};+}++export var CartItemSubtotal = connect(selectSubtotals)(renderSubtotal);++let renderTotal = ({value}) => <b>{value}</b>;++function selectTotal(state) {+ return {'value': state.total};+}++export var CartTotal = connect(selectTotal)(renderTotal);++export class FormShippingToggler extends Component {+ constructor() {+ super(...arguments);+ this.state = {+ value: true+ };+ }++ componentDidMount() {+ $(".form-full").hide();+ }++ formFullToggle(event) {+ this.setState({value: event.target.checked});+ $(".form-full").toggle();+ }++ render() {+ return <div className="checkbox">+ <label>+ <input checked={this.state.value} type="checkbox" onChange={this.formFullToggle.bind(this)} name="shipping_same_as_billing" />+ {this.props.label}+ </label>+ </div>;+ }+}diff --git a/saleor/static/js_src/storefront.jsx b/saleor/static/js_src/storefront.jsxindex 6e2c934000..15bed40814 100644--- a/saleor/static/js_src/storefront.jsx+++ b/saleor/static/js_src/storefront.jsx@@ -1,275 +1,114 @@-class CartItemAmount extends React.Component {+/* @flow */- constructor() {- super(...arguments);- this.state = {- error: null,- lastSavedValue: this.props.value,- renderSelect: false,- renderSubmit: false,- result: null,- sending: false,- value: this.props.value- };- }-- componentDidMount() {- if (this.state.value < this.props.thresholdValue) {- this.setState({renderSelect: true});- }- }-- change(event){- let newValue = event.target.value;- this.setState({result: null});- if (newValue != this.props.thresholdValue || !this.state.renderSelect) {- this.setState({value: newValue});- }- if (newValue >= this.props.thresholdValue) {- this.setState({renderSelect: false});- }- if (newValue < this.props.thresholdValue && this.state.renderSelect) {- this.sendQuantity(newValue);- }-- if (!this.state.renderSelect && !this.state.sending) {- this.setState({renderSubmit: true});- }- }-- valueChanged() {- return this.state.lastSavedValue != this.state.value;- }-- checkKey(event) {- if (event.key == "Enter" && this.valueChanged()) {- this.sendQuantityWrapper();- }- }-- sendQuantityWrapper() {- this.sendQuantity(this.refs.inputQuantity.props.value);- }-- sendQuantity(quantity) {- this.setState({renderSubmit: false});- this.setState({sending: true});+import React from 'react';+import {render} from 'react-dom';+import {Provider} from 'react-redux';+import $ from 'jquery';+import {CartItemAmount, CartItemSubtotal, CartTotal, FormShippingToggler} from './components/cart';+import CartStore from './stores/cart-store';+require('jquery.cookie');+require('bootstrap-sass');- $.ajax({- url: this.props.url,- method: "post",- data: {quantity: quantity},- complete: () => {- this.setState({sending: false});- if (quantity < this.props.thresholdValue) {- this.setState({renderSelect: true});- }- },- success: (response) => {- if (!quantity) {- if (!response.total) {- location.reload();- }- $(React.findDOMNode(this)).parents("tr").fadeOut(function() {- $(this).remove();- });- }- this.setState({result: "success", lastSavedValue: quantity});- setTimeout(() => {- this.setState({result: null});- }, 1000);- },- error: (response) => {- this.setState({error: response.responseJSON.error.quantity, result: "error"});- }- });- }-- removeFromCart() {- this.sendQuantity(0);- }-- render() {- let classNames = React.addons.classSet({- [this.props.className]: true,- "has-success": this.state.result == "success",- "has-error": this.state.result == "error"- });-- let select = <select onChange={this.change.bind(this)} value={this.state.value} className="form-control cart-item-quantity-select">- {this.props.options.map((option) =>- <CartItemAmountOption key={option} value={option} label={option == this.props.thresholdValue ? option+" +" : option} />)}- </select>;-- let classNamesInput = React.addons.classSet({- "input-group": true,- "cart-item-quantity": true,- "no-submit": (!this.state.renderSubmit || !this.valueChanged()) && !(this.state.result == "error")- });- let input =- <div className={classNamesInput}>- <input onKeyUp={this.checkKey.bind(this)} onChange={this.change.bind(this)} id="id_quantity" max={this.props.max} min="1" ref="inputQuantity"- name="quantity" type="number" value={this.state.value} />- <span className="input-group-btn">- <button onClick={this.sendQuantityWrapper.bind(this)} className="btn btn-info" type="submit">Update</button>- </span>- </div>;- return <div className={classNames}>- {this.state.renderSelect ? select : input}- {this.state.sending && !(this.state.result == "error")? <i className="fa fa-circle-o-notch fa-spin"></i> : ""}- {this.state.result == "error" ? <span className="error text-danger">{this.state.error}</span> : ""}- <button type="submit" className="btn btn-link btn-sm cart-item-remove" onClick={this.removeFromCart.bind(this)}>- <span className="text-muted">Remove from cart</span>- </button>- </div>;- }-}--class CartItemAmountOption extends React.Component {- render() {- var value = this.props.value;- var label = this.props.label ? this.props.label : value;- return <option value={value}>{label}</option>;- };-}--class CartItemSubtotal extends React.Component {- constructor() {- super(...arguments);- this.state = {- value: this.props.value- };- }+let textInput = [];+let options = [1,2,3,4,5,6,7,8,9,10];+let csrftoken = $.cookie('csrftoken');- render() {- return <span>{this.state.value}</span>;- }-}--class CartTotal extends React.Component {- constructor() {- super(...arguments);- this.state = {- value: this.props.value- };- }-- render() {- return <b>{this.state.value}</b>;- }-}--var textInput = [];-var options = [1,2,3,4,5,6,7,8,9,10];-var csrftoken = $.cookie('csrftoken');function csrfSafeMethod(method) {- return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));+ return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));}+$.ajaxSetup({- beforeSend: function(xhr, settings) {- if (!csrfSafeMethod(settings.type) && !this.crossDomain) {- xhr.setRequestHeader("X-CSRFToken", csrftoken);- }+ beforeSend: function(xhr, settings) {+ if (!csrfSafeMethod(settings.type) && !this.crossDomain) {+ xhr.setRequestHeader("X-CSRFToken", csrftoken);}+ }});-$(".cart-item-amount").each(function(index) {- var $input = $(this).find("input");- var $button = $(this).find("button");- var value = $input.val();- var name = $input.attr("name");- var max = $input.attr("max");- var props = {- className: "",- index: index,- max: max,- options: options.slice(0, max),- thresholdValue: options[options.length - 1],- url: $(this).find("form").attr("action"),- value: value- };-- $(this).find(".cart-item-quantity").removeClass("js-hidden");- $button.addClass("invisible");- textInput.push(this.firstElementChild);-- React.render(<CartItemAmount {...props} />, this);+$('.cart-item-amount').each(function(index) {+ let $input = $(this).find('input');+ let $button = $(this).find('button');+ let value = $input.val();+ let name = $input.attr('name');+ let max = $input.attr('max');+ let props = {+ className: '',+ index: index,+ max: max,+ options: options.slice(0, max),+ thresholdValue: options[options.length - 1],+ url: $(this).find('form').attr('action'),+ value: value+ };++ $(this).find('.cart-item-quantity').removeClass('js-hidden');+ $button.addClass('invisible');+ textInput.push(this.firstElementChild);++ render(<Provider store={CartStore}>+ <CartItemAmount {...props} />+ </Provider>, this);});-var $cartTotal = $(".cart-total");-var cartTotalValue = $cartTotal.text();+let $cartTotal = $('.cart-total');+let cartTotalValue = $cartTotal.text();if ($cartTotal.length) {- var cartTotal = React.render(<CartTotal value={cartTotalValue}/>, $(".cart-total")[0]);+ CartStore.dispatch({type: 'UPDATE_TOTAL', total: cartTotalValue});+ let cartTotal = render(<Provider store={CartStore}>+ <CartTotal />+ </Provider>, $cartTotal[0]);}-var cartSubtotals = [];$(".cart-item-subtotal").each(function() {- var productId = $(this).data("product-id");- var props = {- productId: productId,- value: $(this).text()- };- cartSubtotals[productId] = React.render(<CartItemSubtotal {...props} />, this);+ let productId = $(this).data('product-id');+ let props = {+ productId,+ subTotal: $(this).text()+ };+ CartStore.dispatch({type: 'UPDATE_SUBTOTAL', ...props});+ render(<Provider store={CartStore}>+ <CartItemSubtotal productId={productId} />+ </Provider>, this);});-$(document).on("ajaxComplete", function(event, response) {- var json = response.responseJSON;- if (json.product_id && $cartTotal.length) {- cartSubtotals[json.product_id].setState({value: json.subtotal});- cartTotal.setState({value: json.total});- }+$(function() {+ let $carousel = $('.carousel');+ let $items = $('.product-gallery-item');+ let $modal = $('.modal');++ $items.on('click', function(e) {+ if ($carousel.is(':visible')) {+ e.preventDefault();+ }+ let index = $(this).index();+ $carousel.carousel(index);+ });++ $modal.on('show.bs.modal', function() {+ let $img = $(this).find('.modal-body img');+ let dataSrc = $img.attr('data-src');+ $img.attr('src', dataSrc);+ });});-class FormShippingToggler extends React.Component {- constructor() {- super(...arguments);- this.state = {- value: true- };- }-- componentDidMount() {- $(".form-full").hide();- }-- formFullToggle() {- this.setState({value: event.target.checked});- $(".form-full").toggle();- }-- render() {- return <div className="checkbox">- <label>- <input checked={this.state.value} type="checkbox" onChange={::this.formFullToggle} name="shipping_same_as_billing" />- {this.props.label}- </label>- </div>;- }-}--var $formFullToggle = $("#form-full-toggle");-if ($formFullToggle.length) {- React.render(<FormShippingToggler label={$formFullToggle.data("label")} />, document.getElementById("form-full-toggle"));-}-$(function() {- $('.conditional-visibility').each(function() {- let $element = $(this);- let controller = $element.data('controller');- let triggerValue = $element.data('value');- let $controller = $(controller);- function updateVisiblity() {- let value = $controller.filter(':checked').val();- if (!value && $controller.prop('type') === 'hidden') {- value = $controller.val();- }- if (value === triggerValue) {- $element.show();- } else {- $element.hide();- }- }- $controller.on('change', updateVisiblity);- updateVisiblity();- });+ $('.conditional-visibility').each(function() {+ let $element = $(this);+ let controller = $element.data('controller');+ let triggerValue = $element.data('value');+ let $controller = $(controller);+ function updateVisiblity() {+ let value = $controller.filter(':checked').val();+ if (!value && $controller.prop('type') === 'hidden') {+ value = $controller.val();+ }+ if (value === triggerValue) {+ $element.show();+ } else {+ $element.hide();+ }+ }+ $controller.on('change', updateVisiblity);+ updateVisiblity();+ });});diff --git a/saleor/static/js_src/stores/cart-store.jsx b/saleor/static/js_src/stores/cart-store.jsxnew file mode 100644index 0000000000..8889ebd3be--- /dev/null+++ b/saleor/static/js_src/stores/cart-store.jsx@@ -0,0 +1,21 @@+/* @flow */++import {createStore} from 'redux';++function updateCart(state = {total: 'N/A', subtotals: {}}, action) {+ switch(action.type) {+ case ('UPDATE_TOTAL'):+ return {...state, total: action.total};+ case ('UPDATE_SUBTOTAL'):+ let {productId, subtotal} = action;+ let subtotals = {...state.subtotals};+ subtotals[productId] = subtotal;+ return {...state, subtotals};+ default:+ return state;+ }+}++let store = createStore(updateCart);++export default store;diff --git a/webpack.config.js b/webpack.config.jsindex 2bad98bdbf..4fe5629dce 100644--- a/webpack.config.js+++ b/webpack.config.js@@ -4,6 +4,7 @@ var webpack = require('webpack');configuration = {entry: {dashboard: './saleor/static/js_src/dashboard.jsx',+ storefront: './saleor/static/js_src/storefront.jsx',},output: {filename: './saleor/static/js/[name].js'@@ -16,7 +17,7 @@ configuration = {]},resolve: {- extensions: ['', '.js']+ extensions: ['', '.jsx', '.js']},plugins: [new webpack.ProvidePlugin({