Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use MobX to share state between VariantPicker and price component
Marcin Gębala057c7a837b59
diff --git a/.babelrc b/.babelrcindex 887658f962..a1384e415d 100644--- a/.babelrc+++ b/.babelrc@@ -1,4 +1,8 @@{"presets": ["es2015", "react"],- "plugins": ["transform-class-properties", "transform-object-rest-spread"]+ "plugins": [+ "transform-decorators-legacy",+ "transform-class-properties",+ "transform-object-rest-spread"+ ]}diff --git a/package.json b/package.jsonindex 2fccdf1319..31b6e1a48b 100644--- a/package.json+++ b/package.json@@ -27,6 +27,8 @@"jquery.cookie": "^1.4.1","material-design-icons": "^3.0.1","materialize-css": "^0.97.7",+ "mobx": "^3.0.0",+ "mobx-react": "^4.1.0","modernizr": "^3.2.0","react": "^0.14.3","react-dom": "^0.14.3",@@ -41,6 +43,7 @@"babel-core": "^6.14.0","babel-loader": "^6.2.5","babel-plugin-transform-class-properties": "^6.11.5",+ "babel-plugin-transform-decorators-legacy": "^1.3.4","babel-plugin-transform-object-rest-spread": "^6.8.0","babel-preset-es2015": "^6.14.0","babel-preset-react": "^6.0.15",diff --git a/saleor/product/utils.py b/saleor/product/utils.pyindex 805a57b221..3ef9a45cf3 100644--- a/saleor/product/utils.py+++ b/saleor/product/utils.py@@ -102,7 +102,7 @@ def products_for_cart(user):def get_variant_picker_data(product, discounts=None):availability = get_availability(product, discounts)variants = product.variants.all()- data = {'productAttributes': [], 'variantAttributes': [], 'variants': []}+ data = {'variantAttributes': [], 'variants': []}variant_attributes = product.product_class.variant_attributes.all()for attribute in variant_attributes:@@ -113,12 +113,6 @@ def get_variant_picker_data(product, discounts=None):'values': [{'pk': value.pk, 'display': value.display}for value in attribute.values.all()]})- product_attributes = get_product_attributes_data(product)- for attribute, value in product_attributes.items():- data['productAttributes'].append({- 'attribute': attribute.display,- 'value': value.display})-for variant in variants:price = variant.get_price_per_item(discounts)price_undiscounted = variant.get_price_per_item()@@ -147,13 +141,12 @@ def get_product_attributes_data(product):def price_as_dict(price):- return {- 'currency': price.currency,- 'gross': float(price.gross),- 'net': float(price.net)} if price else {}+ if not price:+ return {}+ return {'currency': price.currency, 'gross': float(price.gross),+ 'net': float(price.net)}def price_range_as_dict(price_range):- return {- 'maxPrice': price_as_dict(price_range.max_price),- 'minPrice': price_as_dict(price_range.min_price)}+ return {'maxPrice': price_as_dict(price_range.max_price),+ 'minPrice': price_as_dict(price_range.min_price)}diff --git a/saleor/static/js/components/variantPicker/VariantPicker.js b/saleor/static/js/components/variantPicker/VariantPicker.jsindex fbe4b714ef..7a8879e8a9 100644--- a/saleor/static/js/components/variantPicker/VariantPicker.js+++ b/saleor/static/js/components/variantPicker/VariantPicker.js@@ -1,20 +1,20 @@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 VariantPrice from './VariantPrice'+@observerexport default class VariantPicker extends Component {static propTypes = {- availability: PropTypes.object.isRequired,onAddToCartError: PropTypes.func.isRequired,onAddToCartSuccess: PropTypes.func.isRequired,- productAttributes: PropTypes.array.isRequired,+ store: PropTypes.object.isRequired,url: PropTypes.string.isRequired,variantAttributes: PropTypes.array.isRequired,variants: PropTypes.array.isRequired@@ -22,7 +22,7 @@ export default class VariantPicker extends Component {constructor(props) {super(props)- const { variants } = this.props+ const { store, variants } = this.propsconst variant = variants.filter(v => !!Object.keys(v.attributes).length)[0]const selection = variant ? variant.attributes : {}@@ -30,21 +30,21 @@ export default class VariantPicker extends Component {this.state = {errors: {},quantity: 1,- variant: variant,selection: selection}+ store.setVariant(variant)}handleAddToCart = () => {- const { onAddToCartSuccess, onAddToCartError } = this.props;- const { quantity, variant } = this.state- if (quantity > 0 && variant) {+ const { onAddToCartSuccess, onAddToCartError, store } = this.props;+ const { quantity } = this.state+ if (quantity > 0 && !store.isEmpty) {$.ajax({url: this.props.url,method: 'post',data: {quantity: quantity,- variant: variant.id+ variant: store.variant.id},success: () => {onAddToCartSuccess()@@ -69,33 +69,28 @@ export default class VariantPicker extends Component {}matchVariantFromSelection() {+ const { store, variants } = this.propslet matchedVariant = null- this.props.variants.forEach(variant => {+ variants.forEach(variant => {if (_.isEqual(this.state.selection, variant.attributes)) {matchedVariant = variant}})- this.setState({ variant: matchedVariant })+ store.setVariant(matchedVariant)}render() {- const { availability, productAttributes, variantAttributes } = this.props- const { errors, selection, quantity, variant } = this.state+ const { store, variantAttributes } = this.props+ const { errors, selection, quantity } = this.state+ const disableAddToCart = store.isEmptyconst addToCartBtnClasses = classNames({'btn primary': true,- 'disabled': !variant+ 'disabled': disableAddToCart})return (<div>- <VariantPrice availability={availability} variant={variant} />- {productAttributes.map((item, i) =>- <div className="form-group" key={i}>- <label className="control-label"><b>{item.attribute}</b></label>- <p>{item.value}</p>- </div>- )}{variantAttributes.map((attribute, i) =><AttributeSelectionWidgetattribute={attribute}@@ -112,7 +107,8 @@ export default class VariantPicker extends Component {<div className="form-group"><buttonclassName={addToCartBtnClasses}- onClick={this.handleAddToCart}>+ onClick={this.handleAddToCart}+ disabled={disableAddToCart}>Add to cart</button></div>diff --git a/saleor/static/js/components/variantPicker/VariantPrice.js b/saleor/static/js/components/variantPicker/VariantPrice.jsindex 511765c532..c14e2ca030 100644--- a/saleor/static/js/components/variantPicker/VariantPrice.js+++ b/saleor/static/js/components/variantPicker/VariantPrice.js@@ -1,17 +1,21 @@+import { observer } from 'mobx-react'import React, { Component, PropTypes } from 'react'++@observerexport default class VariantPrice extends Component {static propTypes = {availability: PropTypes.object.isRequired,- variant: PropTypes.object+ store: PropTypes.object}render() {let priceText, priceUndiscountedText, isDiscount- const { availability, variant } = this.props+ const { availability, store } = this.props+ const variant = store.variantconst currency = availability.priceRange.minPrice.currency- if (variant) {+ if (!store.isEmpty) {// variant priceisDiscount = variant.price !== variant.priceUndiscountedpriceText = `${variant.price} ${currency}`@@ -19,7 +23,7 @@ export default class VariantPrice extends Component {} else {// if there's no variant, fall back to product priceconst { discount, priceRange, priceRangeUndiscounted } = availability- isDiscount = !!discount+ isDiscount = !!Object.keys(discount).lengthpriceText = `${priceRange.minPrice.gross} ${currency}`priceUndiscountedText = `${priceRangeUndiscounted.minPrice.gross} ${currency}`}diff --git a/saleor/static/js/storefront.js b/saleor/static/js/storefront.jsindex b251bd29a7..4f10338611 100644--- a/saleor/static/js/storefront.js+++ b/saleor/static/js/storefront.js@@ -3,7 +3,10 @@ import 'jquery.cookie'import React from 'react'import ReactDOM from 'react-dom'+import variantPickerStore from './stores/variantPicker'+import VariantPicker from './components/variantPicker/VariantPicker'+import VariantPrice from './components/variantPicker/VariantPrice'let csrftoken = $.cookie('csrftoken')@@ -192,25 +195,38 @@ $('ul.nav-tabs li a:not(:first)').on('shown.bs.tab', (e) => {var hash = window.location.hash;$('.nav-tabs a[href="' + hash + '"]').tab('show')+// Variant Picker-const variantPicker = document.getElementById('variant-picker')-if (variantPicker) {- const variantPickerData = JSON.parse(variantPicker.dataset.variantPickerData)+const variantPickerContainer = document.getElementById('variant-picker')+const variantPriceContainer = document.getElementById('variant-price-component')+const variantPickerData = JSON.parse(variantPickerContainer.dataset.variantPickerData)++if (variantPickerContainer) {ReactDOM.render(<VariantPicker- availability={variantPickerData.availability}onAddToCartError={onAddToCartError}onAddToCartSuccess={onAddToCartSuccess}- productAttributes={variantPickerData.productAttributes}- url={variantPicker.dataset.action}+ store={variantPickerStore}+ url={variantPickerContainer.dataset.action}variantAttributes={variantPickerData.variantAttributes}variants={variantPickerData.variants}/>,- variantPicker+ variantPickerContainer)}+if (variantPriceContainer) {+ ReactDOM.render(+ <VariantPrice+ availability={variantPickerData.availability}+ store={variantPickerStore}+ />,+ variantPriceContainer+ )+}++// Cart quantity formvar $cartLine = $('.cart__line')diff --git a/saleor/static/js/stores/variantPicker.js b/saleor/static/js/stores/variantPicker.jsnew file mode 100644index 0000000000..2d76cfff2c--- /dev/null+++ b/saleor/static/js/stores/variantPicker.js@@ -0,0 +1,17 @@+import { autorun, computed, observable } from 'mobx'+++class VariantPickerStore {+ @observable variant = {}++ setVariant(variant) {+ this.variant = variant ? variant : {}+ }++ @computed get isEmpty() {+ return !this.variant.id+ }+}++const store = new VariantPickerStore()+export default storediff --git a/templates/product/details.html b/templates/product/details.htmlindex 3c47af76a5..83f6a3945f 100644--- a/templates/product/details.html+++ b/templates/product/details.html@@ -37,20 +37,24 @@{% if user.is_staff %}<p><a href="{% url "dashboard:product-update" pk=product.pk %}">{% trans "Edit in dashboard" %}</a></p>{% endif %}- {% if availability.available and not show_variant_picker %}- <h2 itemprop="offers" class="product__info__price" itemscope itemtype="http://schema.org/Offer">- <span>{% price_range availability.price_range %}</span>- {% if availability.discount %}- <small class="product__info__price__undiscounted">{% gross availability.price_range_undiscounted.min_price html=True %}</small>- {% endif %}- {% if availability.price_range_local_currency %}- <br>- <small>- ≈- {% gross availability.price_range_local_currency.min_price html=True %}- </small>- {% endif %}- </h2>+ {% if availability.available %}+ {% if show_variant_picker %}+ <div id="variant-price-component"></div>+ {% else %}+ <h2 itemprop="offers" class="product__info__price" itemscope itemtype="http://schema.org/Offer">+ <span>{% price_range availability.price_range %}</span>+ {% if availability.discount %}+ <small class="product__info__price__undiscounted">{% gross availability.price_range_undiscounted.min_price html=True %}</small>+ {% endif %}+ {% if availability.price_range_local_currency %}+ <br>+ <small>+ ≈+ {% gross availability.price_range_local_currency.min_price html=True %}+ </small>+ {% endif %}+ </h2>+ {% endif %}{% endif %}</div><div class="col-md-7 col-xs-12 product__gallery">@@ -90,16 +94,16 @@<div class="col-md-5 col-xs-12 product__info">{% if is_visible and product.is_in_stock %}{% block orderform %}+ {% for attribute, value in product_attributes.items %}+ <div class="form-group">+ <label class="control-label"><b>{{ attribute }}</b></label>+ <p>{{ value }}</p>+ </div>+ {% endfor %}{% if show_variant_picker %}{% csrf_token %}<div id="variant-picker" data-variant-picker-data="{{ variant_picker_data }}" data-action="{% url 'product:add-to-cart' product_id=product.pk slug=product.get_slug %}"></div>{% else %}- {% for attribute, value in product_attributes.items %}- <div class="form-group">- <label class="control-label"><b>{{ attribute }}</b></label>- <p>{{ value }}</p>- </div>- {% endfor %}<form id="product-form" role="form" class="product-form form-vertical" method="post"action="{% url 'product:add-to-cart' product_id=product.pk slug=product.get_slug %}" novalidate>{% csrf_token %}diff --git a/yarn.lock b/yarn.lockindex a22d0c4c63..d650e59d2c 100644--- a/yarn.lock+++ b/yarn.lock@@ -389,7 +389,7 @@ babel-plugin-syntax-class-properties@^6.8.0:version "6.13.0"resolved "https://registry.yarnpkg.com/babel-plugin-syntax-class-properties/-/babel-plugin-syntax-class-properties-6.13.0.tgz#d7eb23b79a317f8543962c505b827c7d6cac27de"-babel-plugin-syntax-decorators@^6.13.0:+babel-plugin-syntax-decorators@^6.1.18, babel-plugin-syntax-decorators@^6.13.0:version "6.13.0"resolved "https://registry.yarnpkg.com/babel-plugin-syntax-decorators/-/babel-plugin-syntax-decorators-6.13.0.tgz#312563b4dbde3cc806cee3e416cceeaddd11ac0b"@@ -462,6 +462,14 @@ babel-plugin-transform-class-properties@^6.11.5, babel-plugin-transform-class-prbabel-runtime "^6.9.1"babel-template "^6.15.0"+babel-plugin-transform-decorators-legacy@^1.3.4:+ version "1.3.4"+ resolved "https://registry.yarnpkg.com/babel-plugin-transform-decorators-legacy/-/babel-plugin-transform-decorators-legacy-1.3.4.tgz#741b58f6c5bce9e6027e0882d9c994f04f366925"+ dependencies:+ babel-plugin-syntax-decorators "^6.1.18"+ babel-runtime "^6.2.0"+ babel-template "^6.3.0"+babel-plugin-transform-decorators@^6.13.0:version "6.13.0"resolved "https://registry.yarnpkg.com/babel-plugin-transform-decorators/-/babel-plugin-transform-decorators-6.13.0.tgz#82d65c1470ae83e2d13eebecb0a1c2476d62da9d"@@ -814,14 +822,14 @@ babel-register@^6.18.0:mkdirp "^0.5.1"source-map-support "^0.4.2"-babel-runtime@^6.0.0, babel-runtime@^6.11.6, babel-runtime@^6.18.0, babel-runtime@^6.20.0, babel-runtime@^6.9.0, babel-runtime@^6.9.1:+babel-runtime@^6.0.0, babel-runtime@^6.11.6, babel-runtime@^6.18.0, babel-runtime@^6.2.0, babel-runtime@^6.20.0, babel-runtime@^6.9.0, babel-runtime@^6.9.1:version "6.20.0"resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.20.0.tgz#87300bdcf4cd770f09bf0048c64204e17806d16f"dependencies:core-js "^2.4.0"regenerator-runtime "^0.10.0"-babel-template@^6.14.0, babel-template@^6.15.0, babel-template@^6.16.0, babel-template@^6.8.0:+babel-template@^6.14.0, babel-template@^6.15.0, babel-template@^6.16.0, babel-template@^6.3.0, babel-template@^6.8.0:version "6.16.0"resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.16.0.tgz#e149dd1a9f03a35f817ddbc4d0481988e7ebc8ca"dependencies:@@ -1882,7 +1890,7 @@ [email protected]:version "2.16.3"resolved "https://registry.yarnpkg.com/hoek/-/hoek-2.16.3.tgz#20bb7403d3cea398e91dc4710a8ff1b8274a25ed"-hoist-non-react-statics@^1.0.3:+hoist-non-react-statics@^1.0.3, hoist-non-react-statics@^1.2.0:version "1.2.0"resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-1.2.0.tgz#aa448cf0986d55cc40773b17174b7dd066cb7cfb"@@ -2464,6 +2472,16 @@ [email protected], "mkdirp@>=0.5 0", mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@~0.5.0, mkddependencies:minimist "0.0.8"+mobx-react@^4.1.0:+ version "4.1.0"+ resolved "https://registry.yarnpkg.com/mobx-react/-/mobx-react-4.1.0.tgz#0b4927a8c4457dbb296c512693acdf9073d9afc7"+ dependencies:+ hoist-non-react-statics "^1.2.0"++mobx@^3.0.0:+ version "3.0.0"+ resolved "https://registry.yarnpkg.com/mobx/-/mobx-3.0.0.tgz#6d9fb326d51bac9994dd8fe6762ace6ba2bef2ac"+modernizr@^3.2.0:version "3.3.1"resolved "https://registry.yarnpkg.com/modernizr/-/modernizr-3.3.1.tgz#2170b3438a7478c16654324f004802aae6a863e9"