UNPKG

ez-shp-storefront

Version:

A helper function collection for Shopify storefront.

55 lines (54 loc) 2.04 kB
import { Dom } from "./dom"; export const cartFormElementQuery = 'form[action="cart"], form[action="checkout"], form#CartPageForm, form#cart, form.cart'; export const checkoutButtonElementQuery = 'main input[type="submit"], main button.checkout, main button[type="submit"], input[type="submit"]#checkout, button[type="submit"]#checkout, button[type="submit"][name="checkout"]'; export class Cart { constructor() { this.data = { item_count: 0 }; } static getInstance() { if (!this.instance) { this.instance = new Cart(); } return this.instance; } isOnCartPage() { return window.location.pathname.includes('/cart'); } getCartItemCount() { return this.data.item_count; } async get() { this.data = await fetch(window.location.origin + "/cart.js").then((response) => response.json()); return this.data; } async clear(redirectUrl) { try { await fetch(window.location.origin + "/cart/clear"); } catch (_a) { } if (!redirectUrl) { return; } if (redirectUrl === location.href) { return location.reload(); } location.href = redirectUrl; } getCartFormElement() { return document.querySelector(cartFormElementQuery); } getCheckoutButtonElement() { let buttons = []; const cartFormElementQueryParts = cartFormElementQuery.split(','); cartFormElementQueryParts.forEach((cartFormElementQueryPart) => { const checkoutButtonElementQueryParts = checkoutButtonElementQuery.split(','); checkoutButtonElementQueryParts.forEach((checkoutButtonElementQueryPart) => { buttons.concat(Array.from(document.querySelectorAll(`${cartFormElementQueryPart} ${checkoutButtonElementQueryPart}`))); }); }); const dom = Dom.getInstance(); return buttons.find((button) => !dom.isHidden(button)); } } Cart.instance = null;