This repository was archived by the owner on Oct 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy paththeme-product-form.js
More file actions
254 lines (216 loc) · 7.37 KB
/
Copy paththeme-product-form.js
File metadata and controls
254 lines (216 loc) · 7.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import Listeners from './listeners';
import { getVariantFromSerializedArray } from '@shopify/theme-product';
var selectors = {
idInput: '[name="id"]',
optionInput: '[name^="options"]',
quantityInput: '[name="quantity"]',
propertyInput: '[name^="properties"]'
};
// Public Methods
// -----------------------------------------------------------------------------
/**
* Returns a URL with a variant ID query parameter. Useful for updating window.history
* with a new URL based on the currently select product variant.
* @param {string} url - The URL you wish to append the variant ID to
* @param {number} id - The variant ID you wish to append to the URL
* @returns {string} - The new url which includes the variant ID query parameter
*/
export function getUrlWithVariant(url, id) {
if (/variant=/.test(url)) {
return url.replace(/(variant=)[^&]+/, '$1' + id);
} else if (/\?/.test(url)) {
return url.concat('&variant=').concat(id);
}
return url.concat('?variant=').concat(id);
}
/**
* Constructor class that creates a new instance of a product form controller.
*
* @param {Element} element - DOM element which is equal to the <form> node wrapping product form inputs
* @param {Object} product - A product object
* @param {Object} options - Optional options object
* @param {Function} options.onOptionChange - Callback for whenever an option input changes
* @param {Function} options.onQuantityChange - Callback for whenever an quantity input changes
* @param {Function} options.onPropertyChange - Callback for whenever a property input changes
* @param {Function} options.onFormSubmit - Callback for whenever the product form is submitted
*/
export function ProductForm(element, product, options) {
this.element = element;
this.product = _validateProductObject(product);
options = options || {};
if(options.selectors) {
selectors = {
idInput: options.selectors.idInput || selectors.idInput,
optionInput: options.selectors.optionInput || selectors.optionInput,
quantityInput: options.selectors.quantityInput || selectors.quantityInput,
propertyInput: options.selectors.propertyInput || selectors.propertyInput
};
}
this._idInput = this.element.querySelector(selectors.idInput);
if(!this._idInput) {
throw new Error("element must contain id input");
}
this._listeners = new Listeners();
this.optionInputs = this._initInputs(
selectors.optionInput,
this._onOptionChange.bind(this, options)
);
if(options.onFormSubmit) {
this._listeners.add(
this.element,
'submit',
this._onSubmit.bind(this, options)
);
}
if (options.onQuantityChange) {
this.quantityInputs = this._initInputs(
selectors.quantityInput,
options.onQuantityChange
);
}
if (options.onPropertyChange) {
this.propertyInputs = this._initInputs(
selectors.propertyInput,
options.onPropertyChange
);
}
}
/**
* Cleans up all event handlers that were assigned when the Product Form was constructed.
* Useful for use when a section needs to be reloaded in the theme editor.
*/
ProductForm.prototype.destroy = function() {
this._listeners.removeAll();
};
/**
* Getter method which returns the array of currently selected option values
*
* @returns {Array} An array of option values
*/
ProductForm.prototype.options = function() {
return _serializeOptionValues(this.optionInputs, function(item) {
var regex = /(?:^(options\[))(.*?)(?:\])/;
item.name = regex.exec(item.name)[2]; // Use just the value between 'options[' and ']'
return item;
});
};
/**
* Getter method which returns the currently selected variant, or `null` if variant
* doesn't exist.
*
* @returns {Object|null} Variant object
*/
ProductForm.prototype.variant = function() {
return getVariantFromSerializedArray(this.product, this.options());
};
/**
* Getter method which returns a collection of objects containing name and values
* of property inputs
*
* @returns {Array} Collection of objects with name and value keys
*/
ProductForm.prototype.properties = function() {
var properties = _serializePropertyValues(this.propertyInputs, function(
propertyName
) {
var regex = /(?:^(properties\[))(.*?)(?:\])/;
var name = regex.exec(propertyName)[2]; // Use just the value between 'properties[' and ']'
return name;
});
return Object.entries(properties).length === 0 ? null : properties;
};
/**
* Getter method which returns the current quantity or 1 if no quantity input is
* included in the form
*
* @returns {Array} Collection of objects with name and value keys
*/
ProductForm.prototype.quantity = function() {
return this.quantityInputs[0]
? Number.parseInt(this.quantityInputs[0].value, 10)
: 1;
};
// Private Methods
// -----------------------------------------------------------------------------
ProductForm.prototype._setIdInputValue = function (value) {
this._idInput.value = value.toString();
};
ProductForm.prototype._onOptionChange = function (options, event) {
event.dataset = this._getProductFormEventData();
if (event.dataset.variant) {
this._setIdInputValue(event.dataset.variant.id);
}
if (options.onOptionChange) {
options.onOptionChange(event);
}
};
ProductForm.prototype._onSubmit = function(options, event) {
event.dataset = this._getProductFormEventData();
if (event.dataset.variant) {
this._setIdInputValue(event.dataset.variant.id);
}
if (options.onFormSubmit) {
options.onFormSubmit(event);
}
};
ProductForm.prototype._onFormEvent = function(cb) {
if (typeof cb === 'undefined') {
return Function.prototype;
}
return function(event) {
event.dataset = this._getProductFormEventData();
cb(event);
}.bind(this);
};
ProductForm.prototype._initInputs = function(selector, cb) {
var elements = Array.prototype.slice.call(
this.element.querySelectorAll(selector)
);
return elements.map(
function(element) {
this._listeners.add(element, 'change', this._onFormEvent(cb));
return element;
}.bind(this)
);
};
ProductForm.prototype._getProductFormEventData = function() {
return {
options: this.options(),
variant: this.variant(),
properties: this.properties(),
quantity: this.quantity()
};
};
function _serializeOptionValues(inputs, transform) {
return inputs.reduce(function(options, input) {
if (
input.checked || // If input is a checked (means type radio or checkbox)
(input.type !== 'radio' && input.type !== 'checkbox') // Or if its any other type of input
) {
options.push(transform({ name: input.name, value: input.value }));
}
return options;
}, []);
}
function _serializePropertyValues(inputs, transform) {
return inputs.reduce(function(properties, input) {
if (
input.checked || // If input is a checked (means type radio or checkbox)
(input.type !== 'radio' && input.type !== 'checkbox') // Or if its any other type of input
) {
properties[transform(input.name)] = input.value;
}
return properties;
}, {});
}
function _validateProductObject(product) {
if (typeof product !== 'object') {
throw new TypeError(product + ' is not an object.');
}
if (typeof product.variants[0].options === 'undefined') {
throw new TypeError(
'Product object is invalid. Make sure you use the product object that is output from {{ product | json }} or from the http://[your-product-url].js route'
);
}
return product;
}