gw-customer-accounts 1.5.2 → 1.5.3

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.
@@ -1 +1 @@
1
- import{G as a,a as i}from"./assets/index-DkUQsudo.js";customElements.define("gw-address-form",class extends HTMLElement{constructor(){super(),this.form=this.querySelector("form"),this.type=this.getAttribute("type"),this.addressId=this.getAttribute("address-id")}connectedCallback(){if(this._handleFormSubmit(),this.type==="edit"){const e=this.querySelector("[data-delete-address]");if(!e)return;e.addEventListener("click",()=>{this._deleteAddress()})}this.type}async _handleFormSubmit(){await Promise.all([customElements.whenDefined("sl-input")]).then(()=>{this.form.addEventListener("sl-invalid",e=>{e.preventDefault(),this._clearErrorMessages(),this.form.querySelectorAll("sl-input").forEach(t=>{if(t.hasAttribute("data-invalid")){const r=document.createElement("div");r.slot="help-text",r.classList.add("gw-error-message"),r.textContent=t.validationMessage,t.appendChild(r)}}),e.target.focus()},{capture:!0}),this.form.addEventListener("submit",e=>{e.preventDefault();const t=new FormData(this.form),r=Object.fromEntries(t.entries());this._submitAddressForm(r)})})}async _submitAddressForm(e){try{this._clearErrorMessages(),this.form.querySelector("[data-loader]").hidden=!1,e.province&&(e.province=e.province.replaceAll("_"," ")),e.country=e.country.replaceAll("_"," ");let t=e.isDefault;delete e.isDefault;let r=null;if(this.type==="edit"?r=await a.request(i.ENDPOINTS.ADDRESS.EDIT,{address:e,addrID:this.addressId,isDefault:t}):r=await a.request(i.ENDPOINTS.ADDRESS.ADD,{address:e,isDefault:t}),r.error)throw new Error(r.error);this.form.closest("sl-drawer").hide(),a.updateAjaxContent(["[data-gw-addresses-list]","[data-gw-addresses-carousel]"])}catch(t){console.error(t)}finally{this.form.querySelector("[data-loader]").hidden=!0}}async _deleteAddress(){try{this.querySelector("[data-delete-address]").querySelector("[data-loader]").hidden=!1;let e=await a.request(i.ENDPOINTS.ADDRESS.REMOVE,{addrID:this.addressId});if(e.error)throw new Error(e.error);this.form.closest("sl-drawer").hide(),await a.app.updateContent(["[data-gw-addresses-list]","[data-gw-addresses-carousel]"])}catch(e){console.error(e)}}_handleSubmitButton(){const e=this.form.querySelectorAll("sl-input, sl-select, sl-checkbox"),t=this.form.querySelector('button[type="submit"]'),r=()=>Array.from(e).some(s=>{if(s.tagName==="SL-CHECKBOX"){const n=s.getAttribute("defaultChecked"),c=s.getAttribute("checked");return n!==c}const d=s.getAttribute("value"),l=s.value;return d!==l});e.forEach(o=>{o.addEventListener("sl-input",()=>{r()?t.hidden=!1:t.hidden=!0})})}_clearErrorMessages(){this.form.querySelectorAll(".gw-error-message").forEach(e=>e.remove())}});
1
+ import{G as a,a as i}from"./assets/index-CS0ypOUL.js";customElements.define("gw-address-form",class extends HTMLElement{constructor(){super(),this.form=this.querySelector("form"),this.type=this.getAttribute("type"),this.addressId=this.getAttribute("address-id")}connectedCallback(){if(this._handleFormSubmit(),this.type==="edit"){const e=this.querySelector("[data-delete-address]");if(!e)return;e.addEventListener("click",()=>{this._deleteAddress()})}this.type}async _handleFormSubmit(){await Promise.all([customElements.whenDefined("sl-input")]).then(()=>{this.form.addEventListener("sl-invalid",e=>{e.preventDefault(),this._clearErrorMessages(),this.form.querySelectorAll("sl-input").forEach(t=>{if(t.hasAttribute("data-invalid")){const r=document.createElement("div");r.slot="help-text",r.classList.add("gw-error-message"),r.textContent=t.validationMessage,t.appendChild(r)}}),e.target.focus()},{capture:!0}),this.form.addEventListener("submit",e=>{e.preventDefault();const t=new FormData(this.form),r=Object.fromEntries(t.entries());this._submitAddressForm(r)})})}async _submitAddressForm(e){try{this._clearErrorMessages(),this.form.querySelector("[data-loader]").hidden=!1,e.province&&(e.province=e.province.replaceAll("_"," ")),e.country=e.country.replaceAll("_"," ");let t=e.isDefault;delete e.isDefault;let r=null;if(this.type==="edit"?r=await a.request(i.ENDPOINTS.ADDRESS.EDIT,{address:e,addrID:this.addressId,isDefault:t}):r=await a.request(i.ENDPOINTS.ADDRESS.ADD,{address:e,isDefault:t}),r.error)throw new Error(r.error);this.form.closest("sl-drawer").hide(),a.updateAjaxContent(["[data-gw-addresses-list]","[data-gw-addresses-carousel]"])}catch(t){console.error(t)}finally{this.form.querySelector("[data-loader]").hidden=!0}}async _deleteAddress(){try{this.querySelector("[data-delete-address]").querySelector("[data-loader]").hidden=!1;let e=await a.request(i.ENDPOINTS.ADDRESS.REMOVE,{addrID:this.addressId});if(e.error)throw new Error(e.error);this.form.closest("sl-drawer").hide(),await a.app.updateContent(["[data-gw-addresses-list]","[data-gw-addresses-carousel]"])}catch(e){console.error(e)}}_handleSubmitButton(){const e=this.form.querySelectorAll("sl-input, sl-select, sl-checkbox"),t=this.form.querySelector('button[type="submit"]'),r=()=>Array.from(e).some(s=>{if(s.tagName==="SL-CHECKBOX"){const n=s.getAttribute("defaultChecked"),c=s.getAttribute("checked");return n!==c}const d=s.getAttribute("value"),l=s.value;return d!==l});e.forEach(o=>{o.addEventListener("sl-input",()=>{r()?t.hidden=!1:t.hidden=!0})})}_clearErrorMessages(){this.form.querySelectorAll(".gw-error-message").forEach(e=>e.remove())}});
@@ -0,0 +1 @@
1
+ const i=Object.freeze({MAP:{"#my-account":"dashboard","#my-orders":"orders","#my-profile":"profile","#my-favorites":"dashboard##favorites"},STORAGE_KEYS:{TOKEN:"i-shsgi--u0mihh3co1e3y9sns",EMAIL:"gw-customer-accounts-email",RECENTLY_VIEWED:"gw-recently-viewed",RECENTLY_VIEWED_COLLECTION:"gw-recently-viewed-collection",LOYALTY_POINTS:"gw-loyalty-points",YOTPO_POINTS:"gw-yotpo-points",WISHLIST_PRODUCT_IDS:"gw-wishlist-product-ids",RISE_POINTS:"gw-rise-points",REDIRECT_URL:"gw-customer-accounts-login-redirect",TEMP_WISHLIST_PRODUCTS:"gw-temp-wishlist-products",TEMP_CART_PRODUCTS:"gw-temp-cart-products",TEMP_RECENTLY_VIEWED_ITEMS:"gw-temp-recently-viewed-items",TEMP_PRODUCTS_UPDATED:"gw-temp-products-updated"},ENDPOINTS:{AUTH:{SIGN_IN:"/email-sign",SIGN_IN_TEST:"/email-sign-test",VERIFY_CODE:"/code-sign",GET_TOKEN:"/logged-sign",CUSTOMER_LOGGED:"/customer-logged",GET_CAPTCHA_TOKEN:"/get-token"},FAVORITES:{GET_ALL_IDS:"/get-all-favorites",GET:"/get-favorites",ADD:"/add-favorite",REMOVE:"/remove-favorite",ADD_BULK:"/add-favorites"},VIEWED_PRODUCTS:{GET:"/get-viewed-products",ADD:"/add-viewed-product",ADD_BULK:"/add-viewed-products"},CART:{GET:"/get-cart-products",ADD:"/add-cart-product",ADD_BULK:"/add-cart-products",REMOVE:"/remove-cart"},ADDRESS:{ADD:"/add-address",EDIT:"/edit-address",REMOVE:"/remove-address"},CUSTOMER:{UPDATE:"/update-customer"},LOYALTY:{GET_LL:"/get-ll-customer",GET_YOTPO_CUSTOMER:"/get-youtpo-customer",GET_RISE_CREDIT:"/get-rise-customer"},MISC:{GET_MALOMO_ORDER:"/get-malomo-order"}},TAGS_TO_HIDE:["accounts:hidden"],TEMPLATE_IDS:{PRODUCT_CARD:"gw-standard-product-card-template",FORM_PRODUCT_CARD:"gw-form-product-card-template"},CUSTOM_EVENTS:{FAVORITES_STORAGE_UPDATED:"gw:favorites-storage-updated",SAVED_ITEMS_FROM_CART:"gw:saved-items-from-cart"},DRAWER_IDS:{favorites:"#Drawer-Favorites"}});class u{constructor(){}get componentData(){const e=document.querySelector("gw-customer-accounts").shadowRoot.querySelector("[data-component-data]");return JSON.parse(e.textContent)}get customerId(){var t,e;return(e=(t=this.componentData)==null?void 0:t.customer)==null?void 0:e.id}get customerFirstName(){var t,e;return(e=(t=this.componentData)==null?void 0:t.customer)==null?void 0:e.firstName}get customerEmail(){var t,e;return(e=(t=this.componentData)==null?void 0:t.customer)==null?void 0:e.email}get hasCustomer(){var t,e;return!!((e=(t=this.componentData)==null?void 0:t.customer)!=null&&e.id)}get customerToken(){return localStorage.getItem(i.STORAGE_KEYS.TOKEN)}get baseURL(){return this.componentData.baseUrl}get app(){return document.querySelector("gw-customer-accounts")}get appShadow(){return this.app.shadowRoot}get dashboard(){return this.appShadow.querySelector("gw-customer-accounts-dashboard")}get tabId(){return i.MAP[window.location.hash]||"dashboard"}async request(t,e={},s="POST"){const a=()=>{const o={method:s,mode:"cors",cache:"no-cache",headers:{"Content-Type":"application/json"}};return s==="POST"&&(o.body=JSON.stringify(e)),o};if(s==="GET"){const o=new URLSearchParams(e);t=`${t}?${o}`}return s==="POST"&&(e.token=this.customerToken,e.email=this.customerEmail,e.customerID=this.customerId),await(await fetch(this.baseURL+t,a())).json()}notify(t,e="success",s=3e3){const a=document.querySelector("gw-customer-accounts"),r=a.shadowRoot.querySelector("[data-notification-alert]"),o=a.shadowRoot.querySelector("[data-notification-message]");o.innerHTML=t,r.open=!0}async updateAjaxContent(t){return await this.app.updateContent(t)}parseVariantId(t){return String(t).split("/").pop()}formatMoney(t){return(t/100).toLocaleString("en-US",{style:"currency",currency:"USD"})}addToStorage({key:t,values:e,storageType:s="local",position:a="start"}){const r=s==="local"?localStorage:sessionStorage,o=JSON.parse(r.getItem(t))||[];a==="start"?r.setItem(t,JSON.stringify([...e,...o])):r.setItem(t,JSON.stringify([...o,...e]))}removeFromStorage({key:t,values:e,storageType:s="local",nestedKey:a}){const r=s==="local"?localStorage:sessionStorage,o=JSON.parse(r.getItem(t))||[];if(a){const n=o.map(c=>e.includes(c[a])?null:c);r.setItem(t,JSON.stringify(n.filter(Boolean)))}else{const n=o.filter(c=>!e.includes(c));r.setItem(t,JSON.stringify(n))}}}const m=new u;export{m as G,i as a};
@@ -0,0 +1 @@
1
+ import{G as i,a as e}from"./index-CS0ypOUL.js";class l extends HTMLElement{constructor(){var a;super(),this.tabData=this._parseTabData(),this.tabId=(a=this.tabData)==null?void 0:a.id,this.tabGroup=this.closest("sl-tab-group"),this.tabPanel=this.closest("sl-tab-panel"),this.mainDrawerLabel=i.appShadow.querySelector("[data-main-drawer-label]")}connectedCallback(){if(this._addAnimations(),this.tabGroup.addEventListener("sl-tab-show",n=>{n.detail.name===this.tabId?(this._playFadeInAnimations(),this._updateMainDrawerLabel(),this._updateSignInBlockHeading(),this._updateHash(),i.app.reinitializeCarousels()):this._resetAnimations()}),!e.MAP[window.location.hash])return;const a=window.location.hash===this.tabId,t=e.MAP[window.location.hash].includes(this.tabId);(a||t)&&this._playFadeInAnimations()}get animationElements(){const t=[...this.querySelectorAll("sl-animation")],n=i.appShadow.querySelector("[gw-sign-in-block-animation]");return n&&t.unshift(n),t}_parseTabData(){const a=this.querySelector("[data-tab-panel-data]");return a?JSON.parse(a.textContent):{}}_updateHash(){var n,s;const a=window.location.hash;(n=e.MAP[a])!=null&&n.includes("##")||(window.location.hash=(s=this.tabData)==null?void 0:s.hash)}_updateMainDrawerLabel(){var t;const a=(t=this.tabData)==null?void 0:t.label;a&&this.mainDrawerLabel&&(this.mainDrawerLabel.textContent=a)}_updateSignInBlockHeading(){var n;const a=(n=this.tabData)==null?void 0:n.signInBlockHeading,t=i.appShadow.querySelector("[data-sign-in-block-heading]");a&&t&&(t.textContent=a)}_playFadeInAnimations(){this.animationElements.forEach(a=>a.play=!0)}_addAnimations(){this.animationElements.forEach((a,t)=>{a.keyframes=[{offset:0,opacity:"0",transform:"translate3d(0, -10px, 0)",easing:"ease-in-out"},{offset:1,opacity:"1",transform:"translate3d(0, 0, 0)",easing:"ease-in-out"}],a.delay=t*80})}_resetAnimations(){this.animationElements.forEach(a=>{a.currentTime>0&&(a.currentTime=0)})}}export{l as G};
package/dist/dashboard.js CHANGED
@@ -1,4 +1,4 @@
1
- import{G as i,a as m}from"./assets/index-DkUQsudo.js";import{G as f}from"./assets/tab-D4kkRiyw.js";customElements.define("gw-customer-accounts-dashboard",class extends f{constructor(){super()}connectedCallback(){super.connectedCallback(),this._initDashboard()}async _initDashboard(){i.hasCustomer&&this._renderRecentlyViewedCollections(),this.loadSavedCartItems(),this.loadFavoriteItems(),this.loadRecentlyViewedItems()}async loadRecentlyViewedItems(e={}){const{preventDrawerRender:a=!1,preventCarouselRender:r=!1,page:t=1,limit:o=8}=e;try{const n=await this._getRecentlyViewedItems(t,o);this._renderRecentlyViewedItems(n,{preventDrawerRender:a,preventCarouselRender:r,page:t,limit:o})}catch(n){console.error("Error rendering recently viewed items:",n)}}async _getRecentlyViewedItems(e,a){if(!i.hasCustomer)return JSON.parse(localStorage.getItem(m.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS))||[];const r=await i.request(m.ENDPOINTS.VIEWED_PRODUCTS.GET,{customerID:i.customerId,limit:a,page:e},"GET");if(r.error)throw new Error(r.error);return r.products||[]}_renderRecentlyViewedItems(e,a){const r="[data-recently-viewed-container]",t="[data-recently-viewed-drawer-container]";if(i.appShadow.querySelector(r)){if(!e.length){this._renderEmptyState(r,t);return}a.preventCarouselRender||this._renderProductsToCarousel(e,r),a.preventDrawerRender||this._renderProductsToDrawer({products:e,containerSelector:t,productTemplateId:m.TEMPLATE_IDS.PRODUCT_CARD,currentPage:a.page,nextPage:null})}}async _getSavedCartItems(e,a){if(!i.customerId)return JSON.parse(localStorage.getItem(m.STORAGE_KEYS.TEMP_CART_PRODUCTS))||[];const r=await i.request(m.ENDPOINTS.CART.GET,{customerEmail:i.customerEmail,limit:a,page:e},"GET");if(r.error)throw new Error(r.error);return r.products||[]}_renderSavedCartItems(e,a){const r="[data-saved-from-cart-items-container]",t="[data-saved-from-cart-drawer-container]";if(!this.querySelector(r))return;if(!e.length){this._renderEmptyState(r,t);return}const n=this._calculateNextPage({totalItems:e.length,currentPage:a.page,limit:a.limit});a.preventCarouselRender||this._renderProductsToCarousel(e,r),a.preventDrawerRender||this._renderProductsToDrawer({products:e,containerSelector:t,removeButtonAction:"data-saved-from-cart-remove",productTemplateId:m.TEMPLATE_IDS.FORM_PRODUCT_CARD,currentPage:a.page,nextPage:n})}async loadSavedCartItems(e={}){const{preventDrawerRender:a=!1,preventCarouselRender:r=!1,page:t=1,limit:o=10}=e;try{const n=await this._getSavedCartItems(t,o);this._renderSavedCartItems(n,{preventDrawerRender:a,preventCarouselRender:r,page:t,limit:o})}catch(n){console.error("Error rendering saved items from cart:",n)}}async _getFavoriteItems(e,a){if(!i.hasCustomer)return JSON.parse(localStorage.getItem(m.STORAGE_KEYS.TEMP_WISHLIST_PRODUCTS))||[];const r=await i.request(m.ENDPOINTS.FAVORITES.GET,{limit:a,page:e,customerID:i.customerId},"GET");if(r.error)throw new Error(r.error);return r.products||[]}_renderFavoriteItems(e,a){const r="[data-favorites-container]",t="[data-favorites-drawer-container]";if(!i.appShadow.querySelector(r))return;if(!e.length){this._renderEmptyState(r,t,"You have no favorite items.");return}const{preventDrawerRender:n=!1,preventCarouselRender:s=!1,page:d=1,limit:l=10}=a;s||this._renderProductsToCarousel(e,r);const c=this._calculateNextPage({totalItems:e.length,currentPage:d,limit:l});n||this._renderProductsToDrawer({products:e,containerSelector:t,removeButtonAction:"data-wishlist-remove",productTemplateId:m.TEMPLATE_IDS.FORM_PRODUCT_CARD,currentPage:d,nextPage:c})}_renderSingleFavoriteItem(e){const a="[data-favorites-container]",r="[data-favorites-drawer-container]",t=i.appShadow.querySelector(a),o=document.getElementById(m.TEMPLATE_IDS.PRODUCT_CARD);if(!o){console.warn("Product card template not found.");return}const n=o.content.cloneNode(!0),s=this._populateCarouselItem(n,e),d=t.querySelector("sl-carousel");if(d)d.prepend(s);else{const c=document.createElement("sl-carousel");c.setAttribute("navigation",""),c.setAttribute("slides-per-page","3"),c.setAttribute("slides-per-move","3"),c.setAttribute("style","--scroll-hint: 5%; --aspect-ratio: none"),c.appendChild(s),t.innerHTML="",t.appendChild(c)}const l=i.appShadow.querySelector(r);if(l){const c=document.getElementById(m.TEMPLATE_IDS.FORM_PRODUCT_CARD);if(!c){console.warn("Drawer product card template not found.");return}const p=this._createProductElement(e,c,"data-wishlist-remove");this._ensureDrawerNotEmpty(t),l.prepend(p)}}_removeFavoriteItem(e){const a="[data-favorites-container]",r="[data-favorites-drawer-container]",t=i.appShadow.querySelector(a),o=i.appShadow.querySelector(r);if(t){const n=t.querySelector(`[data-product-id="${e}"]`);n&&n.remove(),t.querySelector("sl-carousel-item")||this._renderEmptyState(a,r,"You have no favorite items.")}if(o){const n=o.querySelector(`[data-product-id="${e}"]`);n&&n.remove()}}async loadFavoriteItems(e={}){const{page:a=1,limit:r=10}=e;try{const t=await this._getFavoriteItems(a,r);this._renderFavoriteItems(t,e)}catch(t){console.error("Error rendering favorite items:",t)}}_renderRecentlyViewedCollections(){const e=m.STORAGE_KEYS.RECENTLY_VIEWED_COLLECTION,a=JSON.parse(localStorage.getItem(e))||[],r=this.querySelector("[data-recently-viewed-collections-container]");if(!r||(r.innerHTML="",!a.length))return;const t=document.createElement("sl-carousel");t.setAttribute("navigation",""),t.setAttribute("style","--scroll-hint: 5%; --aspect-ratio: none"),a.forEach(o=>{const n=document.createElement("sl-carousel-item");n.innerHTML=`
1
+ import{G as i,a as m}from"./assets/index-CS0ypOUL.js";import{G as f}from"./assets/tab-vXz_-2og.js";customElements.define("gw-customer-accounts-dashboard",class extends f{constructor(){super()}connectedCallback(){super.connectedCallback(),this._initDashboard()}async _initDashboard(){i.hasCustomer&&this._renderRecentlyViewedCollections(),this.loadSavedCartItems(),this.loadFavoriteItems(),this.loadRecentlyViewedItems()}async loadRecentlyViewedItems(e={}){const{preventDrawerRender:a=!1,preventCarouselRender:r=!1,page:t=1,limit:o=8}=e;try{const n=await this._getRecentlyViewedItems(t,o);this._renderRecentlyViewedItems(n,{preventDrawerRender:a,preventCarouselRender:r,page:t,limit:o})}catch(n){console.error("Error rendering recently viewed items:",n)}}async _getRecentlyViewedItems(e,a){if(!i.hasCustomer)return JSON.parse(localStorage.getItem(m.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS))||[];const r=await i.request(m.ENDPOINTS.VIEWED_PRODUCTS.GET,{customerID:i.customerId,limit:a,page:e},"GET");if(r.error)throw new Error(r.error);return r.products||[]}_renderRecentlyViewedItems(e,a){const r="[data-recently-viewed-container]",t="[data-recently-viewed-drawer-container]";if(i.appShadow.querySelector(r)){if(!e.length){this._renderEmptyState(r,t);return}a.preventCarouselRender||this._renderProductsToCarousel(e,r),a.preventDrawerRender||this._renderProductsToDrawer({products:e,containerSelector:t,productTemplateId:m.TEMPLATE_IDS.PRODUCT_CARD,currentPage:a.page,nextPage:null})}}async _getSavedCartItems(e,a){if(!i.hasCustomer)return JSON.parse(localStorage.getItem(m.STORAGE_KEYS.TEMP_CART_PRODUCTS))||[];const r=await i.request(m.ENDPOINTS.CART.GET,{customerEmail:i.customerEmail,limit:a,page:e},"GET");if(r.error)throw new Error(r.error);return r.products||[]}_renderSavedCartItems(e,a){const r="[data-saved-from-cart-items-container]",t="[data-saved-from-cart-drawer-container]";if(!this.querySelector(r))return;if(!e.length){this._renderEmptyState(r,t);return}const n=this._calculateNextPage({totalItems:e.length,currentPage:a.page,limit:a.limit});a.preventCarouselRender||this._renderProductsToCarousel(e,r),a.preventDrawerRender||this._renderProductsToDrawer({products:e,containerSelector:t,removeButtonAction:"data-saved-from-cart-remove",productTemplateId:m.TEMPLATE_IDS.FORM_PRODUCT_CARD,currentPage:a.page,nextPage:n})}async loadSavedCartItems(e={}){const{preventDrawerRender:a=!1,preventCarouselRender:r=!1,page:t=1,limit:o=10}=e;try{const n=await this._getSavedCartItems(t,o);this._renderSavedCartItems(n,{preventDrawerRender:a,preventCarouselRender:r,page:t,limit:o})}catch(n){console.error("Error rendering saved items from cart:",n)}}async _getFavoriteItems(e,a){if(!i.hasCustomer)return JSON.parse(localStorage.getItem(m.STORAGE_KEYS.TEMP_WISHLIST_PRODUCTS))||[];const r=await i.request(m.ENDPOINTS.FAVORITES.GET,{limit:a,page:e,customerID:i.customerId},"GET");if(r.error)throw new Error(r.error);return r.products||[]}_renderFavoriteItems(e,a){const r="[data-favorites-container]",t="[data-favorites-drawer-container]";if(!i.appShadow.querySelector(r))return;if(!e.length){this._renderEmptyState(r,t,"You have no favorite items.");return}const{preventDrawerRender:n=!1,preventCarouselRender:s=!1,page:d=1,limit:l=10}=a;s||this._renderProductsToCarousel(e,r);const c=this._calculateNextPage({totalItems:e.length,currentPage:d,limit:l});n||this._renderProductsToDrawer({products:e,containerSelector:t,removeButtonAction:"data-wishlist-remove",productTemplateId:m.TEMPLATE_IDS.FORM_PRODUCT_CARD,currentPage:d,nextPage:c})}_renderSingleFavoriteItem(e){const a="[data-favorites-container]",r="[data-favorites-drawer-container]",t=i.appShadow.querySelector(a),o=document.getElementById(m.TEMPLATE_IDS.PRODUCT_CARD);if(!o){console.warn("Product card template not found.");return}const n=o.content.cloneNode(!0),s=this._populateCarouselItem(n,e),d=t.querySelector("sl-carousel");if(d)d.prepend(s);else{const c=document.createElement("sl-carousel");c.setAttribute("navigation",""),c.setAttribute("slides-per-page","3"),c.setAttribute("slides-per-move","3"),c.setAttribute("style","--scroll-hint: 5%; --aspect-ratio: none"),c.appendChild(s),t.innerHTML="",t.appendChild(c)}const l=i.appShadow.querySelector(r);if(l){const c=document.getElementById(m.TEMPLATE_IDS.FORM_PRODUCT_CARD);if(!c){console.warn("Drawer product card template not found.");return}const p=this._createProductElement(e,c,"data-wishlist-remove");this._ensureDrawerNotEmpty(t),l.prepend(p)}}_removeFavoriteItem(e){const a="[data-favorites-container]",r="[data-favorites-drawer-container]",t=i.appShadow.querySelector(a),o=i.appShadow.querySelector(r);if(t){const n=t.querySelector(`[data-product-id="${e}"]`);n&&n.remove(),t.querySelector("sl-carousel-item")||this._renderEmptyState(a,r,"You have no favorite items.")}if(o){const n=o.querySelector(`[data-product-id="${e}"]`);n&&n.remove()}}async loadFavoriteItems(e={}){const{page:a=1,limit:r=10}=e;try{const t=await this._getFavoriteItems(a,r);this._renderFavoriteItems(t,e)}catch(t){console.error("Error rendering favorite items:",t)}}_renderRecentlyViewedCollections(){const e=m.STORAGE_KEYS.RECENTLY_VIEWED_COLLECTION,a=JSON.parse(localStorage.getItem(e))||[],r=this.querySelector("[data-recently-viewed-collections-container]");if(!r||(r.innerHTML="",!a.length))return;const t=document.createElement("sl-carousel");t.setAttribute("navigation",""),t.setAttribute("style","--scroll-hint: 5%; --aspect-ratio: none"),a.forEach(o=>{const n=document.createElement("sl-carousel-item");n.innerHTML=`
2
2
  <a href="${o.url}" class="gw-button-text gw-unstyled-link gw-recently-viewed-collection">
3
3
  ${o.title}
4
4
  </a>
@@ -1,4 +1,4 @@
1
- import{a as i,G as r}from"./assets/index-DkUQsudo.js";customElements.define("gw-integrations-loyalty-points",class extends HTMLElement{constructor(){switch(super(),this.integration=this.getAttribute("integration"),this.loyaltyPageUrl=this.getAttribute("page-url"),this.pointsLabel=this.getAttribute("points-label"),this.linkLabel=this.getAttribute("link-label"),this.innerHTML=`
1
+ import{a as i,G as r}from"./assets/index-CS0ypOUL.js";customElements.define("gw-integrations-loyalty-points",class extends HTMLElement{constructor(){switch(super(),this.integration=this.getAttribute("integration"),this.loyaltyPageUrl=this.getAttribute("page-url"),this.pointsLabel=this.getAttribute("points-label"),this.linkLabel=this.getAttribute("link-label"),this.innerHTML=`
2
2
  <a href="${this.loyaltyPageUrl}" class="gw-loyalty-points__link gw-unstyled-link">
3
3
  <span class="gw-loader" data-loader></span>
4
4
  <span class="gw-loyalty-points__points-value gw-header" data-points-container></span>
package/dist/main.js CHANGED
@@ -1 +1 @@
1
- import{G as i,a as s}from"./assets/index-DkUQsudo.js";customElements.define("gw-customer-accounts",class extends HTMLElement{constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.getElementById("gw-customer-accounts-template");this.shadow.appendChild(t.content.cloneNode(!0)),t.remove(),this.drawer=this.shadowRoot.querySelector("sl-drawer"),this.tabGroup=this.shadowRoot.querySelector("sl-tab-group"),this.closeButtons=this.drawer.querySelectorAll("[data-main-drawer-close]")}connectedCallback(){this._checkCustomerStatus(),this._watchSavedItemsFromCart(),i.hasCustomer&&(this._saveTempWishlistProducts(),this._saveTempCartProducts(),this._saveTempRecentlyViewedProducts()),Promise.all([customElements.whenDefined("sl-drawer")]).then(()=>this.init())}init(){this.drawer.removeAttribute("hidden"),window.location.search.includes("my-account-open")&&!window.location.pathname.includes("/account")&&(window.location.hash="#my-account"),window.addEventListener("hashchange",()=>{this._handleHashChange(),this.reinitializeCarousels()}),this._handleHashChange(),this.closeButtons.forEach(t=>{t.addEventListener("click",()=>{this._closeDrawer()})}),this.drawer.addEventListener("sl-hide",t=>{t.target===this.drawer&&(window.location.hash="",document.body.style.removeProperty("overflow"))}),this._updateAccountLinks(),this._handleInputElements(),this._addRecentlyViewedProducts(),i.hasCustomer&&this._updateRecentlyViewedCollection(),this.reinitializeCarousels(),this.shadowRoot.addEventListener("click",t=>{if(!t.target.closest("[data-drawer-id]"))return;const o=t.target.closest("[data-drawer-id]").getAttribute("data-drawer-id"),r=this.shadowRoot.querySelector(`#${o}`);r.hasAttribute("empty")||(r.open=!0,navigator.userAgent.indexOf("iPhone")>-1&&setTimeout(()=>{this.drawer.classList.add("inner-drawer-open")},150))}),this.shadowRoot.addEventListener("click",t=>{t.target.closest("[data-inner-drawer-close]")&&(t.target.closest("sl-drawer").open=!1,navigator.userAgent.indexOf("iPhone")>-1&&this.drawer.classList.remove("inner-drawer-open"))}),i.hasCustomer&&this.updateFavoriteItemsStorage(),!i.hasCustomer&&sessionStorage.getItem(s.STORAGE_KEYS.TEMP_PRODUCTS_UPDATED)!=="true"&&this._syncTempProducts()}reinitializeCarousels(){Promise.all([customElements.whenDefined("sl-carousel"),customElements.whenDefined("sl-carousel-item")]).then(()=>{setTimeout(()=>{this.shadowRoot.querySelectorAll("sl-carousel").forEach(t=>{t.initializeSlides()})},1e3)})}_updateAccountLinks(){const t=document.querySelectorAll("a[href]");Array.from(t).filter(r=>r.getAttribute("href").includes("/account")||r.getAttribute("href").startsWith("#status")).forEach(r=>{r.hasAttribute("data-ignore-account-link")||(r.getAttribute("href").includes("logout")?r.href="#my-profile":r.href="#my-account",Shopify.designMode&&r.addEventListener("click",()=>{this._openDrawer()}))})}_handleInputElements(){const t=e=>{!e.value&&!e.getAttribute("value")?e.classList.add("input--empty"):e.classList.remove("input--empty")},o=e=>{e.classList.add("input--focus")},r=e=>{e.classList.remove("input--focus")};this.shadowRoot.querySelectorAll("sl-input").forEach(e=>{e.addEventListener("sl-input",()=>t(e)),e.addEventListener("sl-focus",()=>o(e)),e.addEventListener("sl-blur",()=>r(e)),t(e)})}async _handleHashChange(){const t=window.location.hash;if(s.MAP[t]){if(await this._fetchComponents(),s.MAP[t].includes("##")){const[o,r]=s.MAP[t].split("##");this._renderTab(o),setTimeout(()=>{this._renderSubTab(r),this._openDrawer()},100);return}else this.shadowRoot.querySelectorAll("sl-drawer").forEach(o=>{o.open=!1});this._renderTab(),this._openDrawer()}}async _openDrawer(){this.drawer.open||(this.drawer.show(),document.body.style.setProperty("overflow","hidden"))}_closeDrawer(){this.drawer.open&&(this.drawer.hide(),document.body.style.removeProperty("overflow"))}_fetchComponents(){const t="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.19.1/cdn/components/",r=["tab-group","tab-panel","tab","animation","skeleton","select","input","checkbox","carousel","carousel-item","popup","option","alert"].map(e=>new Promise((n,a)=>{if(customElements.get(`sl-${e}`)){n();return}const c=document.createElement("script");c.type="module",c.src=`${t}${e}/${e}.js`,c.onload=n,c.onerror=a,document.body.appendChild(c)}));return Promise.all(r)}async _addRecentlyViewedProducts(){if(!window.location.pathname.includes("/products/"))return;const{product:o}=i.componentData;if(!o||!(o!=null&&o.id))return;const{id:r}=o;if(i.hasCustomer)try{const e=await i.request(s.ENDPOINTS.VIEWED_PRODUCTS.ADD,{prodID:r});if(e.error)throw new Error(e.error);return e}catch(e){console.error(e)}else{if(JSON.parse(localStorage.getItem(s.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS)||"[]").some(n=>n.id===r))return;i.addToStorage({key:s.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS,values:[{...o}]})}}_updateRecentlyViewedCollection(){if(!window.location.pathname.includes("/collections/"))return;const{collection:o}=i.componentData;if(!o)return;const{url:r,title:e}=o,n=localStorage.getItem(s.STORAGE_KEYS.RECENTLY_VIEWED_COLLECTION),c=(JSON.parse(n)||[]).filter(l=>l.url!==r),d=[{url:r,title:e},...c];localStorage.setItem(s.STORAGE_KEYS.RECENTLY_VIEWED_COLLECTION,JSON.stringify(d))}_renderTab(t){Promise.all([(customElements.whenDefined("sl-tab-group"),customElements.whenDefined("sl-tab-panel"),customElements.whenDefined("sl-tab"))]).then(()=>{this.tabGroup.show(t||i.tabId)})}_renderSubTab(t){const o=s.DRAWER_IDS[t];if(!o)return;const r=this.shadowRoot.querySelector(o);r&&(r.open=!0,navigator.userAgent.indexOf("iPhone")>-1&&setTimeout(()=>{this.drawer.classList.add("inner-drawer-open")},150))}async updateContent(t=[]){const o=this.getAttribute("data-section-id"),r=await this._fetchContent(o);t.forEach(e=>{const n=this.shadow.querySelector(e);if(n){const c=r.querySelector("#gw-customer-accounts-template").content.querySelector(e);n.innerHTML=c.innerHTML}})}async _fetchContent(t){const r=await(await fetch(window.location.pathname+`?section_id=${t}`)).text();return new DOMParser().parseFromString(r,"text/html")}async updateFavoriteItemsStorage(t){const{removeIds:o,addIds:r}=t||{};let e=!1;if(r!=null&&r.length&&(i.addToStorage({key:s.STORAGE_KEYS.WISHLIST_PRODUCT_IDS,values:r,storageType:"session"}),e=!0),o!=null&&o.length&&(i.removeFromStorage({key:s.STORAGE_KEYS.WISHLIST_PRODUCT_IDS,values:o,storageType:"session"}),e=!0),e){this.dispatchEvent(new CustomEvent(s.CUSTOM_EVENTS.FAVORITES_STORAGE_UPDATED));return}try{const n=await i.request(s.ENDPOINTS.FAVORITES.GET_ALL_IDS,{customerID:i.customerId},"GET");if(n.error)throw new Error(n.error);sessionStorage.setItem(s.STORAGE_KEYS.WISHLIST_PRODUCT_IDS,JSON.stringify(n.products)),this.dispatchEvent(new CustomEvent(s.CUSTOM_EVENTS.FAVORITES_STORAGE_UPDATED))}catch(n){console.error("Error initializing wishlist:",n)}}async _checkCustomerStatus(){const t=i.customerToken,{id_sha256:o,email:r,tags:e,id:n}=i.componentData.customer;if(!t&&n)try{const a=await i.request(s.ENDPOINTS.AUTH.GET_TOKEN,{customerEmail:r,encode:o},"POST");if(a.error)throw new Error(a.error);a.token&&(localStorage.setItem(s.STORAGE_KEYS.TOKEN,a.token),localStorage.setItem(s.STORAGE_KEYS.EMAIL,r))}catch(a){console.error("Error checking customer status:",a)}if(e&&!e.includes("gw-customer"))try{const a=await i.request(s.ENDPOINTS.AUTH.CUSTOMER_LOGGED,{});if(a.error)throw new Error(a.error)}catch(a){console.error("Error checking customer status:",a)}}async _saveTempWishlistProducts(){var r;const t=JSON.parse(localStorage.getItem(s.STORAGE_KEYS.TEMP_WISHLIST_PRODUCTS));if(!(t!=null&&t.length))return;const o={products:t.map(e=>{const{id:n,variantId:a}=e;return{prodID:n,varID:a}})};try{const e=await i.request(s.ENDPOINTS.FAVORITES.ADD_BULK,o);if(e.error)throw new Error(e.error);localStorage.removeItem(s.STORAGE_KEYS.TEMP_WISHLIST_PRODUCTS),(r=e.products)!=null&&r.length&&(sessionStorage.setItem(s.STORAGE_KEYS.WISHLIST_PRODUCT_IDS,JSON.stringify(e.products)),this.dispatchEvent(new CustomEvent(s.CUSTOM_EVENTS.FAVORITES_STORAGE_UPDATED))),i.dashboard.loadFavoriteItems()}catch(e){console.error("Error saving temp wishlist products:",e)}}async _saveTempCartProducts(){const t=JSON.parse(localStorage.getItem(s.STORAGE_KEYS.TEMP_CART_PRODUCTS));if(!(t!=null&&t.length))return;const o={products:t.map(r=>{const{id:e,variantId:n}=r;return{prodID:e,varID:n}})};try{const r=await i.request(s.ENDPOINTS.CART.ADD_BULK,o);if(r.error)throw new Error(r.error);localStorage.removeItem(s.STORAGE_KEYS.TEMP_CART_PRODUCTS),i.dashboard.loadSavedCartItems()}catch(r){console.error("Error saving temp cart products:",r)}}async _saveTempRecentlyViewedProducts(){const t=JSON.parse(localStorage.getItem(s.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS));if(!(t!=null&&t.length))return;const o={products:t.map(r=>{const{id:e}=r;return{prodID:e}})};try{const r=await i.request(s.ENDPOINTS.VIEWED_PRODUCTS.ADD_BULK,o);if(r.error)throw new Error(r.error);localStorage.removeItem(s.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS),console.log("Saved temp recently viewed products:",r),i.dashboard.loadRecentlyViewedItems()}catch(r){console.error("Error saving temp recently viewed products:",r)}}async _watchSavedItemsFromCart(){this.addEventListener(s.CUSTOM_EVENTS.SAVED_ITEMS_FROM_CART,async t=>{i.hasCustomer?await this._handleAuthedCartEvent(t):this._handleGuestCartEvent(t)})}async _handleGuestCartEvent(t){const o=t.detail.extra,r=o.handle,e={};try{const n=await fetch(`/products/${r}.js`);if(!n.ok)throw new Error("Product not found");const a=await n.json();e.variant_id=o.variant_id,e.featuredImage=o.featured_image,e.title=o.title,e.variants={},e.variants.nodes=a.variants,e.id=a.id,e.tags=a.tags,e.handle=a.handle;const d=(JSON.parse(localStorage.getItem(s.STORAGE_KEYS.TEMP_CART_PRODUCTS))||[]).filter(u=>u.id!==a.id),l=[e,...d];localStorage.setItem(s.STORAGE_KEYS.TEMP_CART_PRODUCTS,JSON.stringify(l)),i.dashboard.loadSavedCartItems()}catch(n){console.error("Error adding product to cart:",n)}}async _handleAuthedCartEvent(t){try{const{productId:o,variantId:r}=t.detail||{};if(!o||!r)return;const e=await i.request(s.ENDPOINTS.CART.ADD,{prodID:o,varID:r});if(e.error)throw new Error(e.error);i.dashboard.loadSavedCartItems()}catch(o){console.error("Error adding product to cart:",o)}}async _syncTempProducts(){const t=[s.STORAGE_KEYS.TEMP_WISHLIST_PRODUCTS,s.STORAGE_KEYS.TEMP_CART_PRODUCTS,s.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS],o=t.flatMap(a=>(JSON.parse(localStorage.getItem(a))||[]).filter(Boolean)),r=[...new Map(o.map(a=>[a.id,a])).values()];console.log("Unique products:",r);const n=(await Promise.all(r.map(async({id:a,handle:c})=>{try{const d=await fetch(`/products/${c}.js`);return d.ok?await d.json():null}catch{return null}}))).reduce((a,c)=>(c&&c.available&&(a[c.id]=c),a),{});t.forEach(a=>{const d=(JSON.parse(localStorage.getItem(a))||[]).map(l=>{if(!l)return null;const u=n[l.id];return u?(l.variants.nodes=u.variants,l):null}).filter(Boolean);localStorage.setItem(a,JSON.stringify(d))}),sessionStorage.setItem(s.STORAGE_KEYS.TEMP_PRODUCTS_UPDATED,"true")}});
1
+ import{G as i,a as s}from"./assets/index-CS0ypOUL.js";customElements.define("gw-customer-accounts",class extends HTMLElement{constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.getElementById("gw-customer-accounts-template");this.shadow.appendChild(t.content.cloneNode(!0)),t.remove(),this.drawer=this.shadowRoot.querySelector("sl-drawer"),this.tabGroup=this.shadowRoot.querySelector("sl-tab-group"),this.closeButtons=this.drawer.querySelectorAll("[data-main-drawer-close]")}connectedCallback(){this._checkCustomerStatus(),this._watchSavedItemsFromCart(),i.hasCustomer&&(this._saveTempWishlistProducts(),this._saveTempCartProducts(),this._saveTempRecentlyViewedProducts()),Promise.all([customElements.whenDefined("sl-drawer")]).then(()=>this.init())}init(){this.drawer.removeAttribute("hidden"),window.location.search.includes("my-account-open")&&!window.location.pathname.includes("/account")&&(window.location.hash="#my-account"),window.addEventListener("hashchange",()=>{this._handleHashChange(),this.reinitializeCarousels()}),this._handleHashChange(),this.closeButtons.forEach(t=>{t.addEventListener("click",()=>{this._closeDrawer()})}),this.drawer.addEventListener("sl-hide",t=>{t.target===this.drawer&&(window.location.hash="",document.body.style.removeProperty("overflow"))}),this._updateAccountLinks(),this._handleInputElements(),this._addRecentlyViewedProducts(),i.hasCustomer&&this._updateRecentlyViewedCollection(),this.reinitializeCarousels(),this.shadowRoot.addEventListener("click",t=>{if(!t.target.closest("[data-drawer-id]"))return;const o=t.target.closest("[data-drawer-id]").getAttribute("data-drawer-id"),r=this.shadowRoot.querySelector(`#${o}`);r.hasAttribute("empty")||(r.open=!0,navigator.userAgent.indexOf("iPhone")>-1&&setTimeout(()=>{this.drawer.classList.add("inner-drawer-open")},150))}),this.shadowRoot.addEventListener("click",t=>{t.target.closest("[data-inner-drawer-close]")&&(t.target.closest("sl-drawer").open=!1,navigator.userAgent.indexOf("iPhone")>-1&&this.drawer.classList.remove("inner-drawer-open"))}),i.hasCustomer&&this.updateFavoriteItemsStorage(),!i.hasCustomer&&sessionStorage.getItem(s.STORAGE_KEYS.TEMP_PRODUCTS_UPDATED)!=="true"&&this._syncTempProducts()}reinitializeCarousels(){Promise.all([customElements.whenDefined("sl-carousel"),customElements.whenDefined("sl-carousel-item")]).then(()=>{setTimeout(()=>{this.shadowRoot.querySelectorAll("sl-carousel").forEach(t=>{t.initializeSlides()})},1e3)})}_updateAccountLinks(){const t=document.querySelectorAll("a[href]");Array.from(t).filter(r=>r.getAttribute("href").includes("/account")||r.getAttribute("href").startsWith("#status")).forEach(r=>{r.hasAttribute("data-ignore-account-link")||(r.getAttribute("href").includes("logout")?r.href="#my-profile":r.href="#my-account",Shopify.designMode&&r.addEventListener("click",()=>{this._openDrawer()}))})}_handleInputElements(){const t=e=>{!e.value&&!e.getAttribute("value")?e.classList.add("input--empty"):e.classList.remove("input--empty")},o=e=>{e.classList.add("input--focus")},r=e=>{e.classList.remove("input--focus")};this.shadowRoot.querySelectorAll("sl-input").forEach(e=>{e.addEventListener("sl-input",()=>t(e)),e.addEventListener("sl-focus",()=>o(e)),e.addEventListener("sl-blur",()=>r(e)),t(e)})}async _handleHashChange(){const t=window.location.hash;if(s.MAP[t]){if(await this._fetchComponents(),s.MAP[t].includes("##")){const[o,r]=s.MAP[t].split("##");this._renderTab(o),setTimeout(()=>{this._renderSubTab(r),this._openDrawer()},100);return}else this.shadowRoot.querySelectorAll("sl-drawer").forEach(o=>{o.open=!1});this._renderTab(),this._openDrawer()}}async _openDrawer(){this.drawer.open||(this.drawer.show(),document.body.style.setProperty("overflow","hidden"))}_closeDrawer(){this.drawer.open&&(this.drawer.hide(),document.body.style.removeProperty("overflow"))}_fetchComponents(){const t="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.19.1/cdn/components/",r=["tab-group","tab-panel","tab","animation","skeleton","select","input","checkbox","carousel","carousel-item","popup","option","alert"].map(e=>new Promise((n,a)=>{if(customElements.get(`sl-${e}`)){n();return}const c=document.createElement("script");c.type="module",c.src=`${t}${e}/${e}.js`,c.onload=n,c.onerror=a,document.body.appendChild(c)}));return Promise.all(r)}async _addRecentlyViewedProducts(){if(!window.location.pathname.includes("/products/"))return;const{product:o}=i.componentData;if(!o||!(o!=null&&o.id))return;const{id:r}=o;if(i.hasCustomer)try{const e=await i.request(s.ENDPOINTS.VIEWED_PRODUCTS.ADD,{prodID:r});if(e.error)throw new Error(e.error);return e}catch(e){console.error(e)}else{if(JSON.parse(localStorage.getItem(s.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS)||"[]").some(n=>n.id===r))return;i.addToStorage({key:s.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS,values:[{...o}]})}}_updateRecentlyViewedCollection(){if(!window.location.pathname.includes("/collections/"))return;const{collection:o}=i.componentData;if(!o)return;const{url:r,title:e}=o,n=localStorage.getItem(s.STORAGE_KEYS.RECENTLY_VIEWED_COLLECTION),c=(JSON.parse(n)||[]).filter(l=>l.url!==r),d=[{url:r,title:e},...c];localStorage.setItem(s.STORAGE_KEYS.RECENTLY_VIEWED_COLLECTION,JSON.stringify(d))}_renderTab(t){Promise.all([(customElements.whenDefined("sl-tab-group"),customElements.whenDefined("sl-tab-panel"),customElements.whenDefined("sl-tab"))]).then(()=>{this.tabGroup.show(t||i.tabId)})}_renderSubTab(t){const o=s.DRAWER_IDS[t];if(!o)return;const r=this.shadowRoot.querySelector(o);r&&(r.open=!0,navigator.userAgent.indexOf("iPhone")>-1&&setTimeout(()=>{this.drawer.classList.add("inner-drawer-open")},150))}async updateContent(t=[]){const o=this.getAttribute("data-section-id"),r=await this._fetchContent(o);t.forEach(e=>{const n=this.shadow.querySelector(e);if(n){const c=r.querySelector("#gw-customer-accounts-template").content.querySelector(e);n.innerHTML=c.innerHTML}})}async _fetchContent(t){const r=await(await fetch(window.location.pathname+`?section_id=${t}`)).text();return new DOMParser().parseFromString(r,"text/html")}async updateFavoriteItemsStorage(t){const{removeIds:o,addIds:r}=t||{};let e=!1;if(r!=null&&r.length&&(i.addToStorage({key:s.STORAGE_KEYS.WISHLIST_PRODUCT_IDS,values:r,storageType:"session"}),e=!0),o!=null&&o.length&&(i.removeFromStorage({key:s.STORAGE_KEYS.WISHLIST_PRODUCT_IDS,values:o,storageType:"session"}),e=!0),e){this.dispatchEvent(new CustomEvent(s.CUSTOM_EVENTS.FAVORITES_STORAGE_UPDATED));return}try{const n=await i.request(s.ENDPOINTS.FAVORITES.GET_ALL_IDS,{customerID:i.customerId},"GET");if(n.error)throw new Error(n.error);sessionStorage.setItem(s.STORAGE_KEYS.WISHLIST_PRODUCT_IDS,JSON.stringify(n.products)),this.dispatchEvent(new CustomEvent(s.CUSTOM_EVENTS.FAVORITES_STORAGE_UPDATED))}catch(n){console.error("Error initializing wishlist:",n)}}async _checkCustomerStatus(){const t=i.customerToken,{id_sha256:o,email:r,tags:e,id:n}=i.componentData.customer;if(!t&&n)try{const a=await i.request(s.ENDPOINTS.AUTH.GET_TOKEN,{customerEmail:r,encode:o},"POST");if(a.error)throw new Error(a.error);a.token&&(localStorage.setItem(s.STORAGE_KEYS.TOKEN,a.token),localStorage.setItem(s.STORAGE_KEYS.EMAIL,r))}catch(a){console.error("Error checking customer status:",a)}if(e&&!e.includes("gw-customer"))try{const a=await i.request(s.ENDPOINTS.AUTH.CUSTOMER_LOGGED,{});if(a.error)throw new Error(a.error)}catch(a){console.error("Error checking customer status:",a)}}async _saveTempWishlistProducts(){var r;const t=JSON.parse(localStorage.getItem(s.STORAGE_KEYS.TEMP_WISHLIST_PRODUCTS));if(!(t!=null&&t.length))return;const o={products:t.map(e=>{const{id:n,variantId:a}=e;return{prodID:n,varID:a}})};try{const e=await i.request(s.ENDPOINTS.FAVORITES.ADD_BULK,o);if(e.error)throw new Error(e.error);localStorage.removeItem(s.STORAGE_KEYS.TEMP_WISHLIST_PRODUCTS),(r=e.products)!=null&&r.length&&(sessionStorage.setItem(s.STORAGE_KEYS.WISHLIST_PRODUCT_IDS,JSON.stringify(e.products)),this.dispatchEvent(new CustomEvent(s.CUSTOM_EVENTS.FAVORITES_STORAGE_UPDATED))),i.dashboard.loadFavoriteItems()}catch(e){console.error("Error saving temp wishlist products:",e)}}async _saveTempCartProducts(){const t=JSON.parse(localStorage.getItem(s.STORAGE_KEYS.TEMP_CART_PRODUCTS));if(!(t!=null&&t.length))return;const o={products:t.map(r=>{const{id:e,variantId:n}=r;return{prodID:e,varID:n}})};try{const r=await i.request(s.ENDPOINTS.CART.ADD_BULK,o);if(r.error)throw new Error(r.error);localStorage.removeItem(s.STORAGE_KEYS.TEMP_CART_PRODUCTS),i.dashboard.loadSavedCartItems()}catch(r){console.error("Error saving temp cart products:",r)}}async _saveTempRecentlyViewedProducts(){const t=JSON.parse(localStorage.getItem(s.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS));if(!(t!=null&&t.length))return;const o={products:t.map(r=>{const{id:e}=r;return{prodID:e}})};try{const r=await i.request(s.ENDPOINTS.VIEWED_PRODUCTS.ADD_BULK,o);if(r.error)throw new Error(r.error);localStorage.removeItem(s.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS),console.log("Saved temp recently viewed products:",r),i.dashboard.loadRecentlyViewedItems()}catch(r){console.error("Error saving temp recently viewed products:",r)}}async _watchSavedItemsFromCart(){this.addEventListener(s.CUSTOM_EVENTS.SAVED_ITEMS_FROM_CART,async t=>{i.hasCustomer?await this._handleAuthedCartEvent(t):this._handleGuestCartEvent(t)})}async _handleGuestCartEvent(t){const o=t.detail.extra,r=o.handle,e={};try{const n=await fetch(`/products/${r}.js`);if(!n.ok)throw new Error("Product not found");const a=await n.json();e.variant_id=o.variant_id,e.featuredImage=o.featured_image,e.title=o.title,e.variants={},e.variants.nodes=a.variants,e.id=a.id,e.tags=a.tags,e.handle=a.handle;const d=(JSON.parse(localStorage.getItem(s.STORAGE_KEYS.TEMP_CART_PRODUCTS))||[]).filter(u=>u.id!==a.id),l=[e,...d];localStorage.setItem(s.STORAGE_KEYS.TEMP_CART_PRODUCTS,JSON.stringify(l)),i.dashboard.loadSavedCartItems()}catch(n){console.error("Error adding product to cart:",n)}}async _handleAuthedCartEvent(t){try{const{productId:o,variantId:r}=t.detail||{};if(!o||!r)return;const e=await i.request(s.ENDPOINTS.CART.ADD,{prodID:o,varID:r});if(e.error)throw new Error(e.error);i.dashboard.loadSavedCartItems()}catch(o){console.error("Error adding product to cart:",o)}}async _syncTempProducts(){const t=[s.STORAGE_KEYS.TEMP_WISHLIST_PRODUCTS,s.STORAGE_KEYS.TEMP_CART_PRODUCTS,s.STORAGE_KEYS.TEMP_RECENTLY_VIEWED_ITEMS],o=t.flatMap(a=>(JSON.parse(localStorage.getItem(a))||[]).filter(Boolean)),r=[...new Map(o.map(a=>[a.id,a])).values()];console.log("Unique products:",r);const n=(await Promise.all(r.map(async({id:a,handle:c})=>{try{const d=await fetch(`/products/${c}.js`);return d.ok?await d.json():null}catch{return null}}))).reduce((a,c)=>(c&&c.available&&(a[c.id]=c),a),{});t.forEach(a=>{const d=(JSON.parse(localStorage.getItem(a))||[]).map(l=>{if(!l)return null;const u=n[l.id];return u?(l.variants.nodes=u.variants,l):null}).filter(Boolean);localStorage.setItem(a,JSON.stringify(d))}),sessionStorage.setItem(s.STORAGE_KEYS.TEMP_PRODUCTS_UPDATED,"true")}});
@@ -1 +1 @@
1
- import{G as o,a as s}from"./assets/index-DkUQsudo.js";customElements.define("gw-malomo-button",class extends HTMLElement{constructor(){super(),this.trackingPageUrl=this.getAttribute("tracking-page-url"),this.orderId=this.getAttribute("order-id")}connectedCallback(){this._initMalomoButton()}async _initMalomoButton(){var r;const t=await o.request(s.ENDPOINTS.MISC.GET_MALOMO_ORDER,{orderID:this.orderId});if(t.error){console.error(t.error);return}if((r=t.order)!=null&&r.url){const e=this.querySelector("a");e.href=t.order.url}else this.remove()}});
1
+ import{G as o,a as s}from"./assets/index-CS0ypOUL.js";customElements.define("gw-malomo-button",class extends HTMLElement{constructor(){super(),this.trackingPageUrl=this.getAttribute("tracking-page-url"),this.orderId=this.getAttribute("order-id")}connectedCallback(){this._initMalomoButton()}async _initMalomoButton(){var r;const t=await o.request(s.ENDPOINTS.MISC.GET_MALOMO_ORDER,{orderID:this.orderId});if(t.error){console.error(t.error);return}if((r=t.order)!=null&&r.url){const e=this.querySelector("a");e.href=t.order.url}else this.remove()}});
package/dist/orders.js CHANGED
@@ -1 +1 @@
1
- import{G as c}from"./assets/tab-D4kkRiyw.js";import"./assets/index-DkUQsudo.js";customElements.define("gw-customer-accounts-orders",class extends c{constructor(){super()}connectedCallback(){super.connectedCallback()}});
1
+ import{G as c}from"./assets/tab-vXz_-2og.js";import"./assets/index-CS0ypOUL.js";customElements.define("gw-customer-accounts-orders",class extends c{constructor(){super()}connectedCallback(){super.connectedCallback()}});
@@ -1 +1 @@
1
- import{G as a,a as o}from"./assets/index-DkUQsudo.js";customElements.define("gw-preferences-form",class extends HTMLElement{constructor(){super(),this.form=this.querySelector("form")}connectedCallback(){this._handleFormSubmit()}async _handleFormSubmit(){await Promise.all([customElements.whenDefined("sl-input")]).then(()=>{this.form.addEventListener("sl-invalid",e=>{e.preventDefault(),this._clearErrorMessages(),this.form.querySelectorAll("sl-input").forEach(r=>{if(r.hasAttribute("data-invalid")){const t=document.createElement("div");t.slot="help-text",t.classList.add("gw-error-message"),t.textContent=r.validationMessage,r.appendChild(t)}})},{capture:!0}),this.form.addEventListener("submit",e=>{e.preventDefault();const r=new FormData(this.form),t=Object.fromEntries(r.entries());this._submitPreferencesForm(t)})})}async _submitPreferencesForm(e){try{this._clearErrorMessages(),this.form.querySelector("[data-loader]").hidden=!1;let r=await a.request(o.ENDPOINTS.CUSTOMER.UPDATE,e);if(r.error)throw new Error(r.error);this.form.closest("sl-drawer").hide(),a.updateAjaxContent(["[data-main-drawer-label]","[data-my-preference-fields]"])}catch(r){this._handleErrors(r)}finally{this.form.querySelector("[data-loader]").hidden=!0}}_clearErrorMessages(){this.form.querySelectorAll(".gw-error-message").forEach(e=>e.remove())}_handleErrors(e){e.message.includes("valid phone number")&&this._displayErrorMessage('[name="phone"]',e.message)}_displayErrorMessage(e,r){let t=e;typeof e=="string"&&(t=this.form.querySelector(e));const s=document.createElement("div");s.slot="help-text",s.classList.add("gw-error-message"),s.textContent=r,t.appendChild(s),t.focus()}});
1
+ import{G as a,a as o}from"./assets/index-CS0ypOUL.js";customElements.define("gw-preferences-form",class extends HTMLElement{constructor(){super(),this.form=this.querySelector("form")}connectedCallback(){this._handleFormSubmit()}async _handleFormSubmit(){await Promise.all([customElements.whenDefined("sl-input")]).then(()=>{this.form.addEventListener("sl-invalid",e=>{e.preventDefault(),this._clearErrorMessages(),this.form.querySelectorAll("sl-input").forEach(r=>{if(r.hasAttribute("data-invalid")){const t=document.createElement("div");t.slot="help-text",t.classList.add("gw-error-message"),t.textContent=r.validationMessage,r.appendChild(t)}})},{capture:!0}),this.form.addEventListener("submit",e=>{e.preventDefault();const r=new FormData(this.form),t=Object.fromEntries(r.entries());this._submitPreferencesForm(t)})})}async _submitPreferencesForm(e){try{this._clearErrorMessages(),this.form.querySelector("[data-loader]").hidden=!1;let r=await a.request(o.ENDPOINTS.CUSTOMER.UPDATE,e);if(r.error)throw new Error(r.error);this.form.closest("sl-drawer").hide(),a.updateAjaxContent(["[data-main-drawer-label]","[data-my-preference-fields]"])}catch(r){this._handleErrors(r)}finally{this.form.querySelector("[data-loader]").hidden=!0}}_clearErrorMessages(){this.form.querySelectorAll(".gw-error-message").forEach(e=>e.remove())}_handleErrors(e){e.message.includes("valid phone number")&&this._displayErrorMessage('[name="phone"]',e.message)}_displayErrorMessage(e,r){let t=e;typeof e=="string"&&(t=this.form.querySelector(e));const s=document.createElement("div");s.slot="help-text",s.classList.add("gw-error-message"),s.textContent=r,t.appendChild(s),t.focus()}});
package/dist/profile.js CHANGED
@@ -1 +1 @@
1
- import{a as t}from"./assets/index-DkUQsudo.js";import{G as c}from"./assets/tab-D4kkRiyw.js";customElements.define("gw-customer-accounts-profile",class extends c{constructor(){super()}connectedCallback(){var e;super.connectedCallback(),(e=this.querySelector("[data-logout-button]"))==null||e.addEventListener("click",function(o){o.preventDefault(),this.querySelector("[data-loader]").hidden=!1,localStorage.removeItem(t.STORAGE_KEYS.TOKEN),localStorage.removeItem(t.STORAGE_KEYS.EMAIL),document.dispatchEvent(new CustomEvent("gw-customer-accounts:logout")),window.location.href="/account/logout"})}});
1
+ import{a as t}from"./assets/index-CS0ypOUL.js";import{G as c}from"./assets/tab-vXz_-2og.js";customElements.define("gw-customer-accounts-profile",class extends c{constructor(){super()}connectedCallback(){var e;super.connectedCallback(),(e=this.querySelector("[data-logout-button]"))==null||e.addEventListener("click",function(o){o.preventDefault(),this.querySelector("[data-loader]").hidden=!1,localStorage.removeItem(t.STORAGE_KEYS.TOKEN),localStorage.removeItem(t.STORAGE_KEYS.EMAIL),document.dispatchEvent(new CustomEvent("gw-customer-accounts:logout")),window.location.href="/account/logout"})}});
@@ -1,4 +1,4 @@
1
- import{G as a,a as d}from"./assets/index-DkUQsudo.js";customElements.define("gw-quick-add-to-cart-form",class extends HTMLElement{constructor(){super(),this.form=this.querySelector("form"),this.productId=this.getAttribute("product-id")}connectedCallback(){this.form.addEventListener("submit",async e=>{e.preventDefault(),this._handleFormSubmit()}),this.addEventListener("click",e=>{e.target.matches("[data-wishlist-remove]")&&this.closest(".gw-product-card").querySelector("gw-wishlist-button").dispatchEvent(new Event("click")),e.target.matches("[data-saved-from-cart-remove]")&&this._handleRemoveFromSavedItems()})}async _handleFormSubmit(){this.form.querySelector("[data-loader]").hidden=!1;const r={method:"POST",body:new FormData(this.form),headers:{Accept:"application/javascript"}};try{const t=await fetch(routes.cart_add_url,r);if(t.error)throw new Error(t.error);const s=[await t.json()];document.dispatchEvent(new CustomEvent("CART_UPDATED",{detail:{added:s}})),a.notify(`
1
+ import{G as a,a as d}from"./assets/index-CS0ypOUL.js";customElements.define("gw-quick-add-to-cart-form",class extends HTMLElement{constructor(){super(),this.form=this.querySelector("form"),this.productId=this.getAttribute("product-id")}connectedCallback(){this.form.addEventListener("submit",async e=>{e.preventDefault(),this._handleFormSubmit()}),this.addEventListener("click",e=>{e.target.matches("[data-wishlist-remove]")&&this.closest(".gw-product-card").querySelector("gw-wishlist-button").dispatchEvent(new Event("click")),e.target.matches("[data-saved-from-cart-remove]")&&this._handleRemoveFromSavedItems()})}async _handleFormSubmit(){this.form.querySelector("[data-loader]").hidden=!1;const r={method:"POST",body:new FormData(this.form),headers:{Accept:"application/javascript"}};try{const t=await fetch(routes.cart_add_url,r);if(t.error)throw new Error(t.error);const s=[await t.json()];document.dispatchEvent(new CustomEvent("CART_UPDATED",{detail:{added:s}})),a.notify(`
2
2
  <span>Product added to cart</span>
3
3
  <a href="/cart" class="gw-notification__link">View</a>
4
4
  `)}catch(t){console.error(t)}finally{if(this.form.querySelector("[data-loader]").hidden=!0,!this.closest("[data-favorites-drawer-container]"))return;const t=this.form.querySelector('[name="productId"]').value,o=this.form.querySelector('[name="id"]').value;if(!t||!o)return;const s=new CustomEvent(d.CUSTOM_EVENTS.SAVED_ITEMS_FROM_CART,{detail:{productId:t,variantId:o,target:this}});a.app.dispatchEvent(s)}}async _handleRemoveFromSavedItems(){if(!a.hasCustomer){const r=this.form.querySelector('[name="productId"]').value,o=(JSON.parse(localStorage.getItem(d.STORAGE_KEYS.TEMP_CART_PRODUCTS))||[]).filter(s=>s.id!=r);localStorage.setItem(d.STORAGE_KEYS.TEMP_CART_PRODUCTS,JSON.stringify(o)),a.dashboard.loadSavedCartItems();return}this.form.closest(".gw-product-card").classList.add("gw-product-card--removing");const e={prodID:this.form.querySelector('[name="productId"]').value};try{const r=await a.request(d.ENDPOINTS.CART.REMOVE,e);if(r.error)throw new Error(r.error);await a.dashboard.loadSavedCartItems()}catch(r){console.error(r)}}});
package/dist/sign-in.js CHANGED
@@ -1 +1 @@
1
- import{G as l,a as c}from"./assets/index-DkUQsudo.js";customElements.define("gw-customer-accounts-sign-in",class extends HTMLElement{constructor(){super(),this.signInType=this.getAttribute("type"),this.signInBlock=this.querySelector("[data-sign-in-block]"),this.signInType!=="password"&&(this.verifyCodeBlock=this.querySelector("[data-verify-code-block]"),this.tryAnotherEmailButton=this.querySelector("[data-try-another-email]"),this.sendAnotherCodeButton=this.querySelector("[data-send-another-code]"),this.inputtedEmail="",this.inputtedCode="")}connectedCallback(){this.signInType==="password"?this._setupPasswordBasedAuth():this._setupEmailBasedAuth()}_setupPasswordBasedAuth(){const i={signIn:this.querySelector("[data-sign-in-form]"),registration:this.querySelector("[data-registeration-form]"),forgotPassword:this.querySelector("[data-forgot-password-form]")},e={signIn:this.querySelectorAll("[data-sign-in-link]"),createAccount:this.querySelectorAll("[data-create-account-link]"),forgotPassword:this.querySelectorAll("[data-forgot-password-link]")};this._setupFormNavigation(e,i),this._setupFormSubmissions(Object.values(i)),this._handleFormVisibility(i)}_handleFormVisibility(i){const t=new URLSearchParams(window.location.search).get("form_id");t&&Object.values(i).forEach(r=>{const s=r.querySelector(".gw-error-message");t===r.getAttribute("id")?(r&&r.removeAttribute("hidden"),s&&s.removeAttribute("hidden"),t==="recover_customer"&&this._showPasswordResetMessage(r),t==="customer_login"&&this._showLoginErrorMessage(r)):(r&&r.setAttribute("hidden",""),s&&s.setAttribute("hidden",""))})}_showPasswordResetMessage(i){const e=i.querySelector("[data-forgot-password-error-message]"),t=i.querySelector('input[type="email"]');e&&(e.textContent="We've sent you an email to reset your password.",e.id||(e.id="forgot-password-success-message")),t&&e&&(t.setAttribute("aria-describedby",e.id),t.focus());const r=i.querySelector("[data-forgot-password-subtext]");r&&r.remove()}_showLoginErrorMessage(i){const e=i.querySelector("[data-login-error-message]"),t=i.querySelector('sl-input[type="email"]'),r=i.querySelector('sl-input[type="password"]');if(e&&(e.textContent="The email or password you entered is incorrect. Please try again.",e.id||(e.id="login-error-message")),t&&e&&(t.setAttribute("aria-describedby",e.id),setTimeout(()=>{t!=null&&t.input&&(t==null||t.input.setAttribute("aria-describedby",e.id))},500)),r&&e){const o=r.getAttribute("aria-describedby");o?r.setAttribute("aria-describedby",o+" "+e.id):r.setAttribute("aria-describedby",e.id),setTimeout(()=>{r!=null&&r.input&&(r==null||r.input.setAttribute("aria-describedby",e.id))},500)}this.closest("[main-drawer]").addEventListener("sl-initial-focus",o=>{o.preventDefault(),t&&(setTimeout(()=>{t.focus()},500),window.addEventListener("load",()=>{t&&setTimeout(()=>{t.focus()},500)}))})}_setupFormNavigation(i,e){const t=s=>{Object.values(e).forEach(o=>{o.setAttribute("hidden","")}),s.removeAttribute("hidden"),setTimeout(()=>{const o=s.querySelector("[data-form-title]");o&&o.focus()},150)},r=()=>{const s=new URL(window.location.href);s.searchParams.delete("form_id"),window.history.replaceState({},"",s.toString())};i.createAccount.forEach(s=>{s.addEventListener("click",()=>{t(e.registration),r()})}),i.forgotPassword.forEach(s=>{s.addEventListener("click",()=>{t(e.forgotPassword),r()})}),i.signIn.forEach(s=>{s.addEventListener("click",()=>{t(e.signIn),r()})})}_setupFormSubmissions(i){i.forEach(e=>{const t=new URL(window.location.href);t.searchParams.forEach((o,a)=>{t.searchParams.delete(a)}),t.searchParams.append("my-account-open",!0),t.searchParams.append("form_id",e.getAttribute("id"));const r=e.querySelector('input[name="return_to"]'),s=e.querySelector('input[name="return_url"]');r&&(r.value=t.pathname+t.search),s&&(s.value=t.pathname+t.search),e.addEventListener("submit",o=>{o.preventDefault(),e.querySelectorAll('button[type="submit"]').forEach(a=>{a.disabled=!0;const n=a.querySelector("[data-loader]");n&&(n.hidden=!1)}),Shopify.captcha.protect(e,()=>{e.submit()})})})}_setupEmailBasedAuth(){this._handleEmailSubmitForm(),this._handleInputCodeGroup(),this.tryAnotherEmailButton.addEventListener("click",()=>{this._resetToEmailInput()}),this.sendAnotherCodeButton.addEventListener("click",()=>{this._resendVerificationCode()})}_resetToEmailInput(){this.signInBlock.removeAttribute("hidden"),this.verifyCodeBlock.setAttribute("hidden","");const i=this.signInBlock.querySelector("sl-input");i.value="",i.focus(),this.inputtedEmail="",this.inputtedCode="",this.acceptsMarketing=!1}_resendVerificationCode(){this._submitEmailForm(this.querySelector("[data-sign-in-form]")),l.notify("Another code has been sent to your email.")}async _handleEmailSubmitForm(){await Promise.all([customElements.whenDefined("sl-input")]).then(()=>{const i=this.querySelector("[data-sign-in-form]"),e=this.querySelector("[data-email-error]");i.addEventListener("sl-invalid",t=>{t.preventDefault(),e.textContent=t.target.validationMessage,e.hidden=!1,t.target.focus()},{capture:!0}),i.addEventListener("submit",t=>{t.preventDefault(),e.hidden=!0,e.textContent="",this._submitEmailForm(i).then(()=>{const r=this.verifyCodeBlock.querySelector(".code-input");r&&r.focus()})})})}async _submitEmailForm(i){const e=i.querySelector('button[type="submit"]');e.disabled=!0,e.querySelector("[data-loader]").hidden=!1;const t=new FormData(i);this.inputtedEmail=t.get("email"),t.has("accepts_marketing")&&(this.acceptsMarketing=t.get("accepts_marketing"));let r="";const s=await this._fetchCaptchaToken();s&&(r=s);try{const o=await this._request({customerEmail:this.inputtedEmail,token:r},c.ENDPOINTS.AUTH.SIGN_IN);if(o.error){console.error(o.error);return}const a=this.querySelector("[data-code-sent-to]");return a&&(a.textContent=this.inputtedEmail),this.signInBlock.setAttribute("hidden",""),this.verifyCodeBlock.removeAttribute("hidden"),o}catch(o){console.error(o),alert("An error occurred. Please try again later.")}finally{e.disabled=!1,e.querySelector("[data-loader]").hidden=!0}}async _submitVerificationCode(){var o,a;const i=this.querySelector(".gw-verify-code__actions"),e=i.querySelectorAll("button, a"),t=i.querySelector("[data-verify-error]"),r=i.querySelector("[data-loader]"),s=this.querySelectorAll("input.code-input");try{s.forEach(u=>{u.disabled=!0}),e.forEach(u=>{u.disabled=!0,u.hidden=!0}),t.hidden=!0,r.hidden=!1;const n=await this._request({customerEmail:this.inputtedEmail,code:this.inputtedCode,is_marketing:this.acceptsMarketing},c.ENDPOINTS.AUTH.VERIFY_CODE);if(!n.url)throw new Error("Verification failed");localStorage.setItem(c.STORAGE_KEYS.TOKEN,n.token),localStorage.setItem(c.STORAGE_KEYS.EMAIL,this.inputtedEmail);const d=await fetch(n.url);if(d.error)throw new Error(d.error);const p=await(await fetch(window.location.href)).text(),h=new DOMParser().parseFromString(p,"text/html"),m=(a=(o=h.querySelector("#gw-customer-accounts-template").content)==null?void 0:o.querySelector("gw-integrations-loyalty-points"))==null?void 0:a.getAttribute("page-url");document.documentElement.innerHTML=h.documentElement.innerHTML,document.dispatchEvent(new CustomEvent("gw-customer-accounts:login"));const f=sessionStorage.getItem(c.STORAGE_KEYS.REDIRECT_URL);if(f&&(sessionStorage.removeItem(c.STORAGE_KEYS.REDIRECT_URL),window.location.href=f),!m)return;window.location.pathname.includes(m)&&window.location.reload()}catch(n){console.error(n),setTimeout(()=>{s[s.length-1].focus()})}finally{s.forEach(n=>{n.disabled=!1}),e.forEach(n=>{n.disabled=!1,n.hidden=!1}),t.hidden=!1,r.hidden=!0}}async _request(i,e,t="POST"){return await(await fetch(l.baseURL+e,{method:t,body:JSON.stringify(i),mode:"cors",cache:"no-cache",headers:{"Content-Type":"application/json"}})).json()}_handleInputCodeGroup(){const i=[...this.querySelectorAll("input.code-input")];i.forEach((e,t)=>{e.addEventListener("keydown",r=>{(r.ctrlKey||r.metaKey)&&r.keyCode===86||(r.keyCode!==8&&(r.keyCode<48||r.keyCode>57)&&r.preventDefault(),r.keyCode===8&&r.target.value===""&&i[Math.max(0,t-1)].focus())}),e.addEventListener("input",r=>{const[s,...o]=r.target.value;r.target.value=s??"";const a=t===i.length-1,n=s!==void 0;n&&!a&&(i[t+1].focus(),i[t+1].value=o.join(""),i[t+1].dispatchEvent(new Event("input"))),n&&a&&i.every(d=>d.value)&&(this.inputtedCode=i.map(d=>d.value).join(""),this._submitVerificationCode())})})}async _fetchCaptchaToken(){const e=await(await fetch(l.baseURL+c.ENDPOINTS.AUTH.GET_CAPTCHA_TOKEN)).json();return e==null?void 0:e.token}});
1
+ import{G as l,a as c}from"./assets/index-CS0ypOUL.js";customElements.define("gw-customer-accounts-sign-in",class extends HTMLElement{constructor(){super(),this.signInType=this.getAttribute("type"),this.signInBlock=this.querySelector("[data-sign-in-block]"),this.signInType!=="password"&&(this.verifyCodeBlock=this.querySelector("[data-verify-code-block]"),this.tryAnotherEmailButton=this.querySelector("[data-try-another-email]"),this.sendAnotherCodeButton=this.querySelector("[data-send-another-code]"),this.inputtedEmail="",this.inputtedCode="")}connectedCallback(){this.signInType==="password"?this._setupPasswordBasedAuth():this._setupEmailBasedAuth()}_setupPasswordBasedAuth(){const i={signIn:this.querySelector("[data-sign-in-form]"),registration:this.querySelector("[data-registeration-form]"),forgotPassword:this.querySelector("[data-forgot-password-form]")},e={signIn:this.querySelectorAll("[data-sign-in-link]"),createAccount:this.querySelectorAll("[data-create-account-link]"),forgotPassword:this.querySelectorAll("[data-forgot-password-link]")};this._setupFormNavigation(e,i),this._setupFormSubmissions(Object.values(i)),this._handleFormVisibility(i)}_handleFormVisibility(i){const t=new URLSearchParams(window.location.search).get("form_id");t&&Object.values(i).forEach(r=>{const s=r.querySelector(".gw-error-message");t===r.getAttribute("id")?(r&&r.removeAttribute("hidden"),s&&s.removeAttribute("hidden"),t==="recover_customer"&&this._showPasswordResetMessage(r),t==="customer_login"&&this._showLoginErrorMessage(r)):(r&&r.setAttribute("hidden",""),s&&s.setAttribute("hidden",""))})}_showPasswordResetMessage(i){const e=i.querySelector("[data-forgot-password-error-message]"),t=i.querySelector('input[type="email"]');e&&(e.textContent="We've sent you an email to reset your password.",e.id||(e.id="forgot-password-success-message")),t&&e&&(t.setAttribute("aria-describedby",e.id),t.focus());const r=i.querySelector("[data-forgot-password-subtext]");r&&r.remove()}_showLoginErrorMessage(i){const e=i.querySelector("[data-login-error-message]"),t=i.querySelector('sl-input[type="email"]'),r=i.querySelector('sl-input[type="password"]');if(e&&(e.textContent="The email or password you entered is incorrect. Please try again.",e.id||(e.id="login-error-message")),t&&e&&(t.setAttribute("aria-describedby",e.id),setTimeout(()=>{t!=null&&t.input&&(t==null||t.input.setAttribute("aria-describedby",e.id))},500)),r&&e){const o=r.getAttribute("aria-describedby");o?r.setAttribute("aria-describedby",o+" "+e.id):r.setAttribute("aria-describedby",e.id),setTimeout(()=>{r!=null&&r.input&&(r==null||r.input.setAttribute("aria-describedby",e.id))},500)}this.closest("[main-drawer]").addEventListener("sl-initial-focus",o=>{o.preventDefault(),t&&(setTimeout(()=>{t.focus()},500),window.addEventListener("load",()=>{t&&setTimeout(()=>{t.focus()},500)}))})}_setupFormNavigation(i,e){const t=s=>{Object.values(e).forEach(o=>{o.setAttribute("hidden","")}),s.removeAttribute("hidden"),setTimeout(()=>{const o=s.querySelector("[data-form-title]");o&&o.focus()},150)},r=()=>{const s=new URL(window.location.href);s.searchParams.delete("form_id"),window.history.replaceState({},"",s.toString())};i.createAccount.forEach(s=>{s.addEventListener("click",()=>{t(e.registration),r()})}),i.forgotPassword.forEach(s=>{s.addEventListener("click",()=>{t(e.forgotPassword),r()})}),i.signIn.forEach(s=>{s.addEventListener("click",()=>{t(e.signIn),r()})})}_setupFormSubmissions(i){i.forEach(e=>{const t=new URL(window.location.href);t.searchParams.forEach((o,a)=>{t.searchParams.delete(a)}),t.searchParams.append("my-account-open",!0),t.searchParams.append("form_id",e.getAttribute("id"));const r=e.querySelector('input[name="return_to"]'),s=e.querySelector('input[name="return_url"]');r&&(r.value=t.pathname+t.search),s&&(s.value=t.pathname+t.search),e.addEventListener("submit",o=>{o.preventDefault(),e.querySelectorAll('button[type="submit"]').forEach(a=>{a.disabled=!0;const n=a.querySelector("[data-loader]");n&&(n.hidden=!1)}),Shopify.captcha.protect(e,()=>{e.submit()})})})}_setupEmailBasedAuth(){this._handleEmailSubmitForm(),this._handleInputCodeGroup(),this.tryAnotherEmailButton.addEventListener("click",()=>{this._resetToEmailInput()}),this.sendAnotherCodeButton.addEventListener("click",()=>{this._resendVerificationCode()})}_resetToEmailInput(){this.signInBlock.removeAttribute("hidden"),this.verifyCodeBlock.setAttribute("hidden","");const i=this.signInBlock.querySelector("sl-input");i.value="",i.focus(),this.inputtedEmail="",this.inputtedCode="",this.acceptsMarketing=!1}_resendVerificationCode(){this._submitEmailForm(this.querySelector("[data-sign-in-form]")),l.notify("Another code has been sent to your email.")}async _handleEmailSubmitForm(){await Promise.all([customElements.whenDefined("sl-input")]).then(()=>{const i=this.querySelector("[data-sign-in-form]"),e=this.querySelector("[data-email-error]");i.addEventListener("sl-invalid",t=>{t.preventDefault(),e.textContent=t.target.validationMessage,e.hidden=!1,t.target.focus()},{capture:!0}),i.addEventListener("submit",t=>{t.preventDefault(),e.hidden=!0,e.textContent="",this._submitEmailForm(i).then(()=>{const r=this.verifyCodeBlock.querySelector(".code-input");r&&r.focus()})})})}async _submitEmailForm(i){const e=i.querySelector('button[type="submit"]');e.disabled=!0,e.querySelector("[data-loader]").hidden=!1;const t=new FormData(i);this.inputtedEmail=t.get("email"),t.has("accepts_marketing")&&(this.acceptsMarketing=t.get("accepts_marketing"));let r="";const s=await this._fetchCaptchaToken();s&&(r=s);try{const o=await this._request({customerEmail:this.inputtedEmail,token:r},c.ENDPOINTS.AUTH.SIGN_IN);if(o.error){console.error(o.error);return}const a=this.querySelector("[data-code-sent-to]");return a&&(a.textContent=this.inputtedEmail),this.signInBlock.setAttribute("hidden",""),this.verifyCodeBlock.removeAttribute("hidden"),o}catch(o){console.error(o),alert("An error occurred. Please try again later.")}finally{e.disabled=!1,e.querySelector("[data-loader]").hidden=!0}}async _submitVerificationCode(){var o,a;const i=this.querySelector(".gw-verify-code__actions"),e=i.querySelectorAll("button, a"),t=i.querySelector("[data-verify-error]"),r=i.querySelector("[data-loader]"),s=this.querySelectorAll("input.code-input");try{s.forEach(u=>{u.disabled=!0}),e.forEach(u=>{u.disabled=!0,u.hidden=!0}),t.hidden=!0,r.hidden=!1;const n=await this._request({customerEmail:this.inputtedEmail,code:this.inputtedCode,is_marketing:this.acceptsMarketing},c.ENDPOINTS.AUTH.VERIFY_CODE);if(!n.url)throw new Error("Verification failed");localStorage.setItem(c.STORAGE_KEYS.TOKEN,n.token),localStorage.setItem(c.STORAGE_KEYS.EMAIL,this.inputtedEmail);const d=await fetch(n.url);if(d.error)throw new Error(d.error);const p=await(await fetch(window.location.href)).text(),h=new DOMParser().parseFromString(p,"text/html"),m=(a=(o=h.querySelector("#gw-customer-accounts-template").content)==null?void 0:o.querySelector("gw-integrations-loyalty-points"))==null?void 0:a.getAttribute("page-url");document.documentElement.innerHTML=h.documentElement.innerHTML,document.dispatchEvent(new CustomEvent("gw-customer-accounts:login"));const f=sessionStorage.getItem(c.STORAGE_KEYS.REDIRECT_URL);if(f&&(sessionStorage.removeItem(c.STORAGE_KEYS.REDIRECT_URL),window.location.href=f),!m)return;window.location.pathname.includes(m)&&window.location.reload()}catch(n){console.error(n),setTimeout(()=>{s[s.length-1].focus()})}finally{s.forEach(n=>{n.disabled=!1}),e.forEach(n=>{n.disabled=!1,n.hidden=!1}),t.hidden=!1,r.hidden=!0}}async _request(i,e,t="POST"){return await(await fetch(l.baseURL+e,{method:t,body:JSON.stringify(i),mode:"cors",cache:"no-cache",headers:{"Content-Type":"application/json"}})).json()}_handleInputCodeGroup(){const i=[...this.querySelectorAll("input.code-input")];i.forEach((e,t)=>{e.addEventListener("keydown",r=>{(r.ctrlKey||r.metaKey)&&r.keyCode===86||(r.keyCode!==8&&(r.keyCode<48||r.keyCode>57)&&r.preventDefault(),r.keyCode===8&&r.target.value===""&&i[Math.max(0,t-1)].focus())}),e.addEventListener("input",r=>{const[s,...o]=r.target.value;r.target.value=s??"";const a=t===i.length-1,n=s!==void 0;n&&!a&&(i[t+1].focus(),i[t+1].value=o.join(""),i[t+1].dispatchEvent(new Event("input"))),n&&a&&i.every(d=>d.value)&&(this.inputtedCode=i.map(d=>d.value).join(""),this._submitVerificationCode())})})}async _fetchCaptchaToken(){const e=await(await fetch(l.baseURL+c.ENDPOINTS.AUTH.GET_CAPTCHA_TOKEN)).json();return e==null?void 0:e.token}});
@@ -1,4 +1,4 @@
1
- import{G as r,a}from"./assets/index-DkUQsudo.js";class u extends HTMLElement{constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}set variantId(t){this.setAttribute("variant-id",t)}get variantId(){return this.getAttribute("variant-id")}get productId(){return this.getAttribute("product-id")}get productImageUrl(){var t,e,o,s;return(e=(t=this.productData.featuredImage)==null?void 0:t.url)!=null&&e.includes("https:")?this.productData.featuredImage:{...this.productData.featuredImage,url:"https:"+((s=(o=this.productData)==null?void 0:o.featuredImage)==null?void 0:s.url)}}get productWishlistData(){return{variant_id:this._getVariantId(),product_id:this.productId,product_url:this.productData.url,product_image:this.productImageUrl,product_price:this.productData.price,product_title:this.productData.title,variant_title:this.currentVariant.title}}connectedCallback(){this.renderButton(),this.button=this.shadowRoot.querySelector("button"),this.loader=this.shadowRoot.querySelector("[data-loader]"),this.addEventListener("click",t=>this._handleFavoriteButtonClick(t)),this._activateButton(this._isProductInFavorites()),document.addEventListener("variant:change",({detail:{productId:t,variant:e}})=>{t!==this.productId||!e||(this.variantId=e.id)}),r.app.addEventListener(a.CUSTOM_EVENTS.FAVORITES_STORAGE_UPDATED,()=>{this._activateButton(this._isProductInFavorites())})}async _fetchAllWishlistItems(){if(!r.hasCustomer)return;const t=await r.request(a.ENDPOINTS.FAVORITES.GET,{customerID:r.customerId,limit:100},"GET");if(t.error)throw new Error(t.error);return t.products.map(o=>{var l,h,m,p;const s=((l=o==null?void 0:o.variants)==null?void 0:l.nodes.find(f=>f.id===(o==null?void 0:o.variant_id)))||((h=o==null?void 0:o.variants)==null?void 0:h.nodes[0]),i=(m=s==null?void 0:s.id)==null?void 0:m.split("/").pop(),d=s==null?void 0:s.price,n=s==null?void 0:s.compareAtPrice,c=o.id.split("/").pop();return{variant_id:i,product_id:c,title:o.title,variant_title:s==null?void 0:s.title,handle:o.handle,image:(p=o.featuredImage)==null?void 0:p.url,price:d,discounted_price:n,url:window.location.host+"/products/"+o.handle}})}async _addWishlistItemToKlaviyo(){if(!r.hasCustomer||typeof klaviyo>"u")return;const t=await this._fetchAllWishlistItems();console.debug("Adding wishlist item to Klaviyo",t);const e={email:r.customerEmail,wishlist_items:t};klaviyo.identify(e,()=>{console.debug("Wishlist item added to Klaviyo",this.productWishlistData),klaviyo.track("Added to Wishlist",this.productWishlistData)})}async _removeWishlistItemFromKlaviyo(){if(!r.hasCustomer||typeof klaviyo>"u")return;const t=await this._fetchAllWishlistItems();console.log("Removing wishlist item from Klaviyo",t);const e={email:r.customerEmail,wishlist_items:t};klaviyo.identify(e,()=>{console.log("Wishlist item removed from Klaviyo"),klaviyo.track("Removed from Wishlist",this.productWishlistData)})}log(t){const e="[GW_WISHLIST_BUTTON] Product ID: "+this.productId;console.log(e,t)}renderButton(){if(this.iconEl=this._createIcon("icon"),this.filledIconEl=this._createIcon("filled-icon"),this.hasAttribute("icon-only")){this.shadowRoot.innerHTML=`
1
+ import{G as r,a}from"./assets/index-CS0ypOUL.js";class u extends HTMLElement{constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}set variantId(t){this.setAttribute("variant-id",t)}get variantId(){return this.getAttribute("variant-id")}get productId(){return this.getAttribute("product-id")}get productImageUrl(){var t,e,o,s;return(e=(t=this.productData.featuredImage)==null?void 0:t.url)!=null&&e.includes("https:")?this.productData.featuredImage:{...this.productData.featuredImage,url:"https:"+((s=(o=this.productData)==null?void 0:o.featuredImage)==null?void 0:s.url)}}get productWishlistData(){return{variant_id:this._getVariantId(),product_id:this.productId,product_url:this.productData.url,product_image:this.productImageUrl,product_price:this.productData.price,product_title:this.productData.title,variant_title:this.currentVariant.title}}connectedCallback(){this.renderButton(),this.button=this.shadowRoot.querySelector("button"),this.loader=this.shadowRoot.querySelector("[data-loader]"),this.addEventListener("click",t=>this._handleFavoriteButtonClick(t)),this._activateButton(this._isProductInFavorites()),document.addEventListener("variant:change",({detail:{productId:t,variant:e}})=>{t!==this.productId||!e||(this.variantId=e.id)}),r.app.addEventListener(a.CUSTOM_EVENTS.FAVORITES_STORAGE_UPDATED,()=>{this._activateButton(this._isProductInFavorites())})}async _fetchAllWishlistItems(){if(!r.hasCustomer)return;const t=await r.request(a.ENDPOINTS.FAVORITES.GET,{customerID:r.customerId,limit:100},"GET");if(t.error)throw new Error(t.error);return t.products.map(o=>{var l,h,m,p;const s=((l=o==null?void 0:o.variants)==null?void 0:l.nodes.find(f=>f.id===(o==null?void 0:o.variant_id)))||((h=o==null?void 0:o.variants)==null?void 0:h.nodes[0]),i=(m=s==null?void 0:s.id)==null?void 0:m.split("/").pop(),d=s==null?void 0:s.price,n=s==null?void 0:s.compareAtPrice,c=o.id.split("/").pop();return{variant_id:i,product_id:c,title:o.title,variant_title:s==null?void 0:s.title,handle:o.handle,image:(p=o.featuredImage)==null?void 0:p.url,price:d,discounted_price:n,url:window.location.host+"/products/"+o.handle}})}async _addWishlistItemToKlaviyo(){if(!r.hasCustomer||typeof klaviyo>"u")return;const t=await this._fetchAllWishlistItems();console.debug("Adding wishlist item to Klaviyo",t);const e={email:r.customerEmail,wishlist_items:t};klaviyo.identify(e,()=>{console.debug("Wishlist item added to Klaviyo",this.productWishlistData),klaviyo.track("Added to Wishlist",this.productWishlistData)})}async _removeWishlistItemFromKlaviyo(){if(!r.hasCustomer||typeof klaviyo>"u")return;const t=await this._fetchAllWishlistItems();console.log("Removing wishlist item from Klaviyo",t);const e={email:r.customerEmail,wishlist_items:t};klaviyo.identify(e,()=>{console.log("Wishlist item removed from Klaviyo"),klaviyo.track("Removed from Wishlist",this.productWishlistData)})}log(t){const e="[GW_WISHLIST_BUTTON] Product ID: "+this.productId;console.log(e,t)}renderButton(){if(this.iconEl=this._createIcon("icon"),this.filledIconEl=this._createIcon("filled-icon"),this.hasAttribute("icon-only")){this.shadowRoot.innerHTML=`
2
2
  <button class="wishlist-button wishlist-button--icon-only" part="button">
3
3
  ${this.iconEl}
4
4
  ${this.filledIconEl}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gw-customer-accounts",
3
- "version": "1.5.2",
3
+ "version": "1.5.3",
4
4
  "description": "",
5
5
  "main": "gw-customer-accounts.js",
6
6
  "type": "module",
@@ -139,7 +139,7 @@ customElements.define(
139
139
  * @returns {Promise<Array>} - Array of saved cart items.
140
140
  */
141
141
  async _getSavedCartItems(page, limit) {
142
- if (!GWUtils.customerId) {
142
+ if (!GWUtils.hasCustomer) {
143
143
  // Not logged in — get from local storage.
144
144
  return (
145
145
  JSON.parse(
@@ -39,7 +39,7 @@ export class GWCustomerAccountsUtils {
39
39
  * @returns {string} - The customer's email address.
40
40
  */
41
41
  get customerEmail() {
42
- return localStorage.getItem(GWCA.STORAGE_KEYS.EMAIL);
42
+ return this.componentData?.customer?.email;
43
43
  }
44
44
 
45
45
  /**