diff --git a/assets/js/cart-drawer.js b/assets/js/cart-drawer.js index 95972c1..439c3d1 100644 --- a/assets/js/cart-drawer.js +++ b/assets/js/cart-drawer.js @@ -32,6 +32,9 @@ // Initialize event listeners setupEventListeners(); + + // Load initial cart state + loadCart(); } function setupEventListeners() { @@ -60,6 +63,18 @@ }); } + async function loadCart() { + if (!cartInstance) return; + + try { + const cart = await cartInstance.getCart(); + currentCart = cart; + renderCart(); + } catch (error) { + console.error('Error loading cart:', error); + } + } + function openDrawer() { drawer.classList.add('is-open'); document.body.style.overflow = 'hidden'; diff --git a/assets/js/shopify-cart.js b/assets/js/shopify-cart.js index 18b1338..396ae38 100644 --- a/assets/js/shopify-cart.js +++ b/assets/js/shopify-cart.js @@ -306,6 +306,58 @@ class ShopifyCart { return cart; } + /** + * Get existing cart by ID + */ + async getCart() { + if (!this.cartId) { + return null; + } + + const query = ` + query getCart($cartId: ID!) { + cart(id: $cartId) { + id + checkoutUrl + lines(first: 10) { + edges { + node { + id + quantity + merchandise { + ... on ProductVariant { + id + title + price { + amount + currencyCode + } + product { + title + } + } + } + } + } + } + } + } + `; + + try { + const data = await this.query(query, { + cartId: this.cartId + }); + + return data.cart; + } catch (error) { + // Cart might be expired or invalid + console.error('Error fetching cart:', error); + this.clearCart(); + return null; + } + } + /** * Get checkout URL to redirect user */ diff --git a/site/snippets/structured-data-product.php b/site/snippets/structured-data-product.php index b6bfefd..2390bc8 100644 --- a/site/snippets/structured-data-product.php +++ b/site/snippets/structured-data-product.php @@ -38,12 +38,18 @@ const language = container.dataset.language || 'fr'; const isEnglish = language === 'en'; - const cart = new ShopifyCart({ - domain: 'nv7cqv-bu.myshopify.com', - storefrontAccessToken: 'dec3d35a2554384d149c72927d1cfd1b' - }); + function initStructuredData() { + if (typeof ShopifyCart === 'undefined') { + setTimeout(initStructuredData, 100); + return; + } - cart.getProductByHandle(handle).then(product => { + const cart = new ShopifyCart({ + domain: 'nv7cqv-bu.myshopify.com', + storefrontAccessToken: 'dec3d35a2554384d149c72927d1cfd1b' + }); + + cart.getProductByHandle(handle).then(product => { if (!product) return; const title = isEnglish && product.titleEn?.value ? product.titleEn.value : product.title; @@ -79,6 +85,10 @@ if (schemaScript) { schemaScript.textContent = JSON.stringify(schema, null, 2); } - }); + }); + } + + // Initialize when ShopifyCart is available + initStructuredData(); })();