@wikala/spmkt 4.0.0-alpha.1 → 4.0.0-alpha.3

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.
Files changed (91) hide show
  1. package/dist/core/api/address.d.ts +6 -1
  2. package/dist/core/api/address.js +6 -1
  3. package/dist/core/api/address.js.map +1 -1
  4. package/dist/core/api/cart.d.ts +2 -21
  5. package/dist/core/api/cart.js +4 -30
  6. package/dist/core/api/cart.js.map +1 -1
  7. package/dist/core/api/checkout.d.ts +2 -9
  8. package/dist/core/api/checkout.js +3 -10
  9. package/dist/core/api/checkout.js.map +1 -1
  10. package/dist/core/api/index.d.ts +4 -4
  11. package/dist/core/api/product.d.ts +2 -10
  12. package/dist/core/api/product.js +0 -12
  13. package/dist/core/api/product.js.map +1 -1
  14. package/dist/core/events.d.ts +4 -3
  15. package/dist/core/events.js.map +1 -1
  16. package/dist/core/index.d.ts +4 -4
  17. package/dist/core/index.js +17 -13
  18. package/dist/core/money.d.ts +2 -0
  19. package/dist/core/money.js +5 -0
  20. package/dist/core/money.js.map +1 -1
  21. package/dist/core/page-events.d.ts +17 -0
  22. package/dist/core/page-events.js +37 -3
  23. package/dist/core/page-events.js.map +1 -1
  24. package/dist/core/state.d.ts +8 -1
  25. package/dist/core/state.js +75 -3
  26. package/dist/core/state.js.map +1 -1
  27. package/dist/core/stores/cart.d.ts +19 -20
  28. package/dist/core/stores/cart.js +38 -46
  29. package/dist/core/stores/cart.js.map +1 -1
  30. package/dist/core/stores/checkout.d.ts +10 -12
  31. package/dist/core/stores/checkout.js +19 -24
  32. package/dist/core/stores/checkout.js.map +1 -1
  33. package/dist/core/stores/index.d.ts +2 -2
  34. package/dist/core/types.d.ts +29 -7
  35. package/dist/elements/add-to-cart/add-to-cart.d.ts +23 -8
  36. package/dist/elements/add-to-cart/add-to-cart.js +62 -28
  37. package/dist/elements/add-to-cart/add-to-cart.js.map +1 -1
  38. package/dist/elements/add-to-cart/index.d.ts +1 -1
  39. package/dist/elements/address-book/address-book.d.ts +20 -15
  40. package/dist/elements/address-book/address-book.js +98 -34
  41. package/dist/elements/address-book/address-book.js.map +1 -1
  42. package/dist/elements/carousel/carousel.d.ts +11 -1
  43. package/dist/elements/carousel/carousel.js +22 -5
  44. package/dist/elements/carousel/carousel.js.map +1 -1
  45. package/dist/elements/cart/cart.d.ts +27 -27
  46. package/dist/elements/cart/cart.js +195 -80
  47. package/dist/elements/cart/cart.js.map +1 -1
  48. package/dist/elements/checkout/checkout.d.ts +13 -20
  49. package/dist/elements/checkout/checkout.js +73 -40
  50. package/dist/elements/checkout/checkout.js.map +1 -1
  51. package/dist/elements/checkout-delivery/checkout-delivery.d.ts +2 -9
  52. package/dist/elements/checkout-delivery/checkout-delivery.js +1 -8
  53. package/dist/elements/checkout-delivery/checkout-delivery.js.map +1 -1
  54. package/dist/elements/checkout-payment/checkout-payment.d.ts +2 -9
  55. package/dist/elements/checkout-payment/checkout-payment.js +2 -9
  56. package/dist/elements/checkout-payment/checkout-payment.js.map +1 -1
  57. package/dist/elements/collection/collection.d.ts +5 -9
  58. package/dist/elements/collection/collection.js +20 -20
  59. package/dist/elements/collection/collection.js.map +1 -1
  60. package/dist/elements/dialog/dialog.d.ts +7 -3
  61. package/dist/elements/dialog/dialog.js +12 -4
  62. package/dist/elements/dialog/dialog.js.map +1 -1
  63. package/dist/elements/mini-cart/mini-cart.d.ts +15 -15
  64. package/dist/elements/mini-cart/mini-cart.js +74 -62
  65. package/dist/elements/mini-cart/mini-cart.js.map +1 -1
  66. package/dist/elements/order-confirmation/index.d.ts +3 -0
  67. package/dist/elements/order-confirmation/index.js +7 -0
  68. package/dist/elements/order-confirmation/index.js.map +1 -0
  69. package/dist/elements/order-confirmation/order-confirmation.d.ts +35 -0
  70. package/dist/elements/order-confirmation/order-confirmation.js +123 -0
  71. package/dist/elements/order-confirmation/order-confirmation.js.map +1 -0
  72. package/dist/elements/quick-view/quick-view.d.ts +10 -7
  73. package/dist/elements/quick-view/quick-view.js +11 -5
  74. package/dist/elements/quick-view/quick-view.js.map +1 -1
  75. package/dist/elements/related/related.d.ts +8 -13
  76. package/dist/elements/related/related.js +20 -17
  77. package/dist/elements/related/related.js.map +1 -1
  78. package/dist/elements/shared/paged-section.js +1 -1
  79. package/dist/elements/shared/paged-section.js.map +1 -1
  80. package/dist/elements/shared/totals.d.ts +53 -0
  81. package/dist/elements/shared/totals.js +82 -0
  82. package/dist/elements/shared/totals.js.map +1 -0
  83. package/dist/elements/variant-picker/variant-picker.d.ts +5 -3
  84. package/dist/elements/variant-picker/variant-picker.js +6 -4
  85. package/dist/elements/variant-picker/variant-picker.js.map +1 -1
  86. package/dist/lit/fragments.d.ts +11 -10
  87. package/dist/lit/fragments.js +9 -10
  88. package/dist/lit/fragments.js.map +1 -1
  89. package/dist/locales/en.json +48 -3
  90. package/dist/locales/sr.json +49 -3
  91. package/package.json +1 -1
@@ -1,124 +1,246 @@
1
+ import { html, nothing } from "lit";
2
+ import { repeat } from "lit/directives/repeat.js";
1
3
  import { SpmktElement } from "../../lit/spmkt-element.js";
2
- import { swapInto } from "../../lit/fragments.js";
4
+ import { SignalController } from "../../lit/signal-controller.js";
3
5
  import { errorMessage } from "../../lit/forms.js";
4
- import { setQuantity, applyCoupon } from "../../core/stores/cart.js";
5
- import { fetchCartFragments } from "../../core/api/cart.js";
6
- import { isAbortError, HttpError, ValidationError } from "../../core/errors.js";
6
+ import { cart, cartLineToItem, setQuantity, applyCoupon } from "../../core/stores/cart.js";
7
+ import { HttpError, ValidationError } from "../../core/errors.js";
7
8
  import { t } from "../../core/i18n.js";
9
+ import { phpRound, formatMoney } from "../../core/money.js";
10
+ import { shopUrl } from "../../core/config.js";
11
+ import { storefront } from "../../core/state.js";
8
12
  import { showToast } from "../toaster/toaster.js";
13
+ import { lineUrl, lineName, hasImage, renderTotals, cartBlocked, withStrong } from "../shared/totals.js";
9
14
  class SpmktCart extends SpmktElement {
10
15
  constructor() {
11
16
  super(...arguments);
12
- this.linesFragment = "cart-lines";
13
- this.summaryFragment = "cart-summary";
17
+ this.coupon = false;
18
+ this.cart = new SignalController(this, () => cart.value);
14
19
  this.busy = false;
20
+ this.couponError = null;
21
+ this.viewed = false;
15
22
  }
16
23
  static {
17
24
  this.properties = {
18
- linesFragment: { type: String, attribute: "lines-fragment" },
19
- summaryFragment: { type: String, attribute: "summary-fragment" }
25
+ coupon: { type: Boolean }
20
26
  };
21
27
  }
22
28
  connectedCallback() {
23
29
  super.connectedCallback();
24
30
  this.requirePart("lines");
25
31
  this.requirePart("summary");
26
- this.listen(this, "change", (event) => {
27
- const select = event.target;
28
- if (select.name === "qty" && select.form?.dataset.part === "quantity") {
29
- if (select.dataset.previous !== void 0 && select.value === select.dataset.previous) return;
30
- void this.changeQuantity(select.form);
31
- }
32
- });
33
- this.listen(document, "spmkt:cart-changed", () => {
34
- if (!this.busy) void this.refresh();
35
- });
36
- this.listen(this, "submit", (event) => {
37
- const form = event.target;
38
- const kind = form.dataset.part;
39
- if (kind !== "quantity" && kind !== "remove" && kind !== "coupon") return;
40
- event.preventDefault();
41
- if (kind === "coupon") void this.coupon(form);
42
- else void this.changeQuantity(form);
43
- });
32
+ if (!this.viewed && this.cart.value.items.length) {
33
+ this.viewed = true;
34
+ const current = this.cart.value;
35
+ this.emit("spmkt:view-cart", {
36
+ currency: current.items[0]?.currency || storefront().currency,
37
+ value: phpRound(current.total, 2),
38
+ items: current.items.map((line) => cartLineToItem(line))
39
+ });
40
+ }
44
41
  }
45
- get fragments() {
46
- return [this.linesFragment, this.summaryFragment];
42
+ updated() {
43
+ const lines = this.requirePart("lines");
44
+ const hadFocus = lines.contains(document.activeElement);
45
+ this.renderPart("lines", this.renderLines(this.cart.value));
46
+ this.renderPart("summary", this.renderSummary(this.cart.value));
47
+ lines.removeAttribute("aria-busy");
48
+ this.requirePart("summary").removeAttribute("aria-busy");
49
+ if (hadFocus && !lines.contains(document.activeElement)) {
50
+ lines.tabIndex = -1;
51
+ lines.focus();
52
+ }
47
53
  }
48
- /** Re-renders both regions from the server without changing anything. */
49
- async refresh() {
50
- try {
51
- this.show(await fetchCartFragments(this.fragments));
52
- } catch (error) {
53
- if (!isAbortError(error)) this.showError(errorMessage(error));
54
+ renderLines(current) {
55
+ if (!current.items.length) {
56
+ return html`<div class="cart__empty" data-test="cart-empty">
57
+ <p>${t("cart.empty")}</p>
58
+ <a class="button button--primary" href=${shopUrl("/")}>${t("cart.continue")}</a>
59
+ </div>`;
54
60
  }
61
+ return html`<ul role="list" class="cart-lines">
62
+ ${repeat(
63
+ current.items,
64
+ (line) => line.id,
65
+ (line) => this.renderLine(line)
66
+ )}
67
+ </ul>`;
55
68
  }
56
- /** A quantity form (the new quantity) or a remove form (0). */
57
- async changeQuantity(form) {
58
- const data = new FormData(form);
59
- const id = Number(data.get("id"));
60
- const qty = Math.max(0, Number(data.get("qty")) || 0);
61
- const line = form.closest("[data-item]");
62
- const select = line?.querySelector('select[name="qty"]');
63
- const previousQty = select?.dataset.previous !== void 0 ? Number(select.dataset.previous) : void 0;
64
- await this.run(async () => {
65
- const { fragments } = await setQuantity({
66
- id,
67
- qty,
68
- previousQty,
69
- item: itemOf(line),
70
- fragments: this.fragments
71
- });
72
- this.show(fragments);
73
- }, t("cart.updateFailed"));
69
+ renderLine(line) {
70
+ const url = lineUrl(line, shopUrl);
71
+ const name = lineName(line);
72
+ const id = `cart-qty-${line.id}`;
73
+ const quantities = Array.from({ length: Math.max(10, line.qty) }, (_, i) => i + 1);
74
+ return html`<li
75
+ class="cart-line${line.error ? " cart-line--error" : ""}"
76
+ data-test="cart-line"
77
+ data-line=${line.id}
78
+ >
79
+ <a class="cart-line__image" href=${url} tabindex="-1" aria-hidden="true">
80
+ ${hasImage(line) ? html`<img src=${line.image_url} alt="" width="96" height="96" loading="lazy" />` : nothing}
81
+ </a>
82
+ <div class="cart-line__info">
83
+ <a class="cart-line__name" href=${url} data-test="cart-item-name">${name}</a>
84
+ ${line.variant ? html`<p class="cart-line__variant">${line.variant}</p>` : nothing}
85
+ <p class="cart-line__price">
86
+ ${formatMoney(line.price)}
87
+ ${line.original_price > line.price ? html`<s class="price__compare"
88
+ ><span class="visually-hidden">${t("cart.oldPrice")}</span>
89
+ ${formatMoney(line.original_price)}</s
90
+ >` : nothing}
91
+ </p>
92
+ </div>
93
+ <form class="cart-line__qty" data-part="quantity" @submit=${(event) => event.preventDefault()}>
94
+ <label class="visually-hidden" for=${id}>${t("cart.quantity")}</label>
95
+ <select
96
+ class="select"
97
+ id=${id}
98
+ name="qty"
99
+ data-test="cart-item-qty"
100
+ @change=${(event) => this.onQuantity(line, event.target)}
101
+ >
102
+ ${quantities.map((qty) => html`<option value=${qty} ?selected=${qty === line.qty}>${qty}</option>`)}
103
+ </select>
104
+ </form>
105
+ <p class="cart-line__total" data-test="cart-line-total">
106
+ ${formatMoney(phpRound(line.price * line.qty, 2))}
107
+ </p>
108
+ <form
109
+ class="cart-line__remove"
110
+ data-part="remove"
111
+ @submit=${(event) => {
112
+ event.preventDefault();
113
+ void this.changeQuantity(line.id, 0);
114
+ }}
115
+ >
116
+ <button
117
+ type="submit"
118
+ class="link-button"
119
+ data-test="cart-item-remove"
120
+ aria-label=${t("cart.removeNamed", { name })}
121
+ >
122
+ ${t("cart.remove")}
123
+ </button>
124
+ </form>
125
+ ${line.error ? html`<p class="cart-line__error" role="alert" data-test="cart-line-error">${line.error}</p>` : nothing}
126
+ </li>`;
74
127
  }
75
- async coupon(form) {
76
- const code = String(new FormData(form).get("coupon_code") ?? "").trim();
128
+ renderSummary(current) {
129
+ if (!current.items.length) return nothing;
130
+ return html`<div class="cart-summary">
131
+ ${this.coupon ? this.renderCoupon(current) : nothing}
132
+ ${renderTotals(
133
+ {
134
+ subtotal: current.subtotal,
135
+ discount: current.discount,
136
+ shipping: current.shipping,
137
+ taxAmount: current.tax_amount,
138
+ taxPercent: current.tax_percent,
139
+ total: current.total
140
+ },
141
+ { shipping: "charged", testId: "cart-totals", totalTestId: "cart-total" }
142
+ )}
143
+ ${cartBlocked(current.items) ? html`<button
144
+ type="button"
145
+ class="button button--primary button--block"
146
+ disabled
147
+ data-test="to-checkout-btn"
148
+ >
149
+ ${t("cart.toCheckout")}
150
+ </button>
151
+ <p class="cart-summary__note">${t("cart.blocked")}</p>` : html`<a
152
+ class="button button--primary button--block"
153
+ href=${shopUrl("/shopping-cart?step=delivery")}
154
+ data-test="to-checkout-btn"
155
+ >${t("cart.toCheckout")}</a
156
+ >`}
157
+ </div>`;
158
+ }
159
+ renderCoupon(current) {
160
+ const error = this.couponError;
161
+ return html`<form
162
+ class="cart-coupon"
163
+ data-part="coupon"
164
+ @submit=${(event) => {
165
+ event.preventDefault();
166
+ void this.applyCoupon(event.target);
167
+ }}
168
+ >
169
+ <label for="cart-coupon-code">${t("cart.coupon")}</label>
170
+ <div class="cart-coupon__field">
171
+ <input
172
+ class="input"
173
+ id="cart-coupon-code"
174
+ name="coupon_code"
175
+ autocomplete="off"
176
+ data-test="coupon-input"
177
+ aria-invalid=${error ? "true" : nothing}
178
+ aria-describedby=${error ? "cart-coupon-error" : nothing}
179
+ />
180
+ <button type="submit" class="button button--small" data-test="coupon-apply">
181
+ ${t("cart.applyCoupon")}
182
+ </button>
183
+ </div>
184
+ <p class="field-error" id="cart-coupon-error" data-part="coupon-error" ?hidden=${!error}>
185
+ ${error ?? ""}
186
+ </p>
187
+ ${current.coupon_code ? html`<p class="cart-coupon__applied" data-test="coupon-applied">
188
+ ${withStrong("cart.couponApplied", "code", current.coupon_code)}
189
+ </p>` : nothing}
190
+ </form>`;
191
+ }
192
+ onQuantity(line, select) {
193
+ const qty = Number(select.value);
194
+ if (!Number.isInteger(qty) || qty === line.qty) return;
195
+ void this.changeQuantity(line.id, qty, () => {
196
+ select.value = String(line.qty);
197
+ });
198
+ }
199
+ /** Sets a line's quantity (0 removes it); `undo` puts the control back when the change fails. */
200
+ async changeQuantity(id, qty, undo) {
201
+ await this.run(() => setQuantity({ id, qty }), t("cart.updateFailed"), void 0, undo);
202
+ }
203
+ async applyCoupon(form) {
77
204
  const input = form.querySelector('[name="coupon_code"]');
78
- const slot = form.querySelector('[data-part="coupon-error"]');
205
+ const code = (input?.value ?? "").trim();
79
206
  if (code === "") {
80
207
  input?.focus();
81
208
  return;
82
209
  }
210
+ this.setCouponError(null);
83
211
  await this.run(
84
212
  async () => {
85
- const { fragments } = await applyCoupon(code, { fragments: this.fragments });
86
- this.show(fragments);
213
+ await applyCoupon(code);
214
+ if (input) input.value = "";
87
215
  },
88
216
  t("cart.couponFailed"),
89
217
  (message) => {
90
- if (!slot) return false;
91
- slot.textContent = message;
92
- slot.hidden = false;
93
- input?.setAttribute("aria-invalid", "true");
218
+ this.setCouponError(message);
94
219
  input?.focus();
95
220
  return true;
96
221
  }
97
222
  );
98
223
  }
99
- show(fragments) {
100
- const lines = this.requirePart("lines");
101
- const hadFocus = lines.contains(document.activeElement);
102
- if (fragments[this.linesFragment] !== void 0) swapInto(lines, fragments[this.linesFragment]);
103
- if (fragments[this.summaryFragment] !== void 0)
104
- swapInto(this.requirePart("summary"), fragments[this.summaryFragment]);
105
- if (hadFocus && !lines.contains(document.activeElement)) {
106
- lines.tabIndex = -1;
107
- lines.focus();
108
- }
224
+ setCouponError(message) {
225
+ this.couponError = message;
226
+ this.requestUpdate();
109
227
  }
110
228
  /**
111
229
  * Runs a change with the element busy. A refusal is shown by `inline` when it can (e.g. next to the coupon
112
230
  * field), otherwise in the error part and as a toast.
113
231
  */
114
- async run(action, fallback, inline) {
115
- if (this.busy) return;
232
+ async run(action, fallback, inline, undo) {
233
+ if (this.busy) {
234
+ undo?.();
235
+ return;
236
+ }
116
237
  this.busy = true;
117
238
  this.setAttribute("aria-busy", "true");
118
239
  this.showError(null);
119
240
  try {
120
241
  await action();
121
242
  } catch (error) {
243
+ undo?.();
122
244
  const message = errorMessage(error, fallback);
123
245
  const refused = error instanceof HttpError && (error.status === 400 || error instanceof ValidationError);
124
246
  if (!(refused && inline?.(message))) {
@@ -140,13 +262,6 @@ class SpmktCart extends SpmktElement {
140
262
  }
141
263
  }
142
264
  }
143
- function itemOf(line) {
144
- try {
145
- return line?.dataset.item ? JSON.parse(line.dataset.item) : void 0;
146
- } catch {
147
- return void 0;
148
- }
149
- }
150
265
  export {
151
266
  SpmktCart
152
267
  };
@@ -1 +1 @@
1
- {"version":3,"file":"cart.js","sources":["../../../src/elements/cart/cart.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { swapInto } from '../../lit/fragments'\nimport { errorMessage } from '../../lit/forms'\nimport { applyCoupon, setQuantity } from '../../core/stores/cart'\nimport { fetchCartFragments, type Fragments } from '../../core/api/cart'\nimport { HttpError, ValidationError, isAbortError } from '../../core/errors'\nimport type { Ga4Item } from '../../core/events'\nimport { t } from '../../core/i18n'\nimport { showToast } from '../toaster/toaster'\n\n/**\n * Parts of <spmkt-cart> (the theme's cart page, whose forms post to the server without JavaScript):\n * - lines (required): the cart's lines, re-rendered from the theme fragment `lines-fragment`. Inside it:\n * - quantity: a form per line with fields `id` and `qty` (a <select> is submitted on change). The select's\n * data-previous holds the quantity shown, and the line's [data-item] the line as a GA4 item (JSON), so\n * analytics gets what was added or removed.\n * - remove: a form per line with `id` and `qty` = 0\n * - summary (required): totals and the coupon form, re-rendered from the theme fragment `summary-fragment`.\n * Inside it: coupon, a form with `coupon_code`, and coupon-error, where an unusable code is explained.\n * - error (optional): why a change failed; render it hidden\n *\n * Every change re-renders both regions with the server's answer to the same request (fragments), so the page\n * shows exactly what the server computed. The element is busy (aria-busy) meanwhile and ignores further input.\n * A change made elsewhere (spmkt:cart-changed, e.g. from the header's drawer) re-renders them too.\n */\nexport interface CartParts {\n lines: HTMLElement\n summary: HTMLElement\n error?: HTMLElement\n}\n\nexport class SpmktCart extends SpmktElement {\n static override properties = {\n linesFragment: { type: String, attribute: 'lines-fragment' },\n summaryFragment: { type: String, attribute: 'summary-fragment' },\n }\n linesFragment = 'cart-lines'\n summaryFragment = 'cart-summary'\n\n private busy = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n this.requirePart('lines')\n this.requirePart('summary')\n // Delegated: the regions are replaced after every change\n this.listen(this, 'change', (event) => {\n const select = event.target as HTMLSelectElement\n if (select.name === 'qty' && select.form?.dataset.part === 'quantity') {\n // A change event without a change (choosing the quantity already shown) sends nothing: a request in\n // flight while the visitor goes on to checkout races the next page for the cart\n if (select.dataset.previous !== undefined && select.value === select.dataset.previous) return\n void this.changeQuantity(select.form)\n }\n })\n // The cart changed elsewhere (the header's drawer, another add): show it as the server has it now\n this.listen(document, 'spmkt:cart-changed', () => {\n if (!this.busy) void this.refresh()\n })\n this.listen(this, 'submit', (event) => {\n const form = event.target as HTMLFormElement\n const kind = form.dataset.part\n if (kind !== 'quantity' && kind !== 'remove' && kind !== 'coupon') return\n event.preventDefault()\n if (kind === 'coupon') void this.coupon(form)\n else void this.changeQuantity(form)\n })\n }\n\n private get fragments(): string[] {\n return [this.linesFragment, this.summaryFragment]\n }\n\n /** Re-renders both regions from the server without changing anything. */\n async refresh(): Promise<void> {\n try {\n this.show(await fetchCartFragments(this.fragments))\n } catch (error) {\n if (!isAbortError(error)) this.showError(errorMessage(error))\n }\n }\n\n /** A quantity form (the new quantity) or a remove form (0). */\n async changeQuantity(form: HTMLFormElement): Promise<void> {\n const data = new FormData(form)\n const id = Number(data.get('id'))\n const qty = Math.max(0, Number(data.get('qty')) || 0)\n const line = form.closest<HTMLElement>('[data-item]')\n const select = line?.querySelector<HTMLSelectElement>('select[name=\"qty\"]')\n const previousQty = select?.dataset.previous !== undefined ? Number(select.dataset.previous) : undefined\n await this.run(async () => {\n const { fragments } = await setQuantity({\n id,\n qty,\n previousQty,\n item: itemOf(line),\n fragments: this.fragments,\n })\n this.show(fragments)\n }, t('cart.updateFailed'))\n }\n\n async coupon(form: HTMLFormElement): Promise<void> {\n const code = String(new FormData(form).get('coupon_code') ?? '').trim()\n const input = form.querySelector<HTMLInputElement>('[name=\"coupon_code\"]')\n const slot = form.querySelector<HTMLElement>('[data-part=\"coupon-error\"]')\n if (code === '') {\n input?.focus()\n return\n }\n await this.run(\n async () => {\n const { fragments } = await applyCoupon(code, { fragments: this.fragments })\n this.show(fragments)\n },\n t('cart.couponFailed'),\n (message) => {\n // An unusable code is the visitor's to fix: say it next to the field\n if (!slot) return false\n slot.textContent = message\n slot.hidden = false\n input?.setAttribute('aria-invalid', 'true')\n input?.focus()\n return true\n },\n )\n }\n\n private show(fragments: Fragments): void {\n const lines = this.requirePart('lines')\n const hadFocus = lines.contains(document.activeElement)\n if (fragments[this.linesFragment] !== undefined) swapInto(lines, fragments[this.linesFragment]!)\n if (fragments[this.summaryFragment] !== undefined)\n swapInto(this.requirePart('summary'), fragments[this.summaryFragment]!)\n // A removed line took the focus with it: keep the visitor in the list\n if (hadFocus && !lines.contains(document.activeElement)) {\n lines.tabIndex = -1\n lines.focus()\n }\n }\n\n /**\n * Runs a change with the element busy. A refusal is shown by `inline` when it can (e.g. next to the coupon\n * field), otherwise in the error part and as a toast.\n */\n private async run(\n action: () => Promise<void>,\n fallback: string,\n inline?: (message: string) => boolean,\n ): Promise<void> {\n if (this.busy) return\n this.busy = true\n this.setAttribute('aria-busy', 'true')\n this.showError(null)\n try {\n await action()\n } catch (error) {\n const message = errorMessage(error, fallback)\n const refused = error instanceof HttpError && (error.status === 400 || error instanceof ValidationError)\n if (!(refused && inline?.(message))) {\n this.showError(message)\n }\n } finally {\n this.busy = false\n this.removeAttribute('aria-busy')\n }\n }\n\n private showError(message: string | null): void {\n const part = this.findPart('error')\n if (part) {\n part.textContent = message ?? ''\n part.hidden = message === null\n }\n if (message !== null) {\n showToast({ message, tone: 'error' })\n }\n }\n}\n\nfunction itemOf(line: HTMLElement | null): Ga4Item | undefined {\n try {\n return line?.dataset.item ? (JSON.parse(line.dataset.item) as Ga4Item) : undefined\n } catch {\n return undefined\n }\n}\n"],"names":[],"mappings":";;;;;;;;AA+BO,MAAM,kBAAkB,aAAa;AAAA,EAArC,cAAA;AAAA,UAAA,GAAA,SAAA;A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AA,EACT;AACF;"}
1
+ {"version":3,"file":"cart.js","sources":["../../../src/elements/cart/cart.ts"],"sourcesContent":["import { html, nothing, type TemplateResult } from 'lit'\nimport { repeat } from 'lit/directives/repeat.js'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { SignalController } from '../../lit/signal-controller'\nimport { errorMessage } from '../../lit/forms'\nimport { applyCoupon, cart, cartLineToItem, setQuantity } from '../../core/stores/cart'\nimport { HttpError, ValidationError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { formatMoney, phpRound } from '../../core/money'\nimport { shopUrl } from '../../core/config'\nimport { storefront } from '../../core/state'\nimport type { Cart, CartLine } from '../../core/types'\nimport { showToast } from '../toaster/toaster'\nimport { cartBlocked, hasImage, lineName, lineUrl, renderTotals, withStrong } from '../shared/totals'\n\n/**\n * Parts of <spmkt-cart> (the cart page; the element renders the lines and the summary from the cart store):\n * - lines (required): empty in the theme's markup (aria-busy=\"true\" shows a skeleton until the first render)\n * - summary (required): the same; totals, the coupon form when the `coupon` attribute is set, and the way on\n * to checkout\n * - error (optional): why a change failed; render it hidden\n *\n * Every view of the cart renders from the same store, so a change here shows in the header's drawer and count\n * at once, and a change made there shows here. The element is busy (aria-busy) while its own change is in\n * flight and ignores further input. A theme changes the markup by overriding the render methods in a\n * subclass registered under the same tag.\n */\nexport interface CartParts {\n lines: HTMLElement\n summary: HTMLElement\n error?: HTMLElement\n}\n\nexport class SpmktCart extends SpmktElement {\n static override properties = {\n coupon: { type: Boolean },\n }\n /** Offer the coupon form (the theme's setting) */\n coupon = false\n\n private readonly cart = new SignalController(this, () => cart.value)\n private busy = false\n private couponError: string | null = null\n private viewed = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n this.requirePart('lines')\n this.requirePart('summary')\n // Once per element: a reconnect (a section swap) is not another view of the cart\n if (!this.viewed && this.cart.value.items.length) {\n this.viewed = true\n const current = this.cart.value\n this.emit('spmkt:view-cart', {\n currency: current.items[0]?.currency || storefront().currency,\n value: phpRound(current.total, 2),\n items: current.items.map((line) => cartLineToItem(line)),\n })\n }\n }\n\n protected override updated(): void {\n const lines = this.requirePart('lines')\n const hadFocus = lines.contains(document.activeElement)\n this.renderPart('lines', this.renderLines(this.cart.value))\n this.renderPart('summary', this.renderSummary(this.cart.value))\n lines.removeAttribute('aria-busy')\n this.requirePart('summary').removeAttribute('aria-busy')\n // A removed line took the focus with it: keep the visitor in the list\n if (hadFocus && !lines.contains(document.activeElement)) {\n lines.tabIndex = -1\n lines.focus()\n }\n }\n\n protected renderLines(current: Cart): TemplateResult {\n if (!current.items.length) {\n return html`<div class=\"cart__empty\" data-test=\"cart-empty\">\n <p>${t('cart.empty')}</p>\n <a class=\"button button--primary\" href=${shopUrl('/')}>${t('cart.continue')}</a>\n </div>`\n }\n return html`<ul role=\"list\" class=\"cart-lines\">\n ${repeat(\n current.items,\n (line) => line.id,\n (line) => this.renderLine(line),\n )}\n </ul>`\n }\n\n protected renderLine(line: CartLine): TemplateResult {\n const url = lineUrl(line, shopUrl)\n const name = lineName(line)\n const id = `cart-qty-${line.id}`\n const quantities = Array.from({ length: Math.max(10, line.qty) }, (_, i) => i + 1)\n return html`<li\n class=\"cart-line${line.error ? ' cart-line--error' : ''}\"\n data-test=\"cart-line\"\n data-line=${line.id}\n >\n <a class=\"cart-line__image\" href=${url} tabindex=\"-1\" aria-hidden=\"true\">\n ${\n hasImage(line)\n ? html`<img src=${line.image_url} alt=\"\" width=\"96\" height=\"96\" loading=\"lazy\" />`\n : nothing\n }\n </a>\n <div class=\"cart-line__info\">\n <a class=\"cart-line__name\" href=${url} data-test=\"cart-item-name\">${name}</a>\n ${line.variant ? html`<p class=\"cart-line__variant\">${line.variant}</p>` : nothing}\n <p class=\"cart-line__price\">\n ${formatMoney(line.price)}\n ${\n line.original_price > line.price\n ? html`<s class=\"price__compare\"\n ><span class=\"visually-hidden\">${t('cart.oldPrice')}</span>\n ${formatMoney(line.original_price)}</s\n >`\n : nothing\n }\n </p>\n </div>\n <form class=\"cart-line__qty\" data-part=\"quantity\" @submit=${(event: Event) => event.preventDefault()}>\n <label class=\"visually-hidden\" for=${id}>${t('cart.quantity')}</label>\n <select\n class=\"select\"\n id=${id}\n name=\"qty\"\n data-test=\"cart-item-qty\"\n @change=${(event: Event) => this.onQuantity(line, event.target as HTMLSelectElement)}\n >\n ${quantities.map((qty) => html`<option value=${qty} ?selected=${qty === line.qty}>${qty}</option>`)}\n </select>\n </form>\n <p class=\"cart-line__total\" data-test=\"cart-line-total\">\n ${formatMoney(phpRound(line.price * line.qty, 2))}\n </p>\n <form\n class=\"cart-line__remove\"\n data-part=\"remove\"\n @submit=${(event: Event) => {\n event.preventDefault()\n void this.changeQuantity(line.id, 0)\n }}\n >\n <button\n type=\"submit\"\n class=\"link-button\"\n data-test=\"cart-item-remove\"\n aria-label=${t('cart.removeNamed', { name })}\n >\n ${t('cart.remove')}\n </button>\n </form>\n ${\n line.error\n ? html`<p class=\"cart-line__error\" role=\"alert\" data-test=\"cart-line-error\">${line.error}</p>`\n : nothing\n }\n </li>`\n }\n\n protected renderSummary(current: Cart): TemplateResult | typeof nothing {\n if (!current.items.length) return nothing\n return html`<div class=\"cart-summary\">\n ${this.coupon ? this.renderCoupon(current) : nothing}\n ${renderTotals(\n {\n subtotal: current.subtotal,\n discount: current.discount,\n shipping: current.shipping,\n taxAmount: current.tax_amount,\n taxPercent: current.tax_percent,\n total: current.total,\n },\n { shipping: 'charged', testId: 'cart-totals', totalTestId: 'cart-total' },\n )}\n ${\n cartBlocked(current.items)\n ? html`<button\n type=\"button\"\n class=\"button button--primary button--block\"\n disabled\n data-test=\"to-checkout-btn\"\n >\n ${t('cart.toCheckout')}\n </button>\n <p class=\"cart-summary__note\">${t('cart.blocked')}</p>`\n : html`<a\n class=\"button button--primary button--block\"\n href=${shopUrl('/shopping-cart?step=delivery')}\n data-test=\"to-checkout-btn\"\n >${t('cart.toCheckout')}</a\n >`\n }\n </div>`\n }\n\n protected renderCoupon(current: Cart): TemplateResult {\n const error = this.couponError\n return html`<form\n class=\"cart-coupon\"\n data-part=\"coupon\"\n @submit=${(event: Event) => {\n event.preventDefault()\n void this.applyCoupon(event.target as HTMLFormElement)\n }}\n >\n <label for=\"cart-coupon-code\">${t('cart.coupon')}</label>\n <div class=\"cart-coupon__field\">\n <input\n class=\"input\"\n id=\"cart-coupon-code\"\n name=\"coupon_code\"\n autocomplete=\"off\"\n data-test=\"coupon-input\"\n aria-invalid=${error ? 'true' : nothing}\n aria-describedby=${error ? 'cart-coupon-error' : nothing}\n />\n <button type=\"submit\" class=\"button button--small\" data-test=\"coupon-apply\">\n ${t('cart.applyCoupon')}\n </button>\n </div>\n <p class=\"field-error\" id=\"cart-coupon-error\" data-part=\"coupon-error\" ?hidden=${!error}>\n ${error ?? ''}\n </p>\n ${\n current.coupon_code\n ? html`<p class=\"cart-coupon__applied\" data-test=\"coupon-applied\">\n ${withStrong('cart.couponApplied', 'code', current.coupon_code)}\n </p>`\n : nothing\n }\n </form>`\n }\n\n private onQuantity(line: CartLine, select: HTMLSelectElement): void {\n const qty = Number(select.value)\n // Choosing the quantity already shown sends nothing: a request in flight while the visitor goes on to\n // checkout races the next page for the cart\n if (!Number.isInteger(qty) || qty === line.qty) return\n void this.changeQuantity(line.id, qty, () => {\n select.value = String(line.qty)\n })\n }\n\n /** Sets a line's quantity (0 removes it); `undo` puts the control back when the change fails. */\n async changeQuantity(id: number, qty: number, undo?: () => void): Promise<void> {\n await this.run(() => setQuantity({ id, qty }), t('cart.updateFailed'), undefined, undo)\n }\n\n async applyCoupon(form: HTMLFormElement): Promise<void> {\n const input = form.querySelector<HTMLInputElement>('[name=\"coupon_code\"]')\n const code = (input?.value ?? '').trim()\n if (code === '') {\n input?.focus()\n return\n }\n this.setCouponError(null)\n await this.run(\n async () => {\n await applyCoupon(code)\n if (input) input.value = ''\n },\n t('cart.couponFailed'),\n (message) => {\n // An unusable code is the visitor's to fix: say it next to the field\n this.setCouponError(message)\n input?.focus()\n return true\n },\n )\n }\n\n private setCouponError(message: string | null): void {\n this.couponError = message\n this.requestUpdate()\n }\n\n /**\n * Runs a change with the element busy. A refusal is shown by `inline` when it can (e.g. next to the coupon\n * field), otherwise in the error part and as a toast.\n */\n private async run(\n action: () => Promise<unknown>,\n fallback: string,\n inline?: (message: string) => boolean,\n undo?: () => void,\n ): Promise<void> {\n if (this.busy) {\n undo?.()\n return\n }\n this.busy = true\n this.setAttribute('aria-busy', 'true')\n this.showError(null)\n try {\n await action()\n } catch (error) {\n undo?.()\n const message = errorMessage(error, fallback)\n const refused = error instanceof HttpError && (error.status === 400 || error instanceof ValidationError)\n if (!(refused && inline?.(message))) {\n this.showError(message)\n }\n } finally {\n this.busy = false\n this.removeAttribute('aria-busy')\n }\n }\n\n private showError(message: string | null): void {\n const part = this.findPart('error')\n if (part) {\n part.textContent = message ?? ''\n part.hidden = message === null\n }\n if (message !== null) {\n showToast({ message, tone: 'error' })\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AAiCO,MAAM,kBAAkB,aAAa;AAAA,EAArC,cAAA;AAAA,UAAA,GAAA,SAAA;AAKL,SAAA,SAAS;AAET,SAAiB,OAAO,IAAI,iBAAiB,MAAM,MAAM,KAAK,KAAK;AACnE,SAAQ,OAAO;AACf,SAAQ,cAA6B;AACrC,SAAQ,SAAS;AAAA,EAAA;AAAA,EATjB,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,QAAQ,EAAE,MAAM,QAAA;AAAA,IAAQ;AAAA,EAC1B;AAAA,EASS,oBAA0B;AACjC,UAAM,kBAAA;AACN,SAAK,YAAY,OAAO;AACxB,SAAK,YAAY,SAAS;AAE1B,QAAI,CAAC,KAAK,UAAU,KAAK,KAAK,MAAM,MAAM,QAAQ;AAChD,WAAK,SAAS;AACd,YAAM,UAAU,KAAK,KAAK;AAC1B,WAAK,KAAK,mBAAmB;AAAA,QAC3B,UAAU,QAAQ,MAAM,CAAC,GAAG,YAAY,aAAa;AAAA,QACrD,OAAO,SAAS,QAAQ,O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9C,UAAM,OAAO,KAAK,SAAS,OAAO;AAClC,QAAI,MAAM;AACR,WAAK,cAAc,WAAW;AAC9B,WAAK,SAAS,YAAY;AAAA,IAC5B;AACA,QAAI,YAAY,MAAM;AACpB,gBAAU,EAAE,SAAS,MAAM,QAAA,CAAS;AAAA,IACtC;AAAA,EACF;AACF;"}
@@ -1,5 +1,7 @@
1
+ import { type TemplateResult } from 'lit';
1
2
  import { SpmktElement } from '../../lit/spmkt-element';
2
3
  import { type CheckoutStep } from '../../core/stores/checkout';
4
+ import type { Cart, CartLine } from '../../core/types';
3
5
  /**
4
6
  * Parts of <spmkt-checkout step="delivery|payment"> (the checkout page; the theme renders every step):
5
7
  * - panel (required, one per step): a step's region, with data-step; hidden unless it is the current step. Its
@@ -7,12 +9,11 @@ import { type CheckoutStep } from '../../core/stores/checkout';
7
9
  * - nav-step (optional, one per step): marked aria-current="step" for the current step
8
10
  * - go (optional, any number): buttons with data-go="<step>"; those leading to payment stay disabled until the
9
11
  * delivery step is complete and no checkout request is in flight (the choice is priced)
10
- * - summary (optional): re-rendered from the theme fragment `summary-fragment` when a checkout request returns
11
- * it (spmkt:checkout-updated, e.g. after a delivery is chosen)
12
- * - cart (optional): <script type="application/json"> with the cart as the page rendered it, for analytics
12
+ * - summary (optional): empty in the theme's markup; the element renders the order's lines and totals from the
13
+ * cart store, so a priced delivery choice (summaryPriced) shows at once
13
14
  *
14
- * When an instant payment places the order, its `confirmation-fragment` (from spmkt:checkout-updated) takes
15
- * the element's place, and the URL becomes ?step=done.
15
+ * When an instant payment places the order (spmkt:order-placed), a <spmkt-order-confirmation> with that order
16
+ * takes the element's place, and the URL becomes ?step=done.
16
17
  *
17
18
  * The step is kept in ?step= (pushState); Back and Forward move between steps. A step that cannot be entered
18
19
  * yet (payment before the delivery step is complete, e.g. after a reload in another tab) shows the first one
@@ -23,7 +24,6 @@ export interface CheckoutParts {
23
24
  'nav-step'?: HTMLElement[];
24
25
  go?: HTMLButtonElement[];
25
26
  summary?: HTMLElement;
26
- cart?: HTMLScriptElement;
27
27
  }
28
28
  type Step = Exclude<CheckoutStep, 'cart' | 'done'>;
29
29
  export declare class SpmktCheckout extends SpmktElement {
@@ -31,35 +31,28 @@ export declare class SpmktCheckout extends SpmktElement {
31
31
  step: {
32
32
  type: StringConstructor;
33
33
  };
34
- summaryFragment: {
35
- type: StringConstructor;
36
- attribute: string;
37
- };
38
- confirmationFragment: {
39
- type: StringConstructor;
40
- attribute: string;
41
- };
42
34
  };
43
35
  /** The step the server rendered (from ?step=) */
44
36
  step: Step;
45
- summaryFragment: string;
46
- /** The fragment of a placed order (instant payment), shown in place of the whole checkout */
47
- confirmationFragment: string;
48
37
  private current;
49
38
  private begun;
39
+ private readonly summary;
50
40
  constructor();
51
41
  connectedCallback(): void;
42
+ protected updated(): void;
43
+ /** The order beside the steps: its lines and totals; shipping is "by the choice" until one is priced. */
44
+ protected renderSummary(current: Cart, priced: boolean): TemplateResult;
45
+ protected renderLine(line: CartLine): TemplateResult;
52
46
  /** Moves to a step (recording it in the history) if it can be entered. */
53
47
  go(step: Step): void;
54
48
  private show;
55
49
  /**
56
- * The order is placed: the server's confirmation takes the element's place (as spmkt-collection does with
57
- * its fragment; replacing only the children would eject Lit's markers), and its purchase event goes out once.
50
+ * The order is placed: a <spmkt-order-confirmation> with it takes the element's place (it announces the
51
+ * purchase once and forgets the checkout draft), and its heading takes the focus once it has rendered.
58
52
  * ?step=done; a reload shows the (now empty) cart.
59
53
  */
60
54
  private confirm;
61
55
  private fromUrl;
62
56
  private isStep;
63
- private readCart;
64
57
  }
65
58
  export {};
@@ -1,21 +1,28 @@
1
+ import { html, nothing } from "lit";
2
+ import { repeat } from "lit/directives/repeat.js";
1
3
  import { SpmktElement } from "../../lit/spmkt-element.js";
2
4
  import { SignalController } from "../../lit/signal-controller.js";
3
- import { swapInto } from "../../lit/fragments.js";
4
- import { dispatchPageEvents } from "../../core/page-events.js";
5
5
  import { dispatch } from "../../core/events.js";
6
6
  import { shopUrl } from "../../core/config.js";
7
- import { deliveryComplete, checkoutPending, setCheckoutCart, completeDelivery, stepToShow, beginCheckout } from "../../core/stores/checkout.js";
7
+ import { t } from "../../core/i18n.js";
8
+ import { formatMoney, phpRound } from "../../core/money.js";
9
+ import { cart } from "../../core/stores/cart.js";
10
+ import { summaryPriced, deliveryComplete, checkoutPending, completeDelivery, stepToShow, beginCheckout } from "../../core/stores/checkout.js";
8
11
  import { customerSignedIn } from "../../core/stores/customer.js";
12
+ import { renderTotals, lineName } from "../shared/totals.js";
9
13
  import { checkoutDraft } from "../../core/stores/checkout-draft.js";
14
+ const CONFIRMATION_TAG = "spmkt-order-confirmation";
10
15
  const STEPS = ["delivery", "payment"];
11
16
  class SpmktCheckout extends SpmktElement {
12
17
  constructor() {
13
18
  super();
14
19
  this.step = "delivery";
15
- this.summaryFragment = "checkout-summary";
16
- this.confirmationFragment = "order-confirmation";
17
20
  this.current = null;
18
21
  this.begun = false;
22
+ this.summary = new SignalController(this, () => ({
23
+ cart: cart.value,
24
+ priced: summaryPriced.value
25
+ }));
19
26
  new SignalController(
20
27
  this,
21
28
  () => {
@@ -32,16 +39,12 @@ class SpmktCheckout extends SpmktElement {
32
39
  }
33
40
  static {
34
41
  this.properties = {
35
- step: { type: String },
36
- summaryFragment: { type: String, attribute: "summary-fragment" },
37
- confirmationFragment: { type: String, attribute: "confirmation-fragment" }
42
+ step: { type: String }
38
43
  };
39
44
  }
40
45
  connectedCallback() {
41
46
  super.connectedCallback();
42
47
  this.requirePart("panel");
43
- const cart = this.readCart();
44
- if (cart) setCheckoutCart(cart);
45
48
  this.listen(this, "click", (event) => {
46
49
  const button = event.target.closest('[data-part="go"][data-go]');
47
50
  if (button && this.contains(button)) {
@@ -49,20 +52,58 @@ class SpmktCheckout extends SpmktElement {
49
52
  this.go(button.dataset.go);
50
53
  }
51
54
  });
52
- this.listen(this, "spmkt:checkout-updated", (event) => {
53
- const fragments = event.detail.fragments;
54
- const confirmation = fragments[this.confirmationFragment];
55
- if (confirmation) {
56
- this.confirm(confirmation);
57
- return;
58
- }
59
- const summary = this.findPart("summary");
60
- const html = fragments[this.summaryFragment];
61
- if (summary && html !== void 0) swapInto(summary, html);
55
+ this.listen(this, "spmkt:order-placed", (event) => {
56
+ void this.confirm(event.detail.order);
62
57
  });
63
58
  this.listen(window, "popstate", () => this.show(this.fromUrl(), { history: "none" }));
64
59
  this.show(this.isStep(this.step) ? this.step : "delivery", { history: "replace", focus: false });
65
60
  }
61
+ updated() {
62
+ const part = this.findPart("summary");
63
+ if (!part) return;
64
+ this.renderPart("summary", this.renderSummary(this.summary.value.cart, this.summary.value.priced));
65
+ part.removeAttribute("aria-busy");
66
+ }
67
+ /** The order beside the steps: its lines and totals; shipping is "by the choice" until one is priced. */
68
+ renderSummary(current, priced) {
69
+ return html`<div class="checkout-summary">
70
+ <h2 class="checkout-summary__title">${t("checkout.summaryTitle")}</h2>
71
+ <ul role="list" class="checkout-summary__lines">
72
+ ${repeat(
73
+ current.items,
74
+ (line) => line.id,
75
+ (line) => this.renderLine(line)
76
+ )}
77
+ </ul>
78
+ ${renderTotals(
79
+ {
80
+ subtotal: current.subtotal,
81
+ discount: current.discount,
82
+ coupon: current.coupon_code,
83
+ shipping: current.shipping,
84
+ taxAmount: current.tax_amount,
85
+ taxPercent: current.tax_percent,
86
+ total: current.total
87
+ },
88
+ {
89
+ shipping: priced ? "always" : "by-choice",
90
+ testId: "checkout-totals",
91
+ totalTestId: "checkout-total",
92
+ shippingTestId: "checkout-shipping"
93
+ }
94
+ )}
95
+ </div>`;
96
+ }
97
+ renderLine(line) {
98
+ return html`<li class="checkout-summary__line">
99
+ <span class="checkout-summary__name">
100
+ ${lineName(line)}
101
+ ${line.variant ? html`<span class="checkout-summary__variant">${line.variant}</span>` : nothing}
102
+ <span class="checkout-summary__qty">${line.qty} &times; ${formatMoney(line.price)}</span>
103
+ </span>
104
+ <span>${formatMoney(phpRound(line.price * line.qty, 2))}</span>
105
+ </li>`;
106
+ }
66
107
  /** Moves to a step (recording it in the history) if it can be entered. */
67
108
  go(step) {
68
109
  if (step === "payment" && this.current === "delivery" && deliveryComplete()) {
@@ -101,26 +142,26 @@ class SpmktCheckout extends SpmktElement {
101
142
  this.emit("spmkt:checkout-step", { step });
102
143
  }
103
144
  /**
104
- * The order is placed: the server's confirmation takes the element's place (as spmkt-collection does with
105
- * its fragment; replacing only the children would eject Lit's markers), and its purchase event goes out once.
145
+ * The order is placed: a <spmkt-order-confirmation> with it takes the element's place (it announces the
146
+ * purchase once and forgets the checkout draft), and its heading takes the focus once it has rendered.
106
147
  * ?step=done; a reload shows the (now empty) cart.
107
148
  */
108
- confirm(html) {
109
- const template = document.createElement("template");
110
- template.innerHTML = html;
111
- const confirmation = template.content.firstElementChild;
149
+ async confirm(order) {
150
+ const confirmation = document.createElement(CONFIRMATION_TAG);
151
+ const content = document.createElement("div");
152
+ content.dataset.part = "content";
153
+ confirmation.append(content);
154
+ confirmation.order = order;
112
155
  this.current = null;
113
- this.replaceWith(template.content);
156
+ this.replaceWith(confirmation);
114
157
  const url = new URL(location.href);
115
158
  url.searchParams.set("step", "done");
116
159
  history.replaceState({ ...history.state, spmktCheckout: "done" }, "", url);
117
- if (confirmation) {
118
- dispatchPageEvents(confirmation);
119
- const heading = confirmation.matches("h1, h2") ? confirmation : confirmation.querySelector("h1, h2");
120
- heading?.focus();
121
- }
122
160
  window.scrollTo({ top: 0 });
123
161
  dispatch(document, "spmkt:checkout-step", { step: "done" });
162
+ await customElements.whenDefined(CONFIRMATION_TAG);
163
+ await confirmation.updateComplete;
164
+ confirmation.querySelector("h1, h2")?.focus();
124
165
  }
125
166
  fromUrl() {
126
167
  const step = new URL(location.href).searchParams.get("step");
@@ -129,14 +170,6 @@ class SpmktCheckout extends SpmktElement {
129
170
  isStep(value) {
130
171
  return STEPS.includes(value);
131
172
  }
132
- readCart() {
133
- try {
134
- const text = this.findPart("cart")?.textContent;
135
- return text ? JSON.parse(text) : null;
136
- } catch {
137
- return null;
138
- }
139
- }
140
173
  }
141
174
  export {
142
175
  SpmktCheckout