@wikala/spmkt 4.0.0-alpha.2 → 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/elements/add-to-cart/add-to-cart.d.ts +19 -3
- package/dist/elements/add-to-cart/add-to-cart.js +29 -9
- 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/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/lit/fragments.d.ts +2 -1
- package/dist/lit/fragments.js +3 -0
- package/dist/lit/fragments.js.map +1 -1
- package/package.json +1 -1
|
@@ -5,16 +5,23 @@ import type { Cart, CartLine } from '../../core/types';
|
|
|
5
5
|
* Parts of <spmkt-add-to-cart> (around the theme's add to cart form, which posts to /cart without JavaScript):
|
|
6
6
|
* - form (required): fields `id` (a product, or the chosen variant) and `qty`
|
|
7
7
|
* - submit (optional): busy while adding
|
|
8
|
+
* - buy-now (optional): a second submit button in the form; busy while adding
|
|
8
9
|
* - error (optional): the reason an add failed; render it hidden
|
|
9
10
|
*
|
|
10
11
|
* After an add, the <spmkt-dialog> whose id is `dialog` opens with what was added (renderAdded(), from the line
|
|
11
|
-
* in the cart's answer: no further request); without that dialog, a toast says so.
|
|
12
|
+
* in the cart's answer: no further request); without that dialog, a toast says so. An add submitted through
|
|
13
|
+
* `buy-now` shows neither: it goes on to `checkout-url` (the checkout's first step by default).
|
|
12
14
|
*/
|
|
13
15
|
export interface AddToCartParts {
|
|
14
16
|
form: HTMLFormElement;
|
|
15
17
|
submit?: HTMLButtonElement;
|
|
18
|
+
'buy-now'?: HTMLButtonElement;
|
|
16
19
|
error?: HTMLElement;
|
|
17
20
|
}
|
|
21
|
+
export interface AddOptions {
|
|
22
|
+
/** Go on to the checkout after a successful add, instead of showing what was added */
|
|
23
|
+
buyNow?: boolean;
|
|
24
|
+
}
|
|
18
25
|
/** Adds to the cart without leaving the page. */
|
|
19
26
|
export declare class SpmktAddToCart extends SpmktElement {
|
|
20
27
|
static properties: {
|
|
@@ -25,15 +32,24 @@ export declare class SpmktAddToCart extends SpmktElement {
|
|
|
25
32
|
type: StringConstructor;
|
|
26
33
|
attribute: string;
|
|
27
34
|
};
|
|
35
|
+
checkoutUrl: {
|
|
36
|
+
type: StringConstructor;
|
|
37
|
+
attribute: string;
|
|
38
|
+
};
|
|
28
39
|
};
|
|
29
40
|
/** Id of the <spmkt-dialog> that shows the result */
|
|
30
41
|
dialog: string;
|
|
31
42
|
/** For the toast when there is no dialog */
|
|
32
43
|
productName: string;
|
|
44
|
+
/** Where buy now goes after the add; empty: the checkout's first step */
|
|
45
|
+
checkoutUrl: string;
|
|
33
46
|
private busy;
|
|
34
47
|
connectedCallback(): void;
|
|
35
|
-
/** Adds what the form says; resolves once the result is shown. */
|
|
36
|
-
add(): Promise<void>;
|
|
48
|
+
/** Adds what the form says; resolves once the result is shown, or once buy now has started to leave. */
|
|
49
|
+
add({ buyNow }?: AddOptions): Promise<void>;
|
|
50
|
+
/** Sends the browser to the checkout after buy now; replaceable (tests, themes). */
|
|
51
|
+
navigate: (url: string) => void;
|
|
52
|
+
private idle;
|
|
37
53
|
private confirm;
|
|
38
54
|
/** The dialog's content after an add: the line added, how much of it, and what the cart holds now. */
|
|
39
55
|
protected renderAdded(line: CartLine, qty: number, cart: Cart): TemplateResult;
|
|
@@ -13,12 +13,17 @@ class SpmktAddToCart extends SpmktElement {
|
|
|
13
13
|
super(...arguments);
|
|
14
14
|
this.dialog = "added-to-cart";
|
|
15
15
|
this.productName = "";
|
|
16
|
+
this.checkoutUrl = "";
|
|
16
17
|
this.busy = false;
|
|
18
|
+
this.navigate = (url) => {
|
|
19
|
+
location.assign(url);
|
|
20
|
+
};
|
|
17
21
|
}
|
|
18
22
|
static {
|
|
19
23
|
this.properties = {
|
|
20
24
|
dialog: { type: String },
|
|
21
|
-
productName: { type: String, attribute: "product-name" }
|
|
25
|
+
productName: { type: String, attribute: "product-name" },
|
|
26
|
+
checkoutUrl: { type: String, attribute: "checkout-url" }
|
|
22
27
|
};
|
|
23
28
|
}
|
|
24
29
|
connectedCallback() {
|
|
@@ -26,31 +31,46 @@ class SpmktAddToCart extends SpmktElement {
|
|
|
26
31
|
const form = this.requirePart("form");
|
|
27
32
|
this.listen(form, "submit", (event) => {
|
|
28
33
|
event.preventDefault();
|
|
29
|
-
|
|
34
|
+
const buyNow = this.findPart("buy-now");
|
|
35
|
+
const submitter = event.submitter;
|
|
36
|
+
void this.add({ buyNow: buyNow !== null && submitter === buyNow });
|
|
37
|
+
});
|
|
38
|
+
this.listen(window, "pageshow", (event) => {
|
|
39
|
+
if (event.persisted) this.idle();
|
|
30
40
|
});
|
|
31
41
|
}
|
|
32
|
-
/** Adds what the form says; resolves once the result is shown. */
|
|
33
|
-
async add() {
|
|
42
|
+
/** Adds what the form says; resolves once the result is shown, or once buy now has started to leave. */
|
|
43
|
+
async add({ buyNow = false } = {}) {
|
|
34
44
|
if (this.busy) {
|
|
35
45
|
return;
|
|
36
46
|
}
|
|
37
47
|
const data = new FormData(this.requirePart("form"));
|
|
38
48
|
const id = Number(data.get("id"));
|
|
39
49
|
const qty = Math.max(1, Number(data.get("qty") ?? 1) || 1);
|
|
40
|
-
const
|
|
50
|
+
const button = this.findPart(buyNow ? "buy-now" : "submit");
|
|
41
51
|
this.busy = true;
|
|
42
52
|
this.showError(null);
|
|
43
|
-
|
|
53
|
+
button?.setAttribute("aria-busy", "true");
|
|
54
|
+
let leaving = false;
|
|
44
55
|
try {
|
|
45
56
|
const cart = await addToCart({ id, qty });
|
|
46
|
-
|
|
57
|
+
if (buyNow) {
|
|
58
|
+
leaving = true;
|
|
59
|
+
this.navigate(this.checkoutUrl || shopUrl("/shopping-cart?step=delivery"));
|
|
60
|
+
} else {
|
|
61
|
+
this.confirm(cart, id, qty);
|
|
62
|
+
}
|
|
47
63
|
} catch (error) {
|
|
48
64
|
this.showError(this.messageFor(error));
|
|
49
65
|
} finally {
|
|
50
|
-
this.
|
|
51
|
-
submit?.removeAttribute("aria-busy");
|
|
66
|
+
if (!leaving) this.idle();
|
|
52
67
|
}
|
|
53
68
|
}
|
|
69
|
+
idle() {
|
|
70
|
+
this.busy = false;
|
|
71
|
+
this.findPart("submit")?.removeAttribute("aria-busy");
|
|
72
|
+
this.findPart("buy-now")?.removeAttribute("aria-busy");
|
|
73
|
+
}
|
|
54
74
|
confirm(cart, id, qty) {
|
|
55
75
|
const host = document.getElementById(this.dialog);
|
|
56
76
|
const line = cart.items.find((item) => item.id === id);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"add-to-cart.js","sources":["../../../src/elements/add-to-cart/add-to-cart.ts"],"sourcesContent":["import { html, nothing, type TemplateResult } from 'lit'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { addToCart } from '../../core/stores/cart'\nimport {\n HttpError,\n SessionExpiredError,\n ValidationError,\n NetworkError,\n TimeoutError,\n} from '../../core/errors'\nimport { plural, t } from '../../core/i18n'\nimport { shopUrl } from '../../core/config'\nimport { formatMoney } from '../../core/money'\nimport type { Cart, CartLine } from '../../core/types'\nimport { showToast } from '../toaster/toaster'\nimport { SpmktDialog } from '../dialog/dialog'\nimport { hasImage, lineName } from '../shared/totals'\n\n/**\n * Parts of <spmkt-add-to-cart> (around the theme's add to cart form, which posts to /cart without JavaScript):\n * - form (required): fields `id` (a product, or the chosen variant) and `qty`\n * - submit (optional): busy while adding\n * - error (optional): the reason an add failed; render it hidden\n *\n * After an add, the <spmkt-dialog> whose id is `dialog` opens with what was added (renderAdded(), from the line\n * in the cart's answer: no further request); without that dialog, a toast says so.\n */\nexport interface AddToCartParts {\n form: HTMLFormElement\n submit?: HTMLButtonElement\n error?: HTMLElement\n}\n\n/** Adds to the cart without leaving the page. */\nexport class SpmktAddToCart extends SpmktElement {\n static override properties = {\n dialog: { type: String },\n productName: { type: String, attribute: 'product-name' },\n }\n /** Id of the <spmkt-dialog> that shows the result */\n dialog = 'added-to-cart'\n /** For the toast when there is no dialog */\n productName = ''\n\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.add()\n })\n }\n\n /** Adds what the form says; resolves once the result is shown. */\n async add(): Promise<void> {\n if (this.busy) {\n return\n }\n const data = new FormData(this.requirePart<HTMLFormElement>('form'))\n const id = Number(data.get('id'))\n const qty = Math.max(1, Number(data.get('qty') ?? 1) || 1)\n const submit = this.findPart<HTMLButtonElement>('submit')\n this.busy = true\n this.showError(null)\n submit?.setAttribute('aria-busy', 'true')\n try {\n const cart = await addToCart({ id, qty })\n this.confirm(cart, id, qty)\n } catch (error) {\n this.showError(this.messageFor(error))\n } finally {\n this.busy = false\n submit?.removeAttribute('aria-busy')\n }\n }\n\n private confirm(cart: Cart, id: number, qty: number): void {\n const host = document.getElementById(this.dialog)\n const line = cart.items.find((item) => item.id === id)\n if (host instanceof SpmktDialog && line) {\n // A dialog this form sits in (a quick view) makes way for the result\n this.closest('dialog')?.close()\n host.open(this.renderAdded(line, qty, cart))\n return\n }\n showToast({\n message: t('cart.added', { name: this.productName || (line ? lineName(line) : '') }),\n tone: 'success',\n action: { label: t('cart.viewCart'), href: shopUrl('/shopping-cart') },\n })\n }\n\n /** The dialog's content after an add: the line added, how much of it, and what the cart holds now. */\n protected renderAdded(line: CartLine, qty: number, cart: Cart): TemplateResult {\n return html`<div class=\"added-to-cart\">\n <h2 class=\"added-to-cart__title\">${t('cart.addedTitle')}</h2>\n <div class=\"added-to-cart__product\">\n ${hasImage(line) ? html`<img src=${line.image_url} alt=\"\" width=\"80\" height=\"80\" />` : nothing}\n <div>\n <p class=\"added-to-cart__name\">${lineName(line)}</p>\n ${line.variant ? html`<p class=\"added-to-cart__variant\">${line.variant}</p>` : nothing}\n <p class=\"added-to-cart__price\">${qty} × ${formatMoney(line.price)}</p>\n </div>\n </div>\n <p class=\"added-to-cart__summary\">${plural('cart.inCart', cart.sumQty)}</p>\n <div class=\"added-to-cart__actions\">\n <button type=\"button\" class=\"button\" data-part=\"close\">${t('cart.continue')}</button>\n <a class=\"button button--primary\" href=${shopUrl('/shopping-cart')} data-test=\"buy-now-btn\"\n >${t('cart.viewCart')}</a\n >\n </div>\n </div>`\n }\n\n private messageFor(error: unknown): string {\n if (error instanceof ValidationError) {\n return error.first('qty') ?? error.first('id') ?? error.message ?? t('cart.addFailed')\n }\n if (error instanceof SessionExpiredError) return t('common.sessionExpired')\n if (error instanceof TimeoutError) return t('common.timeout')\n if (error instanceof NetworkError) return t('common.network')\n // A sold-out product or an expired store choice: the server's own words\n if (error instanceof HttpError && error.status < 500 && error.message) return error.message\n return t('cart.addFailed')\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,uBAAuB,aAAa;AAAA,EAA1C,cAAA;AAAA,UAAA,GAAA,SAAA;AAML,SAAA,SAAS;AAET,SAAA,cAAc;AAEd,SAAQ,OAAO;AAAA,EAAA;AAAA,EATf,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,QAAQ,EAAE,MAAM,OAAA;AAAA,MAChB,aAAa,EAAE,MAAM,QAAQ,WAAW,eAAA;AAAA,IAAe;AAAA,EACzD;AAAA,EAQS,oBAA0B;AACjC,UAAM,kBAAA;AACN,UAAM,OAAO,KAAK,YAA6B,MAAM;AACrD,SAAK,OAAO,MAAM,UAAU,CAAC,UAAU;AACrC,YAAM,eAAA;AACN,WAAK,KAAK,IAAA;AAAA,IACZ,CAAC;AAAA,EACH;AAAA;AAAA,EAGA,MAAM,MAAqB;AACzB,QAAI,KAAK,MAAM;AACb;AAAA,IACF;AACA,UAAM,OAAO,IAAI,SAAS,KAAK,YAA6B,M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C7C,KAAK,UAAU,yCAAyC,KAAK,OAAO,SAAS,OAAO;AAAA,4CACpD,GAAG,YAAY,YAAY,KAAK,KAAK,CAAC;AAAA;AAAA;AAAA,0CAGxC,OAAO,eAAe,KAAK,MAAM,CAAC;AAAA;AAAA,iEAEX,EAAE,eAAe,CAAC;AAAA,iDAClC,QAAQ,gBAAgB,CAAC;AAAA,aAC7D,EAAE,eAAe,CAAC;AAAA;AAAA;AAAA;AAAA,EAI7B;AAAA,EAEQ,WAAW,OAAwB;AACzC,QAAI,iBAAiB,iBAAiB;AACpC,aAAO,MAAM,MAAM,KAAK,KAAK,MAAM,MAAM,IAAI,KAAK,MAAM,WAAW,EAAE,gBAAgB;AAAA,IACvF;AACA,QAAI,iBAAiB,oBAAqB,QAAO,EAAE,uBAAuB;AAC1E,QAAI,iBAAiB,aAAc,QAAO,EAAE,gBAAgB;AAC5D,QAAI,iBAAiB,aAAc,QAAO,EAAE,gBAAgB;AAE5D,QAAI,iBAAiB,aAAa,MAAM,SAAS,OAAO,MAAM,gBAAgB,MAAM;AACpF,WAAO,EAAE,gBAAgB;AAAA,EAC3B;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":"add-to-cart.js","sources":["../../../src/elements/add-to-cart/add-to-cart.ts"],"sourcesContent":["import { html, nothing, type TemplateResult } from 'lit'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { addToCart } from '../../core/stores/cart'\nimport {\n HttpError,\n SessionExpiredError,\n ValidationError,\n NetworkError,\n TimeoutError,\n} from '../../core/errors'\nimport { plural, t } from '../../core/i18n'\nimport { shopUrl } from '../../core/config'\nimport { formatMoney } from '../../core/money'\nimport type { Cart, CartLine } from '../../core/types'\nimport { showToast } from '../toaster/toaster'\nimport { SpmktDialog } from '../dialog/dialog'\nimport { hasImage, lineName } from '../shared/totals'\n\n/**\n * Parts of <spmkt-add-to-cart> (around the theme's add to cart form, which posts to /cart without JavaScript):\n * - form (required): fields `id` (a product, or the chosen variant) and `qty`\n * - submit (optional): busy while adding\n * - buy-now (optional): a second submit button in the form; busy while adding\n * - error (optional): the reason an add failed; render it hidden\n *\n * After an add, the <spmkt-dialog> whose id is `dialog` opens with what was added (renderAdded(), from the line\n * in the cart's answer: no further request); without that dialog, a toast says so. An add submitted through\n * `buy-now` shows neither: it goes on to `checkout-url` (the checkout's first step by default).\n */\nexport interface AddToCartParts {\n form: HTMLFormElement\n submit?: HTMLButtonElement\n 'buy-now'?: HTMLButtonElement\n error?: HTMLElement\n}\n\nexport interface AddOptions {\n /** Go on to the checkout after a successful add, instead of showing what was added */\n buyNow?: boolean\n}\n\n/** Adds to the cart without leaving the page. */\nexport class SpmktAddToCart extends SpmktElement {\n static override properties = {\n dialog: { type: String },\n productName: { type: String, attribute: 'product-name' },\n checkoutUrl: { type: String, attribute: 'checkout-url' },\n }\n /** Id of the <spmkt-dialog> that shows the result */\n dialog = 'added-to-cart'\n /** For the toast when there is no dialog */\n productName = ''\n /** Where buy now goes after the add; empty: the checkout's first step */\n checkoutUrl = ''\n\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 const buyNow = this.findPart('buy-now')\n const submitter = (event as SubmitEvent).submitter\n void this.add({ buyNow: buyNow !== null && submitter === buyNow })\n })\n // Back from the checkout (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 }\n\n /** Adds what the form says; resolves once the result is shown, or once buy now has started to leave. */\n async add({ buyNow = false }: AddOptions = {}): Promise<void> {\n if (this.busy) {\n return\n }\n const data = new FormData(this.requirePart<HTMLFormElement>('form'))\n const id = Number(data.get('id'))\n const qty = Math.max(1, Number(data.get('qty') ?? 1) || 1)\n const button = this.findPart<HTMLButtonElement>(buyNow ? 'buy-now' : 'submit')\n this.busy = true\n this.showError(null)\n button?.setAttribute('aria-busy', 'true')\n let leaving = false\n try {\n const cart = await addToCart({ id, qty })\n if (buyNow) {\n leaving = true\n this.navigate(this.checkoutUrl || shopUrl('/shopping-cart?step=delivery'))\n } else {\n this.confirm(cart, id, qty)\n }\n } catch (error) {\n this.showError(this.messageFor(error))\n } finally {\n // Stay busy while the browser leaves for the checkout (pageshow undoes it if the visitor comes Back)\n if (!leaving) this.idle()\n }\n }\n\n /** Sends the browser to the checkout after buy now; replaceable (tests, themes). */\n navigate: (url: string) => void = (url) => {\n location.assign(url)\n }\n\n private idle(): void {\n this.busy = false\n this.findPart('submit')?.removeAttribute('aria-busy')\n this.findPart('buy-now')?.removeAttribute('aria-busy')\n }\n\n private confirm(cart: Cart, id: number, qty: number): void {\n const host = document.getElementById(this.dialog)\n const line = cart.items.find((item) => item.id === id)\n if (host instanceof SpmktDialog && line) {\n // A dialog this form sits in (a quick view) makes way for the result\n this.closest('dialog')?.close()\n host.open(this.renderAdded(line, qty, cart))\n return\n }\n showToast({\n message: t('cart.added', { name: this.productName || (line ? lineName(line) : '') }),\n tone: 'success',\n action: { label: t('cart.viewCart'), href: shopUrl('/shopping-cart') },\n })\n }\n\n /** The dialog's content after an add: the line added, how much of it, and what the cart holds now. */\n protected renderAdded(line: CartLine, qty: number, cart: Cart): TemplateResult {\n return html`<div class=\"added-to-cart\">\n <h2 class=\"added-to-cart__title\">${t('cart.addedTitle')}</h2>\n <div class=\"added-to-cart__product\">\n ${hasImage(line) ? html`<img src=${line.image_url} alt=\"\" width=\"80\" height=\"80\" />` : nothing}\n <div>\n <p class=\"added-to-cart__name\">${lineName(line)}</p>\n ${line.variant ? html`<p class=\"added-to-cart__variant\">${line.variant}</p>` : nothing}\n <p class=\"added-to-cart__price\">${qty} × ${formatMoney(line.price)}</p>\n </div>\n </div>\n <p class=\"added-to-cart__summary\">${plural('cart.inCart', cart.sumQty)}</p>\n <div class=\"added-to-cart__actions\">\n <button type=\"button\" class=\"button\" data-part=\"close\">${t('cart.continue')}</button>\n <a class=\"button button--primary\" href=${shopUrl('/shopping-cart')} data-test=\"buy-now-btn\"\n >${t('cart.viewCart')}</a\n >\n </div>\n </div>`\n }\n\n private messageFor(error: unknown): string {\n if (error instanceof ValidationError) {\n return error.first('qty') ?? error.first('id') ?? error.message ?? t('cart.addFailed')\n }\n if (error instanceof SessionExpiredError) return t('common.sessionExpired')\n if (error instanceof TimeoutError) return t('common.timeout')\n if (error instanceof NetworkError) return t('common.network')\n // A sold-out product or an expired store choice: the server's own words\n if (error instanceof HttpError && error.status < 500 && error.message) return error.message\n return t('cart.addFailed')\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":";;;;;;;;;;AA0CO,MAAM,uBAAuB,aAAa;AAAA,EAA1C,cAAA;AAAA,UAAA,GAAA,SAAA;AAOL,SAAA,SAAS;AAET,SAAA,cAAc;AAEd,SAAA,cAAc;AAEd,SAAQ,OAAO;AA+Cf,SAAA,WAAkC,CAAC,QAAQ;AACzC,eAAS,OAAO,GAAG;AAAA,IACrB;AAAA,EAAA;AAAA,EA7DA,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,QAAQ,EAAE,MAAM,OAAA;AAAA,MAChB,aAAa,EAAE,MAAM,QAAQ,WAAW,eAAA;AAAA,MACxC,aAAa,EAAE,MAAM,QAAQ,WAAW,eAAA;AAAA,IAAe;AAAA,EACzD;AAAA,EAUS,oBAA0B;AACjC,UAAM,kBAAA;AACN,UAAM,OAAO,KAAK,YAA6B,MAAM;AACrD,SAAK,OAAO,MAAM,UAAU,C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AE,gBAAgB;AAC5D,QAAI,iBAAiB,aAAc,QAAO,EAAE,gBAAgB;AAE5D,QAAI,iBAAiB,aAAa,MAAM,SAAS,OAAO,MAAM,gBAAgB,MAAM;AACpF,WAAO,EAAE,gBAAgB;AAAA,EAC3B;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;"}
|
|
@@ -9,6 +9,8 @@ import { SpmktElement } from '../../lit/spmkt-element';
|
|
|
9
9
|
* `autoplay` is the interval in milliseconds; 0 or absent turns it off.
|
|
10
10
|
* Slides (and their dots) may be hidden with CSS, e.g. per device; the carousel skips them. While fewer than two
|
|
11
11
|
* slides are shown there is nothing to move between, and prev, next, the dots and toggle are `hidden`.
|
|
12
|
+
* The theme may show several slides at once (narrower slides); the first one in view is the current one, and
|
|
13
|
+
* `next` wraps around once the track is scrolled to its end.
|
|
12
14
|
*/
|
|
13
15
|
export interface CarouselParts {
|
|
14
16
|
track: HTMLElement;
|
|
@@ -30,13 +32,15 @@ export declare class SpmktCarousel extends SpmktElement {
|
|
|
30
32
|
};
|
|
31
33
|
};
|
|
32
34
|
autoplay: number;
|
|
33
|
-
/** Index of the slide
|
|
35
|
+
/** Index of the first slide in view */
|
|
34
36
|
current: number;
|
|
35
37
|
private hovered;
|
|
36
38
|
private stopped;
|
|
37
39
|
private inView;
|
|
38
40
|
/** Autoplay is set up (an interval, and no reduced motion) */
|
|
39
41
|
private playing;
|
|
42
|
+
/** Indexes of the slides now (mostly) in view */
|
|
43
|
+
private visible;
|
|
40
44
|
connectedCallback(): void;
|
|
41
45
|
/** The controls show only while there are at least two shown slides to move between. */
|
|
42
46
|
private refreshControls;
|
|
@@ -45,6 +49,12 @@ export declare class SpmktCarousel extends SpmktElement {
|
|
|
45
49
|
* theme's CSS) is skipped in the direction of travel, so arrows, dots and autoplay only land on shown slides.
|
|
46
50
|
*/
|
|
47
51
|
go(index: number): void;
|
|
52
|
+
/**
|
|
53
|
+
* The next slide. With several in view, a next slide that cannot scroll to the track's start is on the last
|
|
54
|
+
* page, which is already shown, so it wraps around to the first. Decided by where the slide sits, not where the
|
|
55
|
+
* track is scrolled, so a click during a scroll does the same.
|
|
56
|
+
*/
|
|
57
|
+
private advance;
|
|
48
58
|
private mark;
|
|
49
59
|
private setUpAutoplay;
|
|
50
60
|
private paintToggle;
|
|
@@ -11,6 +11,7 @@ class SpmktCarousel extends SpmktElement {
|
|
|
11
11
|
this.stopped = false;
|
|
12
12
|
this.inView = true;
|
|
13
13
|
this.playing = false;
|
|
14
|
+
this.visible = /* @__PURE__ */ new Set();
|
|
14
15
|
}
|
|
15
16
|
static {
|
|
16
17
|
this.properties = { autoplay: { type: Number } };
|
|
@@ -25,12 +26,17 @@ class SpmktCarousel extends SpmktElement {
|
|
|
25
26
|
const prev = this.findPart("prev");
|
|
26
27
|
const next = this.findPart("next");
|
|
27
28
|
if (prev) this.listen(prev, "click", () => this.go(this.current - 1));
|
|
28
|
-
if (next) this.listen(next, "click", () => this.
|
|
29
|
+
if (next) this.listen(next, "click", () => this.advance());
|
|
29
30
|
this.findParts("dot").forEach((dot, index) => this.listen(dot, "click", () => this.go(index)));
|
|
30
31
|
const observer = new IntersectionObserver(
|
|
31
|
-
(entries) =>
|
|
32
|
-
(
|
|
33
|
-
|
|
32
|
+
(entries) => {
|
|
33
|
+
for (const entry of entries) {
|
|
34
|
+
const index = slides.indexOf(entry.target);
|
|
35
|
+
if (entry.isIntersecting) this.visible.add(index);
|
|
36
|
+
else this.visible.delete(index);
|
|
37
|
+
}
|
|
38
|
+
if (this.visible.size > 0) this.mark(Math.min(...this.visible));
|
|
39
|
+
},
|
|
34
40
|
{ root: track, threshold: 0.6 }
|
|
35
41
|
);
|
|
36
42
|
slides.forEach((slide) => observer.observe(slide));
|
|
@@ -77,6 +83,17 @@ class SpmktCarousel extends SpmktElement {
|
|
|
77
83
|
}
|
|
78
84
|
}
|
|
79
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* The next slide. With several in view, a next slide that cannot scroll to the track's start is on the last
|
|
88
|
+
* page, which is already shown, so it wraps around to the first. Decided by where the slide sits, not where the
|
|
89
|
+
* track is scrolled, so a click during a scroll does the same.
|
|
90
|
+
*/
|
|
91
|
+
advance() {
|
|
92
|
+
const track = this.findPart("track");
|
|
93
|
+
const target = this.findParts("slide")[this.current + 1];
|
|
94
|
+
const onLastPage = !!track && !!target && isShown(target) && target.offsetLeft - track.offsetLeft > track.scrollWidth - track.clientWidth + 1;
|
|
95
|
+
this.go(onLastPage ? 0 : this.current + 1);
|
|
96
|
+
}
|
|
80
97
|
mark(index) {
|
|
81
98
|
if (index < 0) {
|
|
82
99
|
return;
|
|
@@ -117,7 +134,7 @@ class SpmktCarousel extends SpmktElement {
|
|
|
117
134
|
this.onDisconnect(() => visibility.disconnect());
|
|
118
135
|
const timer = setInterval(() => {
|
|
119
136
|
if (!this.hovered && !this.stopped && this.inView && !document.hidden) {
|
|
120
|
-
this.
|
|
137
|
+
this.advance();
|
|
121
138
|
}
|
|
122
139
|
}, this.autoplay);
|
|
123
140
|
this.onDisconnect(() => clearInterval(timer));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"carousel.js","sources":["../../../src/elements/carousel/carousel.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { t } from '../../core/i18n'\n\n/**\n * Parts of <spmkt-carousel autoplay=\"6000\"> (a scroll-snap track; Blade renders everything):\n * - track (required): the horizontally scrolling element\n * - slide (required, several): its slides\n * - prev, next (optional): buttons\n * - dot (optional, several): one button per slide, in order; the current one gets aria-current=\"true\"\n * - toggle (optional): a pause/play button, aria-pressed=\"true\" while paused (WCAG 2.2.2)\n * `autoplay` is the interval in milliseconds; 0 or absent turns it off.\n * Slides (and their dots) may be hidden with CSS, e.g. per device; the carousel skips them. While fewer than two\n * slides are shown there is nothing to move between, and prev, next, the dots and toggle are `hidden`.\n */\nexport interface CarouselParts {\n track: HTMLElement\n slide: HTMLElement[]\n prev?: HTMLElement\n next?: HTMLElement\n dot?: HTMLElement[]\n toggle?: HTMLElement\n}\n\nconst reducedMotion = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches\n\n/** Whether the page displays the element (not display: none, nor inside something that is) */\nconst isShown = (el: HTMLElement) =>\n typeof el.checkVisibility === 'function' ? el.checkVisibility() : el.offsetParent !== null\n\n/**\n * The track scrolls natively (swipe, keyboard, scrollbar); this adds arrows, dots and autoplay.\n * Autoplay holds for reduced motion, hover, focus, hidden tabs, the pause button, and while the carousel is\n * scrolled out of view.\n */\nexport class SpmktCarousel extends SpmktElement {\n static override properties = { autoplay: { type: Number } }\n autoplay = 0\n /** Index of the slide most in view */\n current = 0\n private hovered = false\n private stopped = false\n private inView = true\n /** Autoplay is set up (an interval, and no reduced motion) */\n private playing = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n const track = this.requirePart('track')\n const slides = this.findParts('slide')\n if (slides.length < 2) {\n return\n }\n\n const prev = this.findPart('prev')\n const next = this.findPart('next')\n if (prev) this.listen(prev, 'click', () => this.go(this.current - 1))\n if (next) this.listen(next, 'click', () => this.go(this.current + 1))\n this.findParts('dot').forEach((dot, index) => this.listen(dot, 'click', () => this.go(index)))\n\n // The slide most in view is the current one, however it got there\n const observer = new IntersectionObserver(\n (entries) =>\n entries.forEach(\n (entry) => entry.isIntersecting && this.mark(slides.indexOf(entry.target as HTMLElement)),\n ),\n { root: track, threshold: 0.6 },\n )\n slides.forEach((slide) => observer.observe(slide))\n this.onDisconnect(() => observer.disconnect())\n this.mark(0)\n\n this.setUpAutoplay()\n\n // Which slides are shown can change with the viewport (device rules)\n this.refreshControls()\n let frame = 0\n this.listen(window, 'resize', () => {\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(() => this.refreshControls())\n })\n this.onDisconnect(() => cancelAnimationFrame(frame))\n }\n\n /** The controls show only while there are at least two shown slides to move between. */\n private refreshControls(): void {\n const single = this.findParts('slide').filter(isShown).length < 2\n for (const part of [this.findPart('prev'), this.findPart('next'), ...this.findParts('dot')]) {\n if (part) part.hidden = single\n }\n const toggle = this.findPart('toggle')\n if (toggle) toggle.hidden = single || !this.playing\n }\n\n /**\n * Scrolls to slide `index` (wraps around). A slide the page does not display (e.g. hidden on this device by the\n * theme's CSS) is skipped in the direction of travel, so arrows, dots and autoplay only land on shown slides.\n */\n go(index: number): void {\n const track = this.findPart('track')\n const slides = this.findParts('slide')\n const count = slides.length\n if (!track || count === 0) {\n return\n }\n const step = index < this.current ? -1 : 1\n for (let tried = 0; tried < count; tried++) {\n const target = slides[(((index + step * tried) % count) + count) % count]!\n if (isShown(target)) {\n track.scrollTo({\n left: target.offsetLeft - track.offsetLeft,\n behavior: reducedMotion() ? 'auto' : 'smooth',\n })\n return\n }\n }\n }\n\n private mark(index: number): void {\n if (index < 0) {\n return\n }\n const changed = index !== this.current\n this.current = index\n this.findParts('dot').forEach((dot, i) => dot.setAttribute('aria-current', String(i === index)))\n if (changed) {\n this.emit('spmkt:slide-change', { index })\n }\n }\n\n private setUpAutoplay(): void {\n const toggle = this.findPart('toggle')\n if (!this.autoplay || reducedMotion()) {\n if (toggle) toggle.hidden = true\n return\n }\n this.playing = true\n const hold = () => (this.hovered = true)\n const release = () => (this.hovered = false)\n this.listen(this, 'pointerenter', hold)\n this.listen(this, 'pointerleave', release)\n this.listen(this, 'focusin', (event) => {\n // The pause button itself does not count as \"reading a slide\"\n if (event.target !== toggle) hold()\n })\n this.listen(this, 'focusout', release)\n if (toggle) {\n this.paintToggle(toggle)\n this.listen(toggle, 'click', () => {\n this.stopped = !this.stopped\n this.paintToggle(toggle)\n })\n }\n const visibility = new IntersectionObserver((entries) => {\n this.inView = entries.some((entry) => entry.isIntersecting)\n })\n // The track, not the element: a custom element styled display: contents has no box to observe\n visibility.observe(this.requirePart('track'))\n this.onDisconnect(() => visibility.disconnect())\n const timer = setInterval(() => {\n if (!this.hovered && !this.stopped && this.inView && !document.hidden) {\n this.go(this.current + 1)\n }\n }, this.autoplay)\n this.onDisconnect(() => clearInterval(timer))\n }\n\n private paintToggle(toggle: HTMLElement): void {\n toggle.setAttribute('aria-pressed', String(this.stopped))\n toggle.setAttribute('aria-label', this.stopped ? t('carousel.play') : t('carousel.pause'))\n }\n}\n"],"names":[],"mappings":";;AAuBA,MAAM,gBAAgB,MAAM,OAAO,WAAW,kCAAkC,EAAE;AAGlF,MAAM,UAAU,CAAC,OACf,OAAO,GAAG,oBAAoB,aAAa,GAAG,gBAAA,IAAoB,GAAG,iBAAiB;AAOjF,MAAM,sBAAsB,aAAa;AAAA,EAAzC,cAAA;AAAA,UAAA,GAAA,SAAA;AAEL,SAAA,WAAW;AAEX,SAAA,UAAU;AACV,SAAQ,UAAU;AAClB,SAAQ,UAAU;AAClB,SAAQ,SAAS;AAEjB,SAAQ,UAAU;AAAA,EAAA;AAAA,EARlB,OAAA;AAAA,SAAgB,aAAa,EAAE,UAAU,EAAE,MAAM,SAAO;AAAA,EAAE;AAAA,EAUjD,oBAA0B;AACjC,UAAM,kBAAA;AACN,UAAM,QAAQ,KAAK,YAAY,OAAO;AACtC,UAAM,SAAS,KAAK,UAAU,OAAO;AACrC,QAAI,OAAO,SAAS,GAAG;AACrB;AAAA,IACF;AAEA,UAAM,OAAO,KAAK,SAAS,MAAM;AACjC,UAAM,OAAO,KAAK,SAAS,MAAM;AACjC,QAAI,KAAM,MAAK,OAAO,MAAM,SAAS,MAAM,KAAK,GAAG,KAAK,UAAU,CAAC,CAAC;AACpE,QAAI,KAAM,MAAK,OAAO,MAAM,SAAS,MAAM,KAAK,GAAG,KAAK,UAAU,CAAC,CAAC;AACpE,SAAK,UAAU,KAAK,EAAE,QAAQ,CAAC,KAAK,UAAU,KAAK,OAAO,KAAK,SAAS,MAAM,K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M,cAAc;AAAA,IAC5D,CAAC;AAED,eAAW,QAAQ,KAAK,YAAY,OAAO,CAAC;AAC5C,SAAK,aAAa,MAAM,WAAW,WAAA,CAAY;AAC/C,UAAM,QAAQ,YAAY,MAAM;AAC9B,UAAI,CAAC,KAAK,WAAW,CAAC,KAAK,WAAW,KAAK,UAAU,CAAC,SAAS,QAAQ;AACrE,aAAK,GAAG,KAAK,UAAU,CAAC;AAAA,MAC1B;AAAA,IACF,GAAG,KAAK,QAAQ;AAChB,SAAK,aAAa,MAAM,cAAc,KAAK,CAAC;AAAA,EAC9C;AAAA,EAEQ,YAAY,QAA2B;AAC7C,WAAO,aAAa,gBAAgB,OAAO,KAAK,OAAO,CAAC;AACxD,WAAO,aAAa,cAAc,KAAK,UAAU,EAAE,eAAe,IAAI,EAAE,gBAAgB,CAAC;AAAA,EAC3F;AACF;"}
|
|
1
|
+
{"version":3,"file":"carousel.js","sources":["../../../src/elements/carousel/carousel.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { t } from '../../core/i18n'\n\n/**\n * Parts of <spmkt-carousel autoplay=\"6000\"> (a scroll-snap track; Blade renders everything):\n * - track (required): the horizontally scrolling element\n * - slide (required, several): its slides\n * - prev, next (optional): buttons\n * - dot (optional, several): one button per slide, in order; the current one gets aria-current=\"true\"\n * - toggle (optional): a pause/play button, aria-pressed=\"true\" while paused (WCAG 2.2.2)\n * `autoplay` is the interval in milliseconds; 0 or absent turns it off.\n * Slides (and their dots) may be hidden with CSS, e.g. per device; the carousel skips them. While fewer than two\n * slides are shown there is nothing to move between, and prev, next, the dots and toggle are `hidden`.\n * The theme may show several slides at once (narrower slides); the first one in view is the current one, and\n * `next` wraps around once the track is scrolled to its end.\n */\nexport interface CarouselParts {\n track: HTMLElement\n slide: HTMLElement[]\n prev?: HTMLElement\n next?: HTMLElement\n dot?: HTMLElement[]\n toggle?: HTMLElement\n}\n\nconst reducedMotion = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches\n\n/** Whether the page displays the element (not display: none, nor inside something that is) */\nconst isShown = (el: HTMLElement) =>\n typeof el.checkVisibility === 'function' ? el.checkVisibility() : el.offsetParent !== null\n\n/**\n * The track scrolls natively (swipe, keyboard, scrollbar); this adds arrows, dots and autoplay.\n * Autoplay holds for reduced motion, hover, focus, hidden tabs, the pause button, and while the carousel is\n * scrolled out of view.\n */\nexport class SpmktCarousel extends SpmktElement {\n static override properties = { autoplay: { type: Number } }\n autoplay = 0\n /** Index of the first slide in view */\n current = 0\n private hovered = false\n private stopped = false\n private inView = true\n /** Autoplay is set up (an interval, and no reduced motion) */\n private playing = false\n /** Indexes of the slides now (mostly) in view */\n private visible = new Set<number>()\n\n override connectedCallback(): void {\n super.connectedCallback()\n const track = this.requirePart('track')\n const slides = this.findParts('slide')\n if (slides.length < 2) {\n return\n }\n\n const prev = this.findPart('prev')\n const next = this.findPart('next')\n if (prev) this.listen(prev, 'click', () => this.go(this.current - 1))\n if (next) this.listen(next, 'click', () => this.advance())\n this.findParts('dot').forEach((dot, index) => this.listen(dot, 'click', () => this.go(index)))\n\n // The first slide in view is the current one, however it got there. Entries report only changes, so the\n // slides in view are kept; mid-swipe none may be, and the current one stays.\n const observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n const index = slides.indexOf(entry.target as HTMLElement)\n if (entry.isIntersecting) this.visible.add(index)\n else this.visible.delete(index)\n }\n if (this.visible.size > 0) this.mark(Math.min(...this.visible))\n },\n { root: track, threshold: 0.6 },\n )\n slides.forEach((slide) => observer.observe(slide))\n this.onDisconnect(() => observer.disconnect())\n this.mark(0)\n\n this.setUpAutoplay()\n\n // Which slides are shown can change with the viewport (device rules)\n this.refreshControls()\n let frame = 0\n this.listen(window, 'resize', () => {\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(() => this.refreshControls())\n })\n this.onDisconnect(() => cancelAnimationFrame(frame))\n }\n\n /** The controls show only while there are at least two shown slides to move between. */\n private refreshControls(): void {\n const single = this.findParts('slide').filter(isShown).length < 2\n for (const part of [this.findPart('prev'), this.findPart('next'), ...this.findParts('dot')]) {\n if (part) part.hidden = single\n }\n const toggle = this.findPart('toggle')\n if (toggle) toggle.hidden = single || !this.playing\n }\n\n /**\n * Scrolls to slide `index` (wraps around). A slide the page does not display (e.g. hidden on this device by the\n * theme's CSS) is skipped in the direction of travel, so arrows, dots and autoplay only land on shown slides.\n */\n go(index: number): void {\n const track = this.findPart('track')\n const slides = this.findParts('slide')\n const count = slides.length\n if (!track || count === 0) {\n return\n }\n const step = index < this.current ? -1 : 1\n for (let tried = 0; tried < count; tried++) {\n const target = slides[(((index + step * tried) % count) + count) % count]!\n if (isShown(target)) {\n track.scrollTo({\n left: target.offsetLeft - track.offsetLeft,\n behavior: reducedMotion() ? 'auto' : 'smooth',\n })\n return\n }\n }\n }\n\n /**\n * The next slide. With several in view, a next slide that cannot scroll to the track's start is on the last\n * page, which is already shown, so it wraps around to the first. Decided by where the slide sits, not where the\n * track is scrolled, so a click during a scroll does the same.\n */\n private advance(): void {\n const track = this.findPart('track')\n const target = this.findParts('slide')[this.current + 1]\n const onLastPage =\n !!track &&\n !!target &&\n isShown(target) &&\n target.offsetLeft - track.offsetLeft > track.scrollWidth - track.clientWidth + 1\n this.go(onLastPage ? 0 : this.current + 1)\n }\n\n private mark(index: number): void {\n if (index < 0) {\n return\n }\n const changed = index !== this.current\n this.current = index\n this.findParts('dot').forEach((dot, i) => dot.setAttribute('aria-current', String(i === index)))\n if (changed) {\n this.emit('spmkt:slide-change', { index })\n }\n }\n\n private setUpAutoplay(): void {\n const toggle = this.findPart('toggle')\n if (!this.autoplay || reducedMotion()) {\n if (toggle) toggle.hidden = true\n return\n }\n this.playing = true\n const hold = () => (this.hovered = true)\n const release = () => (this.hovered = false)\n this.listen(this, 'pointerenter', hold)\n this.listen(this, 'pointerleave', release)\n this.listen(this, 'focusin', (event) => {\n // The pause button itself does not count as \"reading a slide\"\n if (event.target !== toggle) hold()\n })\n this.listen(this, 'focusout', release)\n if (toggle) {\n this.paintToggle(toggle)\n this.listen(toggle, 'click', () => {\n this.stopped = !this.stopped\n this.paintToggle(toggle)\n })\n }\n const visibility = new IntersectionObserver((entries) => {\n this.inView = entries.some((entry) => entry.isIntersecting)\n })\n // The track, not the element: a custom element styled display: contents has no box to observe\n visibility.observe(this.requirePart('track'))\n this.onDisconnect(() => visibility.disconnect())\n const timer = setInterval(() => {\n if (!this.hovered && !this.stopped && this.inView && !document.hidden) {\n this.advance()\n }\n }, this.autoplay)\n this.onDisconnect(() => clearInterval(timer))\n }\n\n private paintToggle(toggle: HTMLElement): void {\n toggle.setAttribute('aria-pressed', String(this.stopped))\n toggle.setAttribute('aria-label', this.stopped ? t('carousel.play') : t('carousel.pause'))\n }\n}\n"],"names":[],"mappings":";;AAyBA,MAAM,gBAAgB,MAAM,OAAO,WAAW,kCAAkC,EAAE;AAGlF,MAAM,UAAU,CAAC,OACf,OAAO,GAAG,oBAAoB,aAAa,GAAG,gBAAA,IAAoB,GAAG,iBAAiB;AAOjF,MAAM,sBAAsB,aAAa;AAAA,EAAzC,cAAA;AAAA,UAAA,GAAA,SAAA;AAEL,SAAA,WAAW;AAEX,SAAA,UAAU;AACV,SAAQ,UAAU;AAClB,SAAQ,UAAU;AAClB,SAAQ,SAAS;AAEjB,SAAQ,UAAU;AAElB,SAAQ,8BAAc,IAAA;AAAA,EAAY;AAAA,EAVlC,OAAA;AAAA,SAAgB,aAAa,EAAE,UAAU,EAAE,MAAM,SAAO;AAAA,EAAE;AAAA,EAYjD,oBAA0B;AACjC,UAAM,kBAAA;AACN,UAAM,QAAQ,KAAK,YAAY,OAAO;AACtC,UAAM,SAAS,KAAK,UAAU,OAAO;AACrC,QAAI,OAAO,SAAS,GAAG;AACrB;AAAA,IACF;AAEA,UAAM,OAAO,KAAK,SAAS,MAAM;AACjC,UAAM,OAAO,KAAK,SAAS,MAAM;AACjC,QAAI,KAAM,MAAK,OAAO,MAAM,SAAS,MAAM,KAAK,GAAG,KAAK,UAAU,CAA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;
|
|
|
18
18
|
export declare function fetchFragments(url: string | URL, options: FetchFragmentsOptions): Promise<FragmentResponse>;
|
|
19
19
|
/**
|
|
20
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.
|
|
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.
|
|
22
23
|
* Returns the new section element, or null when it was removed or `from` is in no section.
|
|
23
24
|
*/
|
|
24
25
|
export declare function swapSection(from: Element, html: string): Element | null;
|
package/dist/lit/fragments.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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.\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 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;AAClD,WAAS,YAAY;AACrB,SAAO,SAAS;AAClB;AAGA,SAAS,UAAU,OAAgB,MAAqC;AACtE,QAAM,SAAS,SAAS;AACxB,QAAM,KAAK,UAAU,MAAM,SAAS,MAAM,KAAK,OAAO,KAAK,OAAO,KAAK;AACvE,QAAM,cAAc,KAAA;AACpB,MAAI,MAAM,aAAa;AACrB,gBAAY,cAA2B,IAAI,IAAI,OAAO,EAAE,CAAC,EAAE,GAAG,MAAA;AAAA,EAChE;AACF;
|
|
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;AAClD,WAAS,YAAY;AACrB,SAAO,SAAS;AAClB;AAGA,SAAS,UAAU,OAAgB,MAAqC;AACtE,QAAM,SAAS,SAAS;AACxB,QAAM,KAAK,UAAU,MAAM,SAAS,MAAM,KAAK,OAAO,KAAK,OAAO,KAAK;AACvE,QAAM,cAAc,KAAA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