ez-shp-storefront
Version:
A helper function collection for Shopify storefront.
1 lines • 7.74 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).EzShpStorefront={})}(this,function(s){"use strict";class t{constructor(){this.eventTopics={}}static getInstance(){return this.instance||(this.instance=new t),this.instance}addEventListener(t,e){return(!this.eventTopics[t]||this.eventTopics[t].length<1)&&(this.eventTopics[t]=[]),this.eventTopics[t].push(e),e}emitEventListeners(t,e){!this.eventTopics[t]||this.eventTopics[t].length<1||this.eventTopics[t].forEach(function(t){t(e||{})})}removeListener(t,e){var n;!this.eventTopics[t]||this.eventTopics[t].length<1||(n=this.eventTopics[t].findIndex(t=>t===e),delete this.eventTopics[t][n])}getListener(t){return this.eventTopics[t]}}t.instance=null;class e{constructor(){const s=window.fetch;XMLHttpRequest.prototype.realSend=XMLHttpRequest.prototype.send;const i=["change","update","add"];window.fetch=async(e,t)=>{if(i.find(t=>e.includes(t))){var n=await s(e,t);return this.getEventBus().emitEventListeners("Ez_CART_CHANGE",{url:e}),n}return s(e,t)};XMLHttpRequest.prototype.send=function(t){this.realSend(t);const e=this._url;i.find(t=>String(e).includes(t))&&this.getEventBus().emitEventListeners("Ez_CART_CHANGE",{url:e})}}static getInstance(){return this.instance||(this.instance=new e),this.instance}setEventBus(t){return this.eventBus=t,this}getEventBus(){return this.eventBus||(this.eventBus=t.getInstance()),this.eventBus}}e.instance=null;class n{constructor(){}static getInstance(){return this.instance||(this.instance=new n),this.instance}setEventBus(t){return this.eventBus=t,this}getEventBus(){return this.eventBus||(this.eventBus=t.getInstance()),this.eventBus}getCheckoutPageError(t){return t.url.includes("account/login")?"You must be signed in to use the discount code":t.url.includes("stock_problems")?"Some items don’t have insufficient stock. Please adjust the quantity.":""}async getCheckoutPage(){this.getCheckoutPagePromise||(this.getCheckoutPagePromise=fetch(window.location.origin+"/checkout",{method:"get"}));const e=(await this.getCheckoutPagePromise).clone();this.getCheckoutPagePromise=null;var t=this.getCheckoutPageError(e);if(t){t={errorMessage:t};return this.getEventBus().emitEventListeners("Ez_GET_CHECKOUT_PAGE_ERROR",t),[null,t]}try{const c=e.url.split("/checkouts/");if(c.length<2){var n={errorMessage:'Cannot get "shopify_checkout_token".'};return this.getEventBus().emitEventListeners("Ez_GET_CHECKOUT_PAGE_ERROR",n),[null,n]}var s=c[1].split("?")[0];this.shopify_checkout_token=s;var i=await e.text();let t=new DOMParser;const u=t.parseFromString(i,"text/html"),h=u.querySelector('meta[name="shopify-checkout-authorization-token"]');if(!h){var o={errorMessage:'Cannot get "shopify_checkout_authorization_token".'};return this.getEventBus().emitEventListeners("Ez_GET_CHECKOUT_PAGE_ERROR",o),[null,o]}var r=h.getAttribute("content"),a={shopify_checkout_token:s,shopify_checkout_authorization_token:this.shopify_checkout_authorization_token=r};return this.getEventBus().emitEventListeners("Ez_GET_CHECKOUT_PAGE_SUCCESS",a),[a,null]}catch(t){return console.log(t),[null,{errorMessage:t}]}}async putDiscountCode(t){const e=await fetch("/wallets/checkouts/"+this.shopify_checkout_token,{method:"PUT",headers:{Accept:"*/*","Cache-Control":"max-age=0","x-shopify-checkout-authorization-token":this.shopify_checkout_authorization_token,"Content-Type":"application/json"},body:JSON.stringify({checkout:{discount_code:t}})});if(200!==e.status){let t="";return t=429===e.status?"Too many attempts: Please try again in a few minutes":(n=(await e.json())["errors"],JSON.stringify(n)),this.getEventBus().emitEventListeners("Ez_PUT_DISCOUNT_CODE_ERROR",t),[null,t]}var n=await e.json();return this.getEventBus().emitEventListeners("Ez_PUT_DISCOUNT_CODE_SUCCESS",n),[n,null]}}n.instance=null;class i{constructor(){}static getInstance(){return this.instance||(this.instance=new i),this.instance}isHidden(t){return null===t.offsetParent}}i.instance=null;const o='form[action="cart"], form[action="checkout"], form#CartPageForm, form#cart, form.cart';class r{constructor(){this.data={item_count:0}}static getInstance(){return this.instance||(this.instance=new r),this.instance}isOnCartPage(){return window.location.pathname.includes("/cart")}getCartItemCount(){return this.data.item_count}async get(){return this.data=await fetch(window.location.origin+"/cart.js").then(t=>t.json()),this.data}async clear(t){try{await fetch(window.location.origin+"/cart/clear")}catch(t){}if(t)return t===location.href?location.reload():void(location.href=t)}getCartFormElement(){return document.querySelector(o)}getCheckoutButtonElement(){let n=[];const t=o.split(",");t.forEach(e=>{const t='main input[type="submit"], main button.checkout, main button[type="submit"], input[type="submit"]#checkout, button[type="submit"]#checkout, button[type="submit"][name="checkout"]'.split(",");t.forEach(t=>{n.concat(Array.from(document.querySelectorAll(e+" "+t)))})});const e=i.getInstance();return n.find(t=>!e.isHidden(t))}}r.instance=null;class a{constructor(){}setMoneyFormat(t){return this.moneyFormat=t,this}getMoneyFormat(){return this.moneyFormat}static getInstance(){return this.instance||(this.instance=new a),this.instance}formatWithDelimiters(t,e,n,s){if(n=n||",",s=s||".",isNaN(t)||null===t)return"0";t=(t=(t/100).toFixed(e)).split(".");return t[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+n)+(t[1]?s+t[1]:"")}get(t,e){"string"==typeof t&&(t=t.replace(".",""));var n="",s=/\{\{\s*(\w+)\s*\}\}/,i=e||this.getMoneyFormat(),e=(i=i.length<2?this.getMoneyFormat():i).match(s);switch(e&&e.length?e[1]:"amount"){case"amount":n=this.formatWithDelimiters(t,2);break;case"amount_no_decimals":n=this.formatWithDelimiters(t,0);break;case"amount_with_comma_separator":n=this.formatWithDelimiters(t,2,".",",");break;case"amount_no_decimals_with_comma_separator":n=this.formatWithDelimiters(t,0,".",",");break;case"amount_no_decimals_with_space_separator":n=this.formatWithDelimiters(t,0," ");break;case"amount_with_apostrophe_separator":n=this.formatWithDelimiters(t,2,"'")}return i.replace(s,n)}}a.instance=null;class c{constructor(){this.isEnabled=!1;const t=new URLSearchParams(window.location.search);this.isEnabled=!!t.get("debug")}static getInstance(){return this.instance||(this.instance=new c),this.instance}enable(){this.isEnabled=!0}disable(){this.isEnabled=!1}debug(t){this.isEnabled&&console.log(t)}}function u(t,e,n){switch(n){case s.Positions.TOP:e.prepend(t);break;case s.Positions.BOTTOM:e.append(t);break;case s.Positions.BEFORE:e.parentNode.insertBefore(t,e);break;case s.Positions.AFTER:e.parentNode.insertBefore(t,e.nextSibling)}}c.instance=null,s.Positions=void 0,(f=s.Positions||(s.Positions={})).TOP="top",f.BOTTOM="bottom",f.BEFORE="before",f.AFTER="after";const h="translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')";const l=t.getInstance();var m=r.getInstance(),d=a.getInstance(),g=n.getInstance().setEventBus(l),p=i.getInstance(),f=c.getInstance();s.cart=m,s.checkout=g,s.dom=p,s.eventBus=l,s.getElementByContent=function(t){const e=document.evaluate(`//button[contains(${h}, "${t}") or contains(${h}, "${t.replace(/ /g,"")}")]`,document,null,XPathResult.ANY_TYPE,null);return e.iterateNext()},s.inIframe=function(){try{return window.self!==window.top}catch(t){return!0}},s.listenOnCartChange=function(){e.getInstance().setEventBus(l)},s.logger=f,s.moneyFormatter=d,s.moveByElementQueries=function(t,e,n){t=document.querySelector(t);let s;try{s=e&&document.querySelector(e)||document.body}catch(t){s=document.body}return u(t,s,n)},s.moveByElements=u,Object.defineProperty(s,"__esModule",{value:!0})});