gw-customer-accounts 1.3.5 → 1.3.7
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.
- package/dist/main.js +1 -1
- package/dist/sign-in.js +1 -1
- package/package.json +1 -1
- package/src/scripts/components/sign-in.js +9 -1
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="",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-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")}});
|
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 t={signIn:this.querySelector("[data-sign-in-form]"),registration:this.querySelector("[data-registeration-form]"),forgotPassword:this.querySelector("[data-forgot-password-form]")},r={signIn:this.querySelectorAll("[data-sign-in-link]"),createAccount:this.querySelectorAll("[data-create-account-link]"),forgotPassword:this.querySelectorAll("[data-forgot-password-link]")};this._setupFormNavigation(r,t),this._setupFormSubmissions(Object.values(t)),this._handleFormVisibility(t)}_handleFormVisibility(t){const i=new URLSearchParams(window.location.search).get("form_id");i&&Object.values(t).forEach(e=>{const o=e.querySelector(".gw-error-message");i===e.getAttribute("id")?(e&&e.removeAttribute("hidden"),o&&o.removeAttribute("hidden")):(e&&e.setAttribute("hidden",""),o&&o.setAttribute("hidden",""))})}_setupFormNavigation(t,r){const i=e=>{Object.values(r).forEach(o=>{o.setAttribute("hidden","")}),e.removeAttribute("hidden")};t.createAccount.forEach(e=>{e.addEventListener("click",()=>i(r.registration))}),t.forgotPassword.forEach(e=>{e.addEventListener("click",()=>i(r.forgotPassword))}),t.signIn.forEach(e=>{e.addEventListener("click",()=>i(r.signIn))})}_setupFormSubmissions(t){t.forEach(r=>{const i=new URL(window.location.href);i.searchParams.append("my-account-open",!0),i.searchParams.append("form_id",r.getAttribute("id"));const e=r.querySelector('input[name="return_to"]'),o=r.querySelector('input[name="return_url"]');e&&(e.value=i.pathname+i.search),o&&(o.value=i.pathname+i.search),r.addEventListener("submit",s=>{s.preventDefault(),r.querySelectorAll('button[type="submit"]').forEach(a=>{a.disabled=!0;const n=a.querySelector("[data-loader]");n&&(n.hidden=!1)}),Shopify.captcha.protect(r,()=>{r.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 t=this.signInBlock.querySelector("sl-input");t.value="",t.focus(),this.inputtedEmail="",this.inputtedCode=""}_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 t=this.querySelector("[data-sign-in-form]"),r=this.querySelector("[data-email-error]");t.addEventListener("sl-invalid",i=>{i.preventDefault(),r.textContent=i.target.validationMessage,r.hidden=!1,i.target.focus()},{capture:!0}),t.addEventListener("submit",i=>{i.preventDefault(),r.hidden=!0,r.textContent="",this._submitEmailForm(t).then(()=>{const e=this.verifyCodeBlock.querySelector(".code-input");e&&e.focus()})})})}async _submitEmailForm(t){const r=t.querySelector('button[type="submit"]');r.disabled=!0,r.querySelector("[data-loader]").hidden=!1;const i=new FormData(t);this.inputtedEmail=i.get("email");let e="";const o=await this._fetchCaptchaToken();o&&(e=o);try{const s=await this._request({customerEmail:this.inputtedEmail,token:e},c.ENDPOINTS.AUTH.SIGN_IN);if(s.error){console.error(s.error);return}const a=this.querySelector("[data-code-sent-to]");return a&&(a.textContent=this.inputtedEmail),this.signInBlock.setAttribute("hidden",""),this.verifyCodeBlock.removeAttribute("hidden"),s}catch(s){console.error(s),alert("An error occurred. Please try again later.")}finally{r.disabled=!1,r.querySelector("[data-loader]").hidden=!0}}async _submitVerificationCode(){var s,a;const t=this.querySelector(".gw-verify-code__actions"),r=t.querySelectorAll("button, a"),i=t.querySelector("[data-verify-error]"),e=t.querySelector("[data-loader]"),o=this.querySelectorAll("input.code-input");try{o.forEach(u=>{u.disabled=!0}),r.forEach(u=>{u.disabled=!0,u.hidden=!0}),i.hidden=!0,e.hidden=!1;const n=await this._request({customerEmail:this.inputtedEmail,code:this.inputtedCode},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 f=await(await fetch(window.location.href)).text(),h=new DOMParser().parseFromString(f,"text/html"),m=(a=(s=h.querySelector("#gw-customer-accounts-template").content)==null?void 0:s.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 p=sessionStorage.getItem(c.STORAGE_KEYS.REDIRECT_URL);if(p&&(sessionStorage.removeItem(c.STORAGE_KEYS.REDIRECT_URL),window.location.href=p),!m)return;window.location.pathname.includes(m)&&window.location.reload()}catch(n){console.error(n),setTimeout(()=>{o[o.length-1].focus()})}finally{o.forEach(n=>{n.disabled=!1}),r.forEach(n=>{n.disabled=!1,n.hidden=!1}),i.hidden=!1,e.hidden=!0}}async _request(t,r,i="POST"){return await(await fetch(l.baseURL+r,{method:i,body:JSON.stringify(t),mode:"cors",cache:"no-cache",headers:{"Content-Type":"application/json"}})).json()}_handleInputCodeGroup(){const t=[...this.querySelectorAll("input.code-input")];t.forEach((r,i)=>{r.addEventListener("keydown",e=>{(e.ctrlKey||e.metaKey)&&e.keyCode===86||(e.keyCode!==8&&(e.keyCode<48||e.keyCode>57)&&e.preventDefault(),e.keyCode===8&&e.target.value===""&&t[Math.max(0,i-1)].focus())}),r.addEventListener("input",e=>{const[o,...s]=e.target.value;e.target.value=o??"";const a=i===t.length-1,n=o!==void 0;n&&!a&&(t[i+1].focus(),t[i+1].value=s.join(""),t[i+1].dispatchEvent(new Event("input"))),n&&a&&t.every(d=>d.value)&&(this.inputtedCode=t.map(d=>d.value).join(""),this._submitVerificationCode())})})}async _fetchCaptchaToken(){const r=await(await fetch(l.baseURL+c.ENDPOINTS.AUTH.GET_CAPTCHA_TOKEN)).json();return r==null?void 0:r.token}});
|
|
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 t={signIn:this.querySelector("[data-sign-in-form]"),registration:this.querySelector("[data-registeration-form]"),forgotPassword:this.querySelector("[data-forgot-password-form]")},r={signIn:this.querySelectorAll("[data-sign-in-link]"),createAccount:this.querySelectorAll("[data-create-account-link]"),forgotPassword:this.querySelectorAll("[data-forgot-password-link]")};this._setupFormNavigation(r,t),this._setupFormSubmissions(Object.values(t)),this._handleFormVisibility(t)}_handleFormVisibility(t){const i=new URLSearchParams(window.location.search).get("form_id");i&&Object.values(t).forEach(e=>{const o=e.querySelector(".gw-error-message");i===e.getAttribute("id")?(e&&e.removeAttribute("hidden"),o&&o.removeAttribute("hidden")):(e&&e.setAttribute("hidden",""),o&&o.setAttribute("hidden",""))})}_setupFormNavigation(t,r){const i=e=>{Object.values(r).forEach(o=>{o.setAttribute("hidden","")}),e.removeAttribute("hidden")};t.createAccount.forEach(e=>{e.addEventListener("click",()=>i(r.registration))}),t.forgotPassword.forEach(e=>{e.addEventListener("click",()=>i(r.forgotPassword))}),t.signIn.forEach(e=>{e.addEventListener("click",()=>i(r.signIn))})}_setupFormSubmissions(t){t.forEach(r=>{const i=new URL(window.location.href);i.searchParams.append("my-account-open",!0),i.searchParams.append("form_id",r.getAttribute("id"));const e=r.querySelector('input[name="return_to"]'),o=r.querySelector('input[name="return_url"]');e&&(e.value=i.pathname+i.search),o&&(o.value=i.pathname+i.search),r.addEventListener("submit",s=>{s.preventDefault(),r.querySelectorAll('button[type="submit"]').forEach(a=>{a.disabled=!0;const n=a.querySelector("[data-loader]");n&&(n.hidden=!1)}),Shopify.captcha.protect(r,()=>{r.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 t=this.signInBlock.querySelector("sl-input");t.value="",t.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 t=this.querySelector("[data-sign-in-form]"),r=this.querySelector("[data-email-error]");t.addEventListener("sl-invalid",i=>{i.preventDefault(),r.textContent=i.target.validationMessage,r.hidden=!1,i.target.focus()},{capture:!0}),t.addEventListener("submit",i=>{i.preventDefault(),r.hidden=!0,r.textContent="",this._submitEmailForm(t).then(()=>{const e=this.verifyCodeBlock.querySelector(".code-input");e&&e.focus()})})})}async _submitEmailForm(t){const r=t.querySelector('button[type="submit"]');r.disabled=!0,r.querySelector("[data-loader]").hidden=!1;const i=new FormData(t);this.inputtedEmail=i.get("email"),i.has("accepts_marketing")&&(this.acceptsMarketing=i.get("accepts_marketing"));let e="";const o=await this._fetchCaptchaToken();o&&(e=o);try{const s=await this._request({customerEmail:this.inputtedEmail,token:e},c.ENDPOINTS.AUTH.SIGN_IN);if(s.error){console.error(s.error);return}const a=this.querySelector("[data-code-sent-to]");return a&&(a.textContent=this.inputtedEmail),this.signInBlock.setAttribute("hidden",""),this.verifyCodeBlock.removeAttribute("hidden"),s}catch(s){console.error(s),alert("An error occurred. Please try again later.")}finally{r.disabled=!1,r.querySelector("[data-loader]").hidden=!0}}async _submitVerificationCode(){var s,a;const t=this.querySelector(".gw-verify-code__actions"),r=t.querySelectorAll("button, a"),i=t.querySelector("[data-verify-error]"),e=t.querySelector("[data-loader]"),o=this.querySelectorAll("input.code-input");try{o.forEach(u=>{u.disabled=!0}),r.forEach(u=>{u.disabled=!0,u.hidden=!0}),i.hidden=!0,e.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 f=await(await fetch(window.location.href)).text(),h=new DOMParser().parseFromString(f,"text/html"),m=(a=(s=h.querySelector("#gw-customer-accounts-template").content)==null?void 0:s.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 p=sessionStorage.getItem(c.STORAGE_KEYS.REDIRECT_URL);if(p&&(sessionStorage.removeItem(c.STORAGE_KEYS.REDIRECT_URL),window.location.href=p),!m)return;window.location.pathname.includes(m)&&window.location.reload()}catch(n){console.error(n),setTimeout(()=>{o[o.length-1].focus()})}finally{o.forEach(n=>{n.disabled=!1}),r.forEach(n=>{n.disabled=!1,n.hidden=!1}),i.hidden=!1,e.hidden=!0}}async _request(t,r,i="POST"){return await(await fetch(l.baseURL+r,{method:i,body:JSON.stringify(t),mode:"cors",cache:"no-cache",headers:{"Content-Type":"application/json"}})).json()}_handleInputCodeGroup(){const t=[...this.querySelectorAll("input.code-input")];t.forEach((r,i)=>{r.addEventListener("keydown",e=>{(e.ctrlKey||e.metaKey)&&e.keyCode===86||(e.keyCode!==8&&(e.keyCode<48||e.keyCode>57)&&e.preventDefault(),e.keyCode===8&&e.target.value===""&&t[Math.max(0,i-1)].focus())}),r.addEventListener("input",e=>{const[o,...s]=e.target.value;e.target.value=o??"";const a=i===t.length-1,n=o!==void 0;n&&!a&&(t[i+1].focus(),t[i+1].value=s.join(""),t[i+1].dispatchEvent(new Event("input"))),n&&a&&t.every(d=>d.value)&&(this.inputtedCode=t.map(d=>d.value).join(""),this._submitVerificationCode())})})}async _fetchCaptchaToken(){const r=await(await fetch(l.baseURL+c.ENDPOINTS.AUTH.GET_CAPTCHA_TOKEN)).json();return r==null?void 0:r.token}});
|
package/package.json
CHANGED
|
@@ -160,6 +160,7 @@ customElements.define(
|
|
|
160
160
|
|
|
161
161
|
this.inputtedEmail = '';
|
|
162
162
|
this.inputtedCode = '';
|
|
163
|
+
this.acceptsMarketing = false;
|
|
163
164
|
}
|
|
164
165
|
|
|
165
166
|
_resendVerificationCode() {
|
|
@@ -217,6 +218,9 @@ customElements.define(
|
|
|
217
218
|
|
|
218
219
|
const formData = new FormData(form);
|
|
219
220
|
this.inputtedEmail = formData.get('email');
|
|
221
|
+
if (formData.has('accepts_marketing')) {
|
|
222
|
+
this.acceptsMarketing = formData.get('accepts_marketing');
|
|
223
|
+
}
|
|
220
224
|
|
|
221
225
|
// Fetch hidden captcha token
|
|
222
226
|
let token = '';
|
|
@@ -284,7 +288,11 @@ customElements.define(
|
|
|
284
288
|
verifyLoader.hidden = false;
|
|
285
289
|
|
|
286
290
|
const verificationResponse = await this._request(
|
|
287
|
-
{
|
|
291
|
+
{
|
|
292
|
+
customerEmail: this.inputtedEmail,
|
|
293
|
+
code: this.inputtedCode,
|
|
294
|
+
is_marketing: this.acceptsMarketing,
|
|
295
|
+
},
|
|
288
296
|
GWCA.ENDPOINTS.AUTH.VERIFY_CODE
|
|
289
297
|
);
|
|
290
298
|
|