@wikala/spmkt 4.0.0-alpha.7 → 4.0.0-alpha.8
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/analytics/facebook-pixel.js +2 -1
- package/dist/analytics/facebook-pixel.js.map +1 -1
- package/dist/analytics/ga4.js +2 -1
- package/dist/analytics/ga4.js.map +1 -1
- package/dist/analytics/spmkt3.js +4 -2
- package/dist/analytics/spmkt3.js.map +1 -1
- package/dist/core/events.d.ts +9 -0
- package/dist/core/events.js.map +1 -1
- package/dist/core/index.d.ts +1 -1
- package/dist/core/stores/cart.d.ts +1 -1
- package/dist/core/stores/cart.js +2 -1
- package/dist/core/stores/cart.js.map +1 -1
- package/dist/elements/add-to-cart/add-to-cart.d.ts +11 -1
- package/dist/elements/add-to-cart/add-to-cart.js +37 -3
- package/dist/elements/add-to-cart/add-to-cart.js.map +1 -1
- package/dist/elements/back-in-stock/back-in-stock.js +1 -2
- package/dist/elements/back-in-stock/back-in-stock.js.map +1 -1
- package/dist/elements/cart/cart.d.ts +2 -1
- package/dist/elements/cart/cart.js +6 -12
- package/dist/elements/cart/cart.js.map +1 -1
- package/dist/elements/checkout-payment/checkout-payment.js +1 -2
- package/dist/elements/checkout-payment/checkout-payment.js.map +1 -1
- package/dist/elements/collection/collection.js +1 -2
- package/dist/elements/collection/collection.js.map +1 -1
- package/dist/elements/questions/questions.js +1 -2
- package/dist/elements/questions/questions.js.map +1 -1
- package/dist/elements/review-form/review-form.js +1 -2
- package/dist/elements/review-form/review-form.js.map +1 -1
- package/dist/elements/shared/coupon.js +2 -1
- package/dist/elements/shared/coupon.js.map +1 -1
- package/dist/elements/shared/json-form.js +1 -2
- package/dist/elements/shared/json-form.js.map +1 -1
- package/dist/elements/shared/paged-section.js +1 -2
- package/dist/elements/shared/paged-section.js.map +1 -1
- package/dist/elements/variant-picker/variant-picker.d.ts +19 -8
- package/dist/elements/variant-picker/variant-picker.js +32 -22
- package/dist/elements/variant-picker/variant-picker.js.map +1 -1
- package/dist/lit/index.d.ts +1 -1
- package/dist/lit/index.js +2 -1
- package/dist/lit/spmkt-element.d.ts +11 -0
- package/dist/lit/spmkt-element.js +19 -1
- package/dist/lit/spmkt-element.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
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 } from '../shared/totals'\nimport { couponCode, renderCouponForm } from '../shared/coupon'\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 return renderCouponForm({\n prefix: 'cart-coupon',\n error: this.couponError,\n applied: current.coupon_code,\n onSubmit: (form) => void this.applyCoupon(form),\n })\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, code } = couponCode(form)\n if (code === '') return\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":";;;;;;;;;;;;;;AAkCO,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,OAAO,CAAC;AAAA,QAChC,OAAO,QAAQ,MAAM,IAAI,CAAC,SAAS,eAAe,IAAI,CAAC;AAAA,MAAA,CACxD;AAAA,IACH;AAAA,EACF;AAAA,EAEmB,UAAgB;AACjC,UAAM,QAAQ,KAAK,YAAY,OAAO;AACtC,UAAM,WAAW,MAAM,SAAS,SAAS,aAAa;AACtD,SAAK,WAAW,SAAS,KAAK,YAAY,KAAK,KAAK,KAAK,CAAC;AAC1D,SAAK,WAAW,WAAW,KAAK,cAAc,KAAK,KAAK,KAAK,CAAC;AAC9D,UAAM,gBAAgB,WAAW;AAC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AAA,IACF;AACA,SAAK,OAAO;AACZ,SAAK,aAAa,aAAa,MAAM;AACrC,SAAK,UAAU,IAAI;AACnB,QAAI;AACF,YAAM,OAAA;AAAA,IACR,SAAS,OAAO;AACd,aAAA;AACA,YAAM,UAAU,aAAa,OAAO,QAAQ;AAC5C,YAAM,UAAU,iBAAiB,cAAc,MAAM,WAAW,OAAO,iBAAiB;AACxF,UAAI,EAAE,WAAW,SAAS,OAAO,IAAI;AACnC,aAAK,UAAU,OAAO;AAAA,MACxB;AAAA,IACF,UAAA;AACE,WAAK,OAAO;AACZ,WAAK,gBAAgB,WAAW;AAAA,IAClC;AAAA,EACF;AAAA,EAEQ,UAAU,SAA8B;AAC9C,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
|
+
{"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 } from '../shared/totals'\nimport { couponCode, renderCouponForm } from '../shared/coupon'\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 * A line's quantity and remove controls are no <form>: the Google tag would report a change as a form start\n * (spmkt 3's cart had none). 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 <div class=\"cart-line__qty\" data-part=\"quantity\">\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 </div>\n <p class=\"cart-line__total\" data-test=\"cart-line-total\">\n ${formatMoney(phpRound(line.price * line.qty, 2))}\n </p>\n <div class=\"cart-line__remove\" data-part=\"remove\">\n <button\n type=\"button\"\n class=\"link-button\"\n data-test=\"cart-item-remove\"\n aria-label=${t('cart.removeNamed', { name })}\n @click=${() => void this.changeQuantity(line.id, 0)}\n >\n ${t('cart.remove')}\n </button>\n </div>\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 return renderCouponForm({\n prefix: 'cart-coupon',\n error: this.couponError,\n applied: current.coupon_code,\n onSubmit: (form) => void this.applyCoupon(form),\n })\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, code } = couponCode(form)\n if (code === '') return\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":";;;;;;;;;;;;;;AAmCO,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,UAA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a,QAAQ;AAAA,MAC3B;AAAA,MACA,EAAE,mBAAmB;AAAA,MACrB,CAAC,YAAY;AAEX,aAAK,eAAe,OAAO;AAC3B,eAAO,MAAA;AACP,eAAO;AAAA,MACT;AAAA,IAAA;AAAA,EAEJ;AAAA,EAEQ,eAAe,SAA8B;AACnD,SAAK,cAAc;AACnB,SAAK,cAAA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,IACZ,QACA,UACA,QACA,MACe;AACf,QAAI,KAAK,MAAM;AACb,aAAA;AACA;AAAA,IACF;AACA,SAAK,OAAO;AACZ,SAAK,aAAa,aAAa,MAAM;AACrC,SAAK,UAAU,IAAI;AACnB,QAAI;AACF,YAAM,OAAA;AAAA,IACR,SAAS,OAAO;AACd,aAAA;AACA,YAAM,UAAU,aAAa,OAAO,QAAQ;AAC5C,YAAM,UAAU,iBAAiB,cAAc,MAAM,WAAW,OAAO,iBAAiB;AACxF,UAAI,EAAE,WAAW,SAAS,OAAO,IAAI;AACnC,aAAK,UAAU,OAAO;AAAA,MACxB;AAAA,IACF,UAAA;AACE,WAAK,OAAO;AACZ,WAAK,gBAAgB,WAAW;AAAA,IAClC;AAAA,EACF;AAAA,EAEQ,UAAU,SAA8B;AAC9C,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;"}
|
|
@@ -39,8 +39,7 @@ class SpmktCheckoutPayment extends SpmktElement {
|
|
|
39
39
|
const form = this.requirePart("form");
|
|
40
40
|
this.requirePart("methods");
|
|
41
41
|
this.restore(form);
|
|
42
|
-
this.
|
|
43
|
-
event.preventDefault();
|
|
42
|
+
this.submitInPlace(form, () => {
|
|
44
43
|
void this.place();
|
|
45
44
|
});
|
|
46
45
|
this.listen(form, "change", (event) => this.changed(event.target));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkout-payment.js","sources":["../../../src/elements/checkout-payment/checkout-payment.ts"],"sourcesContent":["import { html, nothing } from 'lit'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { SignalController } from '../../lit/signal-controller'\nimport { clearFieldErrors, errorMessage, showFieldErrors } from '../../lit/forms'\nimport { HttpError, ValidationError, isAbortError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { recaptchaToken } from '../../core/recaptcha'\nimport { storefront } from '../../core/state'\nimport {\n checkoutDraft,\n loadPaymentMethods,\n postToGateway,\n submitOrder,\n passOrderChecks,\n updateDraft,\n} from '../../core/stores/checkout'\nimport { customerSignedIn } from '../../core/stores/customer'\nimport type { CheckoutAddress, PaymentMethodOption } from '../../core/types'\nimport { showToast } from '../toaster/toaster'\n\n/**\n * Parts of <spmkt-checkout-payment> (the payment step):\n * - form (required): submitting it places the order. Fields: `note`; `accept_tos` (a checkbox, when the shop\n * asks for the terms; its [data-error-for] slot's data-message is shown when it is not ticked). Guests:\n * `business` (checkbox; only when the shop takes business orders, checkout.orderAsBusiness) with\n * company_name, company_tax_id, company_business_id in the `company` part, and\n * `billing_same` (checkbox) with the address fields in the `billing` part. Customers: `billing_address_id`\n * (a select; each option's data-type says personal or business).\n * - methods (required, owned): the payment methods for the chosen delivery (POST cart/payment-methods), radios\n * named payment_method_id (renderMethod)\n * - waiting (optional): shown until a delivery is chosen\n * - submit, error (optional)\n *\n * Payment methods that failed to load are asked for again when the delivery or billing changes, or when the\n * browser comes back online.\n *\n * A two-step method (a card gateway) sends the browser to the gateway with the server's URL and payload. An\n * instant one comes back with the order, which goes out as spmkt:order-placed: spmkt-checkout shows its\n * confirmation in place of the checkout.\n */\nexport interface CheckoutPaymentParts {\n form: HTMLFormElement\n methods: HTMLElement\n company?: HTMLElement\n billing?: HTMLElement\n waiting?: HTMLElement\n submit?: HTMLButtonElement\n error?: HTMLElement\n}\n\nexport class SpmktCheckoutPayment extends SpmktElement {\n private methods: PaymentMethodOption[] = []\n private chosen: number | null = null\n private methodsKey: string | null | undefined = undefined\n private loading: AbortController | undefined\n private busy = false\n private loadFailed = false\n\n constructor() {\n super()\n // The methods depend on the delivery and on whether a business is billed\n new SignalController(\n this,\n () => {\n const draft = checkoutDraft.value\n return draft.delivery ? `${draft.delivery.kind}:${draft.delivery.costId}:${draft.business}` : null\n },\n (key) => {\n if (key === this.methodsKey) return\n this.methodsKey = key\n void this.load(key)\n },\n )\n }\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.requirePart<HTMLFormElement>('form')\n this.requirePart('methods')\n this.restore(form)\n this.listen(form, 'submit', (event) => {\n event.preventDefault()\n void this.place()\n })\n this.listen(form, 'change', (event) => this.changed(event.target as HTMLInputElement))\n // Methods that could not be loaded: try again once there is a connection\n this.listen(window, 'online', () => {\n if (this.methodsKey === undefined) void this.retryMethods()\n })\n // Back from the gateway (the back/forward cache restores the page as it was left): usable again\n this.listen(window, 'pageshow', (event) => {\n if ((event as PageTransitionEvent).persisted) this.idle()\n })\n this.onDisconnect(() => this.loading?.abort())\n }\n\n /** Loads the payment methods for the draft again. */\n private retryMethods(): Promise<void> {\n const draft = checkoutDraft.value\n const key = draft.delivery ? `${draft.delivery.kind}:${draft.delivery.costId}:${draft.business}` : null\n this.methodsKey = key\n return this.load(key)\n }\n\n private idle(): void {\n this.busy = false\n this.findPart('submit')?.removeAttribute('aria-busy')\n }\n\n /** The shop takes business orders (company fields, business billing). */\n private get businessOrders(): boolean {\n return storefront().checkout.orderAsBusiness\n }\n\n /** The draft's billing choices back into the form (after a reload or Back). */\n private restore(form: HTMLFormElement): void {\n const draft = checkoutDraft.value\n const business = form.elements.namedItem('business')\n if (business instanceof HTMLInputElement) {\n business.checked = draft.business && this.businessOrders\n for (const [name, value] of Object.entries(draft.company ?? {})) {\n const input = form.elements.namedItem(name)\n if (input instanceof HTMLInputElement) input.value = value\n }\n }\n const same = form.elements.namedItem('billing_same')\n if (same instanceof HTMLInputElement) {\n same.checked = draft.billingAddress === null\n for (const [name, value] of Object.entries(draft.billingAddress ?? {})) {\n const input = this.findPart('billing')?.querySelector<HTMLInputElement | HTMLSelectElement>(\n `[name=\"${name}\"]`,\n )\n if (input && value !== null && value !== undefined) input.value = String(value)\n }\n }\n const select = form.elements.namedItem('billing_address_id')\n if (select instanceof HTMLSelectElement && draft.billingAddressId !== null) {\n select.value = String(draft.billingAddressId)\n }\n this.toggleParts(form)\n }\n\n private toggleParts(form: HTMLFormElement): void {\n const business = form.elements.namedItem('business')\n const company = this.findPart('company')\n if (company)\n company.hidden = !(business instanceof HTMLInputElement && business.checked && this.businessOrders)\n const same = form.elements.namedItem('billing_same')\n const billing = this.findPart('billing')\n if (billing && same instanceof HTMLInputElement) billing.hidden = same.checked\n }\n\n private changed(input: HTMLInputElement): void {\n const form = this.requirePart<HTMLFormElement>('form')\n if (input.name === 'business') {\n this.toggleParts(form)\n updateDraft({ business: input.checked && this.businessOrders })\n } else if (input.name === 'billing_same') {\n this.toggleParts(form)\n } else if (input.name === 'billing_address_id') {\n const option = (input as unknown as HTMLSelectElement).selectedOptions[0]\n updateDraft({\n billingAddressId: input.value ? Number(input.value) : null,\n business: option?.dataset.type === 'business' && this.businessOrders,\n })\n } else if (input.name === 'payment_method_id') {\n this.chosen = Number(input.value)\n const slot = form.querySelector<HTMLElement>('[data-error-for=\"payment_method_id\"]')\n if (slot) slot.hidden = true\n }\n }\n\n private async load(key: string | null): Promise<void> {\n this.loading?.abort()\n const waiting = this.findPart('waiting')\n if (waiting) waiting.hidden = key !== null\n if (key === null) {\n this.methods = []\n this.paint()\n return\n }\n const controller = (this.loading = new AbortController())\n const list = this.requirePart('methods')\n list.setAttribute('aria-busy', 'true')\n try {\n this.methods = await loadPaymentMethods(controller.signal)\n if (!this.methods.some((method) => method.id === this.chosen)) this.chosen = null\n this.paint()\n if (this.loadFailed) this.showError(null)\n this.loadFailed = false\n } catch (error) {\n if (isAbortError(error)) return\n this.showError(errorMessage(error))\n this.loadFailed = true\n // Not loaded: the next change of the delivery or billing (even to the same choice) asks again\n this.methodsKey = undefined\n } finally {\n if (this.loading === controller) list.removeAttribute('aria-busy')\n }\n }\n\n private paint(): void {\n this.renderPart(\n 'methods',\n html`${this.methods.map((method) => this.renderMethod(method, method.id === this.chosen))}`,\n )\n }\n\n /** One payment method: a radio named payment_method_id inside a label with data-test=\"payment-method-<id>\". */\n protected renderMethod(method: PaymentMethodOption, checked: boolean): unknown {\n return html`<label class=\"checkout-choice\" data-test=\"payment-method-${method.id}\">\n <input type=\"radio\" name=\"payment_method_id\" .value=${String(method.id)} .checked=${checked} />\n <span class=\"checkout-choice__text\">\n <strong>${method.display_name}</strong>\n ${\n method.description\n ? html`<span class=\"checkout-choice__note checkout-choice__note--pre\"\n >${method.description}</span\n >`\n : nothing\n }\n </span>\n </label>`\n }\n\n /** Validates what only the page can, keeps the billing choices in the draft, and places the order. */\n async place(): Promise<void> {\n if (this.busy) return\n const form = this.requirePart<HTMLFormElement>('form')\n clearFieldErrors(form)\n this.showError(null)\n if (!this.checkPage(form)) return\n\n const values = Object.fromEntries(\n Array.from(new FormData(form)).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string',\n ),\n )\n this.keepBilling(form, values)\n const method = this.methods.find((m) => m.id === this.chosen)\n\n const submit = this.findPart('submit')\n this.busy = true\n submit?.setAttribute('aria-busy', 'true')\n let leaving = false\n try {\n // Checks other elements add (the age check); each tells the visitor itself why it stopped\n if (!(await passOrderChecks())) return\n const result = await submitOrder({\n paymentMethodId: this.chosen!,\n paymentName: method?.display_name,\n note: values.note?.trim() || null,\n recaptchaToken: await recaptchaToken('checkout'),\n })\n if (result.kind === 'gateway') {\n leaving = true\n this.navigate(result)\n } else {\n this.emit('spmkt:order-placed', { order: result.order })\n }\n } catch (error) {\n this.showFailure(form, error)\n } finally {\n // Stay busy while the browser leaves for the gateway (pageshow undoes it if the visitor comes Back)\n if (!leaving) this.idle()\n }\n }\n\n /** Sends the browser to the gateway; replaceable (tests, themes). */\n navigate: (redirect: { url: string; payload: Record<string, string | number> }) => void = (redirect) => {\n postToGateway(redirect)\n }\n\n /** What the page can check before asking the server: a method is chosen, and the terms are accepted. */\n private checkPage(form: HTMLFormElement): boolean {\n const errors: Record<string, string[]> = {}\n if (this.chosen === null) {\n errors.payment_method_id = [t('checkout.choosePayment')]\n }\n const tos = form.elements.namedItem('accept_tos')\n if (storefront().checkout.acceptTos && tos instanceof HTMLInputElement && !tos.checked) {\n const slot = form.querySelector<HTMLElement>('[data-error-for=\"accept_tos\"]')\n errors.accept_tos = [slot?.dataset.message || t('checkout.acceptTos')]\n }\n if (Object.keys(errors).length === 0) return true\n showFieldErrors(form, errors)\n form.querySelector<HTMLElement>('[data-error-for]:not([hidden])')?.scrollIntoView({ block: 'center' })\n return false\n }\n\n private keepBilling(form: HTMLFormElement, values: Record<string, string>): void {\n if (customerSignedIn.value) return\n const business = values.business === '1' && this.businessOrders\n const company = business\n ? {\n company_name: values.company_name ?? '',\n company_tax_id: values.company_tax_id ?? '',\n company_business_id: values.company_business_id ?? '',\n }\n : null\n let billingAddress: CheckoutAddress | null = null\n const billing = this.findPart('billing')\n if (billing && !billing.hidden) {\n const field = (name: string) =>\n billing.querySelector<HTMLInputElement | HTMLSelectElement>(`[name=\"${name}\"]`)?.value.trim() ?? ''\n billingAddress = {\n first_name: field('first_name'),\n last_name: field('last_name'),\n address1: field('address1'),\n city: field('city'),\n postcode: field('postcode'),\n country_id: Number(field('country_id')),\n phone: field('phone') || null,\n }\n }\n updateDraft({ business, company, billingAddress })\n }\n\n /** A refused order: fields this step owns get their message; the rest goes to the error part and a toast. */\n private showFailure(form: HTMLFormElement, error: unknown): void {\n if (error instanceof ValidationError) {\n const mine: Record<string, string[]> = {}\n const others: string[] = []\n for (const [field, messages] of Object.entries(error.errors)) {\n const name = field.replace(/^billing_address\\./, '')\n if (form.querySelector(`[data-error-for=\"${CSS.escape(name)}\"]`)) mine[name] = messages\n else if (messages[0]) others.push(messages[0])\n }\n showFieldErrors(form, mine)\n // Errors of the delivery step (an address, the e-mail) send the visitor back there\n if (others.length) this.showError(`${others.join(' ')} ${t('checkout.checkDelivery')}`)\n form.querySelector<HTMLElement>('[aria-invalid=\"true\"]')?.focus()\n return\n }\n const message = errorMessage(error, t('checkout.failed'))\n this.showError(message)\n if (!(error instanceof HttpError && error.status === 400)) return\n showToast({ message, tone: 'error' })\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 }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAkDO,MAAM,6BAA6B,aAAa;AAAA,EAQrD,cAAc;AACZ,UAAA;AARF,SAAQ,UAAiC,CAAA;AACzC,SAAQ,SAAwB;AAChC,SAAQ,aAAwC;AAEhD,SAAQ,OAAO;AACf,SAAQ,aAAa;AAqNrB,SAAA,WAA0F,CAAC,aAAa;AACtG,oBAAc,QAAQ;AAAA,IACxB;AAlNE,QAAI;AAAA,MACF;AAAA,MACA,MAAM;AACJ,cAAM,QAAQ,cAAc;AAC5B,eAAO,MAAM,WAAW,GAAG,MAAM,SAAS,IAAI,IAAI,MAAM,SAAS,MAAM,IAAI,MAAM,QAAQ,KAAK;AAAA,MAChG;AAAA,MACA,CAAC,QAAQ;AACP,YAAI,QAAQ,KAAK,WAAY;AAC7B,aAAK,aAAa;AAClB,aAAK,KAAK,KAAK,GAAG;AAAA,MACpB;AAAA,IAAA;AAAA,EAEJ;AAAA,EAES,oBAA0B;AACjC,UAAM,kBAAA;AACN,UAAM,OAAO,KAAK,YAA6B,MAAM;AACrD,SAAK,YAAY,SAAS;AAC1B,SAAK,QAAQ,IAAI;AACjB,SAAK,OAAO,MAAM,UAAU,CAAC,UAAU;AACrC,YAAM,eAAA;AACN,WAAK,KAAK,MAAA;AAAA,IACZ,CAAC;AACD,SAAK,OAAO,MAAM,UAAU,CAAC,UAAU,KAAK,QAAQ,MAAM,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AQ,KAAK,OAAO,QAAQ,MAAM,MAAM,GAAG;AAC5D,cAAM,OAAO,MAAM,QAAQ,sBAAsB,EAAE;AACnD,YAAI,KAAK,cAAc,oBAAoB,IAAI,OAAO,IAAI,CAAC,IAAI,EAAG,MAAK,IAAI,IAAI;AAAA,iBACtE,SAAS,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC;AAAA,MAC/C;AACA,sBAAgB,MAAM,IAAI;AAE1B,UAAI,OAAO,OAAQ,MAAK,UAAU,GAAG,OAAO,KAAK,GAAG,CAAC,IAAI,EAAE,wBAAwB,CAAC,EAAE;AACtF,WAAK,cAA2B,uBAAuB,GAAG,MAAA;AAC1D;AAAA,IACF;AACA,UAAM,UAAU,aAAa,OAAO,EAAE,iBAAiB,CAAC;AACxD,SAAK,UAAU,OAAO;AACtB,QAAI,EAAE,iBAAiB,aAAa,MAAM,WAAW,KAAM;AAC3D,cAAU,EAAE,SAAS,MAAM,QAAA,CAAS;AAAA,EACtC;AAAA,EAEQ,UAAU,SAA8B;AAC9C,UAAM,OAAO,KAAK,SAAS,OAAO;AAClC,QAAI,MAAM;AACR,WAAK,cAAc,WAAW;AAC9B,WAAK,SAAS,YAAY;AAAA,IAC5B;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"checkout-payment.js","sources":["../../../src/elements/checkout-payment/checkout-payment.ts"],"sourcesContent":["import { html, nothing } from 'lit'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { SignalController } from '../../lit/signal-controller'\nimport { clearFieldErrors, errorMessage, showFieldErrors } from '../../lit/forms'\nimport { HttpError, ValidationError, isAbortError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { recaptchaToken } from '../../core/recaptcha'\nimport { storefront } from '../../core/state'\nimport {\n checkoutDraft,\n loadPaymentMethods,\n postToGateway,\n submitOrder,\n passOrderChecks,\n updateDraft,\n} from '../../core/stores/checkout'\nimport { customerSignedIn } from '../../core/stores/customer'\nimport type { CheckoutAddress, PaymentMethodOption } from '../../core/types'\nimport { showToast } from '../toaster/toaster'\n\n/**\n * Parts of <spmkt-checkout-payment> (the payment step):\n * - form (required): submitting it places the order. Fields: `note`; `accept_tos` (a checkbox, when the shop\n * asks for the terms; its [data-error-for] slot's data-message is shown when it is not ticked). Guests:\n * `business` (checkbox; only when the shop takes business orders, checkout.orderAsBusiness) with\n * company_name, company_tax_id, company_business_id in the `company` part, and\n * `billing_same` (checkbox) with the address fields in the `billing` part. Customers: `billing_address_id`\n * (a select; each option's data-type says personal or business).\n * - methods (required, owned): the payment methods for the chosen delivery (POST cart/payment-methods), radios\n * named payment_method_id (renderMethod)\n * - waiting (optional): shown until a delivery is chosen\n * - submit, error (optional)\n *\n * Payment methods that failed to load are asked for again when the delivery or billing changes, or when the\n * browser comes back online.\n *\n * A two-step method (a card gateway) sends the browser to the gateway with the server's URL and payload. An\n * instant one comes back with the order, which goes out as spmkt:order-placed: spmkt-checkout shows its\n * confirmation in place of the checkout.\n */\nexport interface CheckoutPaymentParts {\n form: HTMLFormElement\n methods: HTMLElement\n company?: HTMLElement\n billing?: HTMLElement\n waiting?: HTMLElement\n submit?: HTMLButtonElement\n error?: HTMLElement\n}\n\nexport class SpmktCheckoutPayment extends SpmktElement {\n private methods: PaymentMethodOption[] = []\n private chosen: number | null = null\n private methodsKey: string | null | undefined = undefined\n private loading: AbortController | undefined\n private busy = false\n private loadFailed = false\n\n constructor() {\n super()\n // The methods depend on the delivery and on whether a business is billed\n new SignalController(\n this,\n () => {\n const draft = checkoutDraft.value\n return draft.delivery ? `${draft.delivery.kind}:${draft.delivery.costId}:${draft.business}` : null\n },\n (key) => {\n if (key === this.methodsKey) return\n this.methodsKey = key\n void this.load(key)\n },\n )\n }\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.requirePart<HTMLFormElement>('form')\n this.requirePart('methods')\n this.restore(form)\n this.submitInPlace(form, () => {\n void this.place()\n })\n this.listen(form, 'change', (event) => this.changed(event.target as HTMLInputElement))\n // Methods that could not be loaded: try again once there is a connection\n this.listen(window, 'online', () => {\n if (this.methodsKey === undefined) void this.retryMethods()\n })\n // Back from the gateway (the back/forward cache restores the page as it was left): usable again\n this.listen(window, 'pageshow', (event) => {\n if ((event as PageTransitionEvent).persisted) this.idle()\n })\n this.onDisconnect(() => this.loading?.abort())\n }\n\n /** Loads the payment methods for the draft again. */\n private retryMethods(): Promise<void> {\n const draft = checkoutDraft.value\n const key = draft.delivery ? `${draft.delivery.kind}:${draft.delivery.costId}:${draft.business}` : null\n this.methodsKey = key\n return this.load(key)\n }\n\n private idle(): void {\n this.busy = false\n this.findPart('submit')?.removeAttribute('aria-busy')\n }\n\n /** The shop takes business orders (company fields, business billing). */\n private get businessOrders(): boolean {\n return storefront().checkout.orderAsBusiness\n }\n\n /** The draft's billing choices back into the form (after a reload or Back). */\n private restore(form: HTMLFormElement): void {\n const draft = checkoutDraft.value\n const business = form.elements.namedItem('business')\n if (business instanceof HTMLInputElement) {\n business.checked = draft.business && this.businessOrders\n for (const [name, value] of Object.entries(draft.company ?? {})) {\n const input = form.elements.namedItem(name)\n if (input instanceof HTMLInputElement) input.value = value\n }\n }\n const same = form.elements.namedItem('billing_same')\n if (same instanceof HTMLInputElement) {\n same.checked = draft.billingAddress === null\n for (const [name, value] of Object.entries(draft.billingAddress ?? {})) {\n const input = this.findPart('billing')?.querySelector<HTMLInputElement | HTMLSelectElement>(\n `[name=\"${name}\"]`,\n )\n if (input && value !== null && value !== undefined) input.value = String(value)\n }\n }\n const select = form.elements.namedItem('billing_address_id')\n if (select instanceof HTMLSelectElement && draft.billingAddressId !== null) {\n select.value = String(draft.billingAddressId)\n }\n this.toggleParts(form)\n }\n\n private toggleParts(form: HTMLFormElement): void {\n const business = form.elements.namedItem('business')\n const company = this.findPart('company')\n if (company)\n company.hidden = !(business instanceof HTMLInputElement && business.checked && this.businessOrders)\n const same = form.elements.namedItem('billing_same')\n const billing = this.findPart('billing')\n if (billing && same instanceof HTMLInputElement) billing.hidden = same.checked\n }\n\n private changed(input: HTMLInputElement): void {\n const form = this.requirePart<HTMLFormElement>('form')\n if (input.name === 'business') {\n this.toggleParts(form)\n updateDraft({ business: input.checked && this.businessOrders })\n } else if (input.name === 'billing_same') {\n this.toggleParts(form)\n } else if (input.name === 'billing_address_id') {\n const option = (input as unknown as HTMLSelectElement).selectedOptions[0]\n updateDraft({\n billingAddressId: input.value ? Number(input.value) : null,\n business: option?.dataset.type === 'business' && this.businessOrders,\n })\n } else if (input.name === 'payment_method_id') {\n this.chosen = Number(input.value)\n const slot = form.querySelector<HTMLElement>('[data-error-for=\"payment_method_id\"]')\n if (slot) slot.hidden = true\n }\n }\n\n private async load(key: string | null): Promise<void> {\n this.loading?.abort()\n const waiting = this.findPart('waiting')\n if (waiting) waiting.hidden = key !== null\n if (key === null) {\n this.methods = []\n this.paint()\n return\n }\n const controller = (this.loading = new AbortController())\n const list = this.requirePart('methods')\n list.setAttribute('aria-busy', 'true')\n try {\n this.methods = await loadPaymentMethods(controller.signal)\n if (!this.methods.some((method) => method.id === this.chosen)) this.chosen = null\n this.paint()\n if (this.loadFailed) this.showError(null)\n this.loadFailed = false\n } catch (error) {\n if (isAbortError(error)) return\n this.showError(errorMessage(error))\n this.loadFailed = true\n // Not loaded: the next change of the delivery or billing (even to the same choice) asks again\n this.methodsKey = undefined\n } finally {\n if (this.loading === controller) list.removeAttribute('aria-busy')\n }\n }\n\n private paint(): void {\n this.renderPart(\n 'methods',\n html`${this.methods.map((method) => this.renderMethod(method, method.id === this.chosen))}`,\n )\n }\n\n /** One payment method: a radio named payment_method_id inside a label with data-test=\"payment-method-<id>\". */\n protected renderMethod(method: PaymentMethodOption, checked: boolean): unknown {\n return html`<label class=\"checkout-choice\" data-test=\"payment-method-${method.id}\">\n <input type=\"radio\" name=\"payment_method_id\" .value=${String(method.id)} .checked=${checked} />\n <span class=\"checkout-choice__text\">\n <strong>${method.display_name}</strong>\n ${\n method.description\n ? html`<span class=\"checkout-choice__note checkout-choice__note--pre\"\n >${method.description}</span\n >`\n : nothing\n }\n </span>\n </label>`\n }\n\n /** Validates what only the page can, keeps the billing choices in the draft, and places the order. */\n async place(): Promise<void> {\n if (this.busy) return\n const form = this.requirePart<HTMLFormElement>('form')\n clearFieldErrors(form)\n this.showError(null)\n if (!this.checkPage(form)) return\n\n const values = Object.fromEntries(\n Array.from(new FormData(form)).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string',\n ),\n )\n this.keepBilling(form, values)\n const method = this.methods.find((m) => m.id === this.chosen)\n\n const submit = this.findPart('submit')\n this.busy = true\n submit?.setAttribute('aria-busy', 'true')\n let leaving = false\n try {\n // Checks other elements add (the age check); each tells the visitor itself why it stopped\n if (!(await passOrderChecks())) return\n const result = await submitOrder({\n paymentMethodId: this.chosen!,\n paymentName: method?.display_name,\n note: values.note?.trim() || null,\n recaptchaToken: await recaptchaToken('checkout'),\n })\n if (result.kind === 'gateway') {\n leaving = true\n this.navigate(result)\n } else {\n this.emit('spmkt:order-placed', { order: result.order })\n }\n } catch (error) {\n this.showFailure(form, error)\n } finally {\n // Stay busy while the browser leaves for the gateway (pageshow undoes it if the visitor comes Back)\n if (!leaving) this.idle()\n }\n }\n\n /** Sends the browser to the gateway; replaceable (tests, themes). */\n navigate: (redirect: { url: string; payload: Record<string, string | number> }) => void = (redirect) => {\n postToGateway(redirect)\n }\n\n /** What the page can check before asking the server: a method is chosen, and the terms are accepted. */\n private checkPage(form: HTMLFormElement): boolean {\n const errors: Record<string, string[]> = {}\n if (this.chosen === null) {\n errors.payment_method_id = [t('checkout.choosePayment')]\n }\n const tos = form.elements.namedItem('accept_tos')\n if (storefront().checkout.acceptTos && tos instanceof HTMLInputElement && !tos.checked) {\n const slot = form.querySelector<HTMLElement>('[data-error-for=\"accept_tos\"]')\n errors.accept_tos = [slot?.dataset.message || t('checkout.acceptTos')]\n }\n if (Object.keys(errors).length === 0) return true\n showFieldErrors(form, errors)\n form.querySelector<HTMLElement>('[data-error-for]:not([hidden])')?.scrollIntoView({ block: 'center' })\n return false\n }\n\n private keepBilling(form: HTMLFormElement, values: Record<string, string>): void {\n if (customerSignedIn.value) return\n const business = values.business === '1' && this.businessOrders\n const company = business\n ? {\n company_name: values.company_name ?? '',\n company_tax_id: values.company_tax_id ?? '',\n company_business_id: values.company_business_id ?? '',\n }\n : null\n let billingAddress: CheckoutAddress | null = null\n const billing = this.findPart('billing')\n if (billing && !billing.hidden) {\n const field = (name: string) =>\n billing.querySelector<HTMLInputElement | HTMLSelectElement>(`[name=\"${name}\"]`)?.value.trim() ?? ''\n billingAddress = {\n first_name: field('first_name'),\n last_name: field('last_name'),\n address1: field('address1'),\n city: field('city'),\n postcode: field('postcode'),\n country_id: Number(field('country_id')),\n phone: field('phone') || null,\n }\n }\n updateDraft({ business, company, billingAddress })\n }\n\n /** A refused order: fields this step owns get their message; the rest goes to the error part and a toast. */\n private showFailure(form: HTMLFormElement, error: unknown): void {\n if (error instanceof ValidationError) {\n const mine: Record<string, string[]> = {}\n const others: string[] = []\n for (const [field, messages] of Object.entries(error.errors)) {\n const name = field.replace(/^billing_address\\./, '')\n if (form.querySelector(`[data-error-for=\"${CSS.escape(name)}\"]`)) mine[name] = messages\n else if (messages[0]) others.push(messages[0])\n }\n showFieldErrors(form, mine)\n // Errors of the delivery step (an address, the e-mail) send the visitor back there\n if (others.length) this.showError(`${others.join(' ')} ${t('checkout.checkDelivery')}`)\n form.querySelector<HTMLElement>('[aria-invalid=\"true\"]')?.focus()\n return\n }\n const message = errorMessage(error, t('checkout.failed'))\n this.showError(message)\n if (!(error instanceof HttpError && error.status === 400)) return\n showToast({ message, tone: 'error' })\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 }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAkDO,MAAM,6BAA6B,aAAa;AAAA,EAQrD,cAAc;AACZ,UAAA;AARF,SAAQ,UAAiC,CAAA;AACzC,SAAQ,SAAwB;AAChC,SAAQ,aAAwC;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;AAC3D,cAAU,EAAE,SAAS,MAAM,QAAA,CAAS;AAAA,EACtC;AAAA,EAEQ,UAAU,SAA8B;AAC9C,UAAM,OAAO,KAAK,SAAS,OAAO;AAClC,QAAI,MAAM;AACR,WAAK,cAAc,WAAW;AAC9B,WAAK,SAAS,YAAY;AAAA,IAC5B;AAAA,EACF;AACF;"}
|
|
@@ -44,8 +44,7 @@ class SpmktCollection extends SpmktElement {
|
|
|
44
44
|
this.schedule();
|
|
45
45
|
}
|
|
46
46
|
});
|
|
47
|
-
this.
|
|
48
|
-
event.preventDefault();
|
|
47
|
+
this.submitInPlace(form, () => {
|
|
49
48
|
this.go(this.formUrl());
|
|
50
49
|
});
|
|
51
50
|
this.listen(this, "click", (event) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collection.js","sources":["../../../src/elements/collection/collection.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { fetchFragments, sectionKey, swapSection } from '../../lit/fragments'\nimport { emitSelectItem } from '../shared/select-item'\nimport { isAbortError } from '../../core/errors'\nimport { dispatchPageEvents } from '../../core/page-events'\nimport { showToast } from '../toaster/toaster'\nimport { t } from '../../core/i18n'\nimport { warnOnce } from '../../core/config'\n\n/**\n * Parts of <spmkt-collection> (a product listing the theme renders; plain HTML works without JS):\n * - form (required): the GET form of the filters; controls elsewhere in the element may join it with\n * form=\"<its id>\" (the sort select next to the grid: product cards hold forms of their own, and forms\n * cannot nest)\n * - results (required): the product grid and paging; aria-busy while loading\n * - items (optional): the list \"load more\" appends to\n * - more (optional): the paging block; load-more (optional) is a link to the next page inside it\n * - apply (optional): the form's submit button, hidden once the element applies changes itself\n * - filters-toggle (optional): a <details> around the filters; opened on wide screens (`wide` media query)\n * and kept as the visitor left it across re-renders\n *\n * Page event scripts (dispatchPageEvents) in the re-rendered markup are dispatched after each change and each\n * \"load more\", so analytics sees every list the visitor was shown. A click on a product link in a card with\n * data-item (the product as a GA4 item, JSON) sends spmkt:select-item, with the closest data-item-list as the\n * list's name.\n *\n * The listing is re-rendered on the server: the section around the element (sections=<key>), whose new markup\n * replaces this element's section, so it is re-created after every change. Outside a section there is nothing\n * to re-render: a markup error, warned about once in debug mode, and the form and links work as plain HTML.\n */\nexport interface CollectionParts {\n form: HTMLFormElement\n results: HTMLElement\n items?: HTMLElement\n more?: HTMLElement\n 'load-more'?: HTMLAnchorElement\n apply?: HTMLElement\n}\n\n/** Marks history entries this element created, so Back re-renders the listing in place. */\nconst HISTORY_KEY = 'spmktCollection'\n\n/** Whether the visitor left the filters open; survives the re-render that replaces the element */\nlet filtersOpen: boolean | undefined\n\nlet inFlight: AbortController | undefined\n\n/** Filters, sort and paging without page loads; Back and Forward restore earlier states. */\nexport class SpmktCollection extends SpmktElement {\n static override properties = {\n debounce: { type: Number },\n wide: { type: String },\n }\n /** Milliseconds to wait after a change (number fields fire on every keystroke) */\n debounce = 400\n /** When the filters start open */\n wide = '(width >= 60rem)'\n\n private timer: ReturnType<typeof setTimeout> | undefined\n private loadingMore = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.requirePart<HTMLFormElement>('form')\n if (!sectionKey(this)) {\n warnOnce(\n 'collection:section',\n `<${this.localName}> is not inside a theme section, so it cannot re-render`,\n )\n return\n }\n const apply = this.findPart('apply')\n if (apply) apply.hidden = true\n const toggle = this.findPart<HTMLDetailsElement>('filters-toggle')\n if (toggle) {\n toggle.open = filtersOpen ?? window.matchMedia(this.wide).matches\n this.listen(toggle, 'toggle', () => (filtersOpen = toggle.open))\n }\n\n // Controls can join the form from outside it (form=\"...\"), e.g. a sort select next to the grid\n this.listen(this, 'change', (event) => {\n if ((event.target as HTMLInputElement | null)?.form === form) {\n this.schedule()\n }\n })\n this.listen(form, 'submit', (event) => {\n event.preventDefault()\n this.go(this.formUrl())\n })\n this.listen(this, 'click', (event) => {\n emitSelectItem(this, event)\n this.onClick(event)\n })\n this.listen(window, 'popstate', (event) => {\n if (((event as PopStateEvent).state as Record<string, unknown> | null)?.[HISTORY_KEY]) {\n void this.show(location.href)\n }\n })\n this.onDisconnect(() => clearTimeout(this.timer))\n // The first entry gets the marker too, so Back to it re-renders instead of doing nothing\n if (!(history.state as Record<string, unknown> | null)?.[HISTORY_KEY]) {\n history.replaceState({ ...(history.state as object), [HISTORY_KEY]: true }, '')\n }\n }\n\n /** The listing URL for the form's current values (empty fields left out, back to page 1). */\n formUrl(): string {\n const form = this.requirePart<HTMLFormElement>('form')\n const url = new URL(form.action || location.href, location.href)\n url.search = ''\n for (const [name, value] of new FormData(form)) {\n if (typeof value === 'string' && value !== '') {\n url.searchParams.append(name, value)\n }\n }\n return url.toString()\n }\n\n /** Shows the listing at `url` and records it in the history. */\n async go(url: string): Promise<void> {\n if (await this.show(url)) {\n history.pushState({ [HISTORY_KEY]: true }, '', url)\n }\n }\n\n private schedule(): void {\n clearTimeout(this.timer)\n this.timer = setTimeout(() => void this.go(this.formUrl()), this.debounce)\n }\n\n private onClick(event: MouseEvent): void {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return\n }\n const link = (event.target as Element).closest<HTMLAnchorElement>('a[href]')\n if (!link || !this.contains(link)) {\n return\n }\n if (link.dataset.part === 'load-more') {\n event.preventDefault()\n void this.loadMore(link.href)\n } else if (link.closest('[data-part=\"more\"]') || link.dataset.part === 'reset') {\n event.preventDefault()\n void this.go(link.href)\n }\n }\n\n private request(url: string, key: string, signal: AbortSignal) {\n return fetchFragments(url, { sections: [key], signal })\n }\n\n /** Replaces the listing with the server's rendering of `url`. False when it did not happen. */\n private async show(url: string): Promise<boolean> {\n inFlight?.abort()\n const controller = (inFlight = new AbortController())\n const results = this.findPart('results')\n results?.setAttribute('aria-busy', 'true')\n try {\n const key = this.key()\n const response = await this.request(url, key, controller.signal)\n const html = response.sections[key]\n if (html === undefined) {\n throw new Error('The listing was not in the response')\n }\n const next = swapSection(this, html)\n if (next) {\n this.scrollIntoViewIfAbove(next)\n // Another view of the listing (filters, sort, page): its view-item-list, if the theme renders one\n dispatchPageEvents(next)\n }\n return true\n } catch (error) {\n if (!isAbortError(error)) {\n results?.removeAttribute('aria-busy')\n showToast({ message: t('common.error'), tone: 'error' })\n }\n return false\n }\n }\n\n /** Appends the next page's products and its paging block. */\n private async loadMore(url: string): Promise<void> {\n // One page at a time: a second click while the next page loads would append it twice\n if (this.loadingMore) return\n this.loadingMore = true\n inFlight?.abort()\n const controller = (inFlight = new AbortController())\n const more = this.findPart('more')\n more?.setAttribute('aria-busy', 'true')\n try {\n const key = this.key()\n const response = await this.request(url, key, controller.signal)\n const html = response.sections[key] ?? ''\n const page = document.createElement('template')\n page.innerHTML = html\n const nextItems = page.content.querySelector('[data-part=\"items\"]')\n const items = this.findPart('items')\n if (items && nextItems) {\n items.append(...Array.from(nextItems.childNodes))\n }\n const nextMore = page.content.querySelector('[data-part=\"more\"]')\n if (more) {\n nextMore ? more.replaceWith(nextMore) : more.remove()\n }\n dispatchPageEvents(page.content)\n } catch (error) {\n if (!isAbortError(error)) {\n more?.removeAttribute('aria-busy')\n showToast({ message: t('common.error'), tone: 'error' })\n }\n } finally {\n this.loadingMore = false\n }\n }\n\n /** The key of the section around the element (connectedCallback made sure there is one). */\n private key(): string {\n return sectionKey(this) ?? ''\n }\n\n private scrollIntoViewIfAbove(el: Element): void {\n if (el.getBoundingClientRect().top < 0) {\n el.scrollIntoView({ block: 'start' })\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAwCA,MAAM,cAAc;AAGpB,IAAI;AAEJ,IAAI;AAGG,MAAM,wBAAwB,aAAa;AAAA,EAA3C,cAAA;AAAA,UAAA,GAAA,SAAA;AAML,SAAA,WAAW;AAEX,SAAA,OAAO;AAGP,SAAQ,cAAc;AAAA,EAAA;AAAA,EAVtB,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,UAAU,EAAE,MAAM,OAAA;AAAA,MAClB,MAAM,EAAE,MAAM,OAAA;AAAA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AI,MAAM;AACR,mBAAW,KAAK,YAAY,QAAQ,IAAI,KAAK,OAAA;AAAA,MAC/C;AACA,yBAAmB,KAAK,OAAO;AAAA,IACjC,SAAS,OAAO;AACd,UAAI,CAAC,aAAa,KAAK,GAAG;AACxB,cAAM,gBAAgB,WAAW;AACjC,kBAAU,EAAE,SAAS,EAAE,cAAc,GAAG,MAAM,SAAS;AAAA,MACzD;AAAA,IACF,UAAA;AACE,WAAK,cAAc;AAAA,IACrB;AAAA,EACF;AAAA;AAAA,EAGQ,MAAc;AACpB,WAAO,WAAW,IAAI,KAAK;AAAA,EAC7B;AAAA,EAEQ,sBAAsB,IAAmB;AAC/C,QAAI,GAAG,wBAAwB,MAAM,GAAG;AACtC,SAAG,eAAe,EAAE,OAAO,QAAA,CAAS;AAAA,IACtC;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"collection.js","sources":["../../../src/elements/collection/collection.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { fetchFragments, sectionKey, swapSection } from '../../lit/fragments'\nimport { emitSelectItem } from '../shared/select-item'\nimport { isAbortError } from '../../core/errors'\nimport { dispatchPageEvents } from '../../core/page-events'\nimport { showToast } from '../toaster/toaster'\nimport { t } from '../../core/i18n'\nimport { warnOnce } from '../../core/config'\n\n/**\n * Parts of <spmkt-collection> (a product listing the theme renders; plain HTML works without JS):\n * - form (required): the GET form of the filters; controls elsewhere in the element may join it with\n * form=\"<its id>\" (the sort select next to the grid: product cards hold forms of their own, and forms\n * cannot nest)\n * - results (required): the product grid and paging; aria-busy while loading\n * - items (optional): the list \"load more\" appends to\n * - more (optional): the paging block; load-more (optional) is a link to the next page inside it\n * - apply (optional): the form's submit button, hidden once the element applies changes itself\n * - filters-toggle (optional): a <details> around the filters; opened on wide screens (`wide` media query)\n * and kept as the visitor left it across re-renders\n *\n * Page event scripts (dispatchPageEvents) in the re-rendered markup are dispatched after each change and each\n * \"load more\", so analytics sees every list the visitor was shown. A click on a product link in a card with\n * data-item (the product as a GA4 item, JSON) sends spmkt:select-item, with the closest data-item-list as the\n * list's name.\n *\n * The listing is re-rendered on the server: the section around the element (sections=<key>), whose new markup\n * replaces this element's section, so it is re-created after every change. Outside a section there is nothing\n * to re-render: a markup error, warned about once in debug mode, and the form and links work as plain HTML.\n */\nexport interface CollectionParts {\n form: HTMLFormElement\n results: HTMLElement\n items?: HTMLElement\n more?: HTMLElement\n 'load-more'?: HTMLAnchorElement\n apply?: HTMLElement\n}\n\n/** Marks history entries this element created, so Back re-renders the listing in place. */\nconst HISTORY_KEY = 'spmktCollection'\n\n/** Whether the visitor left the filters open; survives the re-render that replaces the element */\nlet filtersOpen: boolean | undefined\n\nlet inFlight: AbortController | undefined\n\n/** Filters, sort and paging without page loads; Back and Forward restore earlier states. */\nexport class SpmktCollection extends SpmktElement {\n static override properties = {\n debounce: { type: Number },\n wide: { type: String },\n }\n /** Milliseconds to wait after a change (number fields fire on every keystroke) */\n debounce = 400\n /** When the filters start open */\n wide = '(width >= 60rem)'\n\n private timer: ReturnType<typeof setTimeout> | undefined\n private loadingMore = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.requirePart<HTMLFormElement>('form')\n if (!sectionKey(this)) {\n warnOnce(\n 'collection:section',\n `<${this.localName}> is not inside a theme section, so it cannot re-render`,\n )\n return\n }\n const apply = this.findPart('apply')\n if (apply) apply.hidden = true\n const toggle = this.findPart<HTMLDetailsElement>('filters-toggle')\n if (toggle) {\n toggle.open = filtersOpen ?? window.matchMedia(this.wide).matches\n this.listen(toggle, 'toggle', () => (filtersOpen = toggle.open))\n }\n\n // Controls can join the form from outside it (form=\"...\"), e.g. a sort select next to the grid\n this.listen(this, 'change', (event) => {\n if ((event.target as HTMLInputElement | null)?.form === form) {\n this.schedule()\n }\n })\n this.submitInPlace(form, () => {\n this.go(this.formUrl())\n })\n this.listen(this, 'click', (event) => {\n emitSelectItem(this, event)\n this.onClick(event)\n })\n this.listen(window, 'popstate', (event) => {\n if (((event as PopStateEvent).state as Record<string, unknown> | null)?.[HISTORY_KEY]) {\n void this.show(location.href)\n }\n })\n this.onDisconnect(() => clearTimeout(this.timer))\n // The first entry gets the marker too, so Back to it re-renders instead of doing nothing\n if (!(history.state as Record<string, unknown> | null)?.[HISTORY_KEY]) {\n history.replaceState({ ...(history.state as object), [HISTORY_KEY]: true }, '')\n }\n }\n\n /** The listing URL for the form's current values (empty fields left out, back to page 1). */\n formUrl(): string {\n const form = this.requirePart<HTMLFormElement>('form')\n const url = new URL(form.action || location.href, location.href)\n url.search = ''\n for (const [name, value] of new FormData(form)) {\n if (typeof value === 'string' && value !== '') {\n url.searchParams.append(name, value)\n }\n }\n return url.toString()\n }\n\n /** Shows the listing at `url` and records it in the history. */\n async go(url: string): Promise<void> {\n if (await this.show(url)) {\n history.pushState({ [HISTORY_KEY]: true }, '', url)\n }\n }\n\n private schedule(): void {\n clearTimeout(this.timer)\n this.timer = setTimeout(() => void this.go(this.formUrl()), this.debounce)\n }\n\n private onClick(event: MouseEvent): void {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return\n }\n const link = (event.target as Element).closest<HTMLAnchorElement>('a[href]')\n if (!link || !this.contains(link)) {\n return\n }\n if (link.dataset.part === 'load-more') {\n event.preventDefault()\n void this.loadMore(link.href)\n } else if (link.closest('[data-part=\"more\"]') || link.dataset.part === 'reset') {\n event.preventDefault()\n void this.go(link.href)\n }\n }\n\n private request(url: string, key: string, signal: AbortSignal) {\n return fetchFragments(url, { sections: [key], signal })\n }\n\n /** Replaces the listing with the server's rendering of `url`. False when it did not happen. */\n private async show(url: string): Promise<boolean> {\n inFlight?.abort()\n const controller = (inFlight = new AbortController())\n const results = this.findPart('results')\n results?.setAttribute('aria-busy', 'true')\n try {\n const key = this.key()\n const response = await this.request(url, key, controller.signal)\n const html = response.sections[key]\n if (html === undefined) {\n throw new Error('The listing was not in the response')\n }\n const next = swapSection(this, html)\n if (next) {\n this.scrollIntoViewIfAbove(next)\n // Another view of the listing (filters, sort, page): its view-item-list, if the theme renders one\n dispatchPageEvents(next)\n }\n return true\n } catch (error) {\n if (!isAbortError(error)) {\n results?.removeAttribute('aria-busy')\n showToast({ message: t('common.error'), tone: 'error' })\n }\n return false\n }\n }\n\n /** Appends the next page's products and its paging block. */\n private async loadMore(url: string): Promise<void> {\n // One page at a time: a second click while the next page loads would append it twice\n if (this.loadingMore) return\n this.loadingMore = true\n inFlight?.abort()\n const controller = (inFlight = new AbortController())\n const more = this.findPart('more')\n more?.setAttribute('aria-busy', 'true')\n try {\n const key = this.key()\n const response = await this.request(url, key, controller.signal)\n const html = response.sections[key] ?? ''\n const page = document.createElement('template')\n page.innerHTML = html\n const nextItems = page.content.querySelector('[data-part=\"items\"]')\n const items = this.findPart('items')\n if (items && nextItems) {\n items.append(...Array.from(nextItems.childNodes))\n }\n const nextMore = page.content.querySelector('[data-part=\"more\"]')\n if (more) {\n nextMore ? more.replaceWith(nextMore) : more.remove()\n }\n dispatchPageEvents(page.content)\n } catch (error) {\n if (!isAbortError(error)) {\n more?.removeAttribute('aria-busy')\n showToast({ message: t('common.error'), tone: 'error' })\n }\n } finally {\n this.loadingMore = false\n }\n }\n\n /** The key of the section around the element (connectedCallback made sure there is one). */\n private key(): string {\n return sectionKey(this) ?? ''\n }\n\n private scrollIntoViewIfAbove(el: Element): void {\n if (el.getBoundingClientRect().top < 0) {\n el.scrollIntoView({ block: 'start' })\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAwCA,MAAM,cAAc;AAGpB,IAAI;AAEJ,IAAI;AAGG,MAAM,wBAAwB,aAAa;AAAA,EAA3C,cAAA;AAAA,UAAA,GAAA,SAAA;AAML,SAAA,WAAW;AAEX,SAAA,OAAO;AAGP,SAAQ,cAAc;AAAA,EAAA;AAAA,EAVtB,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,UAAU,EAAE,MAAM,OAAA;AAAA,MAClB,MAAM,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AAM;AACR,mBAAW,KAAK,YAAY,QAAQ,IAAI,KAAK,OAAA;AAAA,MAC/C;AACA,yBAAmB,KAAK,OAAO;AAAA,IACjC,SAAS,OAAO;AACd,UAAI,CAAC,aAAa,KAAK,GAAG;AACxB,cAAM,gBAAgB,WAAW;AACjC,kBAAU,EAAE,SAAS,EAAE,cAAc,GAAG,MAAM,SAAS;AAAA,MACzD;AAAA,IACF,UAAA;AACE,WAAK,cAAc;AAAA,IACrB;AAAA,EACF;AAAA;AAAA,EAGQ,MAAc;AACpB,WAAO,WAAW,IAAI,KAAK;AAAA,EAC7B;AAAA,EAEQ,sBAAsB,IAAmB;AAC/C,QAAI,GAAG,wBAAwB,MAAM,GAAG;AACtC,SAAG,eAAe,EAAE,OAAO,QAAA,CAAS;AAAA,IACtC;AAAA,EACF;AACF;"}
|
|
@@ -17,8 +17,7 @@ class SpmktQuestions extends PagedSectionElement {
|
|
|
17
17
|
super.connectedCallback();
|
|
18
18
|
const form = this.findPart("ask");
|
|
19
19
|
if (form) {
|
|
20
|
-
this.
|
|
21
|
-
event.preventDefault();
|
|
20
|
+
this.submitInPlace(form, () => {
|
|
22
21
|
void this.ask();
|
|
23
22
|
});
|
|
24
23
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"questions.js","sources":["../../../src/elements/questions/questions.ts"],"sourcesContent":["import { PagedSectionElement, type PagedSectionParts } from '../shared/paged-section'\nimport { askQuestion } from '../../core/api/questions'\nimport { HttpError, ValidationError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { clearFieldErrors, errorMessage, showFieldErrors } from '../../lit/forms'\nimport { showToast } from '../toaster/toaster'\n\n/**\n * Parts of <spmkt-questions product-id> (a product's questions in a theme section):\n * - the paged list parts (items, more, load-more; see PagedSectionParts)\n * - ask (optional): the form for a new question, with a `body` field and [data-error-for=body]\n * - ask-submit, ask-error (optional): its button, and a message not tied to a field (render it hidden)\n * - ask-success (optional): shown in place of the form once the question is sent (render it hidden)\n */\nexport interface QuestionsParts extends PagedSectionParts {\n ask?: HTMLFormElement\n 'ask-submit'?: HTMLButtonElement\n 'ask-error'?: HTMLElement\n 'ask-success'?: HTMLElement\n}\n\n/** Question pages, and asking one (signed-in visitors; the server limits how many per hour and day). */\nexport class SpmktQuestions extends PagedSectionElement {\n static override properties = { productId: { type: Number, attribute: 'product-id' } }\n productId = 0\n\n private busy = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.findPart<HTMLFormElement>('ask')\n if (form) {\n this.
|
|
1
|
+
{"version":3,"file":"questions.js","sources":["../../../src/elements/questions/questions.ts"],"sourcesContent":["import { PagedSectionElement, type PagedSectionParts } from '../shared/paged-section'\nimport { askQuestion } from '../../core/api/questions'\nimport { HttpError, ValidationError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { clearFieldErrors, errorMessage, showFieldErrors } from '../../lit/forms'\nimport { showToast } from '../toaster/toaster'\n\n/**\n * Parts of <spmkt-questions product-id> (a product's questions in a theme section):\n * - the paged list parts (items, more, load-more; see PagedSectionParts)\n * - ask (optional): the form for a new question, with a `body` field and [data-error-for=body]\n * - ask-submit, ask-error (optional): its button, and a message not tied to a field (render it hidden)\n * - ask-success (optional): shown in place of the form once the question is sent (render it hidden)\n */\nexport interface QuestionsParts extends PagedSectionParts {\n ask?: HTMLFormElement\n 'ask-submit'?: HTMLButtonElement\n 'ask-error'?: HTMLElement\n 'ask-success'?: HTMLElement\n}\n\n/** Question pages, and asking one (signed-in visitors; the server limits how many per hour and day). */\nexport class SpmktQuestions extends PagedSectionElement {\n static override properties = { productId: { type: Number, attribute: 'product-id' } }\n productId = 0\n\n private busy = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.findPart<HTMLFormElement>('ask')\n if (form) {\n this.submitInPlace(form, () => {\n void this.ask()\n })\n }\n }\n\n /** Sends the ask form's question; ignored while one is being sent. */\n async ask(): Promise<void> {\n if (this.busy) return\n const form = this.requirePart<HTMLFormElement>('ask')\n const submit = this.findPart<HTMLButtonElement>('ask-submit')\n const general = this.findPart('ask-error')\n const body = String(new FormData(form).get('body') ?? '').trim()\n clearFieldErrors(form)\n if (general) general.hidden = true\n if (!body) {\n showFieldErrors(form, { body: [t('validation.required')] })\n return\n }\n this.busy = true\n submit?.setAttribute('aria-busy', 'true')\n try {\n await askQuestion(this.productId, body)\n form.hidden = true\n const success = this.findPart('ask-success')\n if (success) success.hidden = false\n else showToast({ message: t('questions.thanks'), tone: 'success' })\n } catch (error) {\n const unplaced =\n error instanceof ValidationError ? showFieldErrors(form, error.errors) : [errorMessage(error)]\n if (error instanceof HttpError && error.status === 429) unplaced.splice(0, 1, t('questions.tooMany'))\n if (unplaced.length && general) {\n general.textContent = unplaced[0]!\n general.hidden = false\n } else if (unplaced.length) {\n showToast({ message: unplaced[0]!, tone: 'error' })\n }\n } finally {\n this.busy = false\n submit?.removeAttribute('aria-busy')\n }\n }\n}\n"],"names":[],"mappings":";;;;;;AAsBO,MAAM,uBAAuB,oBAAoB;AAAA,EAAjD,cAAA;AAAA,UAAA,GAAA,SAAA;AAEL,SAAA,YAAY;AAEZ,SAAQ,OAAO;AAAA,EAAA;AAAA,EAHf,OAAA;AAAA,SAAgB,aAAa,EAAE,WAAW,EAAE,MAAM,QAAQ,WAAW,eAAa;AAAA,EAAE;AAAA,EAK3E,oBAA0B;AACjC,UAAM,kBAAA;AACN,UAAM,OAAO,KAAK,SAA0B,KAAK;AACjD,QAAI,MAAM;AACR,WAAK,cAAc,MAAM,MAAM;AAC7B,aAAK,KAAK,IAAA;AAAA,MACZ,CAAC;AAAA,IACH;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,MAAqB;AACzB,QAAI,KAAK,KAAM;AACf,UAAM,OAAO,KAAK,YAA6B,KAAK;AACpD,UAAM,SAAS,KAAK,SAA4B,YAAY;AAC5D,UAAM,UAAU,KAAK,SAAS,WAAW;AACzC,UAAM,OAAO,OAAO,IAAI,SAAS,IAAI,EAAE,IAAI,MAAM,KAAK,EAAE,EAAE,KAAA;AAC1D,qBAAiB,IAAI;AACrB,QAAI,iBAAiB,SAAS;AAC9B,QAAI,CAAC,MAAM;AACT,sBAAgB,MAAM,EAAE,MAAM,CAAC,EAAE,qBAAqB,CAAC,GAAG;AAC1D;AAAA,IACF;AACA,SAAK,OAAO;AACZ,YAAQ,aAAa,aAAa,MAAM;AACxC,QAAI;AACF,YAAM,YAAY,KAAK,WAAW,IAAI;AACtC,WAAK,SAAS;AACd,YAAM,UAAU,KAAK,SAAS,aAAa;AAC3C,UAAI,iBAAiB,SAAS;AAAA,UACzB,WAAU,EAAE,SAAS,EAAE,kBAAkB,GAAG,MAAM,WAAW;AAAA,IACpE,SAAS,OAAO;AACd,YAAM,WACJ,iBAAiB,kBAAkB,gBAAgB,MAAM,MAAM,MAAM,IAAI,CAAC,aAAa,KAAK,CAAC;AAC/F,UAAI,iBAAiB,aAAa,MAAM,WAAW,IAAK,UAAS,OAAO,GAAG,GAAG,EAAE,mBAAmB,CAAC;AACpG,UAAI,SAAS,UAAU,SAAS;AAC9B,gBAAQ,cAAc,SAAS,CAAC;AAChC,gBAAQ,SAAS;AAAA,MACnB,WAAW,SAAS,QAAQ;AAC1B,kBAAU,EAAE,SAAS,SAAS,CAAC,GAAI,MAAM,SAAS;AAAA,MACpD;AAAA,IACF,UAAA;AACE,WAAK,OAAO;AACZ,cAAQ,gBAAgB,WAAW;AAAA,IACrC;AAAA,EACF;AACF;"}
|
|
@@ -27,8 +27,7 @@ class SpmktReviewForm extends SpmktElement {
|
|
|
27
27
|
connectedCallback() {
|
|
28
28
|
super.connectedCallback();
|
|
29
29
|
const form = this.requirePart("form");
|
|
30
|
-
this.
|
|
31
|
-
event.preventDefault();
|
|
30
|
+
this.submitInPlace(form, () => {
|
|
32
31
|
void this.submit();
|
|
33
32
|
});
|
|
34
33
|
const input = this.findPart("images");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"review-form.js","sources":["../../../src/elements/review-form/review-form.ts"],"sourcesContent":["import { html } from 'lit'\nimport { repeat } from 'lit/directives/repeat.js'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { deleteReviewImage, submitReview, uploadReviewImage } from '../../core/api/reviews'\nimport { ValidationError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { clearFieldErrors, errorMessage, showFieldErrors } from '../../lit/forms'\nimport { showToast } from '../toaster/toaster'\nimport type { UploadedImage } from '../../core/types'\n\n/**\n * Parts of <spmkt-review-form product-id max-images=\"5\" max-size=\"10\"> (max-size in MB):\n * - form (required): fields `rating` (radios 1-5), `title`, `body`, `recommended` (checkbox), optionally a\n * hidden `token` (a review invitation); [data-error-for=<field>] elements take the server's messages\n * - images (optional): <input type=\"file\" multiple>; each chosen image is uploaded straight away\n * - previews (optional, element-owned): an empty list for the uploaded images, each with a remove button\n * - submit, error (optional): the button, and a message not tied to a field (render it hidden)\n * - success (optional): shown in place of the form once the review is sent (render it hidden)\n */\nexport interface ReviewFormParts {\n form: HTMLFormElement\n images?: HTMLInputElement\n previews?: HTMLElement\n submit?: HTMLButtonElement\n error?: HTMLElement\n success?: HTMLElement\n}\n\ninterface Preview {\n key: number\n name: string\n image?: UploadedImage\n}\n\nlet nextKey = 1\n\n/** Writing a review: rating, text, recommendation and images, sent to the reviews API. */\nexport class SpmktReviewForm extends SpmktElement {\n static override properties = {\n productId: { type: Number, attribute: 'product-id' },\n maxImages: { type: Number, attribute: 'max-images' },\n maxSize: { type: Number, attribute: 'max-size' },\n }\n productId = 0\n maxImages = 5\n maxSize = 10\n\n private previews: Preview[] = []\n private uploads = new Set<Promise<unknown>>()\n private busy = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.requirePart<HTMLFormElement>('form')\n this.listen(form, 'submit', (event) => {\n event.preventDefault()\n void this.submit()\n })\n const input = this.findPart<HTMLInputElement>('images')\n if (input) {\n this.listen(input, 'change', () => {\n this.add(Array.from(input.files ?? []))\n input.value = ''\n })\n }\n }\n\n /** Ids of the uploaded images that stay with the review */\n get imageIds(): number[] {\n return this.previews.flatMap((preview) => (preview.image ? [preview.image.id] : []))\n }\n\n /** Uploads images, within the limits on count and size. */\n add(files: File[]): void {\n for (const file of files) {\n if (this.previews.length >= this.maxImages) {\n showToast({ message: t('reviews.tooManyImages', { max: this.maxImages }), tone: 'error' })\n break\n }\n if (file.size > this.maxSize * 1024 * 1024) {\n showToast({\n message: t('reviews.imageTooLarge', { name: file.name, max: this.maxSize }),\n tone: 'error',\n })\n continue\n }\n const preview: Preview = { key: nextKey++, name: file.name }\n this.previews = [...this.previews, preview]\n const upload = uploadReviewImage(file)\n .then((image) => {\n preview.image = image\n })\n .catch((error: unknown) => {\n this.previews = this.previews.filter((p) => p !== preview)\n const reason = error instanceof ValidationError ? (error.first('media-file') ?? '') : ''\n showToast({\n message: `${t('reviews.uploadFailed', { name: file.name })} ${reason}`.trim(),\n tone: 'error',\n })\n })\n .finally(() => {\n this.uploads.delete(upload)\n this.paint()\n })\n this.uploads.add(upload)\n }\n this.paint()\n }\n\n /** Drops an image from the review, and its uploaded file from the server. */\n removeImage(key: number): void {\n const preview = this.previews.find((p) => p.key === key)\n this.previews = this.previews.filter((p) => p.key !== key)\n this.paint()\n // Best effort: a file left behind belongs to no review and the server cleans it up\n if (preview?.image) void deleteReviewImage(preview.image.id).catch(() => {})\n }\n\n /** Sends the review; ignored while one is being sent. */\n async submit(): Promise<void> {\n if (this.busy) return\n this.busy = true\n const form = this.requirePart<HTMLFormElement>('form')\n const submit = this.findPart<HTMLButtonElement>('submit')\n const general = this.findPart('error')\n clearFieldErrors(form)\n if (general) general.hidden = true\n submit?.setAttribute('aria-busy', 'true')\n try {\n // Images still uploading belong to the review\n await Promise.all(this.uploads)\n const data = new FormData(form)\n const token = String(data.get('token') ?? '')\n await submitReview(this.productId, {\n rating: Number(data.get('rating') ?? 0),\n title: String(data.get('title') ?? '').trim() || undefined,\n body: String(data.get('body') ?? '').trim(),\n recommended: data.get('recommended') !== null,\n images: this.imageIds,\n ...(token ? { token } : {}),\n })\n form.hidden = true\n const success = this.findPart('success')\n if (success) success.hidden = false\n else showToast({ message: t('reviews.thanks'), tone: 'success' })\n } catch (error) {\n const unplaced =\n error instanceof ValidationError ? showFieldErrors(form, error.errors) : [errorMessage(error)]\n if (unplaced.length && general) {\n general.textContent = unplaced[0]!\n general.hidden = false\n } else if (unplaced.length) {\n showToast({ message: unplaced[0]!, tone: 'error' })\n }\n } finally {\n this.busy = false\n submit?.removeAttribute('aria-busy')\n }\n }\n\n /** One preview; override to change the markup. */\n protected renderPreview(preview: Preview): unknown {\n return html`<li\n data-state=${preview.image ? 'done' : 'uploading'}\n aria-busy=${preview.image ? 'false' : 'true'}\n >\n ${preview.image ? html`<img src=${preview.image.thumb_url} alt=\"\" />` : html`<span>${t('common.loading')}</span>`}\n <button\n type=\"button\"\n aria-label=${t('reviews.removeImage', { name: preview.name })}\n @click=${() => this.removeImage(preview.key)}\n >\n ×\n </button>\n </li>`\n }\n\n private paint(): void {\n if (this.findPart('previews')) {\n this.renderPart(\n 'previews',\n html`${repeat(\n this.previews,\n (preview) => preview.key,\n (preview) => this.renderPreview(preview),\n )}`,\n )\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAkCA,IAAI,UAAU;AAGP,MAAM,wBAAwB,aAAa;AAAA,EAA3C,cAAA;AAAA,UAAA,GAAA,SAAA;AAML,SAAA,YAAY;AACZ,SAAA,YAAY;AACZ,SAAA,UAAU;AAEV,SAAQ,WAAsB,CAAA;AAC9B,SAAQ,8BAAc,IAAA;AACtB,SAAQ,OAAO;AAAA,EAAA;AAAA,EAXf,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,WAAW,EAAE,MAAM,QAAQ,WAAW,aAAA;AAAA,MACtC,WAAW,EAAE,MAAM,QAAQ,WAAW,aAAA;AAAA,MACtC,SAAS,EAAE,MAAM,QAAQ,WAAW,WAAA;AAAA,IAAW;AAAA,EACjD;AAAA,EASS,oBAA0B;AACjC,UAAM,kBAAA;AACN,UAAM,OAAO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,QAAA,CACxC;AAAA,MAAA;AAAA,IAEL;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"review-form.js","sources":["../../../src/elements/review-form/review-form.ts"],"sourcesContent":["import { html } from 'lit'\nimport { repeat } from 'lit/directives/repeat.js'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { deleteReviewImage, submitReview, uploadReviewImage } from '../../core/api/reviews'\nimport { ValidationError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { clearFieldErrors, errorMessage, showFieldErrors } from '../../lit/forms'\nimport { showToast } from '../toaster/toaster'\nimport type { UploadedImage } from '../../core/types'\n\n/**\n * Parts of <spmkt-review-form product-id max-images=\"5\" max-size=\"10\"> (max-size in MB):\n * - form (required): fields `rating` (radios 1-5), `title`, `body`, `recommended` (checkbox), optionally a\n * hidden `token` (a review invitation); [data-error-for=<field>] elements take the server's messages\n * - images (optional): <input type=\"file\" multiple>; each chosen image is uploaded straight away\n * - previews (optional, element-owned): an empty list for the uploaded images, each with a remove button\n * - submit, error (optional): the button, and a message not tied to a field (render it hidden)\n * - success (optional): shown in place of the form once the review is sent (render it hidden)\n */\nexport interface ReviewFormParts {\n form: HTMLFormElement\n images?: HTMLInputElement\n previews?: HTMLElement\n submit?: HTMLButtonElement\n error?: HTMLElement\n success?: HTMLElement\n}\n\ninterface Preview {\n key: number\n name: string\n image?: UploadedImage\n}\n\nlet nextKey = 1\n\n/** Writing a review: rating, text, recommendation and images, sent to the reviews API. */\nexport class SpmktReviewForm extends SpmktElement {\n static override properties = {\n productId: { type: Number, attribute: 'product-id' },\n maxImages: { type: Number, attribute: 'max-images' },\n maxSize: { type: Number, attribute: 'max-size' },\n }\n productId = 0\n maxImages = 5\n maxSize = 10\n\n private previews: Preview[] = []\n private uploads = new Set<Promise<unknown>>()\n private busy = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.requirePart<HTMLFormElement>('form')\n this.submitInPlace(form, () => {\n void this.submit()\n })\n const input = this.findPart<HTMLInputElement>('images')\n if (input) {\n this.listen(input, 'change', () => {\n this.add(Array.from(input.files ?? []))\n input.value = ''\n })\n }\n }\n\n /** Ids of the uploaded images that stay with the review */\n get imageIds(): number[] {\n return this.previews.flatMap((preview) => (preview.image ? [preview.image.id] : []))\n }\n\n /** Uploads images, within the limits on count and size. */\n add(files: File[]): void {\n for (const file of files) {\n if (this.previews.length >= this.maxImages) {\n showToast({ message: t('reviews.tooManyImages', { max: this.maxImages }), tone: 'error' })\n break\n }\n if (file.size > this.maxSize * 1024 * 1024) {\n showToast({\n message: t('reviews.imageTooLarge', { name: file.name, max: this.maxSize }),\n tone: 'error',\n })\n continue\n }\n const preview: Preview = { key: nextKey++, name: file.name }\n this.previews = [...this.previews, preview]\n const upload = uploadReviewImage(file)\n .then((image) => {\n preview.image = image\n })\n .catch((error: unknown) => {\n this.previews = this.previews.filter((p) => p !== preview)\n const reason = error instanceof ValidationError ? (error.first('media-file') ?? '') : ''\n showToast({\n message: `${t('reviews.uploadFailed', { name: file.name })} ${reason}`.trim(),\n tone: 'error',\n })\n })\n .finally(() => {\n this.uploads.delete(upload)\n this.paint()\n })\n this.uploads.add(upload)\n }\n this.paint()\n }\n\n /** Drops an image from the review, and its uploaded file from the server. */\n removeImage(key: number): void {\n const preview = this.previews.find((p) => p.key === key)\n this.previews = this.previews.filter((p) => p.key !== key)\n this.paint()\n // Best effort: a file left behind belongs to no review and the server cleans it up\n if (preview?.image) void deleteReviewImage(preview.image.id).catch(() => {})\n }\n\n /** Sends the review; ignored while one is being sent. */\n async submit(): Promise<void> {\n if (this.busy) return\n this.busy = true\n const form = this.requirePart<HTMLFormElement>('form')\n const submit = this.findPart<HTMLButtonElement>('submit')\n const general = this.findPart('error')\n clearFieldErrors(form)\n if (general) general.hidden = true\n submit?.setAttribute('aria-busy', 'true')\n try {\n // Images still uploading belong to the review\n await Promise.all(this.uploads)\n const data = new FormData(form)\n const token = String(data.get('token') ?? '')\n await submitReview(this.productId, {\n rating: Number(data.get('rating') ?? 0),\n title: String(data.get('title') ?? '').trim() || undefined,\n body: String(data.get('body') ?? '').trim(),\n recommended: data.get('recommended') !== null,\n images: this.imageIds,\n ...(token ? { token } : {}),\n })\n form.hidden = true\n const success = this.findPart('success')\n if (success) success.hidden = false\n else showToast({ message: t('reviews.thanks'), tone: 'success' })\n } catch (error) {\n const unplaced =\n error instanceof ValidationError ? showFieldErrors(form, error.errors) : [errorMessage(error)]\n if (unplaced.length && general) {\n general.textContent = unplaced[0]!\n general.hidden = false\n } else if (unplaced.length) {\n showToast({ message: unplaced[0]!, tone: 'error' })\n }\n } finally {\n this.busy = false\n submit?.removeAttribute('aria-busy')\n }\n }\n\n /** One preview; override to change the markup. */\n protected renderPreview(preview: Preview): unknown {\n return html`<li\n data-state=${preview.image ? 'done' : 'uploading'}\n aria-busy=${preview.image ? 'false' : 'true'}\n >\n ${preview.image ? html`<img src=${preview.image.thumb_url} alt=\"\" />` : html`<span>${t('common.loading')}</span>`}\n <button\n type=\"button\"\n aria-label=${t('reviews.removeImage', { name: preview.name })}\n @click=${() => this.removeImage(preview.key)}\n >\n ×\n </button>\n </li>`\n }\n\n private paint(): void {\n if (this.findPart('previews')) {\n this.renderPart(\n 'previews',\n html`${repeat(\n this.previews,\n (preview) => preview.key,\n (preview) => this.renderPreview(preview),\n )}`,\n )\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAkCA,IAAI,UAAU;AAGP,MAAM,wBAAwB,aAAa;AAAA,EAA3C,cAAA;AAAA,UAAA,GAAA,SAAA;AAML,SAAA,YAAY;AACZ,SAAA,YAAY;AACZ,SAAA,UAAU;AAEV,SAAQ,WAAsB,CAAA;AAC9B,SAAQ,8BAAc,IAAA;AACtB,SAAQ,OAAO;AAAA,EAAA;AAAA,EAXf,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,WAAW,EAAE,MAAM,QAAQ,WAAW,aAAA;AAAA,MACtC,WAAW,EAAE,MAAM,QAAQ,WAAW,aAAA;AAAA,MACtC,SAAS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KAAK;AAAA,UACL,CAAC,YAAY,QAAQ;AAAA,UACrB,CAAC,YAAY,KAAK,cAAc,OAAO;AAAA,QAAA,CACxC;AAAA,MAAA;AAAA,IAEL;AAAA,EACF;AACF;"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { nothing, html } from "lit";
|
|
2
2
|
import { t } from "../../core/i18n.js";
|
|
3
3
|
import { withStrong } from "./totals.js";
|
|
4
|
+
import { inPlace } from "../../lit/spmkt-element.js";
|
|
4
5
|
function renderCouponForm(options) {
|
|
5
6
|
const { prefix, error, applied } = options;
|
|
6
7
|
const id = `${prefix}-code`;
|
|
@@ -9,7 +10,7 @@ function renderCouponForm(options) {
|
|
|
9
10
|
class="cart-coupon"
|
|
10
11
|
data-part="coupon"
|
|
11
12
|
@submit=${(event) => {
|
|
12
|
-
event
|
|
13
|
+
inPlace(event);
|
|
13
14
|
options.onSubmit(event.target);
|
|
14
15
|
}}
|
|
15
16
|
>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coupon.js","sources":["../../../src/elements/shared/coupon.ts"],"sourcesContent":["import { html, nothing, type TemplateResult } from 'lit'\nimport { t } from '../../core/i18n'\nimport { withStrong } from './totals'\n\n/**\n * The coupon form the cart and the checkout summary share (`form.cart-coupon`, base's markup and data-test\n * attributes): a code field with its apply button, the refusal under it, and the code applied so far.\n */\nexport interface CouponFormOptions {\n /** Unique on the page: the field is `<prefix>-code`, its error `<prefix>-error` */\n prefix: string\n /** Why the last code was refused, shown under the field */\n error: string | null\n /** The code the cart has, if any */\n applied: string | null | undefined\n onSubmit: (form: HTMLFormElement) => void\n}\n\nexport function renderCouponForm(options: CouponFormOptions): TemplateResult {\n const { prefix, error, applied } = options\n const id = `${prefix}-code`\n const errorId = `${prefix}-error`\n return html`<form\n class=\"cart-coupon\"\n data-part=\"coupon\"\n @submit=${(event: Event) => {\n event
|
|
1
|
+
{"version":3,"file":"coupon.js","sources":["../../../src/elements/shared/coupon.ts"],"sourcesContent":["import { html, nothing, type TemplateResult } from 'lit'\nimport { t } from '../../core/i18n'\nimport { withStrong } from './totals'\nimport { inPlace } from '../../lit/spmkt-element'\n\n/**\n * The coupon form the cart and the checkout summary share (`form.cart-coupon`, base's markup and data-test\n * attributes): a code field with its apply button, the refusal under it, and the code applied so far.\n */\nexport interface CouponFormOptions {\n /** Unique on the page: the field is `<prefix>-code`, its error `<prefix>-error` */\n prefix: string\n /** Why the last code was refused, shown under the field */\n error: string | null\n /** The code the cart has, if any */\n applied: string | null | undefined\n onSubmit: (form: HTMLFormElement) => void\n}\n\nexport function renderCouponForm(options: CouponFormOptions): TemplateResult {\n const { prefix, error, applied } = options\n const id = `${prefix}-code`\n const errorId = `${prefix}-error`\n return html`<form\n class=\"cart-coupon\"\n data-part=\"coupon\"\n @submit=${(event: Event) => {\n inPlace(event)\n options.onSubmit(event.target as HTMLFormElement)\n }}\n >\n <label for=${id}>${t('cart.coupon')}</label>\n <div class=\"cart-coupon__field\">\n <input\n class=\"input\"\n id=${id}\n name=\"coupon_code\"\n autocomplete=\"off\"\n data-test=\"coupon-input\"\n aria-invalid=${error ? 'true' : nothing}\n aria-describedby=${error ? errorId : 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=${errorId} data-part=\"coupon-error\" ?hidden=${!error}>${error ?? ''}</p>\n ${\n applied\n ? html`<p class=\"cart-coupon__applied\" data-test=\"coupon-applied\">\n ${withStrong('cart.couponApplied', 'code', applied)}\n </p>`\n : nothing\n }\n </form>`\n}\n\n/** The code typed in a coupon form, trimmed; empty focuses the field. */\nexport function couponCode(form: HTMLFormElement): { input: HTMLInputElement | null; code: string } {\n const input = form.querySelector<HTMLInputElement>('[name=\"coupon_code\"]')\n const code = (input?.value ?? '').trim()\n if (code === '') input?.focus()\n return { input, code }\n}\n"],"names":[],"mappings":";;;;AAmBO,SAAS,iBAAiB,SAA4C;AAC3E,QAAM,EAAE,QAAQ,OAAO,QAAA,IAAY;AACnC,QAAM,KAAK,GAAG,MAAM;AACpB,QAAM,UAAU,GAAG,MAAM;AACzB,SAAO;AAAA;AAAA;AAAA,cAGK,CAAC,UAAiB;AAC1B,YAAQ,KAAK;AACb,YAAQ,SAAS,MAAM,MAAyB;AAAA,EAClD,CAAC;AAAA;AAAA,iBAEY,EAAE,IAAI,EAAE,aAAa,CAAC;AAAA;AAAA;AAAA;AAAA,aAI1B,EAAE;AAAA;AAAA;AAAA;AAAA,uBAIQ,QAAQ,SAAS,OAAO;AAAA,2BACpB,QAAQ,UAAU,OAAO;AAAA;AAAA;AAAA,UAG1C,EAAE,kBAAkB,CAAC;AAAA;AAAA;AAAA,gCAGC,OAAO,qCAAqC,CAAC,KAAK,IAAI,SAAS,EAAE;AAAA,MAE3F,UACI;AAAA,cACI,WAAW,sBAAsB,QAAQ,OAAO,CAAC;AAAA,kBAErD,OACN;AAAA;AAEJ;AAGO,SAAS,WAAW,MAAyE;AAClG,QAAM,QAAQ,KAAK,cAAgC,sBAAsB;AACzE,QAAM,QAAQ,OAAO,SAAS,IAAI,KAAA;AAClC,MAAI,SAAS,GAAI,QAAO,MAAA;AACxB,SAAO,EAAE,OAAO,KAAA;AAClB;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-form.js","sources":["../../../src/elements/shared/json-form.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { clearFieldErrors, errorMessage, showFieldErrors } from '../../lit/forms'\nimport { ValidationError } from '../../core/errors'\n\n/**\n * A form whose values go to the server as JSON, with the answer's errors shown in the theme's markup. Parts:\n * - form (required): fields named as the endpoint takes them, each with a [data-error-for] slot. It has no\n * `action`, so a submit before the element loads is held (the theme's early-submit guard) rather than sent\n * - submit (optional): busy while the form is sent\n * - error (optional): a message not tied to a field (render it hidden)\n * Subclasses send the values in accept() and react to the result in accepted().\n */\nexport abstract class JsonForm<Result = unknown> extends SpmktElement {\n protected busy = false\n\n /** Sends the values; throws the request's error when the server refuses them. */\n protected abstract accept(values: Record<string, string>): Promise<Result>\n\n /** After the server took the values. */\n protected accepted(_result: Result): void {}\n\n override connectedCallback(): void {\n super.connectedCallback()\n this.
|
|
1
|
+
{"version":3,"file":"json-form.js","sources":["../../../src/elements/shared/json-form.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { clearFieldErrors, errorMessage, showFieldErrors } from '../../lit/forms'\nimport { ValidationError } from '../../core/errors'\n\n/**\n * A form whose values go to the server as JSON, with the answer's errors shown in the theme's markup. Parts:\n * - form (required): fields named as the endpoint takes them, each with a [data-error-for] slot. It has no\n * `action`, so a submit before the element loads is held (the theme's early-submit guard) rather than sent\n * - submit (optional): busy while the form is sent\n * - error (optional): a message not tied to a field (render it hidden)\n * Subclasses send the values in accept() and react to the result in accepted().\n */\nexport abstract class JsonForm<Result = unknown> extends SpmktElement {\n protected busy = false\n\n /** Sends the values; throws the request's error when the server refuses them. */\n protected abstract accept(values: Record<string, string>): Promise<Result>\n\n /** After the server took the values. */\n protected accepted(_result: Result): void {}\n\n override connectedCallback(): void {\n super.connectedCallback()\n this.submitInPlace(this.form(), () => {\n void this.send()\n })\n }\n\n protected form(): HTMLFormElement {\n return this.requirePart<HTMLFormElement>('form')\n }\n\n /**\n * The form's values as strings, trimmed, except passwords: they go exactly as typed, as the plain sign-in and\n * registration forms send them (a space can be part of a password).\n */\n protected values(): Record<string, string> {\n const form = this.form()\n const values: Record<string, string> = {}\n for (const [name, value] of new FormData(form)) {\n if (typeof value !== 'string') continue\n const control = form.elements.namedItem(name)\n values[name] = control instanceof HTMLInputElement && control.type === 'password' ? value : value.trim()\n }\n return values\n }\n\n /** Fills empty (or all, with `overwrite`) fields of the form from `values`. */\n protected fill(values: Record<string, unknown>, overwrite = false): void {\n const form = this.form()\n for (const [name, value] of Object.entries(values)) {\n const control = form.elements.namedItem(name)\n if (\n (control instanceof HTMLInputElement || control instanceof HTMLSelectElement) &&\n value !== null &&\n value !== undefined &&\n (overwrite || control.value === '' || control instanceof HTMLSelectElement)\n ) {\n control.value = String(value)\n }\n }\n }\n\n /** Sends the form once at a time. Resolves true when the server took it. */\n async send(): Promise<boolean> {\n if (this.busy) return false\n const form = this.form()\n const submit = this.findPart('submit')\n this.busy = true\n form.setAttribute('aria-busy', 'true')\n submit?.setAttribute('aria-busy', 'true')\n clearFieldErrors(form)\n this.showError(null)\n try {\n this.accepted(await this.accept(this.values()))\n return true\n } catch (error) {\n if (error instanceof ValidationError) {\n const unplaced = showFieldErrors(form, error.errors)\n if (unplaced.length) this.showError(unplaced.join(' '))\n form.querySelector<HTMLElement>('[aria-invalid=\"true\"]')?.focus()\n } else {\n this.showError(errorMessage(error))\n }\n return false\n } finally {\n this.busy = false\n form.removeAttribute('aria-busy')\n submit?.removeAttribute('aria-busy')\n }\n }\n\n protected 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 }\n}\n"],"names":[],"mappings":";;;AAYO,MAAe,iBAAmC,aAAa;AAAA,EAA/D,cAAA;AAAA,UAAA,GAAA,SAAA;AACL,SAAU,OAAO;AAAA,EAAA;AAAA;AAAA,EAMP,SAAS,SAAuB;AAAA,EAAC;AAAA,EAElC,oBAA0B;AACjC,UAAM,kBAAA;AACN,SAAK,cAAc,KAAK,KAAA,GAAQ,MAAM;AACpC,WAAK,KAAK,KAAA;AAAA,IACZ,CAAC;AAAA,EACH;AAAA,EAEU,OAAwB;AAChC,WAAO,KAAK,YAA6B,MAAM;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMU,SAAiC;AACzC,UAAM,OAAO,KAAK,KAAA;AAClB,UAAM,SAAiC,CAAA;AACvC,eAAW,CAAC,MAAM,KAAK,KAAK,IAAI,SAAS,IAAI,GAAG;AAC9C,UAAI,OAAO,UAAU,SAAU;AAC/B,YAAM,UAAU,KAAK,SAAS,UAAU,IAAI;AAC5C,aAAO,IAAI,IA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ClC,QAAI,MAAM;AACR,WAAK,cAAc,WAAW;AAC9B,WAAK,SAAS,YAAY;AAAA,IAC5B;AAAA,EACF;AACF;"}
|
|
@@ -14,8 +14,7 @@ class PagedSectionElement extends SpmktElement {
|
|
|
14
14
|
const apply = this.findPart("apply");
|
|
15
15
|
if (apply) apply.hidden = true;
|
|
16
16
|
this.listen(sort, "change", () => void this.show(this.formUrl(sort)));
|
|
17
|
-
this.
|
|
18
|
-
event.preventDefault();
|
|
17
|
+
this.submitInPlace(sort, () => {
|
|
19
18
|
void this.show(this.formUrl(sort));
|
|
20
19
|
});
|
|
21
20
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paged-section.js","sources":["../../../src/elements/shared/paged-section.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { fetchFragments, sectionKey, swapSection } from '../../lit/fragments'\nimport { isAbortError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { showToast } from '../toaster/toaster'\n\n/**\n * Parts every paged list in a theme section has (reviews, questions):\n * - items (element-owned for appending): the list; leave it out when there is nothing to list\n * - more (optional): the paging block, with load-more: a link to the next page's URL\n * - sort (optional): a GET form whose changes re-render the section; apply is its submit button\n *\n * Both work as plain links and forms; inside a theme section, the next page is fetched as that section and\n * its items appended (from this element's own copy, when the section holds more than one paged list), and a\n * sort re-renders the section. The page's URL does not change.\n */\nexport interface PagedSectionParts {\n items?: HTMLElement\n more?: HTMLElement\n 'load-more'?: HTMLAnchorElement\n sort?: HTMLFormElement\n apply?: HTMLElement\n}\n\nexport abstract class PagedSectionElement extends SpmktElement {\n private inFlight: AbortController | undefined\n\n override connectedCallback(): void {\n super.connectedCallback()\n if (!sectionKey(this)) {\n return\n }\n const sort = this.findPart<HTMLFormElement>('sort')\n if (sort) {\n const apply = this.findPart('apply')\n if (apply) apply.hidden = true\n this.listen(sort, 'change', () => void this.show(this.formUrl(sort)))\n this.
|
|
1
|
+
{"version":3,"file":"paged-section.js","sources":["../../../src/elements/shared/paged-section.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { fetchFragments, sectionKey, swapSection } from '../../lit/fragments'\nimport { isAbortError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { showToast } from '../toaster/toaster'\n\n/**\n * Parts every paged list in a theme section has (reviews, questions):\n * - items (element-owned for appending): the list; leave it out when there is nothing to list\n * - more (optional): the paging block, with load-more: a link to the next page's URL\n * - sort (optional): a GET form whose changes re-render the section; apply is its submit button\n *\n * Both work as plain links and forms; inside a theme section, the next page is fetched as that section and\n * its items appended (from this element's own copy, when the section holds more than one paged list), and a\n * sort re-renders the section. The page's URL does not change.\n */\nexport interface PagedSectionParts {\n items?: HTMLElement\n more?: HTMLElement\n 'load-more'?: HTMLAnchorElement\n sort?: HTMLFormElement\n apply?: HTMLElement\n}\n\nexport abstract class PagedSectionElement extends SpmktElement {\n private inFlight: AbortController | undefined\n\n override connectedCallback(): void {\n super.connectedCallback()\n if (!sectionKey(this)) {\n return\n }\n const sort = this.findPart<HTMLFormElement>('sort')\n if (sort) {\n const apply = this.findPart('apply')\n if (apply) apply.hidden = true\n this.listen(sort, 'change', () => void this.show(this.formUrl(sort)))\n this.submitInPlace(sort, () => {\n void this.show(this.formUrl(sort))\n })\n }\n this.listen(this, 'click', (event) => {\n const link = (event.target as Element).closest<HTMLAnchorElement>('a[data-part=\"load-more\"]')\n if (\n link &&\n this.contains(link) &&\n !event.defaultPrevented &&\n event.button === 0 &&\n !event.metaKey &&\n !event.ctrlKey\n ) {\n event.preventDefault()\n void this.loadMore(link.href)\n }\n })\n this.onDisconnect(() => this.inFlight?.abort())\n }\n\n /** Appends the items of the page at `url` and takes over its paging block. */\n async loadMore(url: string): Promise<void> {\n const more = this.findPart('more')\n more?.setAttribute('aria-busy', 'true')\n const html = await this.fetchSection(url)\n more?.removeAttribute('aria-busy')\n if (html === null) {\n return\n }\n const page = document.createElement('template')\n page.innerHTML = html\n const own = this.ownCopyIn(page.content)\n const items = own.querySelector('[data-part=\"items\"]')\n if (items) {\n this.findPart('items')?.append(...Array.from(items.children))\n }\n const nextMore = own.querySelector('[data-part=\"more\"]')\n if (more) {\n // The paging block is the server's: the next one, or none on the last page\n if (nextMore) more.replaceChildren(...Array.from(nextMore.childNodes))\n else more.hidden = true\n }\n }\n\n /**\n * This element's copy in the fetched section: a section may hold more than one paged list (reviews with the\n * questions in a tab), so the parts are looked up inside the element of the same tag at the same position.\n */\n private ownCopyIn(fetched: DocumentFragment): ParentNode {\n const section = this.closest('[data-section-id][data-theme-document]')\n const index = section ? Array.from(section.querySelectorAll(this.localName)).indexOf(this) : 0\n return fetched.querySelectorAll(this.localName)[Math.max(index, 0)] ?? fetched\n }\n\n /** Re-renders the section for `url` (a sort). */\n async show(url: string): Promise<void> {\n const key = sectionKey(this)\n const items = this.findPart('items')\n items?.setAttribute('aria-busy', 'true')\n const html = await this.fetchSection(url)\n if (html === null) {\n items?.removeAttribute('aria-busy')\n return\n }\n if (key) swapSection(this, html)\n }\n\n private formUrl(form: HTMLFormElement): string {\n const url = new URL(form.action || location.href, location.href)\n url.search = ''\n url.hash = ''\n for (const [name, value] of new FormData(form)) {\n if (typeof value === 'string' && value !== '') url.searchParams.append(name, value)\n }\n return url.toString()\n }\n\n /** The section's HTML for `url`, or null when it could not be had (the visitor is told). */\n private async fetchSection(url: string): Promise<string | null> {\n const key = sectionKey(this)\n if (!key) return null\n this.inFlight?.abort()\n const controller = (this.inFlight = new AbortController())\n try {\n const target = new URL(url, location.href)\n target.hash = ''\n const response = await fetchFragments(target, { sections: [key], signal: controller.signal })\n return response.sections[key] ?? null\n } catch (error) {\n if (!isAbortError(error)) showToast({ message: t('common.error'), tone: 'error' })\n return null\n }\n }\n}\n"],"names":[],"mappings":";;;;;AAwBO,MAAe,4BAA4B,aAAa;AAAA,EAGpD,oBAA0B;AACjC,UAAM,kBAAA;AACN,QAAI,CAAC,WAAW,IAAI,GAAG;AACrB;AAAA,IACF;AACA,UAAM,OA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AC5F,aAAO,SAAS,SAAS,GAAG,KAAK;AAAA,IACnC,SAAS,OAAO;AACd,UAAI,CAAC,aAAa,KAAK,EAAG,WAAU,EAAE,SAAS,EAAE,cAAc,GAAG,MAAM,QAAA,CAAS;AACjF,aAAO;AAAA,IACT;AAAA,EACF;AACF;"}
|
|
@@ -1,19 +1,23 @@
|
|
|
1
1
|
import { SpmktElement } from '../../lit/spmkt-element';
|
|
2
2
|
/**
|
|
3
3
|
* Parts of <spmkt-variant-picker variant="<id of the variant shown>"> (inside the product section):
|
|
4
|
-
* -
|
|
5
|
-
* options[<attribute id>]
|
|
6
|
-
*
|
|
4
|
+
* - options (required): the controls, one per option group, each with data-group="<attribute id>" (sent as
|
|
5
|
+
* options[<attribute id>]); data-action="<product URL>" (the page's own by default). Not a <form>: Tag
|
|
6
|
+
* Manager and the Google tag report the first change in a form as a form start (form_start), and a variant
|
|
7
|
+
* choice is not one. Without a form, radios with the same name are one group on the whole page, so each
|
|
8
|
+
* copy's controls need names of their own (a quick view puts a second picker beside the page's)
|
|
7
9
|
*
|
|
8
10
|
* A change re-renders the section around the element (its own copy: a quick view puts a second one on the page)
|
|
9
11
|
* for the chosen options (sections=<key>, plus changed=<attribute id> so a missing combination keeps the option
|
|
10
12
|
* just picked), then, for the page's own product (not in a dialog), puts ?variant=<id> in the address bar,
|
|
11
|
-
* read from the new picker's `variant` attribute.
|
|
12
|
-
* variant
|
|
13
|
+
* read from the new picker's `variant` attribute. `keep-url` leaves the address bar alone (a history change is
|
|
14
|
+
* a page view to GA4's enhanced measurement), except a ?variant= already there (a link from a feed or a share),
|
|
15
|
+
* which is taken out once: it would bring back a variant the shopper did not choose on a reload, Back or share.
|
|
16
|
+
* The new section's page events are not announced: another variant is not another product view. Outside a
|
|
17
|
+
* theme section (nothing to re-render) a change loads the product for the chosen options.
|
|
13
18
|
*/
|
|
14
19
|
export interface VariantPickerParts {
|
|
15
|
-
|
|
16
|
-
apply?: HTMLElement;
|
|
20
|
+
options: HTMLElement;
|
|
17
21
|
}
|
|
18
22
|
/** Variant choice without a page load; the product section is re-rendered for the variant. */
|
|
19
23
|
export declare class SpmktVariantPicker extends SpmktElement {
|
|
@@ -21,10 +25,17 @@ export declare class SpmktVariantPicker extends SpmktElement {
|
|
|
21
25
|
variant: {
|
|
22
26
|
type: NumberConstructor;
|
|
23
27
|
};
|
|
28
|
+
keepUrl: {
|
|
29
|
+
type: BooleanConstructor;
|
|
30
|
+
attribute: string;
|
|
31
|
+
};
|
|
24
32
|
};
|
|
25
33
|
variant: number;
|
|
34
|
+
keepUrl: boolean;
|
|
26
35
|
connectedCallback(): void;
|
|
27
|
-
/** The product URL for the
|
|
36
|
+
/** The product URL for the chosen options (and the group just changed). */
|
|
28
37
|
optionsUrl(changed?: number): URL;
|
|
38
|
+
/** Puts the chosen variant in the address bar; with keep-url, only takes out a ?variant= it no longer shows. */
|
|
39
|
+
private showInAddress;
|
|
29
40
|
private choose;
|
|
30
41
|
}
|