@wix/himalaya-cli 0.1648.0 → 0.1649.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/package.json +2 -2
- package/template-icons/wholesale-store.png +0 -0
- package/templates/wholesale-store/README.md +53 -0
- package/templates/wholesale-store/config.ts +247 -0
- package/templates/wholesale-store/dev/index.ts +12194 -0
- package/templates/wholesale-store/himalaya.content.json +43 -0
- package/templates/wholesale-store/himalaya.template.json +14 -0
- package/templates/wholesale-store/icon.png +0 -0
- package/templates/wholesale-store/platforms.json +1 -0
- package/templates/wholesale-store/tier5-src/_shared/app-locale.ts +61 -0
- package/templates/wholesale-store/tier5-src/_shared/branded-lite-hosted.ts +279 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-copy.ts +40 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-history.ts +51 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-message-model.ts +177 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-model.ts +56 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-presenter.ts +576 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +148 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-contract.ts +228 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-query-legacy.ts +194 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-query.ts +252 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-service.ts +423 -0
- package/templates/wholesale-store/tier5-src/_shared/detail-presence.ts +51 -0
- package/templates/wholesale-store/tier5-src/_shared/empty-flags.ts +33 -0
- package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +508 -0
- package/templates/wholesale-store/tier5-src/_shared/exclusive-writes.ts +66 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-account.ts +164 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-copy.ts +89 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-categories.ts +108 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-collection.ts +22 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-saved.ts +57 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store.ts +7 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-text.ts +24 -0
- package/templates/wholesale-store/tier5-src/_shared/hosted-checkout.ts +70 -0
- package/templates/wholesale-store/tier5-src/_shared/iap-presentation.ts +207 -0
- package/templates/wholesale-store/tier5-src/_shared/iap-worker.ts +125 -0
- package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +68 -0
- package/templates/wholesale-store/tier5-src/_shared/live-session.ts +172 -0
- package/templates/wholesale-store/tier5-src/_shared/local-preferences.ts +38 -0
- package/templates/wholesale-store/tier5-src/_shared/member-access.ts +52 -0
- package/templates/wholesale-store/tier5-src/_shared/member-account-routes.ts +52 -0
- package/templates/wholesale-store/tier5-src/_shared/member-orders.ts +8 -0
- package/templates/wholesale-store/tier5-src/_shared/member-screen.ts +99 -0
- package/templates/wholesale-store/tier5-src/_shared/online-actions.ts +76 -0
- package/templates/wholesale-store/tier5-src/_shared/owner-editor-value.ts +164 -0
- package/templates/wholesale-store/tier5-src/_shared/owner-load-error.ts +348 -0
- package/templates/wholesale-store/tier5-src/_shared/payment-setup.ts +6 -0
- package/templates/wholesale-store/tier5-src/_shared/read-service.ts +255 -0
- package/templates/wholesale-store/tier5-src/_shared/restaurant-ordering.ts +201 -0
- package/templates/wholesale-store/tier5-src/_shared/rich-body.ts +78 -0
- package/templates/wholesale-store/tier5-src/_shared/rich-content-link.ts +34 -0
- package/templates/wholesale-store/tier5-src/_shared/sign-in-sheet.ts +18 -0
- package/templates/wholesale-store/tier5-src/_shared/store-order-presentation.ts +56 -0
- package/templates/wholesale-store/tier5-src/_shared/store-product-info.ts +50 -0
- package/templates/wholesale-store/tier5-src/business-chat/index.ts +724 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-cart/index.ts +602 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-order/index.ts +472 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-orders/index.ts +327 -0
- package/templates/wholesale-store/tier5-src/himi-store-account/index.ts +998 -0
- package/templates/wholesale-store/tier5-src/himi-store-product/index.ts +889 -0
- package/templates/wholesale-store/tier5-src/himi-store-saved/index.ts +68 -0
- package/templates/wholesale-store/tier5-src/himi-store-shop/index.ts +150 -0
- package/templates/wholesale-store/tier5-src/himi-wholesale-home/index.ts +507 -0
- package/templates/wholesale-store/tier5-src/wix-spaces-collection-detail/index.ts +195 -0
- package/templates/wholesale-store/tokens.json +340 -0
|
@@ -0,0 +1,889 @@
|
|
|
1
|
+
import { withReadLifecycle, readOptions } from "../_shared/read-service.js";
|
|
2
|
+
import { withOnlineWrites, offlineWritesEnabled, offlineWriteMessage } from "../_shared/online-actions.js";
|
|
3
|
+
import { defineService as registerState } from "@himalaya/state";
|
|
4
|
+
// Tier-5 bundle: himi-store — product detail.
|
|
5
|
+
import { withIapPresentation } from "../_shared/iap-presentation.js";
|
|
6
|
+
import { storesAppleSalesEnabled, storesProductOrders, type IapCommerce, type IapPurchaseFields } from "@himalaya/iap-checkout";
|
|
7
|
+
import { iapPriceCopy, iapPurchaseCopy } from "../_shared/iap-worker.js";
|
|
8
|
+
import { share as shareSheet } from "@himalaya/share";
|
|
9
|
+
import { addToCurrentCart, getCurrentCart } from "@himalaya/wix-ecom";
|
|
10
|
+
import { upsert, enqueue, type DbEntity } from "@himalaya/local-db";
|
|
11
|
+
|
|
12
|
+
async function cartPut(row: DbEntity): Promise<void> { try { await upsert("cart", row); } catch { /* capability not granted */ } }
|
|
13
|
+
async function queueWrite(actionId: string, params: Record<string, string>): Promise<void> { try { await enqueue(actionId, params); } catch { /* capability not granted */ } }
|
|
14
|
+
import { getStoreProduct, plainText, productImage, productPrice, wixMediaUrl, productGallery as sdkProductGallery, WIX_DETAIL_IMAGE, type StoreProduct,
|
|
15
|
+
productOptions, defaultSelection, isSelectionComplete, selectionSummary, cartOptionsPayload,
|
|
16
|
+
type StoreOption, type StoreOptionChoice, type StoreOptionSelection } from "../_shared/himi-store.js";
|
|
17
|
+
import { cleanTitle } from "../_shared/himi-text.js";
|
|
18
|
+
import { stashCopy, copyParam, copyTemplate } from "../_shared/himi-copy.js";
|
|
19
|
+
import { isBridgeUnavailable } from "../_shared/owner-load-error.js";
|
|
20
|
+
import { isProductSaved, toggleSavedProduct } from "../_shared/himi-store-saved.js";
|
|
21
|
+
import { openRichLink } from "../_shared/rich-content-link.js";
|
|
22
|
+
import { descriptionBody } from "../_shared/rich-body.js";
|
|
23
|
+
import { PRODUCT_DETAIL_FIELDS, productInfoSections, type ProductInfoSection } from "../_shared/store-product-info.js";
|
|
24
|
+
|
|
25
|
+
/** Live cart size (sum of line-item quantities) for the top-bar cart badge.
|
|
26
|
+
* Best-effort: a cart error just yields 0 (badge hidden), never fails the screen. */
|
|
27
|
+
async function cartItemCount(): Promise<number> {
|
|
28
|
+
try {
|
|
29
|
+
const cart = await getCurrentCart();
|
|
30
|
+
return (cart.lineItems ?? []).reduce((n, li) => n + (li.quantity ?? 1), 0);
|
|
31
|
+
} catch {
|
|
32
|
+
return 0;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface GalleryItem {
|
|
37
|
+
id: string;
|
|
38
|
+
url: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface OptionChip {
|
|
42
|
+
id: string;
|
|
43
|
+
label: string;
|
|
44
|
+
swatch?: string;
|
|
45
|
+
disabled?: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ---------------------------------------------------------------------------
|
|
49
|
+
// Product options (Colour, Size, …)
|
|
50
|
+
//
|
|
51
|
+
// A product with options is not buyable without them: the cart line goes out with
|
|
52
|
+
// no colour and no size, and the merchant cannot fulfil the order. The reader and
|
|
53
|
+
// the cart payload live in @himalaya/wix-stores (one reader, both catalogs, and a
|
|
54
|
+
// cart payload that is catalog-specific in a way a per-app copy gets wrong) — this
|
|
55
|
+
// worker only holds the shopper's choice and hides the slots it does not need.
|
|
56
|
+
//
|
|
57
|
+
// THREE fixed slots, because a screen descriptor is static: it cannot loop over N
|
|
58
|
+
// groups when N is unknown at authoring time. Catalog V3 allows up to 6. A product
|
|
59
|
+
// with more groups than slots is NOT silently half-configured — the overflow hint
|
|
60
|
+
// renders and Add to cart stays disabled, because a line item for the wrong variant
|
|
61
|
+
// is worse than one the shopper cannot place yet. Give the descriptor a bounded
|
|
62
|
+
// repeater and this cap goes away.
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
const OPTION_SLOTS = 3;
|
|
65
|
+
|
|
66
|
+
/** The raw product behind the current screen. NOT in published state: the V3 cart
|
|
67
|
+
* payload is resolved from `variantsInfo`, which no renderer needs to see. */
|
|
68
|
+
let lastProduct: StoreProduct | undefined;
|
|
69
|
+
|
|
70
|
+
/** Match only merchant-authored product sections with a clear policy title. */
|
|
71
|
+
function productPolicyBody(product: StoreProduct, kind: "returns" | "shipping"): string {
|
|
72
|
+
const sections = [...(product.infoSections ?? []), ...(product.additionalInfoSections ?? [])];
|
|
73
|
+
const section = sections.find((item) => {
|
|
74
|
+
const name = `${item.title ?? ""} ${"uniqueName" in item ? item.uniqueName ?? "" : ""}`;
|
|
75
|
+
return kind === "returns" ? /return|refund/i.test(name) : /shipping|delivery/i.test(name);
|
|
76
|
+
});
|
|
77
|
+
if (!section) return "";
|
|
78
|
+
const html = "plainDescription" in section ? section.plainDescription : undefined;
|
|
79
|
+
return descriptionBody(html || section.description).bodyText;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The product id `lastProduct` was read for. A pooled screen re-appearing calls
|
|
83
|
+
* `refreshServices()` → `load()`, so this is what tells a genuine navigation to a
|
|
84
|
+
* DIFFERENT product (drop the picks) from the same product coming back (keep them). */
|
|
85
|
+
let lastLoadedId: string | undefined;
|
|
86
|
+
let productLoadSequence = 0;
|
|
87
|
+
|
|
88
|
+
interface OptionSlots {
|
|
89
|
+
opt1Label: string; opt1Chips: OptionChip[]; opt1Selected: string[]; opt1SelectedId: string; opt1Placeholder: string; noOpt1: boolean;
|
|
90
|
+
opt2Label: string; opt2Chips: OptionChip[]; opt2Selected: string[]; opt2SelectedId: string; opt2Placeholder: string; noOpt2: boolean;
|
|
91
|
+
opt3Label: string; opt3Chips: OptionChip[]; opt3Selected: string[]; opt3SelectedId: string; opt3Placeholder: string; noOpt3: boolean;
|
|
92
|
+
opt1Error: string; noOpt1Error: boolean; hasOpt1Error: boolean; opt2Error: string; noOpt2Error: boolean; hasOpt2Error: boolean; opt3Error: string; noOpt3Error: boolean; hasOpt3Error: boolean;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function slotsOf(groups: StoreOption[], selection: StoreOptionSelection, showErrors: boolean): OptionSlots {
|
|
96
|
+
const out = {} as Record<string, unknown>;
|
|
97
|
+
for (let i = 0; i < OPTION_SLOTS; i++) {
|
|
98
|
+
const g = groups[i];
|
|
99
|
+
const n = i + 1;
|
|
100
|
+
const chosen = g ? selection[g.id] ?? "" : "";
|
|
101
|
+
const displayName = g?.name ? g.name.charAt(0).toUpperCase() + g.name.slice(1).toLowerCase() : "";
|
|
102
|
+
out[`opt${n}Label`] = displayName ? copyTemplate("product.optionLabel", "{option}:", { option: displayName }) : "";
|
|
103
|
+
// Out-of-stock choices stay selectable but say so — hiding them makes a product
|
|
104
|
+
// look like it has fewer colours than it does, and the stock flag is per-choice
|
|
105
|
+
// across variants, not a promise about the combination.
|
|
106
|
+
out[`opt${n}Chips`] = (g?.choices ?? []).map((c) => ({ id: c.id, label: c.label, ...(g.kind === "color" && c.colorCode ? { swatch: c.colorCode } : {}), disabled: c.inStock === false }));
|
|
107
|
+
out[`opt${n}Selected`] = chosen ? [chosen] : [];
|
|
108
|
+
out[`opt${n}SelectedId`] = chosen;
|
|
109
|
+
out[`opt${n}Placeholder`] = g?.choices.find(c => c.id === chosen)?.label ?? copyTemplate("product.optionPlaceholder", "Select {option}", { option: displayName || "option" });
|
|
110
|
+
const error = showErrors && g && !chosen ? copyTemplate("product.optionRequired", "Select a {option}", { option: g.name.toLowerCase() }) : "";
|
|
111
|
+
out[`opt${n}Error`] = error;
|
|
112
|
+
out[`noOpt${n}Error`] = !error;
|
|
113
|
+
out[`hasOpt${n}Error`] = !!error;
|
|
114
|
+
out[`noOpt${n}`] = !g;
|
|
115
|
+
}
|
|
116
|
+
return out as unknown as OptionSlots;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The chosen choice that cannot be bought, if any. A chip stays SELECTABLE when it
|
|
120
|
+
* is out of stock — hiding it makes a product look like it has fewer colours than it
|
|
121
|
+
* does — but picking it must not reach the cart: the add was accepted and only failed
|
|
122
|
+
* at purchase, which is the worst place to learn it. */
|
|
123
|
+
function outOfStockPick(groups: StoreOption[], selection: StoreOptionSelection): StoreOptionChoice | undefined {
|
|
124
|
+
for (const g of groups) {
|
|
125
|
+
const chosen = g.choices.find((c) => c.id === selection[g.id]);
|
|
126
|
+
if (chosen && chosen.inStock === false) return chosen;
|
|
127
|
+
}
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** What to say under the picker: the groups still unchosen, else the choice made. */
|
|
132
|
+
function optionsHint(groups: StoreOption[], selection: StoreOptionSelection): string {
|
|
133
|
+
const missing = groups.filter((g) => !selection[g.id]).map((g) => g.name);
|
|
134
|
+
if (!missing.length) {
|
|
135
|
+
const blocked = outOfStockPick(groups, selection);
|
|
136
|
+
return blocked
|
|
137
|
+
? copyTemplate("product.optionOutOfStockHint", "{choice} is out of stock. Choose another.", { choice: blocked.label })
|
|
138
|
+
: selectionSummary(groups, selection);
|
|
139
|
+
}
|
|
140
|
+
return copyTemplate("product.optionsChoose", "Choose {options}", { options: missing.join(", ") });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Catalog V3 returns Ricos objects or serialized documents; V1 returns HTML.
|
|
144
|
+
* Keep plainDescription as the independent fallback, never raw document JSON. */
|
|
145
|
+
function productBody(p: StoreProduct): { description: string; descriptionJson: string } {
|
|
146
|
+
const raw = (p as { description?: unknown }).description;
|
|
147
|
+
const html = descriptionBody(p.plainDescription).bodyText;
|
|
148
|
+
const { bodyJson, bodyText } = descriptionBody(raw, html);
|
|
149
|
+
return { description: html || bodyText, descriptionJson: bodyJson };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function productSale(p: StoreProduct): { price: string; wasPrice: string } {
|
|
153
|
+
const raw = p as unknown as { priceData?: Record<string, unknown> };
|
|
154
|
+
const pd = raw.priceData ?? {};
|
|
155
|
+
const formatted = (pd.formatted ?? {}) as Record<string, unknown>;
|
|
156
|
+
const regular = productPrice(p);
|
|
157
|
+
if (p.compareAtPriceRange?.minValue) {
|
|
158
|
+
const original = productPrice({ ...p, price: undefined, priceData: undefined, actualPriceRange: p.compareAtPriceRange });
|
|
159
|
+
if (original && original !== regular) return { price: regular, wasPrice: original };
|
|
160
|
+
}
|
|
161
|
+
const rawRegular = typeof formatted.price === "string" ? formatted.price : regular;
|
|
162
|
+
const saleRaw = formatted.discountedPrice ?? pd.discountedPrice ?? pd.salePrice;
|
|
163
|
+
const sale = typeof saleRaw === "string" ? saleRaw : "";
|
|
164
|
+
const saleDisplay = sale ? productPrice({ ...p, priceData: { ...pd, formatted: { ...formatted, price: sale } } } as StoreProduct) : "";
|
|
165
|
+
return sale && sale !== rawRegular ? { price: saleDisplay, wasPrice: regular } : { price: regular, wasPrice: "" };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The optimistic cart has no Wix-calculated line price yet. Multiply the formatted
|
|
169
|
+
* unit amount while preserving its symbol, separators and decimal precision. */
|
|
170
|
+
function optimisticLineTotal(unitPrice: string, quantity: number): string {
|
|
171
|
+
if (quantity <= 1) return unitPrice;
|
|
172
|
+
const match = /\d(?:[\d.,]|[ \u00a0\u202f](?=\d))*/u.exec(unitPrice);
|
|
173
|
+
if (!match) return "";
|
|
174
|
+
const raw = match[0];
|
|
175
|
+
const compact = raw.replace(/[ \u00a0\u202f]/g, "");
|
|
176
|
+
const last = Math.max(compact.lastIndexOf("."), compact.lastIndexOf(","));
|
|
177
|
+
const fractionalDigits = last >= 0 ? compact.length - last - 1 : 0;
|
|
178
|
+
const decimal = fractionalDigits > 0 && fractionalDigits <= 2 ? compact[last] : "";
|
|
179
|
+
const punctuationGrouping = decimal === "." ? "," : decimal === "," ? "." : compact.includes(",") ? "," : compact.includes(".") ? "." : "";
|
|
180
|
+
const grouping = raw.match(/[ \u00a0\u202f](?=\d)/u)?.[0] ?? punctuationGrouping;
|
|
181
|
+
const amount = Number(compact.replaceAll(punctuationGrouping || "\u0000", "").replace(decimal || "\u0000", "."));
|
|
182
|
+
if (!Number.isFinite(amount)) return "";
|
|
183
|
+
const fixed = (amount * quantity).toFixed(decimal ? fractionalDigits : 0);
|
|
184
|
+
const [whole, fraction] = fixed.split(".");
|
|
185
|
+
const grouped = grouping ? whole.replace(/\B(?=(\d{3})+(?!\d))/g, grouping) : whole;
|
|
186
|
+
return unitPrice.replace(raw, `${grouped}${decimal ? decimal + fraction : ""}`);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function skuOf(p: StoreProduct): string {
|
|
190
|
+
const raw = p as unknown as { sku?: unknown; variantsInfo?: { variants?: Array<{ sku?: unknown }> } };
|
|
191
|
+
if (typeof raw.sku === "string" && raw.sku.trim()) return raw.sku.trim();
|
|
192
|
+
const sku = raw.variantsInfo?.variants?.find(v => typeof v.sku === "string" && v.sku.trim())?.sku;
|
|
193
|
+
return typeof sku === "string" ? sku.trim() : "";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
interface S {
|
|
197
|
+
status: "loading" | "ready" | "error";
|
|
198
|
+
name: string;
|
|
199
|
+
price: string;
|
|
200
|
+
wasPrice: string;
|
|
201
|
+
notOnSale: boolean;
|
|
202
|
+
wasPriceEmpty: boolean;
|
|
203
|
+
noSku: boolean;
|
|
204
|
+
skuLabel: string;
|
|
205
|
+
infoSections: ProductInfoSection[];
|
|
206
|
+
returnPolicyBody: string;
|
|
207
|
+
shippingInfoBody: string;
|
|
208
|
+
noReturnPolicyBody: boolean;
|
|
209
|
+
noShippingInfoBody: boolean;
|
|
210
|
+
returnPolicyCollapsed: boolean;
|
|
211
|
+
shippingInfoCollapsed: boolean;
|
|
212
|
+
noSaveHint: boolean;
|
|
213
|
+
saveIcon: string;
|
|
214
|
+
optionsSummary: string;
|
|
215
|
+
quantityLabel: string;
|
|
216
|
+
quantityIsOne: boolean;
|
|
217
|
+
addedSheetPresented: boolean;
|
|
218
|
+
shareHint: string;
|
|
219
|
+
noShareHint: boolean;
|
|
220
|
+
noCartHint: boolean;
|
|
221
|
+
hideBar: boolean;
|
|
222
|
+
hideProduct: boolean;
|
|
223
|
+
commercePrice?: string;
|
|
224
|
+
/** The plain-text description: RichContent's fallback, and what shows with no document. */
|
|
225
|
+
description: string;
|
|
226
|
+
/** [rico] #3372 — a V3 product's Ricos `description` (read with `fields=DESCRIPTION`) as ONE document string
|
|
227
|
+
* for RichContent; "" for a V1 HTML description, none, or a document the encoder rejected. */
|
|
228
|
+
descriptionJson: string;
|
|
229
|
+
/** descriptionJson !== "" — gates the plain text, because RichContent draws nothing for "". */
|
|
230
|
+
hasDescriptionJson: boolean;
|
|
231
|
+
returnPolicyExpanded: boolean;
|
|
232
|
+
shippingInfoExpanded: boolean;
|
|
233
|
+
image: string;
|
|
234
|
+
/** FULL media gallery (media.items[] with the main image first) — the detail
|
|
235
|
+
* screen renders a Carousel over it when 2+ images exist. */
|
|
236
|
+
gallery: GalleryItem[];
|
|
237
|
+
galleryIndex: number;
|
|
238
|
+
galleryLabel: string;
|
|
239
|
+
hasGallery: boolean;
|
|
240
|
+
noGallery: boolean;
|
|
241
|
+
initial: string;
|
|
242
|
+
/** Share payload — the product page URL when the payload carries one. */
|
|
243
|
+
shareUrl: string;
|
|
244
|
+
cartHint: string;
|
|
245
|
+
cartCount: number;
|
|
246
|
+
/** An add-to-cart write is in flight (pending line under the CTA). */
|
|
247
|
+
adding: boolean;
|
|
248
|
+
addLabel: string;
|
|
249
|
+
notAdding: boolean;
|
|
250
|
+
/** The last add succeeded (confirmation + View cart under the CTA). */
|
|
251
|
+
added: boolean;
|
|
252
|
+
notAdded: boolean;
|
|
253
|
+
emptyText: string;
|
|
254
|
+
isLoading: boolean;
|
|
255
|
+
notLoading: boolean;
|
|
256
|
+
hideContent: boolean;
|
|
257
|
+
isErrored: boolean;
|
|
258
|
+
notErrored: boolean;
|
|
259
|
+
noEmpty: boolean;
|
|
260
|
+
hasImage: boolean;
|
|
261
|
+
noImage: boolean;
|
|
262
|
+
/** True when the single hero image should render (an image exists but there is
|
|
263
|
+
* no multi-image gallery to carousel). */
|
|
264
|
+
hasSingleImage: boolean;
|
|
265
|
+
noSingleImage: boolean;
|
|
266
|
+
/** Quantity picked via the on-screen stepper (default 1) — addToCart adds
|
|
267
|
+
* exactly this many, not a hardcoded 1. */
|
|
268
|
+
quantity: number;
|
|
269
|
+
saved: boolean;
|
|
270
|
+
saveLabel: string;
|
|
271
|
+
saveHint: string;
|
|
272
|
+
/** The product's option groups, in site order — the source the slots below and
|
|
273
|
+
* the cart payload are derived from. */
|
|
274
|
+
optionGroups: StoreOption[];
|
|
275
|
+
/** option id → chosen choice id. A group the shopper has not picked is absent. */
|
|
276
|
+
selection: StoreOptionSelection;
|
|
277
|
+
hasOptions: boolean;
|
|
278
|
+
noOptions: boolean;
|
|
279
|
+
/** More option groups than the descriptor has slots — see OPTION_SLOTS. */
|
|
280
|
+
optionsOverflow: boolean;
|
|
281
|
+
noOptionsOverflow: boolean;
|
|
282
|
+
/** Add to cart is blocked: this product has options and they are not all chosen. */
|
|
283
|
+
optionsIncomplete: boolean;
|
|
284
|
+
showOptionErrors: boolean;
|
|
285
|
+
optionValidationRequest: number;
|
|
286
|
+
optionValidationTarget: string;
|
|
287
|
+
opt1ScrollRequest: string;
|
|
288
|
+
opt2ScrollRequest: string;
|
|
289
|
+
opt3ScrollRequest: string;
|
|
290
|
+
addDisabled: boolean;
|
|
291
|
+
/** The product was served from the offline cache, which carries no option groups.
|
|
292
|
+
* "No groups" here means UNKNOWN, not "none" — so the CTA must stay blocked rather
|
|
293
|
+
* than offer a one-tap add for a product that may need a colour and a size. */
|
|
294
|
+
optionsUnknown: boolean;
|
|
295
|
+
optionsHint: string;
|
|
296
|
+
opt1Label: string; opt1Chips: OptionChip[]; opt1Selected: string[]; opt1SelectedId: string; opt1Placeholder: string; noOpt1: boolean;
|
|
297
|
+
opt2Label: string; opt2Chips: OptionChip[]; opt2Selected: string[]; opt2SelectedId: string; opt2Placeholder: string; noOpt2: boolean;
|
|
298
|
+
opt3Label: string; opt3Chips: OptionChip[]; opt3Selected: string[]; opt3SelectedId: string; opt3Placeholder: string; noOpt3: boolean;
|
|
299
|
+
opt1Error: string; noOpt1Error: boolean; hasOpt1Error: boolean; opt2Error: string; noOpt2Error: boolean; hasOpt2Error: boolean; opt3Error: string; noOpt3Error: boolean; hasOpt3Error: boolean;
|
|
300
|
+
/** The App Store action (`commerce.purchaseFields`), in place of Add to cart while it shows. */
|
|
301
|
+
cartHidden: boolean;
|
|
302
|
+
buyHidden: boolean;
|
|
303
|
+
buyLabel: string;
|
|
304
|
+
buyDisabled: boolean;
|
|
305
|
+
buyNote: string;
|
|
306
|
+
/** Shown once the eCom order reads paid, never on the payment's approval alone. */
|
|
307
|
+
purchasedNote: string;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function inputId(): string {
|
|
311
|
+
// WS-C — `himalaya.input.id` is the PRIMARY contract: hosts thread the row's
|
|
312
|
+
// `id` nav param (himi.open { screenId: "himi_product", id }) into worker input.
|
|
313
|
+
// The screenId-slice below is #570 back-compat for pre-params releases with
|
|
314
|
+
// baked `himi_product_<id>` screenIds — do not author against this.
|
|
315
|
+
const input = (globalThis as { himalaya?: { input?: { id?: string; screenId?: string } } }).himalaya?.input;
|
|
316
|
+
if (input?.id) return input.id;
|
|
317
|
+
return input?.screenId?.startsWith("himi_product_") ? input.screenId.slice("himi_product_".length) : "";
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Every usable image URL in the product's media payload (main first, deduped). */
|
|
321
|
+
export function productGallery(p: StoreProduct): GalleryItem[] {
|
|
322
|
+
const urls: string[] = [];
|
|
323
|
+
const push = (url?: string) => {
|
|
324
|
+
const trimmed = (url ?? "").trim();
|
|
325
|
+
if (trimmed && !urls.includes(trimmed)) urls.push(trimmed);
|
|
326
|
+
};
|
|
327
|
+
// Detail budget, not the list budget: this gallery is a full-bleed hero. Every
|
|
328
|
+
// entry goes through the same CDN transform — the primary AND the extra media
|
|
329
|
+
// items, which would otherwise stay untouched 4000px originals.
|
|
330
|
+
push(productImage(p, WIX_DETAIL_IMAGE));
|
|
331
|
+
// The SDK helper reads BOTH gallery layouts — V1 `media.items` and Catalog V3
|
|
332
|
+
// `media.itemsInfo.items`. This loop used to walk `media.items` itself, which is
|
|
333
|
+
// the V1 spelling only, so a V3 product with a ten-image gallery rendered as one
|
|
334
|
+
// image no matter what the read asked for. One reader, not a private copy per
|
|
335
|
+
// worker — that is how the two layouts drifted apart in the first place.
|
|
336
|
+
for (const url of sdkProductGallery(p, WIX_DETAIL_IMAGE)) push(url);
|
|
337
|
+
for (const group of productOptions(p, WIX_DETAIL_IMAGE)) for (const choice of group.choices) push(choice.image);
|
|
338
|
+
return urls.map((url) => ({ id: url, url }));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** The product's public page URL when the payload carries one ("" otherwise) —
|
|
342
|
+
* probed off the RAW payload so a site-specific URL never gets baked into the
|
|
343
|
+
* descriptor (templates stay site-neutral; text-only share is the fallback). */
|
|
344
|
+
function productShareUrl(p: StoreProduct): string {
|
|
345
|
+
const raw = p as unknown as {
|
|
346
|
+
url?: unknown;
|
|
347
|
+
productPageUrl?: { base?: string; path?: string } | string;
|
|
348
|
+
};
|
|
349
|
+
if (typeof raw.url === "string" && /^https?:\/\//i.test(raw.url)) return raw.url;
|
|
350
|
+
const page = raw.productPageUrl;
|
|
351
|
+
if (typeof page === "string" && /^https?:\/\//i.test(page)) return page;
|
|
352
|
+
if (page && typeof page === "object" && typeof page.base === "string" && page.base) {
|
|
353
|
+
const path = typeof page.path === "string" ? page.path : "";
|
|
354
|
+
return `${page.base.replace(/\/$/, "")}${path && !path.startsWith("/") ? "/" : ""}${path}`;
|
|
355
|
+
}
|
|
356
|
+
return "";
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function argValue(arg: unknown, key: string): string {
|
|
360
|
+
if (arg && typeof arg === "object") {
|
|
361
|
+
const value = (arg as Record<string, unknown>)[key];
|
|
362
|
+
if (typeof value === "string") return value;
|
|
363
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
364
|
+
}
|
|
365
|
+
return typeof arg === "string" ? arg : "";
|
|
366
|
+
}
|
|
367
|
+
/** Quantity from a stepper onChange arg: positive integer, clamped 1–99. */
|
|
368
|
+
function parseQuantity(raw: string): number | undefined {
|
|
369
|
+
const n = Math.floor(Number(raw));
|
|
370
|
+
if (!Number.isFinite(n) || n < 1) return undefined;
|
|
371
|
+
return Math.min(n, 99);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function derive(s: S): S {
|
|
375
|
+
const empty = s.status === "ready" && !s.name;
|
|
376
|
+
const galleryIndex = Math.min(Math.max(0, Math.floor(Number(s.galleryIndex) || 0)), Math.max(0, s.gallery.length - 1));
|
|
377
|
+
const hasGallery = s.gallery.length > 1;
|
|
378
|
+
const hasSingleImage = !!s.image && !hasGallery;
|
|
379
|
+
const groups = s.optionGroups;
|
|
380
|
+
const overflow = groups.length > OPTION_SLOTS;
|
|
381
|
+
const optionsIncomplete = s.optionsUnknown || !!outOfStockPick(groups, s.selection) || (groups.length > 0 && (overflow || !isSelectionComplete(groups, s.selection)));
|
|
382
|
+
return {
|
|
383
|
+
...s,
|
|
384
|
+
galleryIndex,
|
|
385
|
+
galleryLabel: s.gallery.length ? copyTemplate("product.galleryPage", "Image {index} of {count}", { index: String(galleryIndex + 1), count: String(s.gallery.length) }) : "",
|
|
386
|
+
notOnSale: !s.wasPrice,
|
|
387
|
+
wasPriceEmpty: !!s.wasPrice,
|
|
388
|
+
noSku: !s.skuLabel,
|
|
389
|
+
noReturnPolicyBody: !s.returnPolicyBody,
|
|
390
|
+
noShippingInfoBody: !s.shippingInfoBody,
|
|
391
|
+
returnPolicyCollapsed: !s.returnPolicyExpanded,
|
|
392
|
+
shippingInfoCollapsed: !s.shippingInfoExpanded,
|
|
393
|
+
noSaveHint: !s.saveHint,
|
|
394
|
+
noShareHint: !s.shareHint,
|
|
395
|
+
noCartHint: !s.cartHint || s.added,
|
|
396
|
+
hideBar: s.status !== "ready" || !s.name || s.addedSheetPresented,
|
|
397
|
+
hideProduct: s.status !== "ready" || !s.name,
|
|
398
|
+
saveIcon: s.saved ? "heart_fill" : "heart",
|
|
399
|
+
optionsSummary: selectionSummary(s.optionGroups, s.selection),
|
|
400
|
+
quantityLabel: `Qty: ${s.quantity}`,
|
|
401
|
+
quantityIsOne: s.quantity <= 1,
|
|
402
|
+
hasDescriptionJson: s.descriptionJson !== "",
|
|
403
|
+
...slotsOf(groups, s.selection, s.showOptionErrors),
|
|
404
|
+
hasOptions: groups.length > 0,
|
|
405
|
+
noOptions: groups.length === 0,
|
|
406
|
+
optionsOverflow: overflow,
|
|
407
|
+
noOptionsOverflow: !overflow,
|
|
408
|
+
// Overflow counts as incomplete on purpose: the shopper cannot choose a group
|
|
409
|
+
// the screen never rendered, so the only variant we could send would be a guess.
|
|
410
|
+
// `optionsUnknown` blocks too: a cached product whose options we never read is
|
|
411
|
+
// indistinguishable from one with none, and adding it would post the variant-less
|
|
412
|
+
// line this whole feature exists to prevent.
|
|
413
|
+
optionsIncomplete,
|
|
414
|
+
...Object.fromEntries([1, 2, 3].map(n => [`opt${n}ScrollRequest`,
|
|
415
|
+
s.showOptionErrors && groups[n - 1]?.id === s.optionValidationTarget && !s.selection[groups[n - 1].id] ? String(s.optionValidationRequest || "") : ""])),
|
|
416
|
+
addDisabled: s.adding || s.optionsUnknown || overflow || !!outOfStockPick(groups, s.selection),
|
|
417
|
+
optionsHint: groups.length ? optionsHint(groups, s.selection) : "",
|
|
418
|
+
saveLabel: s.saved ? copyParam("savedProducts.removeLabel", "Remove from wishlist") : copyParam("savedProducts.addLabel", "Add to wishlist"),
|
|
419
|
+
addLabel: s.adding ? copyParam("product.adding", "Adding to cart…") : copyParam("product.addToCart", "Add to cart"),
|
|
420
|
+
notAdding: !s.adding,
|
|
421
|
+
notAdded: !s.added,
|
|
422
|
+
isLoading: s.status === "loading",
|
|
423
|
+
notLoading: s.status !== "loading",
|
|
424
|
+
hideContent: s.status !== "ready" || !s.name,
|
|
425
|
+
isErrored: s.status === "error",
|
|
426
|
+
notErrored: s.status !== "error",
|
|
427
|
+
noEmpty: s.status === "loading" || s.status === "error" || !empty,
|
|
428
|
+
hasImage: !!s.image,
|
|
429
|
+
noImage: !s.image,
|
|
430
|
+
hasGallery,
|
|
431
|
+
noGallery: !hasGallery,
|
|
432
|
+
hasSingleImage,
|
|
433
|
+
noSingleImage: !hasSingleImage,
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// Bumped by every add (queued, failed or landed): a cart count read BEFORE it — the load's badge
|
|
438
|
+
// read answering late — must not replace the badge the add set (#3468 review).
|
|
439
|
+
let cartBadgeEpoch = 0;
|
|
440
|
+
|
|
441
|
+
// A digital product with no options sells through the App Store once the platform sells Wix Stores
|
|
442
|
+
// items there (`storesAppleSalesEnabled`): wix-iap StartItemPayment places and charges its order.
|
|
443
|
+
// Until then, and for any other product, an App Store route only blocks the regular checkout.
|
|
444
|
+
const SELLS_THROUGH_APPLE = storesAppleSalesEnabled();
|
|
445
|
+
const WIX_STORES_APP = "215238eb-22a5-4c36-9e7b-e7c08025e04e";
|
|
446
|
+
const NOT_APPLE: IapPurchaseFields = { appleRoute: false, accessReady: false, buyLabel: "", buyDisabled: true, buyBusy: false, buyNote: "" };
|
|
447
|
+
|
|
448
|
+
let productPricing: IapCommerce;
|
|
449
|
+
let checkoutEntered = false;
|
|
450
|
+
const registerProduct = withIapPresentation<S>({
|
|
451
|
+
register: withOnlineWrites(registerState, ["beginAdd", "addToCart", "buy"], { derive, messageFields: action => action === "buy" ? ["buyNote"] : ["cartHint"] }),
|
|
452
|
+
adapters: SELLS_THROUGH_APPLE ? [storesProductOrders] : [],
|
|
453
|
+
onCreate: commerce => { productPricing = commerce; }, prefix: "product",
|
|
454
|
+
transientKeys: ["optionValidationTarget", "optionValidationRequest", "opt1ScrollRequest", "opt2ScrollRequest", "opt3ScrollRequest", "galleryIndex", "price", "optionsIncomplete", "cartHint", "cartHidden", "buyHidden", "buyLabel", "buyDisabled", "buyNote", "purchasedNote", "addedSheetPresented", "shareHint"], contentActions: ["load", "readChanged"], concurrentPublishActions: ["buy"],
|
|
455
|
+
items: state => inputId() ? [{ reference: { kind: "storesProduct", id: inputId() }, commerceDisplayPrice: state.price }] : [],
|
|
456
|
+
present: (state, price, allowed, _appleIapOrResolving, resolving) => {
|
|
457
|
+
const purchase = applePurchase(state);
|
|
458
|
+
const unavailable = iapPriceCopy("product").purchaseUnavailable;
|
|
459
|
+
// A guard still resolving (prices load after the product) is loading, not a refusal: no
|
|
460
|
+
// "Purchasing is not available yet." until a final route blocks the purchase. Add to cart
|
|
461
|
+
// stays disabled meanwhile (`addDisabled`), with no message.
|
|
462
|
+
const pending = !state.optionsUnknown && resolving(inputId());
|
|
463
|
+
const blocked = lastProduct?.productType?.toLowerCase() === "digital" || (!state.optionsUnknown && !pending && !allowed(inputId()));
|
|
464
|
+
const cartHint = state.cartHint === offlineWriteMessage ? state.cartHint
|
|
465
|
+
: !purchase.appleRoute && blocked ? unavailable : state.cartHint === unavailable ? "" : state.cartHint;
|
|
466
|
+
const productState = derive(state);
|
|
467
|
+
return {
|
|
468
|
+
...state, price: price(inputId()), ...(purchase.appleRoute ? { wasPrice: "", wasPriceEmpty: false, notOnSale: true } : {}), optionsIncomplete: productState.optionsIncomplete || !allowed(inputId()) || lastProduct?.productType?.toLowerCase() === "digital",
|
|
469
|
+
cartHint, noCartHint: !cartHint || state.added, addDisabled: productState.addDisabled || blocked || pending,
|
|
470
|
+
cartHidden: state.status !== "ready" || !state.name || purchase.appleRoute,
|
|
471
|
+
buyHidden: state.status !== "ready" || !state.name || !purchase.appleRoute || purchase.accessReady, buyLabel: purchase.buyLabel, buyDisabled: purchase.buyDisabled,
|
|
472
|
+
buyNote: state.buyNote === offlineWriteMessage ? state.buyNote : purchase.buyNote,
|
|
473
|
+
purchasedNote: purchase.accessReady ? copyParam("product.purchasedText", "Purchased") : "",
|
|
474
|
+
};
|
|
475
|
+
},
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
// Read recovery commits content before IAP sidecars project prices. Cache and network
|
|
479
|
+
// reads stay inside one safe read lifecycle; price publications never become read results.
|
|
480
|
+
const defineService = withReadLifecycle(registerProduct, "load", {
|
|
481
|
+
// Missing route input is authored local content, not a server response or cache hit.
|
|
482
|
+
localResult: () => !inputId(),
|
|
483
|
+
onInvalidate: () => {
|
|
484
|
+
productLoadSequence++;
|
|
485
|
+
lastProduct = undefined;
|
|
486
|
+
lastLoadedId = undefined;
|
|
487
|
+
cartBadgeEpoch++;
|
|
488
|
+
},
|
|
489
|
+
unavailable: state => {
|
|
490
|
+
lastProduct = undefined;
|
|
491
|
+
lastLoadedId = undefined;
|
|
492
|
+
return { ...derive(state as unknown as S) };
|
|
493
|
+
},
|
|
494
|
+
authoredFallback: state => !inputId() ? { ...derive({ ...state, status: "ready", emptyText: copyParam("product.notFoundText", "Product not found.") } as unknown as S) } : undefined,
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
/** The App Store action, only for the one shape it sells: digital, with no options to choose, read
|
|
498
|
+
* from the product loaded for the id on screen (as Add to cart is). A cached product whose
|
|
499
|
+
* options were never read is not known to have none. */
|
|
500
|
+
function applePurchase(state: S): IapPurchaseFields {
|
|
501
|
+
const id = inputId();
|
|
502
|
+
const loaded = !!id && lastLoadedId === id;
|
|
503
|
+
const sellable = SELLS_THROUGH_APPLE && loaded && lastProduct?.productType?.toLowerCase() === "digital" && !state.optionsUnknown && state.optionGroups.length === 0;
|
|
504
|
+
const copy = iapPurchaseCopy("product");
|
|
505
|
+
const fields = sellable ? productPricing.purchaseFields({ kind: "storesProduct", id }, copy) : NOT_APPLE;
|
|
506
|
+
return fields.appleRoute ? fields : NOT_APPLE;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** On every entry: the first starts the checkout (recovering held purchases), later ones reconcile. */
|
|
510
|
+
function enterCheckout(): void {
|
|
511
|
+
if (!SELLS_THROUGH_APPLE) return;
|
|
512
|
+
void (checkoutEntered ? productPricing.reconcile() : productPricing.start());
|
|
513
|
+
checkoutEntered = true;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const onlineService = defineService;
|
|
517
|
+
const svc = onlineService<S, {
|
|
518
|
+
load: (s: S, arg?: unknown) => Promise<S>;
|
|
519
|
+
setQuantity: (s: S, arg?: unknown) => S;
|
|
520
|
+
toggleReturnPolicy: (s: S) => S;
|
|
521
|
+
toggleShippingInfo: (s: S) => S;
|
|
522
|
+
selectOption: (s: S, arg?: unknown) => S;
|
|
523
|
+
setGalleryIndex: (s: S, arg?: unknown) => S;
|
|
524
|
+
addToCart: (s: S) => Promise<S>;
|
|
525
|
+
beginAdd: (s: S, arg?: unknown) => S;
|
|
526
|
+
setCartCount: (s: S, arg?: unknown) => S;
|
|
527
|
+
share: (s: S) => Promise<S>;
|
|
528
|
+
toggleSave: (s: S) => S;
|
|
529
|
+
closeAddedSheet: (s: S) => S;
|
|
530
|
+
/** [rico] #3372 — RichContent's on_link: `{ url }` of the tapped link. */
|
|
531
|
+
openLink: (s: S, arg?: unknown) => Promise<S>;
|
|
532
|
+
/** The App Store Buy: through the shared checkout, for the product on screen. */
|
|
533
|
+
buy: (s: S) => Promise<S>;
|
|
534
|
+
}>("himiStoreProduct", {
|
|
535
|
+
state: derive({
|
|
536
|
+
status: "loading",
|
|
537
|
+
name: "",
|
|
538
|
+
price: "",
|
|
539
|
+
wasPrice: "",
|
|
540
|
+
notOnSale: true,
|
|
541
|
+
wasPriceEmpty: false,
|
|
542
|
+
skuLabel: "",
|
|
543
|
+
noSku: true,
|
|
544
|
+
infoSections: [],
|
|
545
|
+
returnPolicyBody: "",
|
|
546
|
+
shippingInfoBody: "",
|
|
547
|
+
noReturnPolicyBody: true,
|
|
548
|
+
noShippingInfoBody: true,
|
|
549
|
+
returnPolicyCollapsed: true,
|
|
550
|
+
shippingInfoCollapsed: true,
|
|
551
|
+
noSaveHint: true,
|
|
552
|
+
saveIcon: "heart",
|
|
553
|
+
optionsSummary: "",
|
|
554
|
+
quantityLabel: "Qty: 1",
|
|
555
|
+
quantityIsOne: true,
|
|
556
|
+
addedSheetPresented: false,
|
|
557
|
+
shareHint: "",
|
|
558
|
+
noShareHint: true,
|
|
559
|
+
noCartHint: true,
|
|
560
|
+
hideBar: true,
|
|
561
|
+
hideProduct: true,
|
|
562
|
+
description: "",
|
|
563
|
+
descriptionJson: "",
|
|
564
|
+
hasDescriptionJson: false,
|
|
565
|
+
returnPolicyExpanded: false,
|
|
566
|
+
shippingInfoExpanded: false,
|
|
567
|
+
image: "",
|
|
568
|
+
gallery: [],
|
|
569
|
+
galleryIndex: 0,
|
|
570
|
+
galleryLabel: "",
|
|
571
|
+
hasGallery: false,
|
|
572
|
+
noGallery: true,
|
|
573
|
+
initial: "",
|
|
574
|
+
shareUrl: "",
|
|
575
|
+
cartHint: "",
|
|
576
|
+
cartCount: 0,
|
|
577
|
+
adding: false,
|
|
578
|
+
addLabel: "",
|
|
579
|
+
notAdding: true,
|
|
580
|
+
added: false,
|
|
581
|
+
notAdded: true,
|
|
582
|
+
emptyText: "",
|
|
583
|
+
isLoading: true,
|
|
584
|
+
notLoading: false, hideContent: true,
|
|
585
|
+
isErrored: false,
|
|
586
|
+
notErrored: true,
|
|
587
|
+
noEmpty: true,
|
|
588
|
+
hasImage: false,
|
|
589
|
+
noImage: true,
|
|
590
|
+
hasSingleImage: false,
|
|
591
|
+
noSingleImage: true,
|
|
592
|
+
quantity: 1,
|
|
593
|
+
saved: false,
|
|
594
|
+
saveLabel: "",
|
|
595
|
+
saveHint: "",
|
|
596
|
+
optionGroups: [],
|
|
597
|
+
selection: {},
|
|
598
|
+
hasOptions: false,
|
|
599
|
+
noOptions: true,
|
|
600
|
+
optionsOverflow: false,
|
|
601
|
+
noOptionsOverflow: true,
|
|
602
|
+
optionsIncomplete: false,
|
|
603
|
+
showOptionErrors: false,
|
|
604
|
+
optionValidationRequest: 0,
|
|
605
|
+
optionValidationTarget: "",
|
|
606
|
+
opt1ScrollRequest: "", opt2ScrollRequest: "", opt3ScrollRequest: "",
|
|
607
|
+
addDisabled: false,
|
|
608
|
+
optionsUnknown: false,
|
|
609
|
+
optionsHint: "",
|
|
610
|
+
opt1Label: "", opt1Chips: [], opt1Selected: [], opt1SelectedId: "", opt1Placeholder: "", noOpt1: true,
|
|
611
|
+
opt2Label: "", opt2Chips: [], opt2Selected: [], opt2SelectedId: "", opt2Placeholder: "", noOpt2: true,
|
|
612
|
+
opt3Label: "", opt3Chips: [], opt3Selected: [], opt3SelectedId: "", opt3Placeholder: "", noOpt3: true,
|
|
613
|
+
opt1Error: "", noOpt1Error: true, hasOpt1Error: false, opt2Error: "", noOpt2Error: true, hasOpt2Error: false, opt3Error: "", noOpt3Error: true, hasOpt3Error: false,
|
|
614
|
+
cartHidden: false,
|
|
615
|
+
buyHidden: true,
|
|
616
|
+
buyLabel: "",
|
|
617
|
+
buyDisabled: true,
|
|
618
|
+
buyNote: "",
|
|
619
|
+
purchasedNote: "",
|
|
620
|
+
}),
|
|
621
|
+
actions: {
|
|
622
|
+
load: async (s, arg): Promise<S> => {
|
|
623
|
+
stashCopy(arg);
|
|
624
|
+
enterCheckout();
|
|
625
|
+
const sequence = ++productLoadSequence;
|
|
626
|
+
const id = inputId();
|
|
627
|
+
// A managed refresh retains the raw product used by the still-visible snapshot.
|
|
628
|
+
// Navigation and legacy loaders keep their existing reset behavior.
|
|
629
|
+
if (!readOptions(arg) || id !== lastLoadedId) lastProduct = undefined;
|
|
630
|
+
// Storage problems must not prevent browsing or buying a product.
|
|
631
|
+
let saved = false;
|
|
632
|
+
try { saved = isProductSaved(id); } catch { /* save action reports a retryable error */ }
|
|
633
|
+
s = { ...s, saved, saveHint: "",
|
|
634
|
+
optionValidationTarget: "",
|
|
635
|
+
...(id !== lastLoadedId ? { adding: false, added: false, shareHint: "", addedSheetPresented: false, quantity: 1, showOptionErrors: false, optionValidationRequest: 0, galleryIndex: 0, returnPolicyExpanded: false, shippingInfoExpanded: false, infoSections: [] } : {}) };
|
|
636
|
+
// A fresh navigation into the product resets any quantity left over
|
|
637
|
+
// from a previous visit to the same worker instance.
|
|
638
|
+
if (!id) {
|
|
639
|
+
lastProduct = undefined;
|
|
640
|
+
lastLoadedId = undefined;
|
|
641
|
+
return derive({ ...s, status: "ready", quantity: 1, optionGroups: [], selection: {}, optionsUnknown: false, descriptionJson: "", emptyText: copyParam("product.notFoundText", "Product not found.") });
|
|
642
|
+
}
|
|
643
|
+
// The cart count only feeds the top-bar badge: ask for it NOW, beside the product, instead
|
|
644
|
+
// of after it — it used to add a whole cart round trip before the page could paint.
|
|
645
|
+
const cartCount = readOptions(arg)?.cache === "only-if-cached" ? Promise.resolve(s.cartCount) : cartItemCount();
|
|
646
|
+
// The badge must never hold the page: remember the count if it is already in, and
|
|
647
|
+
// publish it separately if it lands after the product (#3468 review).
|
|
648
|
+
let cartKnown: number | undefined;
|
|
649
|
+
void cartCount.then((n) => { cartKnown = n; }, () => {});
|
|
650
|
+
// The live product read goes out FIRST too — the local-db read below must never delay it.
|
|
651
|
+
// Settled into a value so a failure is handled where it is awaited, never unhandled.
|
|
652
|
+
// Read the Ricos description, the Product Info sections (V3) and choice-linked images; V3 omits them by default.
|
|
653
|
+
const live = getStoreProduct(id, [...PRODUCT_DETAIL_FIELDS, "PRODUCT_CHOICES_DISPLAY_IMAGE"], readOptions(arg)).then(
|
|
654
|
+
(r) => ({ ok: true as const, r }),
|
|
655
|
+
(error) => ({ ok: false as const, error }),
|
|
656
|
+
);
|
|
657
|
+
const outcome = await live;
|
|
658
|
+
if (sequence !== productLoadSequence || id !== inputId()) return svc.getState() as S;
|
|
659
|
+
// The cache may have painted AFTER this network read started. Check the
|
|
660
|
+
// current state when the response lands, not the captured loading state.
|
|
661
|
+
const current = svc.getState() as S;
|
|
662
|
+
const painted = current.status === "ready" && lastLoadedId === id;
|
|
663
|
+
// Once painted the page is INTERACTIVE while the live read is on the wire: the visitor may
|
|
664
|
+
// save, change the quantity or add to cart. Build on the state as it is NOW, and keep what
|
|
665
|
+
// they did — overwriting it would untick a stored save, reset the quantity, and drop the
|
|
666
|
+
// in-flight add's `adding` guard (a second tap would add the line twice).
|
|
667
|
+
const base: S = painted ? current : s;
|
|
668
|
+
const keep = painted
|
|
669
|
+
? { saved: base.saved, saveHint: base.saveHint, quantity: base.quantity, adding: base.adding, added: base.added, cartHint: base.cartHint }
|
|
670
|
+
: { cartHint: "", quantity: 1 };
|
|
671
|
+
const badge = (): number => {
|
|
672
|
+
if (painted && (base.adding || base.added)) return base.cartCount;
|
|
673
|
+
if (cartKnown !== undefined) return cartKnown;
|
|
674
|
+
const epoch = cartBadgeEpoch;
|
|
675
|
+
void cartCount.then((n) => { void svc.setCartCount({ count: n, epoch }); }, () => {});
|
|
676
|
+
return base.cartCount;
|
|
677
|
+
};
|
|
678
|
+
if (outcome.ok) {
|
|
679
|
+
const p = (outcome.r.product ?? (outcome.r as unknown as StoreProduct)) as StoreProduct;
|
|
680
|
+
const name = cleanTitle(p.name) || "Product";
|
|
681
|
+
const gallery = productGallery(p);
|
|
682
|
+
const image = productImage(p, WIX_DETAIL_IMAGE) || gallery[0]?.url || "";
|
|
683
|
+
lastProduct = p;
|
|
684
|
+
// A group with exactly one choice is chosen for the shopper; a real choice
|
|
685
|
+
// is left blank so the pick is deliberate.
|
|
686
|
+
const optionGroups = productOptions(p, WIX_DETAIL_IMAGE);
|
|
687
|
+
const sale = productSale(p);
|
|
688
|
+
// A pooled screen re-appearing re-runs `load`. Wiping `selection` there means a
|
|
689
|
+
// trip to the cart and back silently clears the size the shopper picked and
|
|
690
|
+
// re-disables the CTA with no explanation. Carry the picks when this is the SAME
|
|
691
|
+
// product, and only for a choice the product still offers — a stale id would
|
|
692
|
+
// resolve to no variant and block the cart just as silently.
|
|
693
|
+
const carried: StoreOptionSelection = {};
|
|
694
|
+
if (id === lastLoadedId) {
|
|
695
|
+
for (const g of optionGroups) {
|
|
696
|
+
const chosen = base.selection[g.id];
|
|
697
|
+
if (chosen && g.choices.some((c) => c.id === chosen)) carried[g.id] = chosen;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
lastLoadedId = id;
|
|
701
|
+
return derive({
|
|
702
|
+
...base,
|
|
703
|
+
...keep,
|
|
704
|
+
status: "ready",
|
|
705
|
+
optionGroups,
|
|
706
|
+
selection: { ...defaultSelection(optionGroups), ...carried },
|
|
707
|
+
optionsUnknown: false,
|
|
708
|
+
name,
|
|
709
|
+
...sale,
|
|
710
|
+
commercePrice: sale.price,
|
|
711
|
+
skuLabel: skuOf(p) ? `SKU: ${skuOf(p)}` : "",
|
|
712
|
+
infoSections: productInfoSections(p, base.infoSections),
|
|
713
|
+
returnPolicyBody: productPolicyBody(p, "returns") || copyParam("product.returnPolicyBody", "") || copyParam("product.policyUnavailable", "Policy details have not been provided by this store."),
|
|
714
|
+
shippingInfoBody: productPolicyBody(p, "shipping") || copyParam("product.shippingInfoBody", "") || copyParam("product.policyUnavailable", "Policy details have not been provided by this store."),
|
|
715
|
+
...productBody(p),
|
|
716
|
+
image,
|
|
717
|
+
gallery,
|
|
718
|
+
initial: (name[0] || "#").toUpperCase(),
|
|
719
|
+
shareUrl: productShareUrl(p),
|
|
720
|
+
cartCount: badge(),
|
|
721
|
+
emptyText: "",
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
throw outcome.error;
|
|
725
|
+
},
|
|
726
|
+
// The stepper fires onChange with { value } on every tap; clamp 1–99 and
|
|
727
|
+
// ignore unparsable/garbage args instead of silently zeroing the quantity.
|
|
728
|
+
setQuantity: (s, arg) => {
|
|
729
|
+
const quantity = parseQuantity(argValue(arg, "value"));
|
|
730
|
+
return quantity ? derive({ ...s, quantity }) : s;
|
|
731
|
+
},
|
|
732
|
+
toggleInfoSection: (s, arg) => {
|
|
733
|
+
const id = argValue(arg, "id");
|
|
734
|
+
if (!s.infoSections.some(section => section.id === id && !section.noTitle)) return s;
|
|
735
|
+
return derive({ ...s, infoSections: s.infoSections.map(section => section.id === id
|
|
736
|
+
? { ...section, expanded: !section.expanded, collapsed: section.expanded } : section) });
|
|
737
|
+
},
|
|
738
|
+
toggleReturnPolicy: s => derive({ ...s, returnPolicyExpanded: !s.returnPolicyExpanded }),
|
|
739
|
+
toggleShippingInfo: s => derive({ ...s, shippingInfoExpanded: !s.shippingInfoExpanded }),
|
|
740
|
+
// One chip row per option group. `group` is the descriptor slot ("1".."3");
|
|
741
|
+
// FilterChips sends back the WHOLE selected set, which for a single-select row
|
|
742
|
+
// is either one id or none (re-tapping the active chip clears it).
|
|
743
|
+
setGalleryIndex: (s, arg) => {
|
|
744
|
+
const raw = argValue(arg, "index") || argValue(arg, "value");
|
|
745
|
+
const index = raw.trim() ? Number(raw) : NaN;
|
|
746
|
+
return Number.isInteger(index) && index >= 0 && index < s.gallery.length ? derive({ ...s, galleryIndex: index }) : s;
|
|
747
|
+
},
|
|
748
|
+
selectOption: (s, arg) => {
|
|
749
|
+
const slot = Math.floor(Number(argValue(arg, "group")));
|
|
750
|
+
const group = s.optionGroups[slot - 1];
|
|
751
|
+
if (!group) return s;
|
|
752
|
+
const raw = (arg as { selectedIds?: unknown; selectedId?: unknown; id?: unknown; value?: unknown } | undefined);
|
|
753
|
+
const selected = raw?.selectedIds;
|
|
754
|
+
const picked = Array.isArray(selected) ? String(selected[0] ?? "") : String(raw?.selectedId ?? raw?.id ?? raw?.value ?? selected ?? "");
|
|
755
|
+
// Only a choice this group actually offers — a stale id from a previous
|
|
756
|
+
// product would otherwise resolve to no variant and block the cart silently.
|
|
757
|
+
const choice = group.choices.some((c) => c.id === picked && c.inStock !== false) ? picked : "";
|
|
758
|
+
const selection = { ...s.selection };
|
|
759
|
+
if (choice) selection[group.id] = choice; else delete selection[group.id];
|
|
760
|
+
// A new choice invalidates the last add's confirmation — it was for the
|
|
761
|
+
// previous variant.
|
|
762
|
+
const image = group.choices.find(c => c.id === choice)?.image;
|
|
763
|
+
const imageIndex = image ? s.gallery.findIndex(page => page.url === image) : -1;
|
|
764
|
+
return derive({ ...s, selection, optionValidationTarget: "", ...(imageIndex >= 0 ? { galleryIndex: imageIndex } : {}), added: false, addedSheetPresented: false, cartHint: "" });
|
|
765
|
+
},
|
|
766
|
+
// The pending half of addToCart, as its own reducer so it PUBLISHES before the
|
|
767
|
+
// network write starts: the pending line shows and the top-bar badge ticks up in the same
|
|
768
|
+
// interaction, instead of the tap looking dead until the round-trip (and the badge re-read)
|
|
769
|
+
// settle. Called from addToCart, not from the descriptor.
|
|
770
|
+
beginAdd: (s, arg) => {
|
|
771
|
+
const quantity = parseQuantity(argValue(arg, "quantity")) ?? 1;
|
|
772
|
+
cartBadgeEpoch += 1;
|
|
773
|
+
return derive({ ...s, adding: true, added: false, addedSheetPresented: false, cartHint: "", cartCount: s.cartCount + quantity });
|
|
774
|
+
},
|
|
775
|
+
// The first paint from the list's synced row (called from load, not from the descriptor):
|
|
776
|
+
// name, price and image are on screen while the live product — description, gallery — loads.
|
|
777
|
+
// The cart count answered after the product: only the top-bar badge changes.
|
|
778
|
+
setCartCount: (s, arg) => {
|
|
779
|
+
// An add since the count was asked for owns the badge — in flight, landed or QUEUED offline
|
|
780
|
+
// (which leaves adding/added false): a pre-add count must not undo it.
|
|
781
|
+
const { count, epoch } = (arg ?? {}) as { count?: unknown; epoch?: unknown };
|
|
782
|
+
if (epoch !== cartBadgeEpoch || s.adding || s.added) return s;
|
|
783
|
+
const n = Math.max(0, Math.floor(Number(count)));
|
|
784
|
+
return Number.isFinite(n) ? derive({ ...s, cartCount: n }) : s;
|
|
785
|
+
},
|
|
786
|
+
|
|
787
|
+
addToCart: async (s) => {
|
|
788
|
+
const id = inputId();
|
|
789
|
+
if (!productPricing.pricing.checkoutGuard({ kind: "storesProduct", id }).allowed || lastProduct?.productType?.toLowerCase() === "digital") return derive({ ...s, cartHint: iapPriceCopy("product").purchaseUnavailable });
|
|
790
|
+
if (!id) return derive({ ...s, cartHint: copyParam("product.cartHintNoProduct", "No product to add.") });
|
|
791
|
+
// A second tap while the first write is in flight must not add the line twice.
|
|
792
|
+
if (s.adding) return s;
|
|
793
|
+
// Missing choices show field errors; unavailable products still fail closed.
|
|
794
|
+
if (s.optionsIncomplete) {
|
|
795
|
+
// With no groups in hand there is nothing for `optionsHint` to name, so the
|
|
796
|
+
// offline case needs its own reason rather than an empty string.
|
|
797
|
+
return derive({ ...s, showOptionErrors: true, optionValidationTarget: s.optionGroups.find(g => !s.selection[g.id])?.id ?? "", optionValidationRequest: (s.optionValidationRequest || 0) + 1, cartHint: s.optionsUnknown
|
|
798
|
+
? copyParam("product.cartHintOffline", "Reconnect to choose options and add this to your cart.")
|
|
799
|
+
: optionsHint(s.optionGroups, s.selection) || copyParam("product.cartHintNoVariant", "That combination is not available. Try another.") });
|
|
800
|
+
}
|
|
801
|
+
if (lastLoadedId !== id || lastProduct?.productType?.toLowerCase() !== "physical") {
|
|
802
|
+
return derive({ ...s, cartHint: copyParam("product.cartHintOffline", "Reconnect to choose options and add this to your cart.") });
|
|
803
|
+
}
|
|
804
|
+
// Which variant the choice resolves to is the SDK's job — V3 addresses the
|
|
805
|
+
// choice by variantId, V1 by a name→choice map, and it throws rather than
|
|
806
|
+
// hand back a payload that would add a line with no variant.
|
|
807
|
+
let cartOptions: Record<string, unknown> | undefined;
|
|
808
|
+
try {
|
|
809
|
+
cartOptions = cartOptionsPayload(lastProduct, s.optionGroups, s.selection);
|
|
810
|
+
} catch {
|
|
811
|
+
return derive({ ...s, cartHint: copyParam("product.cartHintNoVariant", "That combination is not available. Try another.") });
|
|
812
|
+
}
|
|
813
|
+
const quantity = s.quantity > 0 ? s.quantity : 1;
|
|
814
|
+
const before = s.cartCount;
|
|
815
|
+
await svc.beginAdd({ quantity: String(quantity) });
|
|
816
|
+
s = svc.getState() as S;
|
|
817
|
+
// Optimistic local cart line — the cart repaints from cache immediately (offline or not).
|
|
818
|
+
const chosen = selectionSummary(s.optionGroups, s.selection);
|
|
819
|
+
// Keyed by product AND variant. `line-${id}` alone collapses two variants of the
|
|
820
|
+
// same product into one cached row while the badge counts both — the offline cart
|
|
821
|
+
// then shows one line for two adds. Sorted so the key is stable whatever order the
|
|
822
|
+
// groups were picked in, and reduced to id-safe characters.
|
|
823
|
+
const variantKey = Object.keys(s.selection).sort().map((k) => `${k}:${s.selection[k]}`).join("|").replace(/[^A-Za-z0-9]+/g, "_");
|
|
824
|
+
const unitPrice = s.commercePrice || s.price;
|
|
825
|
+
const sale = lastProduct ? productSale(lastProduct) : { wasPrice: "" };
|
|
826
|
+
const swatches = s.optionGroups.flatMap(g => g.kind === "color" ? g.choices.map(c => c.colorCode).filter(Boolean) : []).slice(0, 5);
|
|
827
|
+
const line: DbEntity = { id: variantKey ? `line-${id}-${variantKey}` : `line-${id}`, productId: id, name: s.name || "product", title: s.name || "product", subtitle: chosen ? `${chosen} · Qty ${quantity}` : `Qty ${quantity}`, quantity: String(quantity), image: s.image, unitPrice, wasPrice: sale.wasPrice, swatches, total: optimisticLineTotal(unitPrice, quantity), hasImage: !!s.image, noImage: !s.image };
|
|
828
|
+
if (!offlineWritesEnabled) await cartPut(line);
|
|
829
|
+
try {
|
|
830
|
+
await addToCurrentCart(id, quantity, cartOptions);
|
|
831
|
+
} catch (e) {
|
|
832
|
+
if (!offlineWritesEnabled && isBridgeUnavailable(e)) {
|
|
833
|
+
// Offline / no bridge: the optimistic cache line already shows; queue the
|
|
834
|
+
// add to replay (WriteQueue, idempotent) when connectivity returns.
|
|
835
|
+
await queueWrite("tier5.himiStoreProduct.addToCart", { id, ...(cartOptions ? { options: JSON.stringify(cartOptions) } : {}) });
|
|
836
|
+
return derive({ ...s, adding: false, added: false, cartHint: copyTemplate("product.cartHintQueued", "Added {name} to cart. Will sync when you reconnect.", { name: s.name || "product" }) });
|
|
837
|
+
}
|
|
838
|
+
// Roll the optimistic badge back — nothing was added.
|
|
839
|
+
return derive({ ...s, adding: false, added: false, cartCount: before, cartHint: copyParam("product.cartHintFailed", "Could not add to cart. Try again.") });
|
|
840
|
+
}
|
|
841
|
+
if (offlineWritesEnabled) await cartPut(line);
|
|
842
|
+
// The write LANDED. The badge re-read is outside the write's try on purpose: a failed
|
|
843
|
+
// count must never be mistaken for a failed add. Server count wins; else keep optimistic.
|
|
844
|
+
const count = await cartItemCount().catch(() => 0);
|
|
845
|
+
const confirmation = copyTemplate("product.cartHintAdded", "Added {name} to cart.", { name: s.name || "product" });
|
|
846
|
+
return derive({ ...s, adding: false, added: true, addedSheetPresented: true, cartHint: `${confirmation}${quantity > 1 ? ` Qty: ${quantity}` : ""}`, cartCount: count || s.cartCount });
|
|
847
|
+
},
|
|
848
|
+
toggleSave: (s) => {
|
|
849
|
+
if (s.status !== "ready" || !s.name || !inputId()) return s;
|
|
850
|
+
try {
|
|
851
|
+
const sale = lastProduct ? productSale(lastProduct) : { price: s.commercePrice ?? "", wasPrice: "" };
|
|
852
|
+
const saved = toggleSavedProduct({ id: inputId(), name: s.name, price: sale.price, wasPrice: sale.wasPrice, image: s.image,
|
|
853
|
+
swatches: s.optionGroups.flatMap(g => g.kind === "color" ? g.choices.map(c => c.colorCode).filter(Boolean) : []).slice(0, 5) });
|
|
854
|
+
return derive({ ...s, saved, saveHint: saved
|
|
855
|
+
? copyParam("product.saveSuccess", "Added to wishlist.")
|
|
856
|
+
: copyParam("product.saveRemoved", "Removed from wishlist.") });
|
|
857
|
+
} catch {
|
|
858
|
+
return derive({ ...s, saveHint: copyParam("product.saveError", "Could not save this change. Try again.") });
|
|
859
|
+
}
|
|
860
|
+
},
|
|
861
|
+
share: async (s) => {
|
|
862
|
+
if (!s.name) return s;
|
|
863
|
+
try {
|
|
864
|
+
await shareSheet({ subject: s.name, text: s.name, ...(s.shareUrl ? { url: s.shareUrl } : {}) });
|
|
865
|
+
return derive({ ...s, shareHint: "" });
|
|
866
|
+
} catch {
|
|
867
|
+
// `added: false` — this hint must not render inside the add-to-cart confirmation.
|
|
868
|
+
return derive({ ...s, shareHint: copyParam("product.shareUnavailable", "Sharing is not available on this device.") });
|
|
869
|
+
}
|
|
870
|
+
},
|
|
871
|
+
closeAddedSheet: s => derive({ ...s, addedSheetPresented: false }),
|
|
872
|
+
// Only http(s), mailto and tel links reach open_url; a refused link, or one nothing opened, says so in the
|
|
873
|
+
// hint line (`added: false`, as for share, so it never renders inside the add-to-cart confirmation).
|
|
874
|
+
openLink: async (s, arg) => ((await openRichLink(arg))
|
|
875
|
+
? s
|
|
876
|
+
: derive({ ...s, added: false, cartHint: copyParam("product.linkOpenFailed", "This link could not be opened.") })),
|
|
877
|
+
buy: async (s): Promise<S> => {
|
|
878
|
+
const id = inputId();
|
|
879
|
+
const purchase = applePurchase(s);
|
|
880
|
+
if (!purchase.appleRoute || purchase.buyDisabled) return s;
|
|
881
|
+
await productPricing.buy({ reference: { kind: "storesProduct", id }, catalogReference: { appId: WIX_STORES_APP, catalogItemId: id }, quantity: 1 });
|
|
882
|
+
return svc.getState() as S;
|
|
883
|
+
},
|
|
884
|
+
},
|
|
885
|
+
});
|
|
886
|
+
|
|
887
|
+
// The boot sweep loads the bound product; root onAppear refreshes it when the screen returns.
|
|
888
|
+
svc.load();
|
|
889
|
+
export { svc };
|