@wikala/spmkt 4.0.0-alpha.1 → 4.0.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/api/address.d.ts +6 -1
- package/dist/core/api/address.js +6 -1
- package/dist/core/api/address.js.map +1 -1
- package/dist/core/api/cart.d.ts +2 -21
- package/dist/core/api/cart.js +4 -30
- package/dist/core/api/cart.js.map +1 -1
- package/dist/core/api/checkout.d.ts +2 -9
- package/dist/core/api/checkout.js +3 -10
- package/dist/core/api/checkout.js.map +1 -1
- package/dist/core/api/index.d.ts +4 -4
- package/dist/core/api/product.d.ts +2 -10
- package/dist/core/api/product.js +0 -12
- package/dist/core/api/product.js.map +1 -1
- package/dist/core/events.d.ts +4 -3
- package/dist/core/events.js.map +1 -1
- package/dist/core/index.d.ts +4 -4
- package/dist/core/index.js +17 -13
- package/dist/core/money.d.ts +2 -0
- package/dist/core/money.js +5 -0
- package/dist/core/money.js.map +1 -1
- package/dist/core/page-events.d.ts +17 -0
- package/dist/core/page-events.js +37 -3
- package/dist/core/page-events.js.map +1 -1
- package/dist/core/state.d.ts +8 -1
- package/dist/core/state.js +75 -3
- package/dist/core/state.js.map +1 -1
- package/dist/core/stores/cart.d.ts +19 -20
- package/dist/core/stores/cart.js +38 -46
- package/dist/core/stores/cart.js.map +1 -1
- package/dist/core/stores/checkout.d.ts +10 -12
- package/dist/core/stores/checkout.js +19 -24
- package/dist/core/stores/checkout.js.map +1 -1
- package/dist/core/stores/index.d.ts +2 -2
- package/dist/core/types.d.ts +29 -7
- package/dist/elements/add-to-cart/add-to-cart.d.ts +23 -8
- package/dist/elements/add-to-cart/add-to-cart.js +62 -28
- package/dist/elements/add-to-cart/add-to-cart.js.map +1 -1
- package/dist/elements/add-to-cart/index.d.ts +1 -1
- package/dist/elements/address-book/address-book.d.ts +20 -15
- package/dist/elements/address-book/address-book.js +98 -34
- package/dist/elements/address-book/address-book.js.map +1 -1
- package/dist/elements/carousel/carousel.d.ts +11 -1
- package/dist/elements/carousel/carousel.js +22 -5
- package/dist/elements/carousel/carousel.js.map +1 -1
- package/dist/elements/cart/cart.d.ts +27 -27
- package/dist/elements/cart/cart.js +195 -80
- package/dist/elements/cart/cart.js.map +1 -1
- package/dist/elements/checkout/checkout.d.ts +13 -20
- package/dist/elements/checkout/checkout.js +73 -40
- package/dist/elements/checkout/checkout.js.map +1 -1
- package/dist/elements/checkout-delivery/checkout-delivery.d.ts +2 -9
- package/dist/elements/checkout-delivery/checkout-delivery.js +1 -8
- package/dist/elements/checkout-delivery/checkout-delivery.js.map +1 -1
- package/dist/elements/checkout-payment/checkout-payment.d.ts +2 -9
- package/dist/elements/checkout-payment/checkout-payment.js +2 -9
- package/dist/elements/checkout-payment/checkout-payment.js.map +1 -1
- package/dist/elements/collection/collection.d.ts +5 -9
- package/dist/elements/collection/collection.js +20 -20
- package/dist/elements/collection/collection.js.map +1 -1
- package/dist/elements/dialog/dialog.d.ts +7 -3
- package/dist/elements/dialog/dialog.js +12 -4
- package/dist/elements/dialog/dialog.js.map +1 -1
- package/dist/elements/mini-cart/mini-cart.d.ts +15 -15
- package/dist/elements/mini-cart/mini-cart.js +74 -62
- package/dist/elements/mini-cart/mini-cart.js.map +1 -1
- package/dist/elements/order-confirmation/index.d.ts +3 -0
- package/dist/elements/order-confirmation/index.js +7 -0
- package/dist/elements/order-confirmation/index.js.map +1 -0
- package/dist/elements/order-confirmation/order-confirmation.d.ts +35 -0
- package/dist/elements/order-confirmation/order-confirmation.js +123 -0
- package/dist/elements/order-confirmation/order-confirmation.js.map +1 -0
- package/dist/elements/quick-view/quick-view.d.ts +10 -7
- package/dist/elements/quick-view/quick-view.js +11 -5
- package/dist/elements/quick-view/quick-view.js.map +1 -1
- package/dist/elements/related/related.d.ts +8 -13
- package/dist/elements/related/related.js +20 -17
- package/dist/elements/related/related.js.map +1 -1
- package/dist/elements/shared/paged-section.js +1 -1
- package/dist/elements/shared/paged-section.js.map +1 -1
- package/dist/elements/shared/totals.d.ts +53 -0
- package/dist/elements/shared/totals.js +82 -0
- package/dist/elements/shared/totals.js.map +1 -0
- package/dist/elements/variant-picker/variant-picker.d.ts +5 -3
- package/dist/elements/variant-picker/variant-picker.js +6 -4
- package/dist/elements/variant-picker/variant-picker.js.map +1 -1
- package/dist/lit/fragments.d.ts +11 -10
- package/dist/lit/fragments.js +9 -10
- package/dist/lit/fragments.js.map +1 -1
- package/dist/locales/en.json +48 -3
- package/dist/locales/sr.json +49 -3
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"quick-view.js","sources":["../../../src/elements/quick-view/quick-view.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { fetchFragments } from '../../lit/fragments'\nimport { productUrl } from '../../core/api/product'\nimport { isAbortError } from '../../core/errors'\nimport { dispatchPageEvents } from '../../core/page-events'\nimport { SpmktDialog } from '../dialog/dialog'\n\n/**\n * <spmkt-quick-view dialog=\"<spmkt-dialog id>\"
|
|
1
|
+
{"version":3,"file":"quick-view.js","sources":["../../../src/elements/quick-view/quick-view.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { fetchFragments } from '../../lit/fragments'\nimport { productUrl } from '../../core/api/product'\nimport { isAbortError } from '../../core/errors'\nimport { dispatchPageEvents } from '../../core/page-events'\nimport { SpmktDialog } from '../dialog/dialog'\n\n/**\n * <spmkt-quick-view dialog=\"<spmkt-dialog id>\" [section=\"template:product/main\"]> has no parts: put it once in\n * the layout. Any element with data-spmkt-quick-view=\"<product id>\" opens that product page's `section`\n * (GET /products/{id}?sections=template:product/main) in the dialog: the product as the merchant set it up,\n * which the dialog's CSS compacts. Make the trigger a link to the product page, so a failed request goes there.\n *\n * The section's wrapper loses its id (the product page has its own `main` with the same one); its\n * data-section-id and data-theme-document stay, so a variant change inside swaps the dialog's copy only. The\n * section's page events (its view-item script, see dispatchPageEvents) are announced once it is shown.\n */\nexport class SpmktQuickView extends SpmktElement {\n static override properties = {\n dialog: { type: String },\n section: { type: String },\n }\n dialog = 'quick-view'\n /** The product page's section to show */\n section = 'template:product/main'\n\n private inFlight: AbortController | undefined\n\n override connectedCallback(): void {\n super.connectedCallback()\n this.listen(document, 'click', (event) => this.onClick(event))\n }\n\n /** Opens the quick view of product `id`. Resolves false when it could not be shown. */\n async open(id: number, trigger?: HTMLElement): Promise<boolean> {\n const host = document.getElementById(this.dialog)\n if (!(host instanceof SpmktDialog)) {\n return false\n }\n this.inFlight?.abort()\n const controller = (this.inFlight = new AbortController())\n trigger?.setAttribute('aria-busy', 'true')\n try {\n const response = await fetchFragments(productUrl(id), {\n sections: [this.section],\n signal: controller.signal,\n })\n const html = response.sections[this.section]\n if (!html) {\n return false\n }\n host.open(withoutWrapperId(html))\n dispatchPageEvents(host)\n return true\n } catch (error) {\n return isAbortError(error)\n } finally {\n trigger?.removeAttribute('aria-busy')\n }\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 trigger = (event.target as Element | null)?.closest?.<HTMLElement>('[data-spmkt-quick-view]')\n const id = Number(trigger?.dataset.spmktQuickView)\n if (!trigger || !(id > 0) || !(document.getElementById(this.dialog) instanceof SpmktDialog)) {\n return\n }\n event.preventDefault()\n void this.open(id, trigger).then((shown) => {\n // Could not show it here: the product page can\n if (!shown && trigger instanceof HTMLAnchorElement) {\n location.assign(trigger.href)\n }\n })\n }\n}\n\n/** The section's HTML without its wrapper's id, which the page's own copy of the section has. */\nfunction withoutWrapperId(html: string): string {\n const template = document.createElement('template')\n template.innerHTML = html\n template.content.firstElementChild?.removeAttribute('id')\n return template.innerHTML\n}\n"],"names":[],"mappings":";;;;;;AAiBO,MAAM,uBAAuB,aAAa;AAAA,EAA1C,cAAA;AAAA,UAAA,GAAA,SAAA;AAKL,SAAA,SAAS;AAET,SAAA,UAAU;AAAA,EA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M,eAAA;AACN,SAAK,KAAK,KAAK,IAAI,OAAO,EAAE,KAAK,CAAC,UAAU;AAE1C,UAAI,CAAC,SAAS,mBAAmB,mBAAmB;AAClD,iBAAS,OAAO,QAAQ,IAAI;AAAA,MAC9B;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAGA,SAAS,iBAAiB,MAAsB;AAC9C,QAAM,WAAW,SAAS,cAAc,UAAU;AAClD,WAAS,YAAY;AACrB,WAAS,QAAQ,mBAAmB,gBAAgB,IAAI;AACxD,SAAO,SAAS;AAClB;"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { SpmktElement } from '../../lit/spmkt-element';
|
|
2
2
|
/**
|
|
3
|
-
* Parts of <spmkt-related
|
|
4
|
-
* - items (required, element-owned for appending): the list of cards
|
|
5
|
-
* - more (optional): the "load more" button;
|
|
3
|
+
* Parts of <spmkt-related data-page="N"> (inside the related-products section):
|
|
4
|
+
* - items (required, element-owned for appending): the list of cards
|
|
5
|
+
* - more (optional): the "load more" button; the section renders it only when another page follows
|
|
6
6
|
*
|
|
7
|
-
* "Load more" asks
|
|
8
|
-
*
|
|
7
|
+
* "Load more" asks the page for its own section's next page (?sections=<this section>&related_page=N+1) and
|
|
8
|
+
* appends that section's `items` children; the button goes once a page comes without one. A click on a
|
|
9
9
|
* product link in a card with data-item sends spmkt:select-item (see spmkt-collection).
|
|
10
10
|
*/
|
|
11
11
|
export interface RelatedParts {
|
|
@@ -15,19 +15,14 @@ export interface RelatedParts {
|
|
|
15
15
|
/** Related products: the next ones are rendered by the server, so cards keep one owner. */
|
|
16
16
|
export declare class SpmktRelated extends SpmktElement {
|
|
17
17
|
static properties: {
|
|
18
|
-
|
|
18
|
+
page: {
|
|
19
19
|
type: NumberConstructor;
|
|
20
20
|
attribute: string;
|
|
21
21
|
};
|
|
22
|
-
fragment: {
|
|
23
|
-
type: StringConstructor;
|
|
24
|
-
};
|
|
25
22
|
};
|
|
26
|
-
|
|
27
|
-
|
|
23
|
+
/** The page of related products shown last (1 for the page's own) */
|
|
24
|
+
page: number;
|
|
28
25
|
private inFlight;
|
|
29
26
|
connectedCallback(): void;
|
|
30
|
-
/** Ids of the products shown */
|
|
31
|
-
get shownIds(): number[];
|
|
32
27
|
loadMore(): Promise<void>;
|
|
33
28
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { SpmktElement } from "../../lit/spmkt-element.js";
|
|
2
|
-
import {
|
|
2
|
+
import { sectionKey, fetchFragments } from "../../lit/fragments.js";
|
|
3
|
+
import { warnOnce } from "../../core/config.js";
|
|
3
4
|
import { isAbortError } from "../../core/errors.js";
|
|
4
5
|
import { t } from "../../core/i18n.js";
|
|
5
6
|
import { showToast } from "../toaster/toaster.js";
|
|
@@ -7,13 +8,11 @@ import { emitSelectItem } from "../shared/select-item.js";
|
|
|
7
8
|
class SpmktRelated extends SpmktElement {
|
|
8
9
|
constructor() {
|
|
9
10
|
super(...arguments);
|
|
10
|
-
this.
|
|
11
|
-
this.fragment = "related-page";
|
|
11
|
+
this.page = 1;
|
|
12
12
|
}
|
|
13
13
|
static {
|
|
14
14
|
this.properties = {
|
|
15
|
-
|
|
16
|
-
fragment: { type: String }
|
|
15
|
+
page: { type: Number, attribute: "data-page" }
|
|
17
16
|
};
|
|
18
17
|
}
|
|
19
18
|
connectedCallback() {
|
|
@@ -27,28 +26,32 @@ class SpmktRelated extends SpmktElement {
|
|
|
27
26
|
this.listen(this, "click", (event) => emitSelectItem(this, event));
|
|
28
27
|
this.onDisconnect(() => this.inFlight?.abort());
|
|
29
28
|
}
|
|
30
|
-
/** Ids of the products shown */
|
|
31
|
-
get shownIds() {
|
|
32
|
-
return Array.from(this.requirePart("items").children).map((child) => Number(child.dataset.productId)).filter((id) => id > 0);
|
|
33
|
-
}
|
|
34
29
|
async loadMore() {
|
|
35
30
|
const more = this.findPart("more");
|
|
31
|
+
const key = sectionKey(this);
|
|
32
|
+
if (!key) {
|
|
33
|
+
warnOnce("related:section", "<spmkt-related> is not inside a section, so it cannot load more");
|
|
34
|
+
if (more) more.hidden = true;
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
36
37
|
this.inFlight?.abort();
|
|
37
38
|
const controller = this.inFlight = new AbortController();
|
|
39
|
+
const next = this.page + 1;
|
|
38
40
|
more?.setAttribute("aria-busy", "true");
|
|
39
41
|
try {
|
|
40
|
-
const response = await
|
|
41
|
-
|
|
42
|
+
const response = await fetchFragments(window.location.href, {
|
|
43
|
+
sections: [key],
|
|
44
|
+
query: { related_page: next },
|
|
42
45
|
signal: controller.signal
|
|
43
46
|
});
|
|
44
47
|
const template = document.createElement("template");
|
|
45
|
-
template.innerHTML = response
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
48
|
+
template.innerHTML = response.sections[key] ?? "";
|
|
49
|
+
const items = template.content.querySelector('[data-part="items"]');
|
|
50
|
+
if (items) {
|
|
51
|
+
this.requirePart("items").append(...Array.from(items.children));
|
|
52
|
+
this.page = next;
|
|
50
53
|
}
|
|
51
|
-
if (more && (!
|
|
54
|
+
if (more && (!items || !template.content.querySelector('[data-part="more"]'))) {
|
|
52
55
|
more.hidden = true;
|
|
53
56
|
}
|
|
54
57
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"related.js","sources":["../../../src/elements/related/related.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport
|
|
1
|
+
{"version":3,"file":"related.js","sources":["../../../src/elements/related/related.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { fetchFragments, sectionKey } from '../../lit/fragments'\nimport { warnOnce } from '../../core/config'\nimport { isAbortError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { showToast } from '../toaster/toaster'\nimport { emitSelectItem } from '../shared/select-item'\n\n/**\n * Parts of <spmkt-related data-page=\"N\"> (inside the related-products section):\n * - items (required, element-owned for appending): the list of cards\n * - more (optional): the \"load more\" button; the section renders it only when another page follows\n *\n * \"Load more\" asks the page for its own section's next page (?sections=<this section>&related_page=N+1) and\n * appends that section's `items` children; the button goes once a page comes without one. A click on a\n * product link in a card with data-item sends spmkt:select-item (see spmkt-collection).\n */\nexport interface RelatedParts {\n items: HTMLElement\n more?: HTMLButtonElement\n}\n\n/** Related products: the next ones are rendered by the server, so cards keep one owner. */\nexport class SpmktRelated extends SpmktElement {\n static override properties = {\n page: { type: Number, attribute: 'data-page' },\n }\n /** The page of related products shown last (1 for the page's own) */\n page = 1\n\n private inFlight: AbortController | undefined\n\n override connectedCallback(): void {\n super.connectedCallback()\n this.requirePart('items')\n const more = this.findPart<HTMLButtonElement>('more')\n if (more) {\n more.hidden = false\n this.listen(more, 'click', () => void this.loadMore())\n }\n this.listen(this, 'click', (event) => emitSelectItem(this, event))\n this.onDisconnect(() => this.inFlight?.abort())\n }\n\n async loadMore(): Promise<void> {\n const more = this.findPart<HTMLButtonElement>('more')\n const key = sectionKey(this)\n if (!key) {\n warnOnce('related:section', '<spmkt-related> is not inside a section, so it cannot load more')\n if (more) more.hidden = true\n return\n }\n this.inFlight?.abort()\n const controller = (this.inFlight = new AbortController())\n const next = this.page + 1\n more?.setAttribute('aria-busy', 'true')\n try {\n const response = await fetchFragments(window.location.href, {\n sections: [key],\n query: { related_page: next },\n signal: controller.signal,\n })\n const template = document.createElement('template')\n template.innerHTML = response.sections[key] ?? ''\n const items = template.content.querySelector('[data-part=\"items\"]')\n if (items) {\n this.requirePart('items').append(...Array.from(items.children))\n this.page = next\n }\n if (more && (!items || !template.content.querySelector('[data-part=\"more\"]'))) {\n more.hidden = true\n }\n } catch (error) {\n if (!isAbortError(error)) {\n showToast({ message: t('common.error'), tone: 'error' })\n }\n } finally {\n more?.removeAttribute('aria-busy')\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;AAuBO,MAAM,qBAAqB,aAAa;AAAA,EAAxC,cAAA;AAAA,UAAA,GAAA,SAAA;AAKL,SAAA,OAAO;AAAA,EAAA;AAAA,EAJP,OAAA;AA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,MAChB;AAAA,IACF,SAAS,OAAO;AACd,UAAI,CAAC,aAAa,KAAK,GAAG;AACxB,kBAAU,EAAE,SAAS,EAAE,cAAc,GAAG,MAAM,SAAS;AAAA,MACzD;AAAA,IACF,UAAA;AACE,YAAM,gBAAgB,WAAW;AAAA,IACnC;AAAA,EACF;AACF;"}
|
|
@@ -59,7 +59,7 @@ class PagedSectionElement extends SpmktElement {
|
|
|
59
59
|
items?.removeAttribute("aria-busy");
|
|
60
60
|
return;
|
|
61
61
|
}
|
|
62
|
-
if (key) swapSection(
|
|
62
|
+
if (key) swapSection(this, html);
|
|
63
63
|
}
|
|
64
64
|
formUrl(form) {
|
|
65
65
|
const url = new URL(form.action || location.href, location.href);
|
|
@@ -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, and a 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.listen(sort, 'submit', (event) => {\n event.preventDefault()\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 items = page.content.querySelector('[data-part=\"items\"]')\n if (items) {\n this.findPart('items')?.append(...Array.from(items.children))\n }\n const nextMore = page.content.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 /** 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(
|
|
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, and a 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.listen(sort, 'submit', (event) => {\n event.preventDefault()\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 items = page.content.querySelector('[data-part=\"items\"]')\n if (items) {\n this.findPart('items')?.append(...Array.from(items.children))\n }\n const nextMore = page.content.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 /** 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":";;;;;AAuBO,MAAe,4BAA4B,aAAa;AAAA,EAGpD,oBAA0B;AACjC,UAAM,kBAAA;AACN,QAAI,CAAC,WAAW,IAAI,GAAG;AACrB;AAAA,IACF;AACA,UAAM,OAAO,KAAK,SAA0B,MAAM;AAClD,QAAI,MAAM;AACR,YAAM,QAAQ,KAAK,SAAS,OAAO;AACnC,UAAI,aAAa,SAAS;AAC1B,WAAK,OAAO,MAAM,UAAU,MAAM,KAAK,KAAK,KAAK,KAAK,QAAQ,IAAI,CAAC,CAAC;AACpE,WAAK,OAAO,MAAM,UAAU,CAAC,UAAU;AACrC,cAAM,eAAA;AACN,aAAK,KAAK,KAAK,KAAK,QAAQ,IAAI,CAAC;AAAA,MACnC,CAAC;AAAA,IACH;AACA,SAAK,OAAO,MAAM,SAAS,CAAC,UAAU;AACpC,YAAM,OAAQ,MAAM,OAAmB,QAA2B,0BAA0B;AAC5F,UACE,QACA,KAAK,SAAS,IAAI,KAClB,CAAC,MAAM,oBACP,MAAM,WAAW,KACjB,CAAC,MAAM,WACP,CAAC,MAAM,SACP;AACA,cAAM,eAAA;AACN,aAAK,KAAK,SAAS,KAAK,IAAI;AAAA,MAC9B;AAAA,IACF,CAAC;AACD,SAAK,aAAa,MAA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EAGA,MAAc,aAAa,KAAqC;AAC9D,UAAM,MAAM,WAAW,IAAI;AAC3B,QAAI,CAAC,IAAK,QAAO;AACjB,SAAK,UAAU,MAAA;AACf,UAAM,aAAc,KAAK,WAAW,IAAI,gBAAA;AACxC,QAAI;AACF,YAAM,SAAS,IAAI,IAAI,KAAK,SAAS,IAAI;AACzC,aAAO,OAAO;AACd,YAAM,WAAW,MAAM,eAAe,QAAQ,EAAE,UAAU,CAAC,GAAG,GAAG,QAAQ,WAAW,OAAA,CAAQ;AAC5F,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;"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { nothing, type TemplateResult } from 'lit';
|
|
2
|
+
import type { CartLine } from '../../core/types';
|
|
3
|
+
/**
|
|
4
|
+
* Templates the cart, the mini cart, the checkout summary and the order confirmation share: the totals list
|
|
5
|
+
* (`dl.cart-totals`, base's markup and data-test attributes), its tax row, and pieces of a line.
|
|
6
|
+
*/
|
|
7
|
+
/** What a totals list shows; a row whose value is undefined is left out. */
|
|
8
|
+
export interface Totals {
|
|
9
|
+
subtotal?: number;
|
|
10
|
+
discount?: number;
|
|
11
|
+
/** Named after "Popust" when given */
|
|
12
|
+
coupon?: string | null;
|
|
13
|
+
shipping: number;
|
|
14
|
+
taxAmount: number;
|
|
15
|
+
/** The tax rate, when known (the confirmation does not have it) */
|
|
16
|
+
taxPercent?: number;
|
|
17
|
+
total: number;
|
|
18
|
+
}
|
|
19
|
+
export interface TotalsOptions {
|
|
20
|
+
/**
|
|
21
|
+
* How shipping shows: 'charged' only when there is any (the cart); 'always' as an amount or "free"; 'by-choice'
|
|
22
|
+
* as "by the delivery chosen" until the summary priced a choice (the checkout, before one is chosen)
|
|
23
|
+
*/
|
|
24
|
+
shipping: 'charged' | 'always' | 'by-choice';
|
|
25
|
+
/** The list's data-test */
|
|
26
|
+
testId?: string;
|
|
27
|
+
/** The total's data-test */
|
|
28
|
+
totalTestId: string;
|
|
29
|
+
/** The shipping row's data-test */
|
|
30
|
+
shippingTestId?: string;
|
|
31
|
+
/** More classes on the list */
|
|
32
|
+
className?: string;
|
|
33
|
+
}
|
|
34
|
+
/** The totals list: subtotal, discount, shipping, tax and total. */
|
|
35
|
+
export declare function renderTotals(totals: Totals, options: TotalsOptions): TemplateResult;
|
|
36
|
+
/**
|
|
37
|
+
* The tax row: nothing without tax. The rate has the shop's decimal separator and no trailing zeros ("20%",
|
|
38
|
+
* "8,5%"); "included" is said when the shop's prices include tax (pricesIncludeTax in the page state).
|
|
39
|
+
*/
|
|
40
|
+
export declare function renderTaxRow(amount: number, percent?: number): TemplateResult | typeof nothing;
|
|
41
|
+
/**
|
|
42
|
+
* A translated sentence with one parameter in <strong>, e.g. "Kupon <strong>X</strong> je primenjen.";
|
|
43
|
+
* `testId` goes on the <strong>.
|
|
44
|
+
*/
|
|
45
|
+
export declare function withStrong(key: string, param: string, value: string, testId?: string): TemplateResult;
|
|
46
|
+
/** The name a line shows: its parent product's, without the variant (the variant is shown below it). */
|
|
47
|
+
export declare function lineName(line: CartLine): string;
|
|
48
|
+
/** The product page of a line. */
|
|
49
|
+
export declare function lineUrl(line: CartLine, shopUrl: (path: string) => string): string;
|
|
50
|
+
/** Whether a line has a real image (the platform's placeholder is left out). */
|
|
51
|
+
export declare function hasImage(line: CartLine): boolean;
|
|
52
|
+
/** Whether the cart can go to checkout: no line has a problem (e.g. more than the stock). */
|
|
53
|
+
export declare function cartBlocked(lines: readonly CartLine[]): boolean;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { nothing, html } from "lit";
|
|
2
|
+
import { formatMoney, moneyFormat, numberFormat } from "../../core/money.js";
|
|
3
|
+
import { t } from "../../core/i18n.js";
|
|
4
|
+
import { storefront } from "../../core/state.js";
|
|
5
|
+
function renderTotals(totals, options) {
|
|
6
|
+
const discount = totals.discount ?? 0;
|
|
7
|
+
return html`<dl
|
|
8
|
+
class="cart-totals${options.className ? ` ${options.className}` : ""}"
|
|
9
|
+
data-test=${options.testId ?? nothing}
|
|
10
|
+
>
|
|
11
|
+
${totals.subtotal === void 0 ? nothing : html`<div>
|
|
12
|
+
<dt>${t("totals.subtotal")}</dt>
|
|
13
|
+
<dd>${formatMoney(totals.subtotal)}</dd>
|
|
14
|
+
</div>`}
|
|
15
|
+
${discount > 0 ? html`<div class="cart-totals__discount">
|
|
16
|
+
<dt>
|
|
17
|
+
${totals.coupon ? t("totals.discountCoupon", { code: totals.coupon }) : t("totals.discount")}
|
|
18
|
+
</dt>
|
|
19
|
+
<dd>−${formatMoney(discount)}</dd>
|
|
20
|
+
</div>` : nothing}
|
|
21
|
+
${renderShipping(totals.shipping, options)} ${renderTaxRow(totals.taxAmount, totals.taxPercent)}
|
|
22
|
+
<div class="cart-totals__total">
|
|
23
|
+
<dt>${t("totals.total")}</dt>
|
|
24
|
+
<dd data-test=${options.totalTestId}>${formatMoney(totals.total)}</dd>
|
|
25
|
+
</div>
|
|
26
|
+
</dl>`;
|
|
27
|
+
}
|
|
28
|
+
function renderShipping(shipping, options) {
|
|
29
|
+
if (options.shipping === "charged" && shipping <= 0) return nothing;
|
|
30
|
+
const value = shipping > 0 ? formatMoney(shipping) : options.shipping === "by-choice" ? html`<span class="text-muted">${t("totals.shippingByChoice")}</span>` : t("checkout.free");
|
|
31
|
+
return html`<div data-test=${options.shippingTestId ?? nothing}>
|
|
32
|
+
<dt>${t("totals.shipping")}</dt>
|
|
33
|
+
<dd>${value}</dd>
|
|
34
|
+
</div>`;
|
|
35
|
+
}
|
|
36
|
+
function renderTaxRow(amount, percent) {
|
|
37
|
+
if (!(amount > 0)) return nothing;
|
|
38
|
+
const details = [taxRate(percent), storefront().pricesIncludeTax ? t("totals.taxIncluded") : null].filter(
|
|
39
|
+
(detail) => detail !== null
|
|
40
|
+
);
|
|
41
|
+
const label = details.length ? `${t("totals.tax")} (${details.join(", ")})` : t("totals.tax");
|
|
42
|
+
return html`<div class="cart-totals__tax" data-test="tax-row">
|
|
43
|
+
<dt>${label}</dt>
|
|
44
|
+
<dd>${formatMoney(amount)}</dd>
|
|
45
|
+
</div>`;
|
|
46
|
+
}
|
|
47
|
+
function taxRate(percent) {
|
|
48
|
+
if (percent === void 0 || !(percent > 0)) return null;
|
|
49
|
+
const decimal = moneyFormat().decimal;
|
|
50
|
+
const number = numberFormat(percent, 2, decimal, "");
|
|
51
|
+
return `${number.replace(/0+$/, "").replace(new RegExp(`${escapeRegExp(decimal)}$`), "")}%`;
|
|
52
|
+
}
|
|
53
|
+
function escapeRegExp(text) {
|
|
54
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
55
|
+
}
|
|
56
|
+
function withStrong(key, param, value, testId) {
|
|
57
|
+
const marker = "\0";
|
|
58
|
+
const [before = "", after = ""] = t(key, { [param]: marker }).split(marker);
|
|
59
|
+
return html`${before}<strong data-test=${testId ?? nothing}>${value}</strong>${after}`;
|
|
60
|
+
}
|
|
61
|
+
function lineName(line) {
|
|
62
|
+
return line.parent_name || line.name;
|
|
63
|
+
}
|
|
64
|
+
function lineUrl(line, shopUrl) {
|
|
65
|
+
return shopUrl(`/${line.slug.replace(/^\/+/, "")}`);
|
|
66
|
+
}
|
|
67
|
+
function hasImage(line) {
|
|
68
|
+
return line.image_url !== "" && !line.image_url.includes("image_not_found");
|
|
69
|
+
}
|
|
70
|
+
function cartBlocked(lines) {
|
|
71
|
+
return lines.some((line) => line.error !== "");
|
|
72
|
+
}
|
|
73
|
+
export {
|
|
74
|
+
cartBlocked,
|
|
75
|
+
hasImage,
|
|
76
|
+
lineName,
|
|
77
|
+
lineUrl,
|
|
78
|
+
renderTaxRow,
|
|
79
|
+
renderTotals,
|
|
80
|
+
withStrong
|
|
81
|
+
};
|
|
82
|
+
//# sourceMappingURL=totals.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"totals.js","sources":["../../../src/elements/shared/totals.ts"],"sourcesContent":["import { html, nothing, type TemplateResult } from 'lit'\nimport { formatMoney, moneyFormat, numberFormat } from '../../core/money'\nimport { t } from '../../core/i18n'\nimport { storefront } from '../../core/state'\nimport type { CartLine } from '../../core/types'\n\n/**\n * Templates the cart, the mini cart, the checkout summary and the order confirmation share: the totals list\n * (`dl.cart-totals`, base's markup and data-test attributes), its tax row, and pieces of a line.\n */\n\n/** What a totals list shows; a row whose value is undefined is left out. */\nexport interface Totals {\n subtotal?: number\n discount?: number\n /** Named after \"Popust\" when given */\n coupon?: string | null\n shipping: number\n taxAmount: number\n /** The tax rate, when known (the confirmation does not have it) */\n taxPercent?: number\n total: number\n}\n\nexport interface TotalsOptions {\n /**\n * How shipping shows: 'charged' only when there is any (the cart); 'always' as an amount or \"free\"; 'by-choice'\n * as \"by the delivery chosen\" until the summary priced a choice (the checkout, before one is chosen)\n */\n shipping: 'charged' | 'always' | 'by-choice'\n /** The list's data-test */\n testId?: string\n /** The total's data-test */\n totalTestId: string\n /** The shipping row's data-test */\n shippingTestId?: string\n /** More classes on the list */\n className?: string\n}\n\n/** The totals list: subtotal, discount, shipping, tax and total. */\nexport function renderTotals(totals: Totals, options: TotalsOptions): TemplateResult {\n const discount = totals.discount ?? 0\n return html`<dl\n class=\"cart-totals${options.className ? ` ${options.className}` : ''}\"\n data-test=${options.testId ?? nothing}\n >\n ${\n totals.subtotal === undefined\n ? nothing\n : html`<div>\n <dt>${t('totals.subtotal')}</dt>\n <dd>${formatMoney(totals.subtotal)}</dd>\n </div>`\n }\n ${\n discount > 0\n ? html`<div class=\"cart-totals__discount\">\n <dt>\n ${totals.coupon ? t('totals.discountCoupon', { code: totals.coupon }) : t('totals.discount')}\n </dt>\n <dd>−${formatMoney(discount)}</dd>\n </div>`\n : nothing\n }\n ${renderShipping(totals.shipping, options)} ${renderTaxRow(totals.taxAmount, totals.taxPercent)}\n <div class=\"cart-totals__total\">\n <dt>${t('totals.total')}</dt>\n <dd data-test=${options.totalTestId}>${formatMoney(totals.total)}</dd>\n </div>\n </dl>`\n}\n\nfunction renderShipping(shipping: number, options: TotalsOptions): TemplateResult | typeof nothing {\n if (options.shipping === 'charged' && shipping <= 0) return nothing\n const value =\n shipping > 0\n ? formatMoney(shipping)\n : options.shipping === 'by-choice'\n ? html`<span class=\"text-muted\">${t('totals.shippingByChoice')}</span>`\n : t('checkout.free')\n return html`<div data-test=${options.shippingTestId ?? nothing}>\n <dt>${t('totals.shipping')}</dt>\n <dd>${value}</dd>\n </div>`\n}\n\n/**\n * The tax row: nothing without tax. The rate has the shop's decimal separator and no trailing zeros (\"20%\",\n * \"8,5%\"); \"included\" is said when the shop's prices include tax (pricesIncludeTax in the page state).\n */\nexport function renderTaxRow(amount: number, percent?: number): TemplateResult | typeof nothing {\n if (!(amount > 0)) return nothing\n const details = [taxRate(percent), storefront().pricesIncludeTax ? t('totals.taxIncluded') : null].filter(\n (detail) => detail !== null,\n )\n const label = details.length ? `${t('totals.tax')} (${details.join(', ')})` : t('totals.tax')\n return html`<div class=\"cart-totals__tax\" data-test=\"tax-row\">\n <dt>${label}</dt>\n <dd>${formatMoney(amount)}</dd>\n </div>`\n}\n\nfunction taxRate(percent: number | undefined): string | null {\n if (percent === undefined || !(percent > 0)) return null\n const decimal = moneyFormat().decimal\n const number = numberFormat(percent, 2, decimal, '')\n return `${number.replace(/0+$/, '').replace(new RegExp(`${escapeRegExp(decimal)}$`), '')}%`\n}\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * A translated sentence with one parameter in <strong>, e.g. \"Kupon <strong>X</strong> je primenjen.\";\n * `testId` goes on the <strong>.\n */\nexport function withStrong(key: string, param: string, value: string, testId?: string): TemplateResult {\n const marker = '\\u0000'\n const [before = '', after = ''] = t(key, { [param]: marker }).split(marker)\n return html`${before}<strong data-test=${testId ?? nothing}>${value}</strong>${after}`\n}\n\n/** The name a line shows: its parent product's, without the variant (the variant is shown below it). */\nexport function lineName(line: CartLine): string {\n return line.parent_name || line.name\n}\n\n/** The product page of a line. */\nexport function lineUrl(line: CartLine, shopUrl: (path: string) => string): string {\n return shopUrl(`/${line.slug.replace(/^\\/+/, '')}`)\n}\n\n/** Whether a line has a real image (the platform's placeholder is left out). */\nexport function hasImage(line: CartLine): boolean {\n return line.image_url !== '' && !line.image_url.includes('image_not_found')\n}\n\n/** Whether the cart can go to checkout: no line has a problem (e.g. more than the stock). */\nexport function cartBlocked(lines: readonly CartLine[]): boolean {\n return lines.some((line) => line.error !== '')\n}\n"],"names":[],"mappings":";;;;AAyCO,SAAS,aAAa,QAAgB,SAAwC;AACnF,QAAM,WAAW,OAAO,YAAY;AACpC,SAAO;AAAA,wBACe,QAAQ,YAAY,IAAI,QAAQ,SAAS,KAAK,EAAE;AAAA,gBACxD,QAAQ,UAAU,OAAO;AAAA;AAAA,MAGnC,OAAO,aAAa,SAChB,UACA;AAAA,kBACQ,EAAE,iBAAiB,CAAC;AAAA,kBACpB,YAAY,OAAO,QAAQ,CAAC;AAAA,iBAE1C;AAAA,MAEE,WAAW,IACP;AAAA;AAAA,gBAEM,OAAO,SAAS,EAAE,yBAAyB,EAAE,MAAM,OAAO,OAAA,CAAQ,IAAI,EAAE,iBAAiB,CAAC;AAAA;AAAA,yBAEjF,YAAY,QAAQ,CAAC;AAAA,oBAEpC,OACN;AAAA,MACE,eAAe,OAAO,UAAU,OAAO,CAAC,IAAI,aAAa,OAAO,WAAW,OAAO,UAAU,CAAC;AAAA;AAAA,YAEvF,EAAE,cAAc,CAAC;AAAA,sBACP,QAAQ,WAAW,IAAI,YAAY,OAAO,KAAK,CAAC;AAAA;AAAA;AAGtE;AAEA,SAAS,eAAe,UAAkB,SAAyD;AACjG,MAAI,QAAQ,aAAa,aAAa,YAAY,EAAG,QAAO;AAC5D,QAAM,QACJ,WAAW,IACP,YA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AAClC;AAGO,SAAS,QAAQ,MAAgB,SAA2C;AACjF,SAAO,QAAQ,IAAI,KAAK,KAAK,QAAQ,QAAQ,EAAE,CAAC,EAAE;AACpD;AAGO,SAAS,SAAS,MAAyB;AAChD,SAAO,KAAK,cAAc,MAAM,CAAC,KAAK,UAAU,SAAS,iBAAiB;AAC5E;AAGO,SAAS,YAAY,OAAqC;AAC/D,SAAO,MAAM,KAAK,CAAC,SAAS,KAAK,UAAU,EAAE;AAC/C;"}
|
|
@@ -5,9 +5,11 @@ import { SpmktElement } from '../../lit/spmkt-element';
|
|
|
5
5
|
* options[<attribute id>], each with data-group="<attribute id>"; the server picks the variant
|
|
6
6
|
* - apply (optional): the form's submit button, hidden once the element applies changes itself
|
|
7
7
|
*
|
|
8
|
-
* A change re-renders the section around the element
|
|
9
|
-
* changed=<attribute id> so a missing combination keeps the option
|
|
10
|
-
*
|
|
8
|
+
* A change re-renders the section around the element (its own copy: a quick view puts a second one on the page)
|
|
9
|
+
* for the chosen options (sections=<key>, plus changed=<attribute id> so a missing combination keeps the option
|
|
10
|
+
* 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. The new section's page events are not announced: another
|
|
12
|
+
* variant is not another product view.
|
|
11
13
|
*/
|
|
12
14
|
export interface VariantPickerParts {
|
|
13
15
|
form: HTMLFormElement;
|
|
@@ -61,12 +61,14 @@ class SpmktVariantPicker extends SpmktElement {
|
|
|
61
61
|
if (!html) {
|
|
62
62
|
throw new Error("The product section was not in the response");
|
|
63
63
|
}
|
|
64
|
-
const next = swapSection(
|
|
64
|
+
const next = swapSection(this, html);
|
|
65
65
|
const id = Number(next?.querySelector("spmkt-variant-picker")?.getAttribute("variant"));
|
|
66
66
|
if (id > 0) {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
67
|
+
if (!next?.closest("dialog")) {
|
|
68
|
+
const address = new URL(location.href);
|
|
69
|
+
address.searchParams.set("variant", String(id));
|
|
70
|
+
history.replaceState(history.state, "", address);
|
|
71
|
+
}
|
|
70
72
|
dispatch(next ?? document, "spmkt:variant-change", { id });
|
|
71
73
|
}
|
|
72
74
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"variant-picker.js","sources":["../../../src/elements/variant-picker/variant-picker.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { fetchFragments, sectionKey, swapSection } from '../../lit/fragments'\nimport { dispatch } from '../../core/events'\nimport { isAbortError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { showToast } from '../toaster/toaster'\n\n/**\n * Parts of <spmkt-variant-picker variant=\"<id of the variant shown>\"> (inside the product section):\n * - form (required): a GET form back to the product with one control per option group, named\n * options[<attribute id>], each with data-group=\"<attribute id>\"; the server picks the variant\n * - apply (optional): the form's submit button, hidden once the element applies changes itself\n *\n * A change re-renders the section around the element for the chosen options (sections=<key>, plus
|
|
1
|
+
{"version":3,"file":"variant-picker.js","sources":["../../../src/elements/variant-picker/variant-picker.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { fetchFragments, sectionKey, swapSection } from '../../lit/fragments'\nimport { dispatch } from '../../core/events'\nimport { isAbortError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { showToast } from '../toaster/toaster'\n\n/**\n * Parts of <spmkt-variant-picker variant=\"<id of the variant shown>\"> (inside the product section):\n * - form (required): a GET form back to the product with one control per option group, named\n * options[<attribute id>], each with data-group=\"<attribute id>\"; the server picks the variant\n * - apply (optional): the form's submit button, hidden once the element applies changes itself\n *\n * A change re-renders the section around the element (its own copy: a quick view puts a second one on the page)\n * for the chosen options (sections=<key>, plus changed=<attribute id> so a missing combination keeps the option\n * just picked), then, for the page's own product (not in a dialog), puts ?variant=<id> in the address bar,\n * read from the new picker's `variant` attribute. The new section's page events are not announced: another\n * variant is not another product view.\n */\nexport interface VariantPickerParts {\n form: HTMLFormElement\n apply?: HTMLElement\n}\n\nlet inFlight: AbortController | undefined\n\n/** Variant choice without a page load; the product section is re-rendered for the variant. */\nexport class SpmktVariantPicker extends SpmktElement {\n static override properties = {\n variant: { type: Number },\n }\n variant = 0\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.requirePart<HTMLFormElement>('form')\n // Outside a theme section (nothing to re-render) the form submits as usual\n if (!sectionKey(this)) {\n return\n }\n const apply = this.findPart('apply')\n if (apply) apply.hidden = true\n this.listen(form, 'change', (event) => {\n const group = (event.target as HTMLElement | null)?.dataset?.group\n void this.choose(group ? Number(group) : undefined)\n })\n this.listen(form, 'submit', (event) => {\n event.preventDefault()\n void this.choose()\n })\n }\n\n /** The product URL for the form's options (and the group just changed). */\n optionsUrl(changed?: number): URL {\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') url.searchParams.append(name, value)\n }\n if (changed !== undefined) url.searchParams.set('changed', String(changed))\n return url\n }\n\n private async choose(changed?: number): Promise<void> {\n const key = sectionKey(this)\n if (!key) {\n return\n }\n inFlight?.abort()\n const controller = (inFlight = new AbortController())\n const section = this.closest('[data-section-id]')\n section?.setAttribute('aria-busy', 'true')\n try {\n const response = await fetchFragments(this.optionsUrl(changed), {\n sections: [key],\n signal: controller.signal,\n })\n const html = response.sections[key]\n if (!html) {\n throw new Error('The product section was not in the response')\n }\n const next = swapSection(this, html)\n const id = Number(next?.querySelector('spmkt-variant-picker')?.getAttribute('variant'))\n if (id > 0) {\n // The address bar is the page's product: a quick view's choice stays in the dialog\n if (!next?.closest('dialog')) {\n const address = new URL(location.href)\n address.searchParams.set('variant', String(id))\n history.replaceState(history.state, '', address)\n }\n dispatch(next ?? document, 'spmkt:variant-change', { id })\n }\n } catch (error) {\n if (!isAbortError(error)) {\n section?.removeAttribute('aria-busy')\n showToast({ message: t('common.error'), tone: 'error' })\n }\n }\n }\n}\n"],"names":[],"mappings":";;;;;;AAwBA,I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AS,aAAa,aAAa,MAAM;AACzC,QAAI;AACF,YAAM,WAAW,MAAM,eAAe,KAAK,WAAW,OAAO,GAAG;AAAA,QAC9D,UAAU,CAAC,GAAG;AAAA,QACd,QAAQ,WAAW;AAAA,MAAA,CACpB;AACD,YAAM,OAAO,SAAS,SAAS,GAAG;AAClC,UAAI,CAAC,MAAM;AACT,cAAM,IAAI,MAAM,6CAA6C;AAAA,MAC/D;AACA,YAAM,OAAO,YAAY,MAAM,IAAI;AACnC,YAAM,KAAK,OAAO,MAAM,cAAc,sBAAsB,GAAG,aAAa,SAAS,CAAC;AACtF,UAAI,KAAK,GAAG;AAEV,YAAI,CAAC,MAAM,QAAQ,QAAQ,GAAG;AAC5B,gBAAM,UAAU,IAAI,IAAI,SAAS,IAAI;AACrC,kBAAQ,aAAa,IAAI,WAAW,OAAO,EAAE,CAAC;AAC9C,kBAAQ,aAAa,QAAQ,OAAO,IAAI,OAAO;AAAA,QACjD;AACA,iBAAS,QAAQ,UAAU,wBAAwB,EAAE,IAAI;AAAA,MAC3D;AAAA,IACF,SAAS,OAAO;AACd,UAAI,CAAC,aAAa,KAAK,GAAG;AACxB,iBAAS,gBAAgB,WAAW;AACpC,kBAAU,EAAE,SAAS,EAAE,cAAc,GAAG,MAAM,SAAS;AAAA,MACzD;AAAA,IACF;AAAA,EACF;AACF;"}
|
package/dist/lit/fragments.d.ts
CHANGED
|
@@ -1,27 +1,28 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Sections of a page, keyed as requested (see StorefrontPage on the platform). */
|
|
2
2
|
export interface FragmentResponse {
|
|
3
3
|
/** "<document>/<sectionId>" -> section HTML, wrapper included; "" when hidden or gone */
|
|
4
4
|
sections: Record<string, string>;
|
|
5
|
-
/** theme fragment name -> HTML */
|
|
6
|
-
fragments: Record<string, string>;
|
|
7
5
|
}
|
|
8
6
|
export interface FetchFragmentsOptions {
|
|
9
|
-
sections
|
|
10
|
-
|
|
7
|
+
sections: string[];
|
|
8
|
+
/** More query parameters for the page, e.g. { related_page: 2 }; they replace the URL's own of that name */
|
|
9
|
+
query?: Record<string, string | number>;
|
|
11
10
|
signal?: AbortSignal;
|
|
12
11
|
}
|
|
13
12
|
/** The fragment key of the section that contains `el`, e.g. "template:category/main", or null. */
|
|
14
13
|
export declare function sectionKey(el: Element): string | null;
|
|
15
14
|
/**
|
|
16
|
-
* Asks a storefront URL for some of its
|
|
17
|
-
* GET url?sections=a,b
|
|
15
|
+
* Asks a storefront URL for some of its sections instead of the whole page:
|
|
16
|
+
* GET url?sections=a,b (the URL's own query, e.g. filters, is kept; `query` adds to it).
|
|
18
17
|
*/
|
|
19
18
|
export declare function fetchFragments(url: string | URL, options: FetchFragmentsOptions): Promise<FragmentResponse>;
|
|
20
19
|
/**
|
|
21
|
-
* Replaces
|
|
22
|
-
*
|
|
20
|
+
* Replaces the section that contains `from` (the element asking, so its own copy: a quick view can put a second
|
|
21
|
+
* section with the same key on the page) with its re-rendered HTML; "" removes it. A copy without its wrapper's
|
|
22
|
+
* id (the quick view drops it, since the page's own section has it) stays without one.
|
|
23
|
+
* Returns the new section element, or null when it was removed or `from` is in no section.
|
|
23
24
|
*/
|
|
24
|
-
export declare function swapSection(
|
|
25
|
+
export declare function swapSection(from: Element, html: string): Element | null;
|
|
25
26
|
/** Replaces the children of `el` (an owned part, or a Blade region being re-rendered) with HTML. */
|
|
26
27
|
export declare function swapInto(el: Element, html: string): void;
|
|
27
28
|
/** Appends the HTML's nodes to `el` (load more). */
|
package/dist/lit/fragments.js
CHANGED
|
@@ -9,17 +9,15 @@ function previewHeaders() {
|
|
|
9
9
|
}
|
|
10
10
|
async function fetchFragments(url, options) {
|
|
11
11
|
const target = shopRequestUrl(url);
|
|
12
|
-
|
|
13
|
-
target.searchParams.set(
|
|
14
|
-
}
|
|
15
|
-
if (options.fragments?.length) {
|
|
16
|
-
target.searchParams.set("fragments", options.fragments.join(","));
|
|
12
|
+
for (const [name, value] of Object.entries(options.query ?? {})) {
|
|
13
|
+
target.searchParams.set(name, String(value));
|
|
17
14
|
}
|
|
15
|
+
target.searchParams.set("sections", options.sections.join(","));
|
|
18
16
|
const response = await get(target.toString(), {
|
|
19
17
|
signal: options.signal,
|
|
20
18
|
headers: previewHeaders()
|
|
21
19
|
});
|
|
22
|
-
return { sections: response?.sections ?? {}
|
|
20
|
+
return { sections: response?.sections ?? {} };
|
|
23
21
|
}
|
|
24
22
|
function parse(html) {
|
|
25
23
|
const template = document.createElement("template");
|
|
@@ -34,10 +32,8 @@ function keepFocus(scope, swap) {
|
|
|
34
32
|
replacement.querySelector(`#${CSS.escape(id)}`)?.focus();
|
|
35
33
|
}
|
|
36
34
|
}
|
|
37
|
-
function swapSection(
|
|
38
|
-
const
|
|
39
|
-
const selector = `[data-theme-document="${CSS.escape(key.slice(0, slash))}"][data-section-id="${CSS.escape(key.slice(slash + 1))}"]`;
|
|
40
|
-
const current = root.querySelector(selector);
|
|
35
|
+
function swapSection(from, html) {
|
|
36
|
+
const current = from.closest("[data-section-id][data-theme-document]");
|
|
41
37
|
if (!current) {
|
|
42
38
|
return null;
|
|
43
39
|
}
|
|
@@ -49,6 +45,9 @@ function swapSection(key, html, root = document) {
|
|
|
49
45
|
if (!next) {
|
|
50
46
|
return null;
|
|
51
47
|
}
|
|
48
|
+
if (!current.hasAttribute("id")) {
|
|
49
|
+
next.removeAttribute("id");
|
|
50
|
+
}
|
|
52
51
|
keepFocus(current, () => {
|
|
53
52
|
current.replaceWith(next);
|
|
54
53
|
return next;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fragments.js","sources":["../../src/lit/fragments.ts"],"sourcesContent":["import { get, shopRequestUrl } from '../core/request'\n\n/**
|
|
1
|
+
{"version":3,"file":"fragments.js","sources":["../../src/lit/fragments.ts"],"sourcesContent":["import { get, shopRequestUrl } from '../core/request'\n\n/** Sections of a page, keyed as requested (see StorefrontPage on the platform). */\nexport interface FragmentResponse {\n /** \"<document>/<sectionId>\" -> section HTML, wrapper included; \"\" when hidden or gone */\n sections: Record<string, string>\n}\n\nexport interface FetchFragmentsOptions {\n sections: string[]\n /** More query parameters for the page, e.g. { related_page: 2 }; they replace the URL's own of that name */\n query?: Record<string, string | number>\n signal?: AbortSignal\n}\n\n/** The fragment key of the section that contains `el`, e.g. \"template:category/main\", or null. */\nexport function sectionKey(el: Element): string | null {\n const section = el.closest<HTMLElement>('[data-section-id][data-theme-document]')\n return section ? `${section.dataset.themeDocument}/${section.dataset.sectionId}` : null\n}\n\n/** In the theme editor's preview, requests carry the preview token so drafts render. */\nfunction previewHeaders(): Record<string, string> {\n const token = (window as unknown as { __themePreview?: { token?: string } }).__themePreview?.token\n return token ? { 'X-Theme-Preview': token } : {}\n}\n\n/**\n * Asks a storefront URL for some of its sections instead of the whole page:\n * GET url?sections=a,b (the URL's own query, e.g. filters, is kept; `query` adds to it).\n */\nexport async function fetchFragments(\n url: string | URL,\n options: FetchFragmentsOptions,\n): Promise<FragmentResponse> {\n // Same origin only (the HTML goes into the page); a root-relative URL gets the shop's base path\n const target = shopRequestUrl(url)\n for (const [name, value] of Object.entries(options.query ?? {})) {\n target.searchParams.set(name, String(value))\n }\n target.searchParams.set('sections', options.sections.join(','))\n const response = await get<Partial<FragmentResponse>>(target.toString(), {\n signal: options.signal,\n headers: previewHeaders(),\n })\n return { sections: response?.sections ?? {} }\n}\n\nfunction parse(html: string): DocumentFragment {\n const template = document.createElement('template')\n template.innerHTML = html\n return template.content\n}\n\n/** Re-focuses the element that had focus inside `scope` before a swap, found again by id. */\nfunction keepFocus(scope: Element, swap: () => ParentNode | null): void {\n const active = document.activeElement\n const id = active && scope.contains(active) && active.id ? active.id : null\n const replacement = swap()\n if (id && replacement) {\n replacement.querySelector<HTMLElement>(`#${CSS.escape(id)}`)?.focus()\n }\n}\n\n/**\n * Replaces the section that contains `from` (the element asking, so its own copy: a quick view can put a second\n * section with the same key on the page) with its re-rendered HTML; \"\" removes it. A copy without its wrapper's\n * id (the quick view drops it, since the page's own section has it) stays without one.\n * Returns the new section element, or null when it was removed or `from` is in no section.\n */\nexport function swapSection(from: Element, html: string): Element | null {\n const current = from.closest('[data-section-id][data-theme-document]')\n if (!current) {\n return null\n }\n if (html === '') {\n current.remove()\n return null\n }\n const next = parse(html).firstElementChild\n if (!next) {\n return null\n }\n if (!current.hasAttribute('id')) {\n next.removeAttribute('id')\n }\n keepFocus(current, () => {\n current.replaceWith(next)\n return next\n })\n return next\n}\n\n/** Replaces the children of `el` (an owned part, or a Blade region being re-rendered) with HTML. */\nexport function swapInto(el: Element, html: string): void {\n keepFocus(el, () => {\n el.replaceChildren(parse(html))\n return el\n })\n}\n\n/** Appends the HTML's nodes to `el` (load more). */\nexport function appendInto(el: Element, html: string): void {\n el.append(parse(html))\n}\n"],"names":[],"mappings":";AAgBO,SAAS,WAAW,IAA4B;AACrD,QAAM,UAAU,GAAG,QAAqB,wCAAwC;AAChF,SAAO,UAAU,GAAG,QAAQ,QAAQ,aAAa,IAAI,QAAQ,QAAQ,SAAS,KAAK;AACrF;AAGA,SAAS,iBAAyC;AAChD,QAAM,QAAS,OAA8D,gBAAgB;AAC7F,SAAO,QAAQ,EAAE,mBAAmB,MAAA,IAAU,CAAA;AAChD;AAMA,eAAsB,eACpB,KACA,SAC2B;AAE3B,QAAM,SAAS,eAAe,GAAG;AACjC,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,QAAQ,SAAS,CAAA,CAAE,GAAG;AAC/D,WAAO,aAAa,IAAI,MAAM,OAAO,KAAK,CAAC;AAAA,EAC7C;AACA,SAAO,aAAa,IAAI,YAAY,QAAQ,SAAS,KAAK,GAAG,CAAC;AAC9D,QAAM,WAAW,MAAM,IAA+B,OAAO,YAAY;AAAA,IACvE,QAAQ,QAAQ;AAAA,IAChB,SAAS,eAAA;AAAA,EAAe,CACzB;AACD,SAAO,EAAE,UAAU,UAAU,YAAY,CAAA,EAAC;AAC5C;AAEA,SAAS,MAAM,MAAgC;AAC7C,QAAM,WAAW,SAAS,cAAc,UAAU;AA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