forked from bigcommerce/cornerstone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproduct-details.js
767 lines (654 loc) · 26.4 KB
/
product-details.js
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
import utils from '@bigcommerce/stencil-utils';
import 'foundation-sites/js/foundation/foundation';
import 'foundation-sites/js/foundation/foundation.reveal';
import ImageGallery from '../product/image-gallery';
import modalFactory, { showAlertModal } from '../global/modal';
import _ from 'lodash';
import Wishlist from '../wishlist';
export default class ProductDetails {
constructor($scope, context, productAttributesData = {}) {
this.$overlay = $('[data-cart-item-add] .loadingOverlay');
this.$scope = $scope;
this.context = context;
this.imageGallery = new ImageGallery($('[data-image-gallery]', this.$scope));
this.imageGallery.init();
this.listenQuantityChange();
this.initRadioAttributes();
Wishlist.load(this.context);
this.getTabRequests();
const $form = $('form[data-cart-item-add]', $scope);
const $productOptionsElement = $('[data-product-option-change]', $form);
const hasOptions = $productOptionsElement.html().trim().length;
const hasDefaultOptions = $productOptionsElement.find('[data-default]').length;
$productOptionsElement.on('change', event => {
this.productOptionsChanged(event);
this.setProductVariant();
});
$form.on('submit', event => {
this.addProductToCart(event, $form[0]);
});
// Update product attributes. Also update the initial view in case items are oos
// or have default variant properties that change the view
if ((_.isEmpty(productAttributesData) || hasDefaultOptions) && hasOptions) {
const $productId = $('[name="product_id"]', $form).val();
utils.api.productAttributes.optionChange($productId, $form.serialize(), 'products/bulk-discount-rates', (err, response) => {
const attributesData = response.data || {};
const attributesContent = response.content || {};
this.updateProductAttributes(attributesData);
if (hasDefaultOptions) {
this.updateView(attributesData, attributesContent);
} else {
this.updateDefaultAttributesForOOS(attributesData);
}
});
} else {
this.updateProductAttributes(productAttributesData);
}
$productOptionsElement.show();
this.previewModal = modalFactory('#previewModal')[0];
}
/**
* https://stackoverflow.com/questions/49672992/ajax-request-fails-when-sending-formdata-including-empty-file-input-in-safari
* Safari browser with jquery 3.3.1 has an issue uploading empty file parameters. This function removes any empty files from the form params
* @param formData: FormData object
* @returns FormData object
*/
filterEmptyFilesFromForm(formData) {
try {
for (const [key, val] of formData) {
if (val instanceof File && !val.name && !val.size) {
formData.delete(key);
}
}
} catch (e) {
console.error(e); // eslint-disable-line no-console
}
return formData;
}
setProductVariant() {
const unsatisfiedRequiredFields = [];
const options = [];
$.each($('[data-product-attribute]'), (index, value) => {
const optionLabel = value.children[0].innerText;
const optionTitle = optionLabel.split(':')[0].trim();
const required = optionLabel.toLowerCase().includes('required');
const type = value.getAttribute('data-product-attribute');
if ((type === 'input-file' || type === 'input-text' || type === 'input-number') && value.querySelector('input').value === '' && required) {
unsatisfiedRequiredFields.push(value);
}
if (type === 'textarea' && value.querySelector('textarea').value === '' && required) {
unsatisfiedRequiredFields.push(value);
}
if (type === 'date') {
const isSatisfied = Array.from(value.querySelectorAll('select')).every((select) => select.selectedIndex !== 0);
if (isSatisfied) {
const dateString = Array.from(value.querySelectorAll('select')).map((x) => x.value).join('-');
options.push(`${optionTitle}:${dateString}`);
return;
}
if (required) {
unsatisfiedRequiredFields.push(value);
}
}
if (type === 'set-select') {
const select = value.querySelector('select');
const selectedIndex = select.selectedIndex;
if (selectedIndex !== 0) {
options.push(`${optionTitle}:${select.options[selectedIndex].innerText}`);
return;
}
if (required) {
unsatisfiedRequiredFields.push(value);
}
}
if (type === 'set-rectangle' || type === 'set-radio' || type === 'swatch' || type === 'input-checkbox' || type === 'product-list') {
const checked = value.querySelector(':checked');
if (checked) {
if (type === 'set-rectangle' || type === 'set-radio' || type === 'product-list') {
const label = checked.labels[0].innerText;
if (label) {
options.push(`${optionTitle}:${label}`);
}
}
if (type === 'swatch') {
const label = checked.labels[0].children[0];
if (label) {
options.push(`${optionTitle}:${label.title}`);
}
}
if (type === 'input-checkbox') {
options.push(`${optionTitle}:Yes`);
}
return;
}
if (type === 'input-checkbox') {
options.push(`${optionTitle}:No`);
}
if (required) {
unsatisfiedRequiredFields.push(value);
}
}
});
let productVariant = unsatisfiedRequiredFields.length === 0 ? options.sort().join(', ') : 'unsatisfied';
const view = $('.productView');
if (productVariant) {
productVariant = productVariant === 'unsatisfied' ? '' : productVariant;
if (view.attr('data-event-type')) {
view.attr('data-product-variant', productVariant);
} else {
const productName = view.find('.productView-title')[0].innerText.replace(/"/g, '\\$&');
const card = $(`[data-name="${productName}"]`);
card.attr('data-product-variant', productVariant);
}
}
}
/**
* Since $productView can be dynamically inserted using render_with,
* We have to retrieve the respective elements
*
* @param $scope
*/
getViewModel($scope) {
return {
$priceWithTax: $('[data-product-price-with-tax]', $scope),
$priceWithoutTax: $('[data-product-price-without-tax]', $scope),
rrpWithTax: {
$div: $('.rrp-price--withTax', $scope),
$span: $('[data-product-rrp-with-tax]', $scope),
},
rrpWithoutTax: {
$div: $('.rrp-price--withoutTax', $scope),
$span: $('[data-product-rrp-price-without-tax]', $scope),
},
nonSaleWithTax: {
$div: $('.non-sale-price--withTax', $scope),
$span: $('[data-product-non-sale-price-with-tax]', $scope),
},
nonSaleWithoutTax: {
$div: $('.non-sale-price--withoutTax', $scope),
$span: $('[data-product-non-sale-price-without-tax]', $scope),
},
priceSaved: {
$div: $('.price-section--saving', $scope),
$span: $('[data-product-price-saved]', $scope),
},
priceNowLabel: {
$span: $('.price-now-label', $scope),
},
priceLabel: {
$span: $('.price-label', $scope),
},
$weight: $('.productView-info [data-product-weight]', $scope),
$increments: $('.form-field--increments :input', $scope),
$addToCart: $('#form-action-addToCart', $scope),
$wishlistVariation: $('[data-wishlist-add] [name="variation_id"]', $scope),
stock: {
$container: $('.form-field--stock', $scope),
$input: $('[data-product-stock]', $scope),
},
sku: {
$label: $('dt.sku-label', $scope),
$value: $('[data-product-sku]', $scope),
},
upc: {
$label: $('dt.upc-label', $scope),
$value: $('[data-product-upc]', $scope),
},
quantity: {
$text: $('.incrementTotal', $scope),
$input: $('[name=qty\\[\\]]', $scope),
},
$bulkPricing: $('.productView-info-bulkPricing', $scope),
};
}
/**
* Checks if the current window is being run inside an iframe
* @returns {boolean}
*/
isRunningInIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
/**
*
* Handle product options changes
*
*/
productOptionsChanged(event) {
const $changedOption = $(event.target);
const $form = $changedOption.parents('form');
const productId = $('[name="product_id"]', $form).val();
// Do not trigger an ajax request if it's a file or if the browser doesn't support FormData
if ($changedOption.attr('type') === 'file' || window.FormData === undefined) {
return;
}
utils.api.productAttributes.optionChange(productId, $form.serialize(), 'products/bulk-discount-rates', (err, response) => {
const productAttributesData = response.data || {};
const productAttributesContent = response.content || {};
this.updateProductAttributes(productAttributesData);
this.updateView(productAttributesData, productAttributesContent);
});
}
showProductImage(image) {
if (_.isPlainObject(image)) {
const zoomImageUrl = utils.tools.imageSrcset.getSrcset(
image.data,
{ '1x': this.context.themeSettings.zoom_size },
/*
Should match zoom size used for data-zoom-image in
components/products/product-view.html
Note that this will only be used as a fallback image for browsers that do not support srcset
Also note that getSrcset returns a simple src string when exactly one size is provided
*/
);
const mainImageUrl = utils.tools.imageSrcset.getSrcset(
image.data,
{ '1x': this.context.themeSettings.product_size },
/*
Should match fallback image size used for the main product image in
components/products/product-view.html
Note that this will only be used as a fallback image for browsers that do not support srcset
Also note that getSrcset returns a simple src string when exactly one size is provided
*/
);
const mainImageSrcset = utils.tools.imageSrcset.getSrcset(image.data);
this.imageGallery.setAlternateImage({
mainImageUrl,
zoomImageUrl,
mainImageSrcset,
});
} else {
this.imageGallery.restoreImage();
}
}
/**
*
* Handle action when the shopper clicks on + / - for quantity
*
*/
listenQuantityChange() {
this.$scope.on('click', '[data-quantity-change] button', event => {
event.preventDefault();
const $target = $(event.currentTarget);
const viewModel = this.getViewModel(this.$scope);
const $input = viewModel.quantity.$input;
const quantityMin = parseInt($input.data('quantityMin'), 10);
const quantityMax = parseInt($input.data('quantityMax'), 10);
let qty = parseInt($input.val(), 10);
// If action is incrementing
if ($target.data('action') === 'inc') {
// If quantity max option is set
if (quantityMax > 0) {
// Check quantity does not exceed max
if ((qty + 1) <= quantityMax) {
qty++;
}
} else {
qty++;
}
} else if (qty > 1) {
// If quantity min option is set
if (quantityMin > 0) {
// Check quantity does not fall below min
if ((qty - 1) >= quantityMin) {
qty--;
}
} else {
qty--;
}
}
// update hidden input
viewModel.quantity.$input.val(qty);
// update text
viewModel.quantity.$text.text(qty);
});
// Prevent triggering quantity change when pressing enter
this.$scope.on('keypress', '.form-input--incrementTotal', event => {
// If the browser supports event.which, then use event.which, otherwise use event.keyCode
const x = event.which || event.keyCode;
if (x === 13) {
// Prevent default
event.preventDefault();
}
});
}
/**
*
* Add a product to cart
*
*/
addProductToCart(event, form) {
const $addToCartBtn = $('#form-action-addToCart', $(event.target));
const originalBtnVal = $addToCartBtn.val();
const waitMessage = $addToCartBtn.data('waitMessage');
// Do not do AJAX if browser doesn't support FormData
if (window.FormData === undefined) {
return;
}
// Prevent default
event.preventDefault();
$addToCartBtn
.val(waitMessage)
.prop('disabled', true);
this.$overlay.show();
// Add item to cart
utils.api.cart.itemAdd(this.filterEmptyFilesFromForm(new FormData(form)), (err, response) => {
const errorMessage = err || response.data.error;
$addToCartBtn
.val(originalBtnVal)
.prop('disabled', false);
this.$overlay.hide();
// Guard statement
if (errorMessage) {
// Strip the HTML from the error message
const tmp = document.createElement('DIV');
tmp.innerHTML = errorMessage;
return showAlertModal(tmp.textContent || tmp.innerText);
}
// Open preview modal and update content
if (this.previewModal) {
this.previewModal.open();
this.updateCartContent(this.previewModal, response.data.cart_item.id);
} else {
this.$overlay.show();
// if no modal, redirect to the cart page
this.redirectTo(response.data.cart_item.cart_url || this.context.urls.cart);
}
});
}
/**
* Get cart contents
*
* @param {String} cartItemId
* @param {Function} onComplete
*/
getCartContent(cartItemId, onComplete) {
const options = {
template: 'cart/preview',
params: {
suggest: cartItemId,
},
config: {
cart: {
suggestions: {
limit: 4,
},
},
},
};
utils.api.cart.getContent(options, onComplete);
}
/**
* Redirect to url
*
* @param {String} url
*/
redirectTo(url) {
if (this.isRunningInIframe() && !window.iframeSdk) {
window.top.location = url;
} else {
window.location = url;
}
}
/**
* Update cart content
*
* @param {Modal} modal
* @param {String} cartItemId
* @param {Function} onComplete
*/
updateCartContent(modal, cartItemId, onComplete) {
this.getCartContent(cartItemId, (err, response) => {
if (err) {
return;
}
modal.updateContent(response);
// Update cart counter
const $body = $('body');
const $cartQuantity = $('[data-cart-quantity]', modal.$content);
const $cartCounter = $('.navUser-action .cart-count');
const quantity = $cartQuantity.data('cartQuantity') || 0;
$cartCounter.addClass('cart-count--positive');
$body.trigger('cart-quantity-update', quantity);
if (onComplete) {
onComplete(response);
}
});
}
/**
* Show an message box if a message is passed
* Hide the box if the message is empty
* @param {String} message
*/
showMessageBox(message) {
const $messageBox = $('.productAttributes-message');
if (message) {
$('.alertBox-message', $messageBox).text(message);
$messageBox.show();
} else {
$messageBox.hide();
}
}
/**
* Hide the pricing elements that will show up only when the price exists in API
* @param viewModel
*/
clearPricingNotFound(viewModel) {
viewModel.rrpWithTax.$div.hide();
viewModel.rrpWithoutTax.$div.hide();
viewModel.nonSaleWithTax.$div.hide();
viewModel.nonSaleWithoutTax.$div.hide();
viewModel.priceSaved.$div.hide();
viewModel.priceNowLabel.$span.hide();
viewModel.priceLabel.$span.hide();
}
/**
* Update the view of price, messages, SKU and stock options when a product option changes
* @param {Object} data Product attribute data
*/
updatePriceView(viewModel, price) {
this.clearPricingNotFound(viewModel);
if (price.with_tax) {
viewModel.priceLabel.$span.show();
viewModel.$priceWithTax.html(price.with_tax.formatted);
}
if (price.without_tax) {
viewModel.priceLabel.$span.show();
viewModel.$priceWithoutTax.html(price.without_tax.formatted);
}
if (price.rrp_with_tax) {
viewModel.rrpWithTax.$div.show();
viewModel.rrpWithTax.$span.html(price.rrp_with_tax.formatted);
}
if (price.rrp_without_tax) {
viewModel.rrpWithoutTax.$div.show();
viewModel.rrpWithoutTax.$span.html(price.rrp_without_tax.formatted);
}
if (price.saved) {
viewModel.priceSaved.$div.show();
viewModel.priceSaved.$span.html(price.saved.formatted);
}
if (price.non_sale_price_with_tax) {
viewModel.priceLabel.$span.hide();
viewModel.nonSaleWithTax.$div.show();
viewModel.priceNowLabel.$span.show();
viewModel.nonSaleWithTax.$span.html(price.non_sale_price_with_tax.formatted);
}
if (price.non_sale_price_without_tax) {
viewModel.priceLabel.$span.hide();
viewModel.nonSaleWithoutTax.$div.show();
viewModel.priceNowLabel.$span.show();
viewModel.nonSaleWithoutTax.$span.html(price.non_sale_price_without_tax.formatted);
}
}
/**
* Update the view of price, messages, SKU and stock options when a product option changes
* @param {Object} data Product attribute data
*/
updateView(data, content = null) {
const viewModel = this.getViewModel(this.$scope);
this.showMessageBox(data.stock_message || data.purchasing_message);
if (_.isObject(data.price)) {
this.updatePriceView(viewModel, data.price);
}
if (_.isObject(data.weight)) {
viewModel.$weight.html(data.weight.formatted);
}
// Set variation_id if it exists for adding to wishlist
if (data.variantId) {
viewModel.$wishlistVariation.val(data.variantId);
}
// If SKU is available
if (data.sku) {
viewModel.sku.$value.text(data.sku);
viewModel.sku.$label.show();
} else {
viewModel.sku.$label.hide();
viewModel.sku.$value.text('');
}
// If UPC is available
if (data.upc) {
viewModel.upc.$value.text(data.upc);
viewModel.upc.$label.show();
} else {
viewModel.upc.$label.hide();
viewModel.upc.$value.text('');
}
// if stock view is on (CP settings)
if (viewModel.stock.$container.length && _.isNumber(data.stock)) {
// if the stock container is hidden, show
viewModel.stock.$container.removeClass('u-hiddenVisually');
viewModel.stock.$input.text(data.stock);
} else {
viewModel.stock.$container.addClass('u-hiddenVisually');
viewModel.stock.$input.text(data.stock);
}
this.updateDefaultAttributesForOOS(data);
// If Bulk Pricing rendered HTML is available
if (data.bulk_discount_rates && content) {
viewModel.$bulkPricing.html(content);
} else if (typeof (data.bulk_discount_rates) !== 'undefined') {
viewModel.$bulkPricing.html('');
}
}
updateDefaultAttributesForOOS(data) {
const viewModel = this.getViewModel(this.$scope);
if (!data.purchasable || !data.instock) {
viewModel.$addToCart.prop('disabled', true);
viewModel.$increments.prop('disabled', true);
} else {
viewModel.$addToCart.prop('disabled', false);
viewModel.$increments.prop('disabled', false);
}
}
/**
* Hide or mark as unavailable out of stock attributes if enabled
* @param {Object} data Product attribute data
*/
updateProductAttributes(data) {
const behavior = data.out_of_stock_behavior;
const inStockIds = data.in_stock_attributes;
const outOfStockMessage = ` (${data.out_of_stock_message})`;
this.showProductImage(data.image);
if (behavior !== 'hide_option' && behavior !== 'label_option') {
return;
}
$('[data-product-attribute-value]', this.$scope).each((i, attribute) => {
const $attribute = $(attribute);
const attrId = parseInt($attribute.data('productAttributeValue'), 10);
if (inStockIds.indexOf(attrId) !== -1) {
this.enableAttribute($attribute, behavior, outOfStockMessage);
} else {
this.disableAttribute($attribute, behavior, outOfStockMessage);
}
});
}
disableAttribute($attribute, behavior, outOfStockMessage) {
if (this.getAttributeType($attribute) === 'set-select') {
return this.disableSelectOptionAttribute($attribute, behavior, outOfStockMessage);
}
if (behavior === 'hide_option') {
$attribute.hide();
} else {
$attribute.addClass('unavailable');
}
}
disableSelectOptionAttribute($attribute, behavior, outOfStockMessage) {
const $select = $attribute.parent();
if (behavior === 'hide_option') {
$attribute.toggleOption(false);
// If the attribute is the selected option in a select dropdown, select the first option (MERC-639)
if ($select.val() === $attribute.attr('value')) {
$select[0].selectedIndex = 0;
}
} else {
$attribute.attr('disabled', 'disabled');
$attribute.html($attribute.html().replace(outOfStockMessage, '') + outOfStockMessage);
}
}
enableAttribute($attribute, behavior, outOfStockMessage) {
if (this.getAttributeType($attribute) === 'set-select') {
return this.enableSelectOptionAttribute($attribute, behavior, outOfStockMessage);
}
if (behavior === 'hide_option') {
$attribute.show();
} else {
$attribute.removeClass('unavailable');
}
}
enableSelectOptionAttribute($attribute, behavior, outOfStockMessage) {
if (behavior === 'hide_option') {
$attribute.toggleOption(true);
} else {
$attribute.prop('disabled', false);
$attribute.html($attribute.html().replace(outOfStockMessage, ''));
}
}
getAttributeType($attribute) {
const $parent = $attribute.closest('[data-product-attribute]');
return $parent ? $parent.data('productAttribute') : null;
}
/**
* Allow radio buttons to get deselected
*/
initRadioAttributes() {
$('[data-product-attribute] input[type="radio"]', this.$scope).each((i, radio) => {
const $radio = $(radio);
// Only bind to click once
if ($radio.attr('data-state') !== undefined) {
$radio.on('click', () => {
if ($radio.data('state') === true) {
$radio.prop('checked', false);
$radio.data('state', false);
$radio.trigger('change');
} else {
$radio.data('state', true);
}
this.initRadioAttributes();
});
}
$radio.attr('data-state', $radio.prop('checked'));
});
}
/**
* Check for fragment identifier in URL requesting a specific tab
*/
getTabRequests() {
if (window.location.hash && window.location.hash.indexOf('#tab-') === 0) {
const $activeTab = $('.tabs').has(`[href='${window.location.hash}']`);
const $tabContent = $(`${window.location.hash}`);
if ($activeTab.length > 0) {
$activeTab.find('.tab')
.removeClass('is-active')
.has(`[href='${window.location.hash}']`)
.addClass('is-active');
$tabContent.addClass('is-active')
.siblings()
.removeClass('is-active');
}
}
}
}