@vectoriox/iox-ui 5.93.0 → 5.95.0
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/actions-core/index.d.ts +7 -2
- package/commerce-core/index.d.ts +863 -3
- package/composite-core/index.d.ts +290 -2
- package/design-core/index.d.ts +1049 -105
- package/fesm2022/vectoriox-iox-ui-actions-core.mjs +15 -4
- package/fesm2022/vectoriox-iox-ui-actions-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui-commerce-core.mjs +1509 -5
- package/fesm2022/vectoriox-iox-ui-commerce-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui-composite-core.mjs +1170 -177
- package/fesm2022/vectoriox-iox-ui-composite-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui-design-core.mjs +1147 -43
- package/fesm2022/vectoriox-iox-ui-design-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui-generation-core.mjs +2 -2
- package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui.mjs +8 -1
- package/fesm2022/vectoriox-iox-ui.mjs.map +1 -1
- package/generation-core/index.d.ts +2 -2
- package/index.d.ts +2 -0
- package/package.json +1 -1
- package/src/actions-core/action.model.ts +1 -1
- package/src/actions-core/element-actions.ts +17 -3
- package/src/commerce-core/cart-transport.ts +211 -0
- package/src/commerce-core/cart.ts +305 -0
- package/src/commerce-core/catalog.ts +42 -0
- package/src/commerce-core/checkout.ts +202 -0
- package/src/commerce-core/decimal.ts +28 -0
- package/src/commerce-core/labels.ts +29 -0
- package/src/commerce-core/limits.ts +9 -0
- package/src/commerce-core/money-error.ts +1 -0
- package/src/commerce-core/order-snapshot.ts +151 -0
- package/src/commerce-core/orders.ts +172 -0
- package/src/commerce-core/payments.ts +196 -0
- package/src/commerce-core/public-api.ts +19 -4
- package/src/commerce-core/quantity.ts +56 -0
- package/src/commerce-core/shipping.ts +168 -0
- package/src/commerce-core/shop-display.ts +117 -0
- package/src/commerce-core/text.ts +13 -0
- package/src/commerce-core/variants.ts +296 -0
- package/src/commerce-core/vat.ts +38 -0
- package/src/composite-core/exclusive-runtime.ts +20 -7
- package/src/composite-core/public-api.ts +2 -0
- package/src/composite-core/shop-runtime.ts +626 -0
- package/src/composite-core/shop.ts +433 -0
- package/src/design-core/flavor-spec.generated.ts +1147 -43
- package/src/generation-core/site-spec.generated.ts +2 -2
- package/styles/iox-design.css +95 -0
|
@@ -0,0 +1,626 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CART_TRANSPORT_ERROR_LABELS, CartTransport, CartTransportError, CartTransportErrorCode, cartIssueWords, CartView, CartViewLine, chooseValue,
|
|
3
|
+
defaultChoice, emptyCartView, findVariant, formatMoney, optionValueStates, ProductOption, ProductVariantView, productOptions, productVariants,
|
|
4
|
+
QuantityBounds, quantityBounds, QuantityStep, canStep, clampQuantity, ShopSlot, ShopWord, shopWord, stepQuantity, StorefrontProduct, VariantChoice,
|
|
5
|
+
variantWords,
|
|
6
|
+
} from '@vectoriox/iox-ui/commerce-core';
|
|
7
|
+
import { roleClass } from '@vectoriox/iox-ui/design-core';
|
|
8
|
+
|
|
9
|
+
import { ITEM_KEY_ATTRIBUTE } from './accordion';
|
|
10
|
+
import { CompositeKind } from './composite-kinds';
|
|
11
|
+
import { attachExclusiveAt, exclusiveRuntimeOf, ExclusiveRuntime } from './exclusive-runtime';
|
|
12
|
+
import {
|
|
13
|
+
ADDED_HOLD_MS, CART_EMPTY_ATTRIBUTE, CART_LINE_ATTRIBUTE, CART_TITLE_COUNT_ATTRIBUTE, ShopPickerKind, shopPickerKind, ShopRole, shopSelector,
|
|
14
|
+
SHOP_ADDED_ATTRIBUTE, SHOP_CLONE_ATTRIBUTE, SHOP_HIDDEN_ATTRIBUTE, SHOP_LIVE_CLASS, SHOP_SELECT_CLASS, SHOP_UNUSED_ATTRIBUTE, swatchFill,
|
|
15
|
+
variantGroupLabel, variantGroupNote,
|
|
16
|
+
} from './shop';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* THE SHOP RUNTIME (commerce E1c) — ONE copy, DOM only, for the builder canvas and the live site. It finds the shop parts
|
|
20
|
+
* by their role classes inside a scope (the page), so it reads the markup both renderers write the same way, and it
|
|
21
|
+
* never decides a price: every line, total and issue comes from the HOST's cart transport (the server's `priceCart` on
|
|
22
|
+
* the live site — E1d; an in-memory simulation on the canvas), and `$variant` / `$cart` are published to the host's
|
|
23
|
+
* context channel for the ordinary bindings (`$variant.price | money`, `$cart.count`).
|
|
24
|
+
*
|
|
25
|
+
* Templates: an option group, a value (chip or swatch) and a cart line are each ONE builder node, shown as the first
|
|
26
|
+
* instance; the rest are copies stamped after it (`data-iox-shop-clone`), restamped only when the list changes.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
export interface ShopHost {
|
|
30
|
+
/** The cart: the engine's (E1d) on a live site, `simulatedCartTransport` on the builder canvas. */
|
|
31
|
+
transport: CartTransport;
|
|
32
|
+
/** The product an element belongs to (its row's, else the route's, else the page's first) — `productInScope`. */
|
|
33
|
+
productFor: (el: Element) => StorefrontProduct | null;
|
|
34
|
+
/** The page's language (money, words). */
|
|
35
|
+
locale?: () => string | null | undefined;
|
|
36
|
+
/** Write a shop slot into the host's context channel (`ContextStore.set`). */
|
|
37
|
+
publish?: (slot: ShopSlot, value: unknown) => void;
|
|
38
|
+
/** Open the page's cart drawer (the host's own dialog path: the engine's `openDialog`, the canvas twin). */
|
|
39
|
+
openDrawer?: (drawer: HTMLElement) => void;
|
|
40
|
+
/** Go to the fixed checkout route (`checkoutHref(orgLabel)`); the canvas simulates it. */
|
|
41
|
+
goToCheckout?: () => void;
|
|
42
|
+
/** A change the cart refused (words in the page language) — the host may toast it; it is announced either way. */
|
|
43
|
+
onRefused?: (words: string, error: unknown) => void;
|
|
44
|
+
/** The colours a value is drawn with when it is not a colour word itself (the canvas' sample glazes). */
|
|
45
|
+
swatches?: (product: StorefrontProduct) => Readonly<Record<string, string>> | null;
|
|
46
|
+
/** A copy was clicked: the canvas selects its template (the copy is display-only). */
|
|
47
|
+
onCloneClick?: (template: HTMLElement) => void;
|
|
48
|
+
/** Restamp when the markup under the scope changes (the builder canvas re-renders parts). */
|
|
49
|
+
observe?: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface ProductState {
|
|
53
|
+
product: StorefrontProduct;
|
|
54
|
+
options: ProductOption[];
|
|
55
|
+
views: ProductVariantView[];
|
|
56
|
+
choice: VariantChoice;
|
|
57
|
+
quantity: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const sel = shopSelector;
|
|
61
|
+
const CLONE = `[${SHOP_CLONE_ATTRIBUTE}]`;
|
|
62
|
+
const VALUE_TRIGGERS = `${sel(ShopRole.VariantValue)}:not([${SHOP_UNUSED_ATTRIBUTE}]), ${sel(ShopRole.VariantSwatch)}:not([${SHOP_UNUSED_ATTRIBUTE}])`;
|
|
63
|
+
const SCOPES = new Map<Element, ShopRuntime>();
|
|
64
|
+
|
|
65
|
+
function setAttr(el: Element | null | undefined, name: string, value: string | null): void {
|
|
66
|
+
if (!el) return;
|
|
67
|
+
if (value === null) { if (el.hasAttribute(name)) el.removeAttribute(name); }
|
|
68
|
+
else if (el.getAttribute(name) !== value) el.setAttribute(name, value);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function setText(el: Element | null | undefined, words: string): void {
|
|
72
|
+
if (el && el.textContent !== words) el.textContent = words;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The deepest element of a Text / Heading part that holds its words (a host may wrap them). */
|
|
76
|
+
function wordsOf(el: Element | null | undefined): Element | null {
|
|
77
|
+
if (!el) return null;
|
|
78
|
+
let cur: Element = el;
|
|
79
|
+
while (cur.children.length === 1 && !cur.hasAttribute(CART_TITLE_COUNT_ATTRIBUTE)) cur = cur.children[0];
|
|
80
|
+
return cur;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A part's own element when it is a copy's template part, so a copy's parts are found inside the copy. */
|
|
84
|
+
function own(scope: Element, selector: string): HTMLElement[] {
|
|
85
|
+
return Array.from(scope.querySelectorAll<HTMLElement>(selector));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function first(scope: Element, selector: string): HTMLElement | null {
|
|
89
|
+
return scope.querySelector<HTMLElement>(selector);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Copies of `template` (siblings after it, marked as its copies), made or dropped to `count - 1`. */
|
|
93
|
+
function stampCopies(template: HTMLElement, count: number, key: string): HTMLElement[] {
|
|
94
|
+
const parent = template.parentElement;
|
|
95
|
+
if (!parent) return [template];
|
|
96
|
+
const mark = template.getAttribute(SHOP_CLONE_ATTRIBUTE) === null ? key : '';
|
|
97
|
+
const copies = Array.from(parent.children).filter(c => c !== template && c.getAttribute(SHOP_CLONE_ATTRIBUTE) === mark) as HTMLElement[];
|
|
98
|
+
while (copies.length > Math.max(0, count - 1)) copies.pop()!.remove();
|
|
99
|
+
let anchor: HTMLElement = copies[copies.length - 1] ?? template;
|
|
100
|
+
while (copies.length < count - 1) {
|
|
101
|
+
const copy = template.cloneNode(true) as HTMLElement;
|
|
102
|
+
copy.setAttribute(SHOP_CLONE_ATTRIBUTE, mark);
|
|
103
|
+
for (const inner of Array.from(copy.querySelectorAll(CLONE))) inner.remove();
|
|
104
|
+
for (const id of Array.from(copy.querySelectorAll('[id]'))) id.removeAttribute('id');
|
|
105
|
+
copy.removeAttribute('id');
|
|
106
|
+
anchor.after(copy);
|
|
107
|
+
anchor = copy;
|
|
108
|
+
copies.push(copy);
|
|
109
|
+
}
|
|
110
|
+
return [template, ...copies];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Only the words on screen are in the button's name: "Add to cart", or "Added ✓" while it holds. */
|
|
114
|
+
function syncAddedWords(button: Element, added: boolean): void {
|
|
115
|
+
setAttr(button, SHOP_ADDED_ATTRIBUTE, added ? '' : null);
|
|
116
|
+
for (const label of Array.from(button.querySelectorAll(sel(ShopRole.AddLabel)))) setAttr(label, 'aria-hidden', added ? 'true' : null);
|
|
117
|
+
for (const label of Array.from(button.querySelectorAll(sel(ShopRole.AddedLabel)))) setAttr(label, 'aria-hidden', added ? null : 'true');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function announce(scope: Element, words: string): void {
|
|
121
|
+
const doc = scope.ownerDocument;
|
|
122
|
+
if (!doc) return;
|
|
123
|
+
let live = scope.querySelector<HTMLElement>(`.${SHOP_LIVE_CLASS}`);
|
|
124
|
+
if (!live) {
|
|
125
|
+
live = doc.createElement('div');
|
|
126
|
+
live.className = SHOP_LIVE_CLASS;
|
|
127
|
+
live.setAttribute('role', 'status');
|
|
128
|
+
live.setAttribute('aria-live', 'polite');
|
|
129
|
+
scope.appendChild(live);
|
|
130
|
+
}
|
|
131
|
+
live.textContent = '';
|
|
132
|
+
live.textContent = words;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export class ShopRuntime {
|
|
136
|
+
private readonly products = new Map<string, ProductState>();
|
|
137
|
+
private cart: CartView = emptyCartView();
|
|
138
|
+
private observer: MutationObserver | null = null;
|
|
139
|
+
private stampQueued = false;
|
|
140
|
+
private stamping = false;
|
|
141
|
+
private addedTimers = new Map<Element, ReturnType<typeof setTimeout>>();
|
|
142
|
+
private pageProduct: string | null = null;
|
|
143
|
+
private destroyed = false;
|
|
144
|
+
/** What each slot last carried: an unchanged value is never published again (a host's binding re-render must not
|
|
145
|
+
* wake the runtime into publishing the same thing for ever). */
|
|
146
|
+
private readonly published = new Map<ShopSlot, string>();
|
|
147
|
+
|
|
148
|
+
constructor(readonly scope: HTMLElement, private readonly host: ShopHost) {
|
|
149
|
+
SCOPES.set(scope, this);
|
|
150
|
+
scope.addEventListener('click', this.onClick, true);
|
|
151
|
+
scope.addEventListener('change', this.onChange, true);
|
|
152
|
+
if (host.observe && typeof MutationObserver !== 'undefined') {
|
|
153
|
+
this.observer = new MutationObserver(() => { if (!this.stamping) this.queueStamp(); });
|
|
154
|
+
this.observer.observe(scope, { childList: true, subtree: true });
|
|
155
|
+
}
|
|
156
|
+
this.stamp();
|
|
157
|
+
void this.host.transport.read().then(view => this.setCart(view), () => undefined);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
private get lang(): string {
|
|
161
|
+
return this.host.locale?.() || 'en';
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The cart the runtime shows (the transport's last answer). */
|
|
165
|
+
get view(): CartView {
|
|
166
|
+
return this.cart;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The variant an element's product has chosen, or null (no product, no full choice). */
|
|
170
|
+
variantFor(el: Element): ProductVariantView | null {
|
|
171
|
+
const state = this.stateFor(el);
|
|
172
|
+
return state ? this.variantOf(state) : null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The quantity an element's product would add. */
|
|
176
|
+
quantityFor(el: Element): number {
|
|
177
|
+
return this.stateFor(el)?.quantity ?? 1;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Re-read every product and restamp (the host's data changed). */
|
|
181
|
+
refresh(): void {
|
|
182
|
+
this.products.clear();
|
|
183
|
+
this.stamp();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Add the element's product — its chosen variant, its quantity — then say "Added ✓" in place and open the bag. */
|
|
187
|
+
async add(el: Element): Promise<CartView | null> {
|
|
188
|
+
const state = this.stateFor(el);
|
|
189
|
+
const variant = state ? this.variantOf(state) : null;
|
|
190
|
+
if (!state || !variant?.sellable) {
|
|
191
|
+
if (state) this.refuse(shopWord(ShopWord.SoldOut, this.lang), null);
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
const button = el.closest(sel(ShopRole.Add)) ?? el;
|
|
195
|
+
setAttr(button, 'aria-busy', 'true');
|
|
196
|
+
try {
|
|
197
|
+
const view = await this.host.transport.add({ productId: String(state.product._id), variantId: variant.variantId, quantity: state.quantity });
|
|
198
|
+
this.setCart(view);
|
|
199
|
+
this.markAdded(button);
|
|
200
|
+
this.openCart();
|
|
201
|
+
return view;
|
|
202
|
+
} catch (error) {
|
|
203
|
+
this.refuse(this.refusalWords(error), error);
|
|
204
|
+
return null;
|
|
205
|
+
} finally {
|
|
206
|
+
setAttr(button, 'aria-busy', null);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Buy now: add, then go straight to checkout. */
|
|
211
|
+
async buyNow(el: Element): Promise<boolean> {
|
|
212
|
+
const view = await this.add(el);
|
|
213
|
+
if (view && !view.empty) this.host.goToCheckout?.();
|
|
214
|
+
return !!view;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Open the page's cart drawer. False when the page has none. */
|
|
218
|
+
openCart(): boolean {
|
|
219
|
+
const drawer = first(this.scope, sel(ShopRole.CartDrawer));
|
|
220
|
+
if (!drawer) return false;
|
|
221
|
+
if (this.host.openDrawer) this.host.openDrawer(drawer);
|
|
222
|
+
else if (drawer instanceof HTMLDialogElement && !drawer.open && typeof drawer.showModal === 'function') drawer.showModal();
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** The transport answered: publish `$cart` and fill the cart parts. */
|
|
227
|
+
setCart(view: CartView): void {
|
|
228
|
+
if (this.destroyed) return;
|
|
229
|
+
this.cart = view;
|
|
230
|
+
this.publish(ShopSlot.Cart, view);
|
|
231
|
+
this.stamp();
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
destroy(): void {
|
|
235
|
+
this.destroyed = true;
|
|
236
|
+
if (SCOPES.get(this.scope) === this) SCOPES.delete(this.scope);
|
|
237
|
+
this.scope.removeEventListener('click', this.onClick, true);
|
|
238
|
+
this.scope.removeEventListener('change', this.onChange, true);
|
|
239
|
+
this.observer?.disconnect();
|
|
240
|
+
this.observer = null;
|
|
241
|
+
for (const timer of this.addedTimers.values()) clearTimeout(timer);
|
|
242
|
+
this.addedTimers.clear();
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ── state ─────────────────────────────────────────────────────────────────────────────────
|
|
246
|
+
|
|
247
|
+
private stateFor(el: Element): ProductState | null {
|
|
248
|
+
const product = this.host.productFor(el);
|
|
249
|
+
if (!product || product._id === undefined || product._id === null) return null;
|
|
250
|
+
const id = String(product._id);
|
|
251
|
+
const known = this.products.get(id);
|
|
252
|
+
if (known && known.product === product) return known;
|
|
253
|
+
const options = productOptions(product);
|
|
254
|
+
const views = productVariants(product);
|
|
255
|
+
const state: ProductState = {
|
|
256
|
+
product, options, views,
|
|
257
|
+
choice: known?.choice ?? defaultChoice(options, views),
|
|
258
|
+
quantity: known?.quantity ?? 1,
|
|
259
|
+
};
|
|
260
|
+
this.products.set(id, state);
|
|
261
|
+
return state;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
private variantOf(state: ProductState): ProductVariantView | null {
|
|
265
|
+
return state.options.length ? findVariant(state.options, state.views, state.choice) : state.views[0] ?? null;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
private boundsOf(state: ProductState): QuantityBounds {
|
|
269
|
+
const variant = this.variantOf(state);
|
|
270
|
+
return quantityBounds(variant ? { availability: variant.availability } : undefined);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private choose(state: ProductState, option: string, value: string): void {
|
|
274
|
+
const next = chooseValue(state.options, state.views, state.choice, option, value);
|
|
275
|
+
if (JSON.stringify(next) === JSON.stringify(state.choice)) return;
|
|
276
|
+
state.choice = next;
|
|
277
|
+
state.quantity = clampQuantity(state.quantity, this.boundsOf(state));
|
|
278
|
+
this.pageProduct = String(state.product._id);
|
|
279
|
+
this.stamp();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
private publishVariant(state: ProductState): void {
|
|
283
|
+
const variant = this.variantOf(state);
|
|
284
|
+
this.publish(ShopSlot.Variant, variant ? {
|
|
285
|
+
...variant,
|
|
286
|
+
productId: state.product._id,
|
|
287
|
+
words: variantWords(variant.choice, state.options),
|
|
288
|
+
quantity: state.quantity,
|
|
289
|
+
} : null);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
private publish(slot: ShopSlot, value: unknown): void {
|
|
293
|
+
const json = JSON.stringify(value ?? null);
|
|
294
|
+
if (this.published.get(slot) === json) return;
|
|
295
|
+
this.published.set(slot, json);
|
|
296
|
+
this.host.publish?.(slot, value);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// ── stamping ──────────────────────────────────────────────────────────────────────────────
|
|
300
|
+
|
|
301
|
+
private queueStamp(): void {
|
|
302
|
+
if (this.stampQueued) return;
|
|
303
|
+
this.stampQueued = true;
|
|
304
|
+
const run = () => { this.stampQueued = false; this.stamp(); };
|
|
305
|
+
if (typeof queueMicrotask === 'function') queueMicrotask(run); else Promise.resolve().then(run);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Write every part's state into its markup. Idempotent; the observer is deaf while it runs. */
|
|
309
|
+
stamp(): void {
|
|
310
|
+
if (this.destroyed) return;
|
|
311
|
+
this.stamping = true;
|
|
312
|
+
try {
|
|
313
|
+
let page: ProductState | null = null;
|
|
314
|
+
for (const root of own(this.scope, sel(ShopRole.Variants)).filter(r => !r.closest(CLONE))) {
|
|
315
|
+
const state = this.stateFor(root);
|
|
316
|
+
this.stampPicker(root, state);
|
|
317
|
+
page = page ?? state;
|
|
318
|
+
}
|
|
319
|
+
for (const el of own(this.scope, `${sel(ShopRole.Quantity)}, ${sel(ShopRole.Add)}, ${sel(ShopRole.BuyNow)}, ${sel(ShopRole.Price)}`)) {
|
|
320
|
+
if (el.closest(sel(ShopRole.CartLine))) continue;
|
|
321
|
+
const state = this.stateFor(el);
|
|
322
|
+
page = page ?? state;
|
|
323
|
+
if (!state) continue;
|
|
324
|
+
if (el.matches(sel(ShopRole.Quantity))) this.stampQuantity(el, state.quantity, this.boundsOf(state));
|
|
325
|
+
else if (!el.matches(sel(ShopRole.Price))) {
|
|
326
|
+
setAttr(el, 'aria-disabled', this.variantOf(state)?.sellable ? null : 'true');
|
|
327
|
+
if (el.matches(sel(ShopRole.Add))) syncAddedWords(el, this.addedTimers.has(el));
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const shown = (this.pageProduct && this.products.get(this.pageProduct)) || page;
|
|
331
|
+
if (shown) this.publishVariant(shown);
|
|
332
|
+
this.stampCart();
|
|
333
|
+
} finally {
|
|
334
|
+
this.observer?.takeRecords();
|
|
335
|
+
this.stamping = false;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private stampPicker(root: HTMLElement, state: ProductState | null): void {
|
|
340
|
+
const template = Array.from(root.querySelectorAll<HTMLElement>(sel(ShopRole.VariantGroup))).find(g => !g.closest(CLONE));
|
|
341
|
+
if (!template) return;
|
|
342
|
+
const options = state?.options ?? [];
|
|
343
|
+
setAttr(root, SHOP_HIDDEN_ATTRIBUTE, options.length ? null : '');
|
|
344
|
+
if (!state || !options.length) { stampCopies(template, 1, ShopRole.VariantGroup); return; }
|
|
345
|
+
const groups = stampCopies(template, options.length, ShopRole.VariantGroup);
|
|
346
|
+
const states = optionValueStates(options, state.views, state.choice);
|
|
347
|
+
const own = this.host.swatches?.(state.product) ?? null;
|
|
348
|
+
groups.forEach((group, i) => this.stampGroup(group, state, options[i], states[i].values, own));
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
private stampGroup(group: HTMLElement, state: ProductState, option: ProductOption, values: ReadonlyArray<{ value: string; available: boolean }>,
|
|
352
|
+
fills: Readonly<Record<string, string>> | null): void {
|
|
353
|
+
const kind = shopPickerKind(option, fills);
|
|
354
|
+
const chosen = state.choice[option.name];
|
|
355
|
+
setText(wordsOf(first(group, sel(ShopRole.VariantLabel))), variantGroupLabel(option, chosen, kind));
|
|
356
|
+
const soldOut = values.filter(v => !v.available).map(v => v.value);
|
|
357
|
+
const note = first(group, sel(ShopRole.VariantNote));
|
|
358
|
+
const noteWords = variantGroupNote(soldOut, kind, this.lang);
|
|
359
|
+
setText(wordsOf(note), noteWords);
|
|
360
|
+
setAttr(note, SHOP_HIDDEN_ATTRIBUTE, noteWords ? null : '');
|
|
361
|
+
const box = first(group, sel(ShopRole.VariantValues));
|
|
362
|
+
if (!box) return;
|
|
363
|
+
const chip = Array.from(box.querySelectorAll<HTMLElement>(sel(ShopRole.VariantValue))).find(v => !v.hasAttribute(SHOP_CLONE_ATTRIBUTE));
|
|
364
|
+
const swatch = Array.from(box.querySelectorAll<HTMLElement>(sel(ShopRole.VariantSwatch))).find(v => !v.hasAttribute(SHOP_CLONE_ATTRIBUTE));
|
|
365
|
+
const used = kind === ShopPickerKind.Swatches ? swatch ?? chip : kind === ShopPickerKind.Chips ? chip ?? swatch : null;
|
|
366
|
+
for (const t of [chip, swatch]) {
|
|
367
|
+
if (!t) continue;
|
|
368
|
+
setAttr(t, SHOP_UNUSED_ATTRIBUTE, t === used ? null : '');
|
|
369
|
+
if (t !== used) stampCopies(t, 1, t === chip ? ShopRole.VariantValue : ShopRole.VariantSwatch);
|
|
370
|
+
}
|
|
371
|
+
this.stampSelect(box, kind === ShopPickerKind.Select ? option : null, values, chosen);
|
|
372
|
+
if (!used) {
|
|
373
|
+
exclusiveRuntimeOf(box)?.destroy();
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const items = stampCopies(used, option.values.length, used === chip ? ShopRole.VariantValue : ShopRole.VariantSwatch);
|
|
377
|
+
items.forEach((item, i) => {
|
|
378
|
+
const value = values[i];
|
|
379
|
+
setAttr(item, ITEM_KEY_ATTRIBUTE, value.value);
|
|
380
|
+
setAttr(item, 'aria-disabled', value.available ? null : 'true');
|
|
381
|
+
if (used === swatch) {
|
|
382
|
+
const fill = swatchFill(value.value, fills);
|
|
383
|
+
if (fill) item.style.setProperty('--iox-swatch-fill', fill); else item.style.removeProperty('--iox-swatch-fill');
|
|
384
|
+
setAttr(item, 'aria-label', value.available ? value.value : shopWord(ShopWord.ValueSoldOut, this.lang, { name: value.value }));
|
|
385
|
+
setAttr(item, 'title', value.value);
|
|
386
|
+
} else {
|
|
387
|
+
setText(wordsOf(item), value.value);
|
|
388
|
+
setAttr(item, 'aria-label', value.available ? null : shopWord(ShopWord.ValueSoldOut, this.lang, { name: value.value }));
|
|
389
|
+
}
|
|
390
|
+
});
|
|
391
|
+
const rt = exclusiveRuntimeOf(box) ?? this.attachValues(box, state, option.name);
|
|
392
|
+
rt.refresh();
|
|
393
|
+
if (chosen && rt.liveKey !== chosen) rt.activate(chosen);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
private attachValues(box: HTMLElement, state: ProductState, option: string): ExclusiveRuntime {
|
|
397
|
+
const id = String(state.product._id);
|
|
398
|
+
return attachExclusiveAt(box, {
|
|
399
|
+
kind: CompositeKind.Segmented,
|
|
400
|
+
triggerSelector: VALUE_TRIGGERS,
|
|
401
|
+
label: () => option,
|
|
402
|
+
defaultKey: () => this.products.get(id)?.choice[option] ?? null,
|
|
403
|
+
onChange: key => { const s = this.products.get(id); if (s) this.choose(s, option, key); },
|
|
404
|
+
})!;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** Past four values (T26): a native select, sold-out values disabled with their words. */
|
|
408
|
+
private stampSelect(box: HTMLElement, option: ProductOption | null, values: ReadonlyArray<{ value: string; available: boolean }>, chosen: string | undefined): void {
|
|
409
|
+
let select = box.querySelector<HTMLSelectElement>(`select.${SHOP_SELECT_CLASS}`);
|
|
410
|
+
if (!option) { select?.remove(); return; }
|
|
411
|
+
if (!select) {
|
|
412
|
+
select = box.ownerDocument.createElement('select');
|
|
413
|
+
select.className = SHOP_SELECT_CLASS;
|
|
414
|
+
box.appendChild(select);
|
|
415
|
+
}
|
|
416
|
+
select.setAttribute('aria-label', shopWord(ShopWord.ChooseOption, this.lang, { name: option.name }));
|
|
417
|
+
select.setAttribute('data-iox-option', option.name);
|
|
418
|
+
const signature = values.map(v => `${v.value}:${v.available}`).join('|');
|
|
419
|
+
if (select.getAttribute('data-iox-values') !== signature) {
|
|
420
|
+
select.setAttribute('data-iox-values', signature);
|
|
421
|
+
select.textContent = '';
|
|
422
|
+
for (const v of values) {
|
|
423
|
+
const opt = box.ownerDocument.createElement('option');
|
|
424
|
+
opt.value = v.value;
|
|
425
|
+
opt.textContent = v.available ? v.value : `${v.value} — ${shopWord(ShopWord.SoldOut, this.lang)}`;
|
|
426
|
+
opt.disabled = !v.available;
|
|
427
|
+
select.appendChild(opt);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
if (chosen !== undefined && select.value !== chosen) select.value = chosen;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
private stampQuantity(root: HTMLElement, quantity: number, bounds: QuantityBounds): void {
|
|
434
|
+
setAttr(root, 'role', 'group');
|
|
435
|
+
setAttr(root, 'aria-label', shopWord(ShopWord.Quantity, this.lang));
|
|
436
|
+
const value = first(root, sel(ShopRole.QuantityValue));
|
|
437
|
+
setText(wordsOf(value), String(quantity));
|
|
438
|
+
setAttr(value, 'aria-live', 'polite');
|
|
439
|
+
const down = first(root, sel(ShopRole.QuantityDown));
|
|
440
|
+
const up = first(root, sel(ShopRole.QuantityUp));
|
|
441
|
+
setAttr(down, 'aria-label', shopWord(ShopWord.Decrease, this.lang));
|
|
442
|
+
setAttr(up, 'aria-label', shopWord(ShopWord.Increase, this.lang));
|
|
443
|
+
setAttr(down, 'aria-disabled', canStep(quantity, QuantityStep.Down, bounds) ? null : 'true');
|
|
444
|
+
setAttr(up, 'aria-disabled', canStep(quantity, QuantityStep.Up, bounds) ? null : 'true');
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
private stampCart(): void {
|
|
448
|
+
const view = this.cart;
|
|
449
|
+
const lang = this.lang;
|
|
450
|
+
for (const button of own(this.scope, sel(ShopRole.CartButton))) {
|
|
451
|
+
setAttr(button, CART_EMPTY_ATTRIBUTE, view.empty ? '' : null);
|
|
452
|
+
setAttr(button, 'aria-label', view.empty ? shopWord(ShopWord.Cart, lang) : shopWord(ShopWord.CartCount, lang, { n: view.count }));
|
|
453
|
+
setAttr(button, 'aria-haspopup', 'dialog');
|
|
454
|
+
}
|
|
455
|
+
for (const drawer of own(this.scope, sel(ShopRole.CartDrawer))) {
|
|
456
|
+
setAttr(drawer, CART_EMPTY_ATTRIBUTE, view.empty ? '' : null);
|
|
457
|
+
const title = wordsOf(first(drawer, sel(ShopRole.CartTitle)));
|
|
458
|
+
if (title) {
|
|
459
|
+
let count = title.querySelector(`[${CART_TITLE_COUNT_ATTRIBUTE}]`);
|
|
460
|
+
if (!count) {
|
|
461
|
+
count = title.ownerDocument.createElement('span');
|
|
462
|
+
count.setAttribute(CART_TITLE_COUNT_ATTRIBUTE, '');
|
|
463
|
+
title.appendChild(count);
|
|
464
|
+
}
|
|
465
|
+
setText(count, view.empty ? '' : ` (${view.count})`);
|
|
466
|
+
}
|
|
467
|
+
const template = Array.from(drawer.querySelectorAll<HTMLElement>(sel(ShopRole.CartLine))).find(l => !l.hasAttribute(SHOP_CLONE_ATTRIBUTE));
|
|
468
|
+
if (template) {
|
|
469
|
+
const lines = stampCopies(template, Math.max(1, view.lines.length), ShopRole.CartLine);
|
|
470
|
+
setAttr(template, SHOP_HIDDEN_ATTRIBUTE, view.lines.length ? null : '');
|
|
471
|
+
view.lines.forEach((line, i) => this.stampLine(lines[i], line));
|
|
472
|
+
}
|
|
473
|
+
const issues = first(drawer, sel(ShopRole.CartIssues));
|
|
474
|
+
const words = cartIssueWords(view, lang).join(' ');
|
|
475
|
+
setText(wordsOf(issues), words);
|
|
476
|
+
setAttr(issues, 'role', words ? 'alert' : null);
|
|
477
|
+
setAttr(issues, SHOP_HIDDEN_ATTRIBUTE, words ? null : '');
|
|
478
|
+
const note = first(drawer, sel(ShopRole.CartShippingNote));
|
|
479
|
+
const gap = view.freeShippingRemaining && view.freeShippingRemaining.amount > 0 ? formatMoney(view.freeShippingRemaining, lang) : '';
|
|
480
|
+
setText(wordsOf(note), gap ? shopWord(ShopWord.FreeShippingGap, lang, { amount: gap }) : '');
|
|
481
|
+
setAttr(note, SHOP_HIDDEN_ATTRIBUTE, gap ? null : '');
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private stampLine(el: HTMLElement, line: CartViewLine): void {
|
|
486
|
+
const lang = this.lang;
|
|
487
|
+
setAttr(el, CART_LINE_ATTRIBUTE, line.lineId);
|
|
488
|
+
const image = first(el, sel(ShopRole.CartLineImage));
|
|
489
|
+
const img = image?.tagName === 'IMG' ? image as HTMLImageElement : image?.querySelector('img');
|
|
490
|
+
if (img) {
|
|
491
|
+
if (line.image && img.getAttribute('src') !== line.image) img.setAttribute('src', line.image);
|
|
492
|
+
setAttr(img, 'alt', '');
|
|
493
|
+
}
|
|
494
|
+
setText(wordsOf(first(el, sel(ShopRole.CartLineTitle))), line.title);
|
|
495
|
+
const variant = first(el, sel(ShopRole.CartLineVariant));
|
|
496
|
+
setText(wordsOf(variant), line.variantName ?? '');
|
|
497
|
+
setAttr(variant, SHOP_HIDDEN_ATTRIBUTE, line.variantName ? null : '');
|
|
498
|
+
setText(wordsOf(first(el, sel(ShopRole.CartLineTotal))), formatMoney(line.lineTotal, lang));
|
|
499
|
+
const quantity = first(el, sel(ShopRole.Quantity));
|
|
500
|
+
if (quantity) this.stampQuantity(quantity, line.quantity, { min: 1, max: line.maxQuantity });
|
|
501
|
+
setAttr(first(el, sel(ShopRole.CartLineRemove)), 'aria-label', shopWord(ShopWord.Remove, lang, { name: line.title }));
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
private markAdded(button: Element): void {
|
|
505
|
+
const previous = this.addedTimers.get(button);
|
|
506
|
+
if (previous) clearTimeout(previous);
|
|
507
|
+
syncAddedWords(button, true);
|
|
508
|
+
announce(this.scope, shopWord(ShopWord.Added, this.lang));
|
|
509
|
+
this.addedTimers.set(button, setTimeout(() => {
|
|
510
|
+
this.addedTimers.delete(button);
|
|
511
|
+
syncAddedWords(button, false);
|
|
512
|
+
}, ADDED_HOLD_MS));
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
private refusalWords(error: unknown): string {
|
|
516
|
+
const code = error instanceof CartTransportError ? error.code : CartTransportErrorCode.Network;
|
|
517
|
+
const label = CART_TRANSPORT_ERROR_LABELS[code];
|
|
518
|
+
return this.lang.toLowerCase().startsWith('he') ? label.he : label.en;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
private refuse(words: string, error: unknown): void {
|
|
522
|
+
announce(this.scope, words);
|
|
523
|
+
this.host.onRefused?.(words, error);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// ── events ────────────────────────────────────────────────────────────────────────────────
|
|
527
|
+
|
|
528
|
+
private async changeLine(line: Element, quantity: number | null): Promise<void> {
|
|
529
|
+
const id = line.getAttribute(CART_LINE_ATTRIBUTE);
|
|
530
|
+
if (!id) return;
|
|
531
|
+
try {
|
|
532
|
+
this.setCart(quantity === null ? await this.host.transport.remove(id) : await this.host.transport.setQuantity(id, quantity));
|
|
533
|
+
} catch (error) {
|
|
534
|
+
this.refuse(this.refusalWords(error), error);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
private readonly onClick = (event: Event): void => {
|
|
539
|
+
const target = event.target as Element | null;
|
|
540
|
+
if (!target?.closest) return;
|
|
541
|
+
const copy = target.closest(CLONE) as HTMLElement | null;
|
|
542
|
+
if (copy && this.host.onCloneClick) this.selectTemplateOf(copy, target);
|
|
543
|
+
const step = target.closest(`${sel(ShopRole.QuantityDown)}, ${sel(ShopRole.QuantityUp)}`);
|
|
544
|
+
if (step) {
|
|
545
|
+
if (step.getAttribute('aria-disabled') === 'true') return;
|
|
546
|
+
const dir = step.matches(sel(ShopRole.QuantityUp)) ? QuantityStep.Up : QuantityStep.Down;
|
|
547
|
+
const line = step.closest(`[${CART_LINE_ATTRIBUTE}]`);
|
|
548
|
+
if (line) {
|
|
549
|
+
const known = this.cart.lines.find(l => l.lineId === line.getAttribute(CART_LINE_ATTRIBUTE));
|
|
550
|
+
if (known) void this.changeLine(line, stepQuantity(known.quantity, dir, { min: 1, max: known.maxQuantity }));
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
const state = this.stateFor(step);
|
|
554
|
+
if (!state) return;
|
|
555
|
+
state.quantity = stepQuantity(state.quantity, dir, this.boundsOf(state));
|
|
556
|
+
this.pageProduct = String(state.product._id);
|
|
557
|
+
this.stamp();
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
const remove = target.closest(sel(ShopRole.CartLineRemove));
|
|
561
|
+
const removeLine = remove?.closest(`[${CART_LINE_ATTRIBUTE}]`);
|
|
562
|
+
if (removeLine) { void this.changeLine(removeLine, null); return; }
|
|
563
|
+
if (target.closest(sel(ShopRole.CartButton))) { this.openCart(); return; }
|
|
564
|
+
if (target.closest(sel(ShopRole.Checkout)) && !this.cart.empty) this.host.goToCheckout?.();
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
private readonly onChange = (event: Event): void => {
|
|
568
|
+
const select = (event.target as Element | null)?.closest?.(`select.${SHOP_SELECT_CLASS}`) as HTMLSelectElement | null;
|
|
569
|
+
if (!select) return;
|
|
570
|
+
const state = this.stateFor(select);
|
|
571
|
+
const option = select.getAttribute('data-iox-option');
|
|
572
|
+
if (state && option) this.choose(state, option, select.value);
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
/** A copy is display-only on the canvas: a click on it (or a part inside it) selects the template's part. */
|
|
576
|
+
private selectTemplateOf(copy: HTMLElement, target: Element): void {
|
|
577
|
+
const template = this.templateOf(copy);
|
|
578
|
+
if (!template) return;
|
|
579
|
+
const path: number[] = [];
|
|
580
|
+
for (let el: Element | null = target; el && el !== copy; el = el.parentElement) {
|
|
581
|
+
path.unshift(Array.prototype.indexOf.call(el.parentElement?.children ?? [], el));
|
|
582
|
+
}
|
|
583
|
+
let part: Element = template;
|
|
584
|
+
for (const i of path) part = part.children[i] ?? part;
|
|
585
|
+
// The bubble that follows would select whatever ancestor has a listener; the template's part wins.
|
|
586
|
+
target.addEventListener('click', e => e.stopPropagation(), { once: true });
|
|
587
|
+
this.host.onCloneClick?.(part as HTMLElement);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
private templateOf(copy: HTMLElement): HTMLElement | null {
|
|
591
|
+
const mark = copy.getAttribute(SHOP_CLONE_ATTRIBUTE);
|
|
592
|
+
for (let prev = copy.previousElementSibling; prev; prev = prev.previousElementSibling) {
|
|
593
|
+
if (!prev.hasAttribute(SHOP_CLONE_ATTRIBUTE) && Array.from(prev.classList).some(c => c === roleClass(mark))) return prev as HTMLElement;
|
|
594
|
+
}
|
|
595
|
+
return null;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** Attach the shop runtime to a page scope, unless one runs there already. */
|
|
600
|
+
export function attachShop(scope: HTMLElement, host: ShopHost): ShopRuntime {
|
|
601
|
+
return SCOPES.get(scope) ?? new ShopRuntime(scope, host);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** The shop runtime an element sits under, or null. */
|
|
605
|
+
export function shopRuntimeOf(el: Element | null | undefined): ShopRuntime | null {
|
|
606
|
+
for (let cur: Element | null | undefined = el; cur; cur = cur.parentElement) {
|
|
607
|
+
const rt = SCOPES.get(cur);
|
|
608
|
+
if (rt) return rt;
|
|
609
|
+
}
|
|
610
|
+
return null;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** The shop actions (actions-core `SHOP_ACTION_TYPES`). */
|
|
614
|
+
export enum ShopActionType {
|
|
615
|
+
AddToCart = 'addToCart',
|
|
616
|
+
StartCheckout = 'startCheckout',
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** Run a shop action from the element that fired it (both interaction engines call this). False when no shop runs. */
|
|
620
|
+
export async function runShopAction(el: Element, type: string): Promise<boolean> {
|
|
621
|
+
const rt = shopRuntimeOf(el);
|
|
622
|
+
if (!rt) return false;
|
|
623
|
+
if (type === ShopActionType.AddToCart) return !!(await rt.add(el));
|
|
624
|
+
if (type === ShopActionType.StartCheckout) return rt.buyNow(el);
|
|
625
|
+
return false;
|
|
626
|
+
}
|