Debian Codegraph @

addons/website_sale/static/src/interactions/website_sale.js

raw symbols SCIP
1 import { Interaction } from '@web/public/interaction';
2 import { registry } from '@web/core/registry';
3 import { hasTouch, isBrowserFirefox } from '@web/core/browser/feature_detection';
4 import { redirect, url } from '@web/core/utils/urls';
5 import { uniqueId } from '@web/core/utils/functions';
6 import { markup } from '@odoo/owl';
7 import wSaleUtils from '@website_sale/js/website_sale_utils';
8 import { ProductImageViewer } from '@website_sale/js/components/website_sale_image_viewer';
9 import VariantMixin from '@website_sale/js/variant_mixin';
10
11 export class WebsiteSale extends Interaction {
12 static selector = '.oe_website_sale';
13 dynamicContent = {
14 '.js_main_product input[name="add_qty"]': { 't-on-change': this.onChangeAddQuantity },
15 'a.js_add_cart_json': { 't-on-click.prevent': this.onChangeQuantity },
16 'form.js_attributes input, form.js_attributes select': {
17 't-on-change.prevent': this.onChangeAttribute,
18 },
19 '.o_wsale_products_searchbar_form': { 't-on-submit': this.onSubmitSaleSearch },
20 '#add_to_cart, .o_we_buy_now, #products_grid .o_wsale_product_btn .a-submit': {
21 't-on-click.prevent': this.onClickAdd,
22 },
23 '.js_main_product [data-attribute-exclusions]': { 't-on-change': this.onChangeVariant },
24 '.o_product_page_reviews_link': { 't-on-click': this.onClickReviewsLink },
25 '.o_wsale_filmstrip_wrapper': {
26 't-on-mousedown': this.onMouseDown,
27 't-on-mouseleave': this.onMouseLeave,
28 't-on-mouseup': this.onMouseUp,
29 't-on-mousemove': this.onMouseMove,
30 't-on-click': this.onClickHandler,
31 },
32 'form[name="o_wsale_confirm_order"]': {
33 't-on-submit': this.locked(this.onClickConfirmOrder),
34 },
35 '.o_wsale_attribute_search_bar': { 't-on-input': this.searchAttributeValues },
36 '.o_wsale_view_more_btn': { 't-on-click': this.onToggleViewMoreLabel },
37 '.css_attribute_color input': { 't-on-change': this.onChangeColorAttribute },
38 'label[name="o_wsale_attribute_image_selector"] input': {
39 't-on-change': this.onChangeImageAttribute,
40 },
41 '.o_variant_pills': { 't-on-click': this.onChangePillsAttribute },
42 };
43
44 setup() {
45 this.isWebsite = true;
46 this.filmStripStartX = 0;
47 this.filmStripIsDown = false;
48 this.filmStripScrollLeft = 0;
49 this.filmStripMoved = false;
50 this.imageRatio = this.el.dataset.imageRatio;
51 }
52
53 start() {
54 this._applySearch();
55
56 // This has to be triggered to compute the "out of stock" feature and the hash variant changes
57 this.triggerVariantChange(this.el);
58
59 this._startZoom();
60
61 // Triggered when selecting a variant of a product in a carousel element
62 window.addEventListener('hashchange', (ev) => {
63 this._applySearch();
64 this.triggerVariantChange(this.el);
65 });
66
67 // This allows conditional styling for the filmstrip
68 const filmstripContainer = this.el.querySelector('#o_wsale_categories_filmstrip');
69 const filmstripWrapper = this.el.querySelector('.o_wsale_filmstrip_wrapper');
70 const isFilmstripScrollable = filmstripWrapper
71 ? filmstripWrapper.scrollWidth > filmstripWrapper.clientWidth
72 : false;
73
74 if (isBrowserFirefox() || hasTouch() || !isFilmstripScrollable) {
75 filmstripContainer?.classList.add('o_wsale_filmstrip_fancy_disabled');
76 }
77 }
78
79 destroy() {
80 this._cleanupZoom();
81 }
82
83 onMouseDown(ev) {
84 this.filmStripIsDown = true;
85 this.filmStripStartX = ev.pageX - ev.currentTarget.offsetLeft;
86 this.filmStripScrollLeft = ev.currentTarget.scrollLeft;
87 this.filmStripMoved = false;
88 }
89
90 onMouseLeave(ev) {
91 if (!this.filmStripIsDown) {
92 return;
93 }
94 ev.currentTarget.classList.remove('activeDrag');
95 this.filmStripIsDown = false
96 }
97
98 onMouseUp(ev) {
99 this.filmStripIsDown = false;
100 ev.currentTarget.classList.remove('activeDrag');
101 }
102
103 onMouseMove(ev) {
104 if (!this.filmStripIsDown) return;
105 ev.preventDefault();
106 ev.currentTarget.classList.add('activeDrag');
107 this.filmStripMoved = true;
108 const x = ev.pageX - ev.currentTarget.offsetLeft;
109 const walk = (x - this.filmStripStartX) * 2;
110 ev.currentTarget.scrollLeft = this.filmStripScrollLeft - walk;
111 }
112
113 onClickHandler(ev) {
114 if (this.filmStripMoved) {
115 ev.stopPropagation();
116 ev.preventDefault();
117 }
118 }
119
120 _applySearch() {
121 let params = new URLSearchParams(window.location.search);
122 let attributeValues = params.get('attribute_values')
123 if (!attributeValues) {
124 // TODO remove in 20 (or later): hash support of attribute values
125 params = new URLSearchParams(window.location.hash.substring(1));
126 attributeValues = params.get('attribute_values')
127 }
128 if (attributeValues) {
129 const attributeValueIds = attributeValues.split(',');
130 const inputs = document.querySelectorAll(
131 'input.js_variant_change, select.js_variant_change option'
132 );
133 let combinationChanged = false;
134 inputs.forEach((element) => {
135 if (attributeValueIds.includes(element.dataset.attributeValueId)) {
136 if (element.tagName === 'INPUT' && !element.checked) {
137 element.checked = true;
138 combinationChanged = true;
139 } else if (element.tagName === 'OPTION' && !element.selected) {
140 element.selected = true;
141 combinationChanged = true;
142 }
143 }
144 });
145 if (combinationChanged) {
146 this._changeAttribute(
147 '.css_attribute_color, [name="o_wsale_attribute_image_selector"], .o_variant_pills'
148 );
149 }
150 }
151 }
152
153 /**
154 * Sets the url hash from the selected product options.
155 */
156 _setUrlHash() {
157 const inputs = document.querySelectorAll(
158 'input.js_variant_change:checked, select.js_variant_change option:checked'
159 );
160 let attributeIds = [];
161 inputs.forEach((element) => attributeIds.push(element.dataset.attributeValueId));
162 if (attributeIds.length > 0) {
163 const params = new URLSearchParams(window.location.search);
164 params.set('attribute_values', attributeIds.join(','))
165 // Avoid adding new entries in session history by replacing the current one
166 history.replaceState(null, '', url(window.location.pathname, Object.fromEntries(params)));
167 }
168 }
169
170 /**
171 * Set the checked values active.
172 *
173 * @param {String} selector - The selector matching the attributes to change.
174 */
175 _changeAttribute(selector) {
176 this.el.querySelectorAll(selector).forEach((el) => {
177 const input = el.querySelector('input');
178 const isActive = input?.checked;
179 el.classList.toggle('active', isActive);
180 if (isActive) input.dispatchEvent(new Event('change', { bubbles: true }));
181 });
182 }
183
184 _getProductImageLayout() {
185 return document.querySelector("#product_detail_main").dataset.image_layout;
186 }
187
188 _getProductImageWidth() {
189 return document.querySelector("#product_detail_main").dataset.image_width;
190 }
191
192 _getProductImageContainerSelector() {
193 return {
194 'carousel': "#o-carousel-product",
195 'grid': "#o-grid-product",
196 }[this._getProductImageLayout()];
197 }
198
199 _isEditorEnabled() {
200 return document.body.classList.contains("editor_enable");
201 }
202
203 _startZoom() {
204 const salePage = document.querySelector(".o_wsale_product_page");
205 if (!salePage || this._getProductImageWidth() === "none") {
206 return;
207 }
208 this._cleanupZoom();
209 this.zoomCleanup = [];
210 // Zoom on click
211 if (salePage.dataset.ecomZoomClick) {
212 // In this case we want all the images not just the ones that are "zoomables"
213 const images = this.el.querySelectorAll('.product_detail_img');
214 for (const [idx, image] of images.entries()) {
215 const handler = () => {
216 this.services.dialog.add(ProductImageViewer, {
217 selectedImageIdx: idx,
218 images,
219 imageRatio: this.imageRatio,
220 });
221 };
222 image.addEventListener("click", handler);
223 this.zoomCleanup.push(() => {
224 image.removeEventListener("click", handler);
225 });
226 }
227 }
228 }
229
230 _cleanupZoom() {
231 if (!this.zoomCleanup || !this.zoomCleanup.length) {
232 return;
233 }
234 for (const cleanup of this.zoomCleanup) {
235 cleanup();
236 }
237 this.zoomCleanup = undefined;
238 }
239
240 /**
241 * On website, we display a carousel instead of only one image
242 */
243 _updateProductImage(productContainer, newImages) {
244 let images = productContainer.querySelector(this._getProductImageContainerSelector());
245 // When using the web editor, don't reload this or the images won't
246 // be able to be edited depending on if this is done loading before
247 // or after the editor is ready.
248 if (images && !this._isEditorEnabled() && newImages ) {
249 images.insertAdjacentHTML('beforebegin', markup(newImages));
250 images.remove();
251
252 // Re-query the latest images.
253 images = productContainer.querySelector(this._getProductImageContainerSelector());
254 // Update the sharable image (only work for Pinterest).
255 const shareImageSrc = images.querySelector('img').src;
256 document.querySelector('meta[property="og:image"]')
257 .setAttribute('content', shareImageSrc);
258
259 if (images.id === 'o-carousel-product') {
260 window.Carousel.getOrCreateInstance(images).to(0);
261 }
262 this._startZoom();
263 }
264 }
265
266 /**
267 * @param {MouseEvent} ev
268 */
269 async onClickAdd(ev) {
270 const el = ev.currentTarget;
271 if (this.el.querySelector('.js_add_cart_variants')?.children?.length) {
272 await this.waitFor(this._getCombinationInfo(ev));
273 if (!ev.target.closest('.js_product').classList.contains('.css_not_available')) {
274 return this._addToCart(el);
275 }
276 } else {
277 return this._addToCart(el);
278 }
279 }
280
281 /**
282 * @param {HTMLElement} el
283 */
284 async _addToCart(el) {
285 const form = wSaleUtils.getClosestProductForm(el);
286 this._updateRootProduct(form);
287 const isBuyNow = el.classList.contains('o_we_buy_now');
288 const isConfigured = el.parentElement.id === 'add_to_cart_wrap';
289 const showQuantity = Boolean(el.dataset.showQuantity);
290 return this.services['cart'].add(this.rootProduct, {
291 isBuyNow: isBuyNow,
292 isConfigured: isConfigured,
293 showQuantity: showQuantity,
294 });
295 }
296
297 /**
298 * Event handler to increase or decrease quantity from the product page.
299 *
300 * @param {MouseEvent} ev
301 */
302 onChangeQuantity(ev) {
303 const input = ev.currentTarget.closest('.input-group').querySelector('input');
304 const min = parseFloat(input.dataset.min || 0);
305 const max = parseFloat(input.dataset.max || Infinity);
306 const previousQty = parseFloat(input.value || 0);
307 const quantity = (
308 ev.currentTarget.name === 'remove_one' ? -1 : 1
309 ) + previousQty;
310 const newQty = quantity > min ? (quantity < max ? quantity : max) : min;
311
312 if (newQty !== previousQty) {
313 input.value = newQty;
314 // Trigger `onChangeAddQuantity`.
315 input.dispatchEvent(new Event('change', { bubbles: true }));
316 }
317 }
318
319 /**
320 * Search attribute values based on the input text.
321 *
322 * @param {Event} ev
323 */
324 searchAttributeValues(ev) {
325 const input = ev.target;
326 const searchValue = input.value.toLowerCase();
327
328 document.querySelectorAll(`#${input.dataset.containerId} .form-check`).forEach(item => {
329 const labelText = item.querySelector('.form-check-label').textContent.toLowerCase();
330 item.style.display = labelText.includes(searchValue) ? '' : 'none'
331 });
332 }
333
334 /**
335 * Toggle the button text between "View More" and "View Less"
336 *
337 * @param {MouseEvent} ev
338 */
339 onToggleViewMoreLabel(ev) {
340 const button = ev.target;
341 const isExpanded = button.getAttribute('aria-expanded') === 'true';
342
343 button.innerHTML = isExpanded ? "View Less" : "View More";
344 }
345
346 /**
347 * When the quantity is changed, we need to query the new price of the product.
348 * Based on the pricelist, the price might change when quantity exceeds a certain amount.
349 *
350 * @param {MouseEvent} ev
351 */
352 onChangeAddQuantity(ev) {
353 const parent = wSaleUtils.getClosestProductForm(ev.currentTarget);
354 if (parent) this.triggerVariantChange(parent);
355 }
356
357 /**
358 * @param {Event} ev
359 */
360 onChangeAttribute(ev) {
361 const productGrid = this.el.querySelector('.o_wsale_products_grid_table_wrapper');
362 if (productGrid) {
363 productGrid.classList.add('opacity-50');
364 }
365 const form = wSaleUtils.getClosestProductForm(ev.currentTarget);
366 const filters = form.querySelectorAll('input:checked, select');
367 const attributeValues = new Map();
368 const tags = new Set();
369 for (const filter of filters) {
370 if (filter.value) {
371 if (filter.name === 'attribute_value') {
372 // Group attribute value ids by attribute id.
373 const [attributeId, attributeValueId] = filter.value.split('-');
374 const valueIds = attributeValues.get(attributeId) ?? new Set();
375 valueIds.add(attributeValueId);
376 attributeValues.set(attributeId, valueIds);
377 } else if (filter.name === 'tags') {
378 tags.add(filter.value);
379 }
380 }
381 }
382 const url = new URL(form.action);
383 const searchParams = url.searchParams;
384 // Aggregate all attribute values belonging to the same attribute into a single
385 // `attribute_values` search param.
386 for (const entry of attributeValues.entries()) {
387 searchParams.append('attribute_values', `${entry[0]}-${[...entry[1]].join(',')}`);
388 }
389 // Aggregate all tags into a single `tags` search param.
390 if (tags.size) {
391 searchParams.set('tags', [...tags].join(','));
392 }
393 redirect(`${url.pathname}?${searchParams.toString()}`);
394 }
395
396 /**
397 * @param {Event} ev
398 */
399 onSubmitSaleSearch(ev) {
400 if (!this.el.querySelector('.dropdown_sorty_by')) return;
401 const form = ev.currentTarget;
402 if (!ev.defaultPrevented && !form.matches('.disabled')) {
403 ev.preventDefault();
404 const url = new URL(form.action);
405 const searchParams = url.searchParams;
406 if (form.querySelector('[name=noFuzzy]')?.value === 'true') {
407 searchParams.set('noFuzzy', 'true');
408 }
409 const input = form.querySelector('input.search-query');
410 searchParams.set(input.name, input.value);
411 redirect(`${url.pathname}?${searchParams.toString()}`);
412 }
413 }
414
415 /**
416 * Toggles the disabled class on the parent element and the "add to cart" and "buy now" buttons
417 * depending on whether the current combination is possible.
418 *
419 * @param {Element} parent
420 * @param {boolean} isCombinationPossible
421 */
422 _toggleDisable(parent, isCombinationPossible) {
423 parent.classList.toggle('css_not_available', !isCombinationPossible);
424 parent.querySelector('#add_to_cart')?.classList?.toggle('disabled', !isCombinationPossible);
425 parent.querySelector('.o_we_buy_now')?.classList?.toggle('disabled', !isCombinationPossible);
426 }
427
428 /**
429 * When the variant is changed, this method will recompute:
430 * - Whether the selected combination is possible,
431 * - The extra price, if applicable,
432 * - The total price,
433 * - The display name of the product (e.g. "Customizable desk (White, Steel)"),
434 * - Whether a "custom value" input should be shown,
435 *
436 * "Custom value" changes are ignored since they don't change the combination.
437 *
438 * @param {MouseEvent} ev
439 */
440 onChangeVariant(ev) {
441 // Write the properties of the form elements in the DOM to prevent the current selection
442 // from being lost when activating the web editor.
443 const parent = ev.currentTarget.closest('.js_product');
444 parent.querySelectorAll('input').forEach(
445 el => el.checked ? el.setAttribute('checked', true) : el.removeAttribute('checked')
446 );
447 parent.querySelectorAll('select option').forEach(
448 el => el.selected ? el.setAttribute('selected', true) : el.removeAttribute('selected')
449 );
450
451 this._setUrlHash();
452
453 if (!parent.dataset.uniqueId) {
454 parent.dataset.uniqueId = uniqueId();
455 }
456 this._throttledGetCombinationInfo(this, parent.dataset.uniqueId)(ev);
457 }
458
459 onClickReviewsLink() {
460 Collapse.getOrCreateInstance(
461 document.querySelector('#o_product_page_reviews_content')
462 ).show();
463 }
464
465 /**
466 * Prevent multiple clicks on the confirm button when the form is submitted.
467 */
468 onClickConfirmOrder(ev) {
469 const button = ev.currentTarget.querySelector('button[type="submit"]');
470 button.disabled = true;
471 // TODO(loti): "random" timeout seems brittle.
472 this.waitForTimeout(() => button.disabled = false, 5000);
473 }
474
475 /**
476 * Highlight selected color
477 *
478 * @param {MouseEvent} ev
479 */
480 onChangeColorAttribute(ev) {
481 const eventTarget = ev.target;
482 const parent = eventTarget.closest('.js_product');
483 parent.querySelectorAll('.css_attribute_color').forEach(
484 el => el.classList.toggle('active', el.matches(':has(input:checked)'))
485 );
486 const attrValueEl = eventTarget.closest('.variant_attribute')
487 ?.querySelector('.attribute_value');
488 if (attrValueEl) {
489 attrValueEl.innerText = eventTarget.dataset.valueName;
490 }
491 }
492
493 /**
494 * Highlight selected image
495 *
496 * @param {MouseEvent} ev
497 */
498 onChangeImageAttribute(ev) {
499 const parent = ev.target.closest('.js_product');
500 const images = parent.querySelectorAll('label[name="o_wsale_attribute_image_selector"]');
501 images.forEach(el => el.classList.remove('active'));
502 images.forEach(el => {
503 const input = el.querySelector('input');
504 if (input && input.checked) {
505 el.classList.add('active');
506 }
507 });
508 const attrValueEl = ev.target
509 .closest('[name="variant_attribute"]')?.querySelector('[name="attribute_value"]');
510 if (attrValueEl) {
511 attrValueEl.innerText = ev.target.dataset.valueName;
512 }
513 }
514
515 onChangePillsAttribute(ev) {
516 const radio = ev.target.closest('.o_variant_pills').querySelector('input');
517 radio.click(); // Trigger onChangeVariant.
518 const parent = ev.target.closest('.js_product');
519 parent.querySelectorAll('.o_variant_pills').forEach(el => {
520 if (el.matches(':has(input:checked)')) {
521 el.classList.add(
522 'active', 'border-primary', 'text-primary-emphasis', 'bg-primary-subtle'
523 );
524 } else {
525 el.classList.remove(
526 'active', 'border-primary', 'text-primary-emphasis', 'bg-primary-subtle'
527 );
528 }
529 });
530 }
531
532 // -------------------------------------
533 // Utils
534 // -------------------------------------
535
536 /**
537 * Update the root product during based on the form elements.
538 *
539 * @param {HTMLFormElement} form - The form in which the product is.
540 */
541 _updateRootProduct(form) {
542 const productId = parseInt(
543 form.querySelector('input[type="hidden"][name="product_id"]')?.value
544 );
545 const productEl = form.closest('.js_product') ?? form;
546 const quantity = parseFloat(productEl.querySelector('input[name="add_qty"]')?.value);
547 const uomId = this._getUoMId(form);
548 const isCombo = form.querySelector(
549 'input[type="hidden"][name="product_type"]'
550 )?.value === 'combo';
551 this.rootProduct = {
552 ...(productId ? {productId: productId} : {}),
553 productTemplateId: parseInt(form.querySelector(
554 'input[type="hidden"][name="product_template_id"]',
555 ).value),
556 ...(quantity ? {quantity: quantity} : {}),
557 ...(uomId ? {uomId: uomId} : {}),
558 ptavs: this._getSelectedPTAV(form),
559 productCustomAttributeValues: this._getCustomPTAVValues(form),
560 noVariantAttributeValues: this._getSelectedNoVariantPTAV(form),
561 ...(isCombo ? {isCombo: isCombo} : {}),
562 };
563 }
564
565 /**
566 * Return the selected stored PTAV(s) of in the provided form.
567 *
568 * @param {HTMLFormElement} form - The form in which the product is.
569 *
570 * @returns {Number[]} - The selected stored attribute(s), as a list of
571 * `product.template.attribute.value` ids.
572 */
573 _getSelectedPTAV(form) {
574 const selectedPTAVElements = form.querySelectorAll([
575 '.js_product input.js_variant_change:not(.no_variant):checked',
576 '.js_product select.js_variant_change:not(.no_variant)'
577 ].join(','));
578 let selectedPTAV = [];
579 for(const el of selectedPTAVElements) {
580 selectedPTAV.push(parseInt(el.value));
581 }
582 return selectedPTAV;
583 }
584
585 /**
586 * Return the custom PTAV(s) values in the provided form.
587 *
588 * @param {HTMLFormElement} form - The form in which the product is.
589 *
590 * @returns {{id: number, value: string}[]} An array of objects where each object contains:
591 * - `custom_product_template_attribute_value_id`: The ID of the custom attribute.
592 * - `custom_value`: The value assigned to the custom attribute.
593 */
594 _getCustomPTAVValues(form) {
595 const customPTAVsValuesElements = form.querySelectorAll('.variant_custom_value');
596 let customPTAVsValues = [];
597 for(const el of customPTAVsValuesElements) {
598 customPTAVsValues.push({
599 'custom_product_template_attribute_value_id': parseInt(
600 el.dataset.customProductTemplateAttributeValueId
601 ),
602 'custom_value': el.value,
603 });
604 }
605 return customPTAVsValues;
606 }
607
608 /**
609 * Return the selected non-stored PTAV(s) of the product in the provided form.
610 *
611 * @param {HTMLFormElement} form - The form in which the product is.
612 *
613 * @returns {Number[]} - The selected non-stored attribute(s), as a list of
614 * `product.template.attribute.value` ids.
615 */
616 _getSelectedNoVariantPTAV(form) {
617 const selectedNoVariantPTAVElements = form.querySelectorAll([
618 'input.no_variant.js_variant_change:checked',
619 'select.no_variant.js_variant_change',
620 ].join(','));
621 let selectedNoVariantPTAV = [];
622 for(const el of selectedNoVariantPTAVElements) {
623 selectedNoVariantPTAV.push(parseInt(el.value));
624 }
625 return selectedNoVariantPTAV;
626 }
627 }
628
629 // TODO(loti): temporary hack. VariantMixin will be dropped.
630 Object.assign(WebsiteSale.prototype, VariantMixin);
631
632 registry.category('public.interactions').add('website_sale.website_sale', WebsiteSale);