@joy-loyalty/hydrogen 0.2.0 → 0.3.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/README.md +118 -4
- package/dist/csp.d.ts +1 -1
- package/dist/csp.js +2 -2
- package/dist/headless-host-adapter.js +3 -2
- package/dist/host-adapter/capabilities.d.ts +1 -0
- package/dist/host-adapter/capabilities.js +3 -0
- package/dist/host-adapter/product-fetcher.d.ts +1 -1
- package/dist/host-adapter/product-fetcher.js +3 -2
- package/dist/host-adapter/promoted-collections.d.ts +1 -1
- package/dist/host-adapter/promoted-collections.js +3 -2
- package/dist/hydrogen-cart-port.d.ts +49 -1
- package/dist/hydrogen-cart-port.js +24 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +1 -0
- package/dist/joy-widget.js +2 -2
- package/dist/lib/core-loader.d.ts +23 -0
- package/dist/lib/recommended-loader.d.ts +2 -1
- package/dist/lib/recommended-loader.js +5 -3
- package/dist/lib/redeem-cart-snapshot.d.ts +51 -0
- package/dist/lib/redeem-cart-snapshot.js +173 -0
- package/dist/orchestrator/handlers/account.js +1 -1
- package/dist/orchestrator/handlers/earn.js +9 -0
- package/dist/orchestrator/handlers/milestone-tier.js +1 -1
- package/dist/redeem-cart/JoyRedeemCart.d.ts +19 -0
- package/dist/redeem-cart/JoyRedeemCart.js +321 -0
- package/dist/routes/joy-products.js +22 -10
- package/dist/server/get-joy-initial-data.d.ts +1 -0
- package/dist/server/get-joy-initial-data.js +5 -1
- package/dist/server/get-joy-loyalty-page-data.d.ts +1 -0
- package/dist/server/get-joy-loyalty-page-data.js +1 -1
- package/dist/widget-orchestrator.d.ts +1 -0
- package/dist/widget-orchestrator.js +8 -2
- package/package.json +2 -2
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
const COLLECTIONS_PAGE_SIZE = 20;
|
|
2
|
+
function toCents(amount) {
|
|
3
|
+
const value = parseFloat(amount ?? '');
|
|
4
|
+
return Number.isFinite(value) ? Math.round(value * 100) : null;
|
|
5
|
+
}
|
|
6
|
+
function numericId(gid) {
|
|
7
|
+
const id = parseInt(String(gid ?? '').split('?')[0].split('/').pop() || '', 10);
|
|
8
|
+
return Number.isFinite(id) ? id : null;
|
|
9
|
+
}
|
|
10
|
+
function readAllocations(list) {
|
|
11
|
+
return (list || []).flatMap(allocation => {
|
|
12
|
+
const cents = toCents(allocation?.discountedAmount?.amount);
|
|
13
|
+
if (!allocation || cents == null)
|
|
14
|
+
return [];
|
|
15
|
+
const code = allocation.code || null;
|
|
16
|
+
return [{ key: code ? code.toUpperCase() : '', code, cents, shipping: allocation.targetType === 'SHIPPING_LINE' }];
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
const merchandise = (allocations) => allocations.filter(allocation => !allocation.shipping);
|
|
20
|
+
const sum = (allocations) => allocations.reduce((total, allocation) => total + allocation.cents, 0);
|
|
21
|
+
function application(allocation) {
|
|
22
|
+
return { type: allocation.code ? 'discount_code' : 'automatic', title: allocation.code || '' };
|
|
23
|
+
}
|
|
24
|
+
function orderShares(all, lineLevel) {
|
|
25
|
+
const byKey = new Map();
|
|
26
|
+
for (const allocation of all) {
|
|
27
|
+
const existing = byKey.get(allocation.key);
|
|
28
|
+
byKey.set(allocation.key, existing ? { ...existing, cents: existing.cents + allocation.cents } : { ...allocation });
|
|
29
|
+
}
|
|
30
|
+
for (const allocation of lineLevel) {
|
|
31
|
+
const existing = byKey.get(allocation.key);
|
|
32
|
+
if (!existing)
|
|
33
|
+
return null;
|
|
34
|
+
existing.cents -= allocation.cents;
|
|
35
|
+
}
|
|
36
|
+
const shares = [...byKey.values()];
|
|
37
|
+
return shares.some(share => share.cents < 0) ? null : shares.filter(share => share.cents > 0);
|
|
38
|
+
}
|
|
39
|
+
function legacyOrderAllocations(cartLevel, lineLevel) {
|
|
40
|
+
const lineByKey = new Map();
|
|
41
|
+
for (const allocation of lineLevel.flat()) {
|
|
42
|
+
if (!allocation.key)
|
|
43
|
+
continue;
|
|
44
|
+
const existing = lineByKey.get(allocation.key) || { cents: 0, count: 0 };
|
|
45
|
+
lineByKey.set(allocation.key, { cents: existing.cents + allocation.cents, count: existing.count + 1 });
|
|
46
|
+
}
|
|
47
|
+
const byKey = new Map();
|
|
48
|
+
for (const allocation of cartLevel) {
|
|
49
|
+
const existing = byKey.get(allocation.key);
|
|
50
|
+
byKey.set(allocation.key, existing ? { ...existing, cents: existing.cents + allocation.cents } : { ...allocation });
|
|
51
|
+
}
|
|
52
|
+
const shares = [];
|
|
53
|
+
for (const allocation of byKey.values()) {
|
|
54
|
+
const line = allocation.key ? lineByKey.get(allocation.key) : undefined;
|
|
55
|
+
const cents = line ? allocation.cents - line.cents : allocation.cents;
|
|
56
|
+
if (line && cents < -line.count)
|
|
57
|
+
return null;
|
|
58
|
+
if (cents > 0)
|
|
59
|
+
shares.push({ ...allocation, cents });
|
|
60
|
+
}
|
|
61
|
+
return shares;
|
|
62
|
+
}
|
|
63
|
+
function collectionsOf(line) {
|
|
64
|
+
const collections = line.merchandise?.product?.collections;
|
|
65
|
+
if (!collections || !Array.isArray(collections.nodes))
|
|
66
|
+
return { ids: [], known: false };
|
|
67
|
+
const ids = collections.nodes.flatMap(node => {
|
|
68
|
+
const id = numericId(node?.id);
|
|
69
|
+
return id == null ? [] : [id];
|
|
70
|
+
});
|
|
71
|
+
const complete = collections.pageInfo
|
|
72
|
+
? collections.pageInfo.hasNextPage !== true
|
|
73
|
+
: collections.nodes.length < COLLECTIONS_PAGE_SIZE;
|
|
74
|
+
return { ids, known: complete };
|
|
75
|
+
}
|
|
76
|
+
function currencyOf(cart, lines) {
|
|
77
|
+
const lineCurrency = lines.find(line => line?.cost?.subtotalAmount?.currencyCode)?.cost?.subtotalAmount?.currencyCode;
|
|
78
|
+
return cart.cost?.totalAmount?.currencyCode || cart.cost?.subtotalAmount?.currencyCode || lineCurrency || null;
|
|
79
|
+
}
|
|
80
|
+
export function normalizeRedeemCartSnapshot(cart) {
|
|
81
|
+
if (!cart)
|
|
82
|
+
return null;
|
|
83
|
+
const lines = (Array.isArray(cart.lines?.nodes) ? cart.lines.nodes : []).filter((line) => !!line);
|
|
84
|
+
const currency = currencyOf(cart, lines);
|
|
85
|
+
const discountCodes = (Array.isArray(cart.discountCodes) ? cart.discountCodes : []).flatMap(discount => discount?.code ? [{ code: discount.code, applicable: discount.applicable === true }] : []);
|
|
86
|
+
const originals = lines.map(line => toCents(line.cost?.subtotalAmount?.amount));
|
|
87
|
+
const hasLineLevel = lines.every(line => Array.isArray(line.discountAllocations));
|
|
88
|
+
const hasAll = lines.every(line => Array.isArray(line.joyAllDiscounts));
|
|
89
|
+
const hasLegacyCartLevel = Array.isArray(cart.discountAllocations);
|
|
90
|
+
const discountComplete = !discountCodes.some(discount => discount.applicable) || (hasLineLevel && (hasLegacyCartLevel || hasAll));
|
|
91
|
+
const cartStateKnown = Array.isArray(cart.lines?.nodes) && originals.every(original => original != null) && discountComplete;
|
|
92
|
+
const lineLevel = lines.map(line => merchandise(readAllocations(line.discountAllocations)));
|
|
93
|
+
let productByLine = lines.map(() => []);
|
|
94
|
+
let orderAllocations = [];
|
|
95
|
+
let classesKnown = false;
|
|
96
|
+
if (hasLineLevel && hasAll) {
|
|
97
|
+
const shares = lines.map((line, index) => orderShares(merchandise(readAllocations(line.joyAllDiscounts)), lineLevel[index]));
|
|
98
|
+
if (shares.every(share => share)) {
|
|
99
|
+
productByLine = lineLevel;
|
|
100
|
+
orderAllocations = shares.flatMap(share => share || []);
|
|
101
|
+
classesKnown = true;
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
productByLine = lines.map(line => merchandise(readAllocations(line.joyAllDiscounts)));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
else if (hasAll) {
|
|
108
|
+
productByLine = lines.map(line => merchandise(readAllocations(line.joyAllDiscounts)));
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
productByLine = lineLevel;
|
|
112
|
+
const cartLevel = merchandise(readAllocations(cart.discountAllocations));
|
|
113
|
+
const shares = legacyOrderAllocations(cartLevel, lineLevel);
|
|
114
|
+
orderAllocations = shares || cartLevel;
|
|
115
|
+
classesKnown = !!shares && hasLineLevel && hasLegacyCartLevel;
|
|
116
|
+
}
|
|
117
|
+
const infoItems = [];
|
|
118
|
+
const cartItems = lines.map((line, index) => {
|
|
119
|
+
const productId = numericId(line.merchandise?.product?.id);
|
|
120
|
+
const variantId = numericId(line.merchandise?.id);
|
|
121
|
+
const quantity = typeof line.quantity === 'number' && Number.isFinite(line.quantity) ? line.quantity : 0;
|
|
122
|
+
const original = originals[index] ?? 0;
|
|
123
|
+
const lineDiscount = cartStateKnown ? sum(productByLine[index]) : 0;
|
|
124
|
+
const finalLinePrice = original - lineDiscount;
|
|
125
|
+
infoItems.push({
|
|
126
|
+
variant_id: variantId,
|
|
127
|
+
product_id: productId,
|
|
128
|
+
quantity,
|
|
129
|
+
original_line_price: original,
|
|
130
|
+
final_line_price: finalLinePrice,
|
|
131
|
+
line_level_total_discount: lineDiscount,
|
|
132
|
+
line_level_discount_allocations: productByLine[index].map(allocation => ({
|
|
133
|
+
amount: allocation.cents,
|
|
134
|
+
discount_application: application(allocation)
|
|
135
|
+
}))
|
|
136
|
+
});
|
|
137
|
+
return {
|
|
138
|
+
id: productId,
|
|
139
|
+
product_id: productId,
|
|
140
|
+
variant_id: variantId,
|
|
141
|
+
quantity,
|
|
142
|
+
original_line_price: original,
|
|
143
|
+
final_line_price: finalLinePrice,
|
|
144
|
+
final_price: quantity > 0 ? Math.round(finalLinePrice / quantity) : finalLinePrice,
|
|
145
|
+
collectionIds: collectionsOf(line).ids
|
|
146
|
+
};
|
|
147
|
+
});
|
|
148
|
+
const cartLevel = new Map();
|
|
149
|
+
for (const allocation of orderAllocations) {
|
|
150
|
+
const existing = cartLevel.get(allocation.key);
|
|
151
|
+
if (existing)
|
|
152
|
+
existing.total_allocated_amount += allocation.cents;
|
|
153
|
+
else
|
|
154
|
+
cartLevel.set(allocation.key, { ...application(allocation), total_allocated_amount: allocation.cents });
|
|
155
|
+
}
|
|
156
|
+
const originalTotal = cartStateKnown ? cartItems.reduce((total, item) => total + item.original_line_price, 0) : 0;
|
|
157
|
+
const totalDiscount = cartStateKnown
|
|
158
|
+
? infoItems.reduce((total, item) => total + item.line_level_total_discount, 0) + sum(orderAllocations)
|
|
159
|
+
: 0;
|
|
160
|
+
return {
|
|
161
|
+
cartItems,
|
|
162
|
+
cartInfo: {
|
|
163
|
+
currency,
|
|
164
|
+
original_total_price: originalTotal,
|
|
165
|
+
total_discount: totalDiscount,
|
|
166
|
+
discount_codes: discountCodes,
|
|
167
|
+
...(classesKnown ? { items: infoItems, cart_level_discount_applications: [...cartLevel.values()] } : {})
|
|
168
|
+
},
|
|
169
|
+
cartStateKnown,
|
|
170
|
+
collectionIdsKnown: lines.every(line => collectionsOf(line).known),
|
|
171
|
+
currency
|
|
172
|
+
};
|
|
173
|
+
}
|
|
@@ -35,7 +35,7 @@ export function mapActivityRows(activities, ctx, countryCode) {
|
|
|
35
35
|
return activities.map(activity => toActivityViewModel(activity, locale));
|
|
36
36
|
}
|
|
37
37
|
const blob = (ctx.activeBlob ?? {});
|
|
38
|
-
const mapped = mapActivities(activities.map(activity => ({ ...activity, type: activity.rawType })), {
|
|
38
|
+
const mapped = mapActivities(activities.map(({ title: _composedTitle, ...activity }) => ({ ...activity, type: activity.rawType })), {
|
|
39
39
|
translation: resolveActiveTranslation(blob.translation, locale),
|
|
40
40
|
settings: blob.settings ?? {},
|
|
41
41
|
shop: blob.shop ?? {},
|
|
@@ -38,6 +38,12 @@ export function registerEarnHandlers(ctx) {
|
|
|
38
38
|
element
|
|
39
39
|
.setEarnActionResult?.(success, extra);
|
|
40
40
|
}
|
|
41
|
+
function settleSocialEarn(option, success, response) {
|
|
42
|
+
const widget = element;
|
|
43
|
+
widget.socialPending = { option, pending: false };
|
|
44
|
+
widget.handleEarnResult?.(option, success);
|
|
45
|
+
element.dispatchEvent(new CustomEvent('joy-earn-result', { bubbles: true, composed: true, detail: { option, success, response } }));
|
|
46
|
+
}
|
|
41
47
|
function resetEarnAction() {
|
|
42
48
|
element.resetEarnActionState?.();
|
|
43
49
|
}
|
|
@@ -117,10 +123,13 @@ export function registerEarnHandlers(ctx) {
|
|
|
117
123
|
if (typeof totalPoints === 'number')
|
|
118
124
|
writeProps(element, { points: totalPoints });
|
|
119
125
|
setEarnResult(true);
|
|
126
|
+
settleSocialEarn(d.option, true, result);
|
|
120
127
|
ctx.loadActivities();
|
|
121
128
|
}
|
|
122
129
|
catch (error) {
|
|
123
130
|
setEarnResult(false);
|
|
131
|
+
if (isSocial && !hasForm && !hasReceipt)
|
|
132
|
+
settleSocialEarn(d.option, false);
|
|
124
133
|
surface(Promise.reject(error));
|
|
125
134
|
}
|
|
126
135
|
}
|
|
@@ -30,7 +30,7 @@ export function registerMilestoneTierHandlers(ctx, deps) {
|
|
|
30
30
|
const facade = buildLoaderFacade();
|
|
31
31
|
if (!facade)
|
|
32
32
|
return;
|
|
33
|
-
surface(Promise.resolve(apply(facade, {})));
|
|
33
|
+
surface(Promise.resolve(apply(facade, facade._renderInput || {})));
|
|
34
34
|
}
|
|
35
35
|
async function runMilestoneClaim(d) {
|
|
36
36
|
const { programId } = d;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { HydrogenCartFetcher, StorefrontCart } from '../hydrogen-cart-port.js';
|
|
3
|
+
import type { JoyInitialDataResult } from '../server/get-joy-initial-data.js';
|
|
4
|
+
export interface JoyRedeemCartProps {
|
|
5
|
+
apiUrl: string;
|
|
6
|
+
shopDomain: string;
|
|
7
|
+
tokenRoute?: string;
|
|
8
|
+
assetUrl?: string;
|
|
9
|
+
initialData: JoyInitialDataResult | null | undefined;
|
|
10
|
+
loginUrl?: string;
|
|
11
|
+
onNavigate?: (url: string) => void;
|
|
12
|
+
className?: string;
|
|
13
|
+
cart?: StorefrontCart | (() => StorefrontCart | null | undefined);
|
|
14
|
+
cartFetcher?: HydrogenCartFetcher;
|
|
15
|
+
cartRevalidate?: () => void;
|
|
16
|
+
cartRoute?: string;
|
|
17
|
+
onCartUpdated?: (cart: StorefrontCart) => void;
|
|
18
|
+
}
|
|
19
|
+
export declare function JoyRedeemCart({ apiUrl, shopDomain, tokenRoute, assetUrl, initialData, loginUrl, onNavigate, className, cart, cartFetcher, cartRevalidate, cartRoute, onCartUpdated }: JoyRedeemCartProps): ReactNode;
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { createElement, useEffect, useRef, useState } from 'react';
|
|
3
|
+
import { loadWidgetCore } from '../lib/core-loader.js';
|
|
4
|
+
import { WidgetCorePreloadLinks } from '../lib/core-preload-links.js';
|
|
5
|
+
import { ensureClient, useJoyProviderCart, useJoyProviderCartHandlers } from '../lib/JoyProvider.js';
|
|
6
|
+
import { normalizeRedeemCartSnapshot } from '../lib/redeem-cart-snapshot.js';
|
|
7
|
+
import { safeNavigationUrl } from '../lib/safe-navigation-url.js';
|
|
8
|
+
import { DEFAULT_TOKEN_ROUTE, getJoyToken } from '../lib/token.js';
|
|
9
|
+
import { resolveActiveTranslation, resolveContentLocale } from '../render-adapter.js';
|
|
10
|
+
const PLACEHOLDER_MIN_HEIGHT = 96;
|
|
11
|
+
const CART_UPDATE_DEBOUNCE_MS = 50;
|
|
12
|
+
const PLACEHOLDER_RELEASE_FALLBACK_MS = 1500;
|
|
13
|
+
const COPY_MODE_PORT = {
|
|
14
|
+
capabilities: { discountCodes: false, freeGift: false, mergeCodes: false, revalidate: false },
|
|
15
|
+
applyDiscount: () => Promise.reject(new Error('Cart discounts are not supported by this host.')),
|
|
16
|
+
removeDiscount: async () => { },
|
|
17
|
+
addLines: () => Promise.reject(new Error('Adding cart lines is not supported by this host.')),
|
|
18
|
+
redeemGift: () => Promise.reject(new Error('Free gifts are not supported by this host.')),
|
|
19
|
+
getCart: async () => null,
|
|
20
|
+
revalidate: () => { }
|
|
21
|
+
};
|
|
22
|
+
class StageError extends Error {
|
|
23
|
+
stage;
|
|
24
|
+
detail;
|
|
25
|
+
constructor(stage, detail) {
|
|
26
|
+
super(stage);
|
|
27
|
+
this.stage = stage;
|
|
28
|
+
this.detail = detail;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
async function guarded(stage, run) {
|
|
32
|
+
try {
|
|
33
|
+
return await run();
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
throw new StageError(stage, error);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function resolveCart(cart) {
|
|
40
|
+
try {
|
|
41
|
+
return typeof cart === 'function' ? cart() : cart;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function resolveCustomerKey(initialData) {
|
|
48
|
+
const shopifyId = initialData?.shopifyCustomer?.id;
|
|
49
|
+
if (shopifyId)
|
|
50
|
+
return `s:${shopifyId}`;
|
|
51
|
+
const joyId = initialData?.customer?.id;
|
|
52
|
+
return joyId ? `j:${joyId}` : null;
|
|
53
|
+
}
|
|
54
|
+
function toRedeemCartPort(port) {
|
|
55
|
+
return {
|
|
56
|
+
capabilities: port.capabilities,
|
|
57
|
+
applyDiscount: code => port.applyDiscount(code),
|
|
58
|
+
removeDiscount: code => port.removeDiscount(code),
|
|
59
|
+
addLines: async (lines) => port.addLines(lines),
|
|
60
|
+
redeemGift: input => port.redeemGift(input),
|
|
61
|
+
getCart: async () => port.getCart(),
|
|
62
|
+
revalidate: () => port.revalidate(),
|
|
63
|
+
setDiscountCodes: codes => port.setDiscountCodes(codes)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function createMemberClient(options) {
|
|
67
|
+
const { apiUrl, tokenRoute, locale, shopDomain } = options;
|
|
68
|
+
const client = ensureClient(apiUrl, tokenRoute ?? DEFAULT_TOKEN_ROUTE, locale, shopDomain);
|
|
69
|
+
const withToken = async (run) => {
|
|
70
|
+
const token = await getJoyToken(tokenRoute ? { tokenRoute } : {});
|
|
71
|
+
if (token)
|
|
72
|
+
client.setToken(token);
|
|
73
|
+
return run();
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
redeem: (programId, redeemOptions) => withToken(() => client.redeem(programId, redeemOptions)),
|
|
77
|
+
revokeReward: (rewardId) => withToken(() => client.cancelRedeem(rewardId)),
|
|
78
|
+
getRewards: (params) => withToken(() => client.getRewards(params)),
|
|
79
|
+
checkSegmentPrograms: (queries) => withToken(() => client.checkSegmentPrograms(queries))
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function flattenTranslation(blobTranslation, locale) {
|
|
83
|
+
return { ...resolveActiveTranslation(blobTranslation), ...resolveActiveTranslation(blobTranslation, locale) };
|
|
84
|
+
}
|
|
85
|
+
export function JoyRedeemCart({ apiUrl, shopDomain, tokenRoute, assetUrl, initialData, loginUrl, onNavigate, className, cart, cartFetcher, cartRevalidate, cartRoute, onCartUpdated }) {
|
|
86
|
+
const providerCart = useJoyProviderCart();
|
|
87
|
+
const providerHandlers = useJoyProviderCartHandlers();
|
|
88
|
+
const effectiveCart = cart ?? providerCart;
|
|
89
|
+
const effectiveOnCartUpdated = onCartUpdated ?? providerHandlers.onCartUpdated;
|
|
90
|
+
const cartRef = useRef(effectiveCart);
|
|
91
|
+
cartRef.current = effectiveCart;
|
|
92
|
+
const cartFetcherRef = useRef(cartFetcher);
|
|
93
|
+
cartFetcherRef.current = cartFetcher;
|
|
94
|
+
const cartRevalidateRef = useRef(cartRevalidate);
|
|
95
|
+
cartRevalidateRef.current = cartRevalidate;
|
|
96
|
+
const onCartUpdatedRef = useRef(effectiveOnCartUpdated);
|
|
97
|
+
onCartUpdatedRef.current = effectiveOnCartUpdated;
|
|
98
|
+
const onNavigateRef = useRef(onNavigate);
|
|
99
|
+
onNavigateRef.current = onNavigate;
|
|
100
|
+
const initialDataRef = useRef(initialData);
|
|
101
|
+
initialDataRef.current = initialData;
|
|
102
|
+
const loginUrlRef = useRef(loginUrl);
|
|
103
|
+
loginUrlRef.current = loginUrl;
|
|
104
|
+
const cartRouteRef = useRef(cartRoute);
|
|
105
|
+
cartRouteRef.current = cartRoute;
|
|
106
|
+
const cartPortRef = useRef(null);
|
|
107
|
+
const handleRef = useRef(null);
|
|
108
|
+
const hostRef = useRef(null);
|
|
109
|
+
const updateWarnedRef = useRef(false);
|
|
110
|
+
const [reserved, setReserved] = useState(true);
|
|
111
|
+
const [collapsed, setCollapsed] = useState(false);
|
|
112
|
+
useEffect(() => {
|
|
113
|
+
try {
|
|
114
|
+
cartPortRef.current?.settle();
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
const customerKey = resolveCustomerKey(initialData);
|
|
120
|
+
const locale = initialData?.locale;
|
|
121
|
+
const hasInitialData = Boolean(initialData);
|
|
122
|
+
const isCollapsed = collapsed || !hasInitialData;
|
|
123
|
+
useEffect(() => {
|
|
124
|
+
if (!hasInitialData)
|
|
125
|
+
return;
|
|
126
|
+
setCollapsed(false);
|
|
127
|
+
setReserved(true);
|
|
128
|
+
let disposed = false;
|
|
129
|
+
let handle = null;
|
|
130
|
+
let ownPort = null;
|
|
131
|
+
let releaseObserver = null;
|
|
132
|
+
let releaseTimer;
|
|
133
|
+
let warned = false;
|
|
134
|
+
const warnOnce = (message, detail) => {
|
|
135
|
+
if (warned)
|
|
136
|
+
return;
|
|
137
|
+
warned = true;
|
|
138
|
+
console.warn(`[joy] JoyRedeemCart: ${message}`, ...(detail === undefined ? [] : [detail]));
|
|
139
|
+
};
|
|
140
|
+
const disposeHandle = () => {
|
|
141
|
+
const current = handle;
|
|
142
|
+
handle = null;
|
|
143
|
+
if (handleRef.current === current)
|
|
144
|
+
handleRef.current = null;
|
|
145
|
+
if (!current)
|
|
146
|
+
return;
|
|
147
|
+
try {
|
|
148
|
+
current.dispose();
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
warnOnce('dispose failed', error);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const fail = (message, detail) => {
|
|
155
|
+
if (disposed)
|
|
156
|
+
return;
|
|
157
|
+
disposeHandle();
|
|
158
|
+
warnOnce(message, detail);
|
|
159
|
+
setCollapsed(true);
|
|
160
|
+
};
|
|
161
|
+
const getSnapshot = () => {
|
|
162
|
+
try {
|
|
163
|
+
return normalizeRedeemCartSnapshot(resolveCart(cartRef.current));
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
warnOnce('reading the cart snapshot failed', error);
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
const run = async () => {
|
|
171
|
+
const data = initialDataRef.current;
|
|
172
|
+
if (!data)
|
|
173
|
+
return;
|
|
174
|
+
const loadOptions = {
|
|
175
|
+
core: data.core,
|
|
176
|
+
preloadLazy: ['redeemCart'],
|
|
177
|
+
...(assetUrl ? { assetUrl } : {})
|
|
178
|
+
};
|
|
179
|
+
const loaded = await guarded('widget core load failed', () => loadWidgetCore(loadOptions));
|
|
180
|
+
if (disposed)
|
|
181
|
+
return;
|
|
182
|
+
if (!loaded.loaded)
|
|
183
|
+
throw new StageError('widget core load failed', loaded);
|
|
184
|
+
const loadRedeemCartCore = loaded.coreExports?.loadRedeemCartCore;
|
|
185
|
+
if (typeof loadRedeemCartCore !== 'function') {
|
|
186
|
+
throw new StageError('the widget core has no redeem-cart surface (older CDN core), rendering nothing', undefined);
|
|
187
|
+
}
|
|
188
|
+
const surface = await guarded('loading the redeem-cart core failed', () => loadRedeemCartCore());
|
|
189
|
+
if (disposed)
|
|
190
|
+
return;
|
|
191
|
+
const mount = surface?.mountRedeemCartCore;
|
|
192
|
+
if (typeof mount !== 'function') {
|
|
193
|
+
throw new StageError('the redeem-cart core has no mountRedeemCartCore, rendering nothing', undefined);
|
|
194
|
+
}
|
|
195
|
+
let builtPort = null;
|
|
196
|
+
if (cartFetcherRef.current && cartRevalidateRef.current) {
|
|
197
|
+
try {
|
|
198
|
+
const { HydrogenCartPort: Port } = await import('../hydrogen-cart-port.js');
|
|
199
|
+
if (!disposed) {
|
|
200
|
+
builtPort = new Port({
|
|
201
|
+
fetcher: {
|
|
202
|
+
get state() {
|
|
203
|
+
return cartFetcherRef.current?.state ?? 'idle';
|
|
204
|
+
},
|
|
205
|
+
get data() {
|
|
206
|
+
return cartFetcherRef.current?.data;
|
|
207
|
+
},
|
|
208
|
+
submit: (payload, submitOptions) => cartFetcherRef.current?.submit(payload, submitOptions)
|
|
209
|
+
},
|
|
210
|
+
getCart: () => resolveCart(cartRef.current),
|
|
211
|
+
revalidate: () => cartRevalidateRef.current?.(),
|
|
212
|
+
onCartUpdated: updated => onCartUpdatedRef.current?.(updated),
|
|
213
|
+
...(cartRouteRef.current ? { cartRoute: cartRouteRef.current } : {})
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
console.warn('[joy] JoyRedeemCart: cart-port failed, using copy mode', error);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (disposed)
|
|
222
|
+
return;
|
|
223
|
+
let cartPort = COPY_MODE_PORT;
|
|
224
|
+
if (builtPort) {
|
|
225
|
+
ownPort = builtPort;
|
|
226
|
+
cartPortRef.current = builtPort;
|
|
227
|
+
cartPort = toRedeemCartPort(builtPort);
|
|
228
|
+
}
|
|
229
|
+
const options = await guarded('setting up the mount failed', () => {
|
|
230
|
+
const blob = data.blob;
|
|
231
|
+
const blobTranslation = blob?.translation;
|
|
232
|
+
return {
|
|
233
|
+
source: {
|
|
234
|
+
blob,
|
|
235
|
+
customer: data.customer,
|
|
236
|
+
customerKey: resolveCustomerKey(data),
|
|
237
|
+
translation: flattenTranslation(blobTranslation, data.locale),
|
|
238
|
+
locale: resolveContentLocale(data.locale, blobTranslation),
|
|
239
|
+
loginUrl: loginUrlRef.current ?? data.login_url
|
|
240
|
+
},
|
|
241
|
+
client: data.customer ? createMemberClient({ apiUrl, tokenRoute, locale: data.locale, shopDomain }) : null,
|
|
242
|
+
cartPort,
|
|
243
|
+
getSnapshot,
|
|
244
|
+
hooks: {
|
|
245
|
+
navigate: (url) => onNavigateRef.current
|
|
246
|
+
? onNavigateRef.current(url)
|
|
247
|
+
: window.location.assign(safeNavigationUrl(url)?.href ?? '/')
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
});
|
|
251
|
+
if (disposed)
|
|
252
|
+
return;
|
|
253
|
+
const host = hostRef.current;
|
|
254
|
+
if (!host)
|
|
255
|
+
return;
|
|
256
|
+
const created = await guarded('mount failed', () => mount(host, options));
|
|
257
|
+
handle = created ?? null;
|
|
258
|
+
if (disposed) {
|
|
259
|
+
disposeHandle();
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
handleRef.current = handle;
|
|
263
|
+
await guarded('reading the first cart snapshot failed', () => normalizeRedeemCartSnapshot(resolveCart(cartRef.current)));
|
|
264
|
+
if (disposed)
|
|
265
|
+
return;
|
|
266
|
+
if (host.childNodes.length > 0)
|
|
267
|
+
return setReserved(false);
|
|
268
|
+
releaseObserver = new MutationObserver(() => {
|
|
269
|
+
if (host.childNodes.length === 0)
|
|
270
|
+
return;
|
|
271
|
+
releaseObserver?.disconnect();
|
|
272
|
+
setReserved(false);
|
|
273
|
+
});
|
|
274
|
+
releaseObserver.observe(host, { childList: true });
|
|
275
|
+
releaseTimer = setTimeout(() => {
|
|
276
|
+
releaseObserver?.disconnect();
|
|
277
|
+
setReserved(false);
|
|
278
|
+
}, PLACEHOLDER_RELEASE_FALLBACK_MS);
|
|
279
|
+
};
|
|
280
|
+
void run()
|
|
281
|
+
.catch(error => {
|
|
282
|
+
if (error instanceof StageError)
|
|
283
|
+
fail(error.stage, error.detail);
|
|
284
|
+
else
|
|
285
|
+
fail('unexpected failure', error);
|
|
286
|
+
})
|
|
287
|
+
.catch(() => { });
|
|
288
|
+
return () => {
|
|
289
|
+
disposed = true;
|
|
290
|
+
releaseObserver?.disconnect();
|
|
291
|
+
clearTimeout(releaseTimer);
|
|
292
|
+
if (cartPortRef.current === ownPort)
|
|
293
|
+
cartPortRef.current = null;
|
|
294
|
+
disposeHandle();
|
|
295
|
+
};
|
|
296
|
+
}, [apiUrl, shopDomain, tokenRoute, assetUrl, customerKey, locale, hasInitialData]);
|
|
297
|
+
const resolvedCart = resolveCart(effectiveCart);
|
|
298
|
+
useEffect(() => {
|
|
299
|
+
if (!handleRef.current)
|
|
300
|
+
return;
|
|
301
|
+
const timer = setTimeout(() => {
|
|
302
|
+
const handle = handleRef.current;
|
|
303
|
+
if (!handle)
|
|
304
|
+
return;
|
|
305
|
+
Promise.resolve()
|
|
306
|
+
.then(() => handle.update())
|
|
307
|
+
.catch(error => {
|
|
308
|
+
if (updateWarnedRef.current)
|
|
309
|
+
return;
|
|
310
|
+
updateWarnedRef.current = true;
|
|
311
|
+
console.warn('[joy] JoyRedeemCart: update failed', error);
|
|
312
|
+
});
|
|
313
|
+
}, CART_UPDATE_DEBOUNCE_MS);
|
|
314
|
+
return () => clearTimeout(timer);
|
|
315
|
+
}, [resolvedCart]);
|
|
316
|
+
return (_jsxs("div", { className: className, hidden: isCollapsed, style: isCollapsed ? { display: 'none' } : undefined, children: [_jsx(WidgetCorePreloadLinks, { core: initialData?.core, assetUrl: assetUrl, lazy: ['redeemCart'] }), createElement('div', {
|
|
317
|
+
ref: hostRef,
|
|
318
|
+
'data-joy-redeem-cart': '',
|
|
319
|
+
style: reserved && !isCollapsed ? { minHeight: PLACEHOLDER_MIN_HEIGHT } : undefined
|
|
320
|
+
})] }));
|
|
321
|
+
}
|
|
@@ -116,24 +116,29 @@ const COLLECTION_SORT_KEYS = new Set([
|
|
|
116
116
|
const DEFAULT_SORT = { sortKey: 'BEST_SELLING', reverse: false };
|
|
117
117
|
export async function loader({ context, request }) {
|
|
118
118
|
const params = new URL(request.url).searchParams;
|
|
119
|
+
const market = marketVariables(params);
|
|
119
120
|
if (params.has('recommend')) {
|
|
120
|
-
return loadRecommendations(context.storefront, params);
|
|
121
|
+
return loadRecommendations(context.storefront, params, market);
|
|
121
122
|
}
|
|
122
123
|
const collectionsParam = params.get('collections');
|
|
123
124
|
if (collectionsParam !== null) {
|
|
124
|
-
return loadCollections(context.storefront, collectionsParam);
|
|
125
|
+
return loadCollections(context.storefront, collectionsParam, market);
|
|
125
126
|
}
|
|
126
127
|
const handlesParam = params.get('handles');
|
|
127
128
|
if (handlesParam !== null) {
|
|
128
|
-
return loadByHandles(context.storefront, handlesParam);
|
|
129
|
+
return loadByHandles(context.storefront, handlesParam, market);
|
|
129
130
|
}
|
|
130
131
|
return json({ products: [], currencyCode: null }, 400);
|
|
131
132
|
}
|
|
132
|
-
|
|
133
|
+
function marketVariables(params) {
|
|
134
|
+
const country = params.get('country');
|
|
135
|
+
return country && /^[A-Z]{2}$/.test(country) ? { country } : {};
|
|
136
|
+
}
|
|
137
|
+
async function loadByHandles(storefront, raw, market) {
|
|
133
138
|
const handles = parseHandles(raw);
|
|
134
139
|
if (!handles.length)
|
|
135
140
|
return json({ products: [], currencyCode: null, handles }, 200);
|
|
136
|
-
const variables = {};
|
|
141
|
+
const variables = { ...market };
|
|
137
142
|
handles.forEach((handle, index) => {
|
|
138
143
|
variables[`h${index}`] = handle;
|
|
139
144
|
});
|
|
@@ -150,7 +155,7 @@ async function loadByHandles(storefront, raw) {
|
|
|
150
155
|
}
|
|
151
156
|
return json({ products: nodes.map(toAjaxProduct), currencyCode: pickCurrencyCode(nodes), handles }, 200);
|
|
152
157
|
}
|
|
153
|
-
async function loadRecommendations(storefront, params) {
|
|
158
|
+
async function loadRecommendations(storefront, params, market) {
|
|
154
159
|
const seed = sanitizeHandle(params.get('recommend'));
|
|
155
160
|
const collectionHandle = sanitizeHandle(params.get('fallbackCollection'));
|
|
156
161
|
const { sortKey, reverse } = resolveSort(params.get('fallbackSort'));
|
|
@@ -158,6 +163,7 @@ async function loadRecommendations(storefront, params) {
|
|
|
158
163
|
try {
|
|
159
164
|
const data = (await storefront.query(RECOMMENDATIONS_QUERY, {
|
|
160
165
|
variables: {
|
|
166
|
+
...market,
|
|
161
167
|
handle: seed,
|
|
162
168
|
useRecommended: !!seed,
|
|
163
169
|
collectionHandle,
|
|
@@ -180,11 +186,11 @@ async function loadRecommendations(storefront, params) {
|
|
|
180
186
|
.filter((product) => !!product && product.handle !== seed);
|
|
181
187
|
return json({ products, currencyCode: pickCurrencyCode(nodes) }, 200);
|
|
182
188
|
}
|
|
183
|
-
async function loadCollections(storefront, raw) {
|
|
189
|
+
async function loadCollections(storefront, raw, market) {
|
|
184
190
|
const handles = parseHandles(raw, MAX_COLLECTIONS);
|
|
185
191
|
if (!handles.length)
|
|
186
192
|
return json({ collections: [] }, 200);
|
|
187
|
-
const variables = {};
|
|
193
|
+
const variables = { ...market };
|
|
188
194
|
handles.forEach((handle, index) => {
|
|
189
195
|
variables[`h${index}`] = handle;
|
|
190
196
|
});
|
|
@@ -274,7 +280,7 @@ function toAjaxProduct(node) {
|
|
|
274
280
|
handle: node.handle,
|
|
275
281
|
title: node.title ?? '',
|
|
276
282
|
url: `/products/${node.handle}`,
|
|
277
|
-
price:
|
|
283
|
+
price: toPriceCents(node.priceRange?.minVariantPrice),
|
|
278
284
|
compare_at_price: toCents(node.compareAtPriceRange?.maxVariantPrice),
|
|
279
285
|
featured_image: featuredImage,
|
|
280
286
|
images,
|
|
@@ -290,11 +296,17 @@ function toAjaxVariant(variant) {
|
|
|
290
296
|
.map(perDeliveryPrice => ({ perDeliveryPrice })));
|
|
291
297
|
return {
|
|
292
298
|
id: numericId(variant.id),
|
|
293
|
-
price:
|
|
299
|
+
price: toPriceCents(variant.price),
|
|
294
300
|
compare_at_price: toCents(variant.compareAtPrice),
|
|
295
301
|
sellingPlanAllocations: allocations
|
|
296
302
|
};
|
|
297
303
|
}
|
|
304
|
+
function toPriceCents(money) {
|
|
305
|
+
const amount = Number(money?.amount);
|
|
306
|
+
if (money?.amount == null || !Number.isFinite(amount) || amount < 0)
|
|
307
|
+
return null;
|
|
308
|
+
return Math.round(amount * 100);
|
|
309
|
+
}
|
|
298
310
|
function toCents(money) {
|
|
299
311
|
const amount = Number(money?.amount);
|
|
300
312
|
if (!Number.isFinite(amount) || amount <= 0)
|