diff --git a/js/variant-selector-script.js b/js/variant-selector-script.js index c5e123f..387bebc 100644 --- a/js/variant-selector-script.js +++ b/js/variant-selector-script.js @@ -13,6 +13,8 @@ const VariantSelector = ( quantity: 1, color: undefined, size: undefined, + attributes_definition: [], + attributes: {}, }, triggers: { buyNow: "", @@ -41,108 +43,110 @@ const VariantSelector = ( setLoading: () => { const loading = document.createElement("div"); loading.innerHTML = ` - -
`; + + + + `; document.body.appendChild(loading); @@ -240,19 +244,41 @@ const VariantSelector = ( if (!quantity) throw new Error("VariantSelector: No quantity"); - const color = - typeof config.product.color === "function" - ? config.product.color() - : config.product.color; + const { attributes_definition, attributes } = config.product; + + if (attributes_definition.length && Object.keys(attributes).length) { + attributesToValue = attributes_definition.reduce( + (result, attributeName) => { + const variant = attributes[attributeName]; + const value = typeof variant === "function" ? variant() : variant; + + if (!value) { + throw new Error(`VariantSelector: No ${attributeName}`); + } + + result[attributeName] = value; + return result; + }, + {} + ); + } else { + const color = + typeof config.product.color === "function" + ? config.product.color() + : config.product.color; - if (!color) throw new Error("VariantSelector: No color"); + if (!color) throw new Error("VariantSelector: No color"); - const size = - typeof config.product.size === "function" - ? config.product.size() - : config.product.size; + const size = + typeof config.product.size === "function" + ? config.product.size() + : config.product.size; - if (!size) throw new Error("VariantSelector: No size"); + if (!size) throw new Error("VariantSelector: No size"); + + attributesToValue[ATTRIBUTES.Color] = color; + attributesToValue[ATTRIBUTES.Size] = size; + } Utils.setLoading(); @@ -260,12 +286,9 @@ const VariantSelector = ( state.product.variations_definition.product_variations.find((variant) => { const isTheRightVariant = variant.variation_attributes.every( (attribute) => { - if (attribute.name === ATTRIBUTES.Color) { - return attribute.value === color; - } - if (attribute.name === ATTRIBUTES.Size) { - return attribute.value === size; - } + const value = attributesToValue[attribute.name]; + + if (value) return attribute.value === value; return false; }