@pernod-ricard-global-cms/jsutils 3.1.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/jsutils.mjs +61 -0
  2. package/package.json +1 -1
package/jsutils.mjs CHANGED
@@ -611,6 +611,67 @@ export function appendPreconnect(domain) {
611
611
  }
612
612
  }
613
613
 
614
+ /**
615
+ *
616
+ * @param {string} src The URL src to load
617
+ */
618
+ async function loadScript(src) {
619
+ const script = document.createElement('script');
620
+ script.type = 'text/javascript';
621
+ script.src = src;
622
+ script.async = true;
623
+ document.head.appendChild(script);
624
+ await new Promise((resolve, reject) => {
625
+ script.onload = resolve;
626
+ script.onerror = () => reject(new Error(`Script load error for ${src}`));
627
+ });
628
+ }
629
+
630
+ /**
631
+ *
632
+ * @param {object} event The click event object
633
+ */
634
+ async function handleCTBClick(event) {
635
+ if (!window.isCTBLoaded) {
636
+ const domain = window.location.hostname;
637
+ // Assuming PR-CLICKTOBUY plugin is enabled to make the script load
638
+ await loadScript(`/wp-content/plugins/pr-clicktobuy/public/js/pr-clicktobuy-public.js`);
639
+ window.isCTBLoaded = true;
640
+
641
+ // This is important!! Never remove this code
642
+ const clonedEvent = new event.constructor(event.type, event);
643
+ const repeatEventInterval = setInterval(() => {
644
+ event.target.dispatchEvent(clonedEvent);
645
+ if (document.querySelector('.ctbuy-modal') !== null) {
646
+ clearInterval(repeatEventInterval);
647
+ }
648
+ }, 100)
649
+ }
650
+ }
651
+
652
+ /**
653
+ *
654
+ * @param {HTMLElement} element The element which needs to set the Attributes
655
+ */
656
+ function setAttributesToMenuItem(element) {
657
+ const body = document.querySelector('body');
658
+ const localLang = body.dataset.sitelanguage;
659
+ const locale = localLang.replace(/_/g,'-');
660
+ element.setAttribute('data-ctbuy-lang', locale);
661
+ }
662
+
663
+ /**
664
+ *
665
+ * @param {HTMLElement} block The element CTA which triggers
666
+ */
667
+ export function ctbCTAClickHandler(block = document) {
668
+ const elements = block.querySelectorAll('[data-ctbuy]');
669
+ elements.forEach(element => {
670
+ setAttributesToMenuItem(element);
671
+ element.addEventListener('click', handleCTBClick);
672
+ });
673
+ }
674
+
614
675
  const api = {
615
676
  copyToClipboard,
616
677
  checkDevice,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pernod-ricard-global-cms/jsutils",
3
- "version": "3.1.0",
3
+ "version": "3.2.1",
4
4
  "description": "Handy collection of Javascript utility functions",
5
5
  "type": "commonjs",
6
6
  "main": "jsutils.mjs",