2021-11-22 17:51:50 +00:00
|
|
|
import { CartBaseController } from "./cart_base_controller";
|
2021-06-01 21:33:49 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Renders the order table. All products are stored on localStorage, so
|
|
|
|
* we just fetch that information and render the cart contents using
|
|
|
|
* Liquid.
|
|
|
|
*/
|
|
|
|
export default class extends CartBaseController {
|
2021-11-22 17:51:50 +00:00
|
|
|
static targets = ["cart", "subtotal", "itemCount"];
|
2021-06-01 21:33:49 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
async connect() {
|
|
|
|
const products = this.products;
|
|
|
|
const site = window.site;
|
2021-06-01 21:33:49 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
this.render({ products, site });
|
|
|
|
this.subtotalUpdate();
|
|
|
|
this.itemCountUpdate();
|
|
|
|
this.subscribe();
|
2021-06-01 21:33:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Subscribe to change on the storage to update the cart.
|
|
|
|
*/
|
2021-11-22 17:51:50 +00:00
|
|
|
subscribe() {
|
|
|
|
window.addEventListener("storage", async (event) => {
|
|
|
|
if (!event.key?.startsWith("cart:item:")) return;
|
2021-06-01 21:33:49 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
const products = this.products;
|
|
|
|
const site = window.site;
|
2021-06-01 21:33:49 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
this.render({ products, site });
|
|
|
|
this.subtotalUpdate();
|
|
|
|
this.itemCountUpdate();
|
|
|
|
});
|
2021-06-01 21:33:49 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
window.addEventListener("cart:subtotal:update", (event) => {
|
|
|
|
this.itemCountUpdate();
|
|
|
|
this.subtotalUpdate();
|
|
|
|
});
|
2021-06-01 21:33:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Download the item template and render the order
|
|
|
|
*/
|
2021-11-22 17:51:50 +00:00
|
|
|
render(data = {}) {
|
|
|
|
const template = window.templates[this.data.get("itemTemplate")];
|
2021-10-28 13:00:00 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
this.engine
|
|
|
|
.parseAndRender(template, data)
|
|
|
|
.then((html) => (this.cartTarget.innerHTML = html));
|
2021-06-01 21:33:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Updates the subtotal
|
|
|
|
*
|
|
|
|
* XXX: This also updates the currency
|
|
|
|
*/
|
2021-11-22 17:51:50 +00:00
|
|
|
subtotalUpdate() {
|
|
|
|
if (!this.cart) return;
|
2021-06-01 21:33:49 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
this.subtotalTarget.innerText = this.cart.data.attributes.display_total;
|
2021-06-01 21:33:49 +00:00
|
|
|
}
|
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
itemCountUpdate() {
|
|
|
|
if (!this.hasItemCountTarget) return;
|
|
|
|
if (!this.cart) return;
|
2021-06-01 21:33:49 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
this.itemCountTarget.innerText = this.cart.data.attributes.item_count;
|
2021-06-01 21:33:49 +00:00
|
|
|
}
|
|
|
|
}
|