gw-customer-accounts 1.3.2 → 1.3.4
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/package.json +1 -1
- package/src/scripts/index.js +1 -0
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="")}),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="",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/package.json
CHANGED