@joy-loyalty/hydrogen 0.2.1 → 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 +115 -1
- package/dist/hydrogen-cart-port.d.ts +49 -1
- package/dist/hydrogen-cart-port.js +23 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +1 -0
- package/dist/lib/core-loader.d.ts +23 -0
- package/dist/lib/redeem-cart-snapshot.d.ts +51 -0
- package/dist/lib/redeem-cart-snapshot.js +173 -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/widget-orchestrator.js +2 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @joy-loyalty/hydrogen
|
|
2
2
|
|
|
3
|
-
Joy Loyalty for Hydrogen / headless Shopify storefronts. Embeds the Joy Loyalty Widget V4 (`<JoyWidget/>`) and
|
|
3
|
+
Joy Loyalty for Hydrogen / headless Shopify storefronts. Embeds the Joy Loyalty Widget V4 (`<JoyWidget/>`) and the new loyalty page (`<JoyLoyaltyPage/>`) in any Hydrogen app, plus the server helpers and resource routes they need. No Weaverse dependency (for Weaverse use [`@joy-loyalty/weaverse-hydrogen`](../weaverse-hydrogen), which builds on this package).
|
|
4
4
|
|
|
5
5
|
The widget core is a shared, host-neutral Lit bundle loaded at runtime from `https://api.joy.so`. It talks to the Joy Headless API; this package supplies the host side (token exchange, SSR data, cart wiring).
|
|
6
6
|
|
|
@@ -90,6 +90,120 @@ import {JoyLoyaltyPage} from '@joy-loyalty/hydrogen';
|
|
|
90
90
|
```
|
|
91
91
|
The server-rendered data carries no customer information by design; customer data loads client-side with the JWT. Set `sectionId` to render a single section.
|
|
92
92
|
|
|
93
|
+
### Cart drawer block (`<JoyRedeemCart/>`)
|
|
94
|
+
|
|
95
|
+
The headless counterpart of the Liquid "Joy: Redeem in Cart" block: points balance, redeemable
|
|
96
|
+
rewards (fixed and dynamic), apply to cart, applied-rewards list with revoke/remove, combinability
|
|
97
|
+
and best-value hints, earn-back line, and a guest "earn / sign in" state, styled from the Joy admin
|
|
98
|
+
Redeem-in-Cart design settings. Mount it inside your cart drawer or cart page:
|
|
99
|
+
|
|
100
|
+
```tsx
|
|
101
|
+
import {JoyRedeemCart} from '@joy-loyalty/hydrogen';
|
|
102
|
+
import {useFetcher, useRevalidator} from 'react-router';
|
|
103
|
+
|
|
104
|
+
const cartFetcher = useFetcher({key: 'joy-redeem-cart'}); // dedicated key — don't share the merchant's cart form fetcher
|
|
105
|
+
const {revalidate} = useRevalidator();
|
|
106
|
+
|
|
107
|
+
<JoyRedeemCart
|
|
108
|
+
apiUrl={data.joyApiUrl}
|
|
109
|
+
shopDomain={data.joyShopDomain}
|
|
110
|
+
initialData={data.joy}
|
|
111
|
+
cart={cart}
|
|
112
|
+
cartFetcher={cartFetcher}
|
|
113
|
+
cartRevalidate={revalidate}
|
|
114
|
+
cartRoute="/cart" // locale-aware if your app uses markets, e.g. /fr-ca/cart
|
|
115
|
+
/>;
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
| Prop | Type | Required | Notes |
|
|
119
|
+
|---|---|---|---|
|
|
120
|
+
| `apiUrl` | `string` | yes | Headless API base URL (`JOY_API_URL`). |
|
|
121
|
+
| `shopDomain` | `string` | yes | The shop's `*.myshopify.com` domain. |
|
|
122
|
+
| `initialData` | `JoyInitialDataResult \| null` | yes | The root loader's `getJoyInitialData()` result — the same value `<JoyWidget/>` takes. |
|
|
123
|
+
| `cart` | `StorefrontCart \| () => StorefrontCart` | no | The storefront cart (needs the fragment fields below). Falls back to `<JoyProvider cart>`. Without a cart (or with an empty one) the block renders nothing, like the Liquid block. |
|
|
124
|
+
| `cartFetcher` | `useFetcher()` result | no | With `cartRevalidate`, enables applying codes to the cart. Falls back to the `<JoyProvider>` handlers. |
|
|
125
|
+
| `cartRevalidate` | `() => void` | no | `useRevalidator().revalidate`. |
|
|
126
|
+
| `cartRoute` | `string` | no | Cart action route; default `/cart`. |
|
|
127
|
+
| `onCartUpdated` | `(cart) => void` | no | Called with the cart each of this block's cart mutations returns. |
|
|
128
|
+
| `tokenRoute` | `string` | no | Same-origin token route; default `/api/joy-token`. |
|
|
129
|
+
| `loginUrl` | `string` | no | Overrides `initialData.login_url` for the guest "Sign in" link. |
|
|
130
|
+
| `onNavigate` | `(url) => void` | no | Client-side navigation (`useNavigate()`); omitted → full page load. |
|
|
131
|
+
| `assetUrl` | `string` | no | Overrides the widget-core CDN URL (`JOY_WIDGET_ASSET_URL`). |
|
|
132
|
+
| `className` | `string` | no | Class for the wrapper element. |
|
|
133
|
+
|
|
134
|
+
**Cart action requirement.** The cart route's action must return the updated `cart` in its
|
|
135
|
+
response — the Hydrogen skeleton's default `{cart, errors, warnings}` from `CartForm` actions does.
|
|
136
|
+
The block only trusts the cart returned by its own mutation: without it, it cannot confirm a
|
|
137
|
+
discount write, so every apply is rolled back (the shopper's own applicable codes are restored, as
|
|
138
|
+
in Liquid, and the reward is refunded when the merchant enabled that).
|
|
139
|
+
|
|
140
|
+
**No cart adapter (copy-code mode).** Without `cartFetcher` + `cartRevalidate` the block still
|
|
141
|
+
redeems: the issued code is shown with a Copy button and a "copy this code and apply it at
|
|
142
|
+
checkout" hint. "Copied" appears only after a confirmed clipboard write; on origins where the
|
|
143
|
+
Clipboard API is unavailable or rejected, the code is selected for manual copy instead. If the
|
|
144
|
+
optional cart-port chunk fails to load, the block falls back to this mode. Issued codes are
|
|
145
|
+
remembered per customer for the browser session only (never shown to a guest or another customer).
|
|
146
|
+
|
|
147
|
+
**Cart fragment.** Merge these fields into your `CART_QUERY_FRAGMENT`. Two variants, both
|
|
148
|
+
validated with the Shopify toolkit:
|
|
149
|
+
|
|
150
|
+
Default — Storefront API 2025-10 → 2026-10 (uses the deprecated-but-valid `Cart.discountAllocations`):
|
|
151
|
+
|
|
152
|
+
```graphql
|
|
153
|
+
fragment JoyRedeemCartDefault on Cart {
|
|
154
|
+
discountCodes { code applicable }
|
|
155
|
+
cost { subtotalAmount { amount currencyCode } totalAmount { amount currencyCode } }
|
|
156
|
+
discountAllocations { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } }
|
|
157
|
+
lines(first: $numCartLines) { nodes {
|
|
158
|
+
id quantity
|
|
159
|
+
cost { subtotalAmount { amount currencyCode } totalAmount { amount currencyCode } }
|
|
160
|
+
discountAllocations { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } }
|
|
161
|
+
merchandise { ... on ProductVariant { id product { id collections(first: 20) { nodes { id } pageInfo { hasNextPage } } } } }
|
|
162
|
+
} }
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Modern — Storefront API 2026-07+ only (invalid on 2026-04 and earlier):
|
|
167
|
+
|
|
168
|
+
```graphql
|
|
169
|
+
fragment JoyRedeemCartModern on Cart {
|
|
170
|
+
discountCodes { code applicable }
|
|
171
|
+
cost { subtotalAmount { amount currencyCode } totalAmount { amount currencyCode } }
|
|
172
|
+
lines(first: $numCartLines) { nodes {
|
|
173
|
+
id quantity
|
|
174
|
+
cost { subtotalAmount { amount currencyCode } totalAmount { amount currencyCode } }
|
|
175
|
+
discountAllocations { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } }
|
|
176
|
+
joyAllDiscounts: discountAllocations(lineLevelOnly: false) { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } }
|
|
177
|
+
merchandise { ... on ProductVariant { id product { id collections(first: 20) { nodes { id } pageInfo { hasNextPage } } } } }
|
|
178
|
+
} }
|
|
179
|
+
deliveryGroups(first: 10) { nodes { discountAllocations { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } } } }
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
**Notes**
|
|
184
|
+
|
|
185
|
+
- **Cart totals.** Merchandise totals are rebuilt from line costs + discount allocations
|
|
186
|
+
(product- vs order-level by which list an allocation appears in; shipping excluded), never from
|
|
187
|
+
`cost.totalAmount`, which can include tax, duties and delivery. If your merged fragment lacks the
|
|
188
|
+
allocation fields while a code is applied, the block treats the cart as unknown and disables
|
|
189
|
+
redemption; if it cannot tell an external code's class, it shows no pre-emptive "can't combine"
|
|
190
|
+
hint for it.
|
|
191
|
+
- **Collections.** `collections(first: 20)` is optional. Absent **or** truncated
|
|
192
|
+
(`pageInfo.hasNextPage: true`) collection data hides collection-scoped rewards (fail-closed).
|
|
193
|
+
- **Multi-market.** v1 has no market-rate conversion (planned for v1.1): when the cart's currency
|
|
194
|
+
differs from the shop's base currency the block renders nothing, so no amount is ever shown with
|
|
195
|
+
the wrong currency. Carts in the shop currency are unaffected.
|
|
196
|
+
- **Earn-back estimate (rule-engine shops).** The cart fragment carries no product tags, vendor,
|
|
197
|
+
type or collection details, so on shops migrated to the rule engine a place-order rule scoped
|
|
198
|
+
to a collection, tag or vendor is not matched and the "Earn X points" line can be lower than the
|
|
199
|
+
Liquid block shows for the same cart. It is an estimate only; points are awarded on the order.
|
|
200
|
+
- **Guests** see the earn-back line and a "Sign in" link (`login_url`), as in the Liquid block;
|
|
201
|
+
the "hide for guest" setting is honoured.
|
|
202
|
+
- **Requires a widget core with `loadRedeemCartCore`.** Against an older core the block renders
|
|
203
|
+
nothing and logs one `[joy] JoyRedeemCart: …` warning. It never throws into your drawer: any load
|
|
204
|
+
or mount failure collapses the block and warns once.
|
|
205
|
+
- **Not yet supported:** the "prefer higher-value reward" swap setting (planned for v1.1).
|
|
206
|
+
|
|
93
207
|
## Optional resource routes
|
|
94
208
|
|
|
95
209
|
Each is a one-line re-export; the widget degrades gracefully without them.
|
|
@@ -1,10 +1,37 @@
|
|
|
1
|
-
type
|
|
1
|
+
import type { CartPort } from '@joy-loyalty/sdk/ports';
|
|
2
|
+
type StorefrontMoney = {
|
|
3
|
+
amount?: string | null;
|
|
4
|
+
currencyCode?: string | null;
|
|
5
|
+
};
|
|
6
|
+
export type StorefrontCartDiscountAllocation = {
|
|
7
|
+
targetType?: string | null;
|
|
8
|
+
discountedAmount?: StorefrontMoney | null;
|
|
9
|
+
code?: string | null;
|
|
10
|
+
};
|
|
11
|
+
export type CartLine = {
|
|
2
12
|
id?: string | null;
|
|
3
13
|
merchandise?: {
|
|
4
14
|
id?: string | null;
|
|
5
15
|
availableForSale?: boolean | null;
|
|
16
|
+
product?: {
|
|
17
|
+
id?: string | null;
|
|
18
|
+
collections?: {
|
|
19
|
+
nodes?: Array<{
|
|
20
|
+
id?: string | null;
|
|
21
|
+
} | null> | null;
|
|
22
|
+
pageInfo?: {
|
|
23
|
+
hasNextPage?: boolean | null;
|
|
24
|
+
} | null;
|
|
25
|
+
} | null;
|
|
26
|
+
} | null;
|
|
6
27
|
} | null;
|
|
7
28
|
quantity?: number | null;
|
|
29
|
+
cost?: {
|
|
30
|
+
totalAmount?: StorefrontMoney | null;
|
|
31
|
+
subtotalAmount?: StorefrontMoney | null;
|
|
32
|
+
} | null;
|
|
33
|
+
discountAllocations?: StorefrontCartDiscountAllocation[] | null;
|
|
34
|
+
joyAllDiscounts?: StorefrontCartDiscountAllocation[] | null;
|
|
8
35
|
};
|
|
9
36
|
export type StorefrontCart = {
|
|
10
37
|
updatedAt?: string | null;
|
|
@@ -25,6 +52,12 @@ export type StorefrontCart = {
|
|
|
25
52
|
currencyCode?: string | null;
|
|
26
53
|
} | null;
|
|
27
54
|
} | null;
|
|
55
|
+
discountAllocations?: StorefrontCartDiscountAllocation[] | null;
|
|
56
|
+
deliveryGroups?: {
|
|
57
|
+
nodes?: Array<{
|
|
58
|
+
discountAllocations?: StorefrontCartDiscountAllocation[] | null;
|
|
59
|
+
} | null> | null;
|
|
60
|
+
} | null;
|
|
28
61
|
};
|
|
29
62
|
export interface HydrogenCartFetcher {
|
|
30
63
|
state: string;
|
|
@@ -41,6 +74,17 @@ export interface HydrogenCartPortOptions {
|
|
|
41
74
|
cartRoute?: string;
|
|
42
75
|
onCartUpdated?: (cart: StorefrontCart) => void;
|
|
43
76
|
}
|
|
77
|
+
export type SetDiscountCodesResult = {
|
|
78
|
+
ok: true;
|
|
79
|
+
discountCodes: Array<{
|
|
80
|
+
code: string;
|
|
81
|
+
applicable: boolean;
|
|
82
|
+
}>;
|
|
83
|
+
source: 'mutation' | 'host';
|
|
84
|
+
} | {
|
|
85
|
+
ok: false;
|
|
86
|
+
reason: string;
|
|
87
|
+
};
|
|
44
88
|
export declare function normalizeHydrogenCart(cart: StorefrontCart | null | undefined): {
|
|
45
89
|
lines: {
|
|
46
90
|
variantId: string;
|
|
@@ -113,6 +157,7 @@ export declare class HydrogenCartPort {
|
|
|
113
157
|
reason: string;
|
|
114
158
|
}>;
|
|
115
159
|
removeDiscount(code: string): Promise<void>;
|
|
160
|
+
setDiscountCodes(codes: string[]): Promise<SetDiscountCodesResult>;
|
|
116
161
|
addLines(lines: Array<{
|
|
117
162
|
id: string;
|
|
118
163
|
quantity?: number;
|
|
@@ -130,5 +175,8 @@ export declare class HydrogenCartPort {
|
|
|
130
175
|
private submit;
|
|
131
176
|
private publishCart;
|
|
132
177
|
}
|
|
178
|
+
export type RedeemCartPort = CartPort & {
|
|
179
|
+
setDiscountCodes: HydrogenCartPort['setDiscountCodes'];
|
|
180
|
+
};
|
|
133
181
|
export declare function settleHydrogenCartPort(port: HydrogenCartPort): void;
|
|
134
182
|
export {};
|
|
@@ -123,6 +123,29 @@ export class HydrogenCartPort {
|
|
|
123
123
|
});
|
|
124
124
|
});
|
|
125
125
|
}
|
|
126
|
+
setDiscountCodes(codes) {
|
|
127
|
+
return this.serialize(async () => {
|
|
128
|
+
try {
|
|
129
|
+
const seen = new Set();
|
|
130
|
+
const discountCodes = codes.filter(code => {
|
|
131
|
+
const key = code.toLowerCase();
|
|
132
|
+
if (seen.has(key))
|
|
133
|
+
return false;
|
|
134
|
+
seen.add(key);
|
|
135
|
+
return true;
|
|
136
|
+
});
|
|
137
|
+
const result = await this.submit(CartForm.ACTIONS.DiscountCodesUpdate, { discountCodes });
|
|
138
|
+
const updated = normalizeHydrogenCart(cartFromResult(result));
|
|
139
|
+
if (updated)
|
|
140
|
+
return { ok: true, discountCodes: updated.discountCodes, source: 'mutation' };
|
|
141
|
+
const host = this.getCart();
|
|
142
|
+
return host ? { ok: true, discountCodes: host.discountCodes, source: 'host' } : { ok: false, reason: 'NO_CART' };
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
return { ok: false, reason: error.message };
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
}
|
|
126
149
|
addLines(lines) {
|
|
127
150
|
for (const line of lines) {
|
|
128
151
|
if (!isVariantGid(line.id))
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,9 @@ export { JoyWidget } from './joy-widget.js';
|
|
|
2
2
|
export type { JoyWidgetProps } from './joy-widget.js';
|
|
3
3
|
export { JoyLoyaltyPage, isLoyaltyPageV2Enabled } from './loyalty-page/JoyLoyaltyPage.js';
|
|
4
4
|
export type { JoyLoyaltyPageInitialData, JoyLoyaltyPageProps } from './loyalty-page/JoyLoyaltyPage.js';
|
|
5
|
+
export { JoyRedeemCart } from './redeem-cart/JoyRedeemCart.js';
|
|
6
|
+
export type { JoyRedeemCartProps } from './redeem-cart/JoyRedeemCart.js';
|
|
7
|
+
export type { StorefrontCart } from './hydrogen-cart-port.js';
|
|
5
8
|
export { createHeadlessHostAdapter, createJoyDataSource } from './headless-host-adapter.js';
|
|
6
9
|
export type { ActivityQuery, DataCapabilities, EarnRequest, HeadlessHostAdapter, HeadlessHostAdapterOptions, HeadlessHostContext, HeadlessDataPort, JoyDataSource, JoyInitialData, RedeemOptions, RedeemRecipient, ReferralHistoryItem, ReferralHistoryPage, RewardQuery } from './headless-host-adapter.js';
|
|
7
10
|
export { JOY_API_ORIGIN, JOY_CDN_ORIGIN, JOY_CSP_DIRECTIVES, joyCspDirectives } from './csp.js';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { JoyWidget } from './joy-widget.js';
|
|
2
2
|
export { JoyLoyaltyPage, isLoyaltyPageV2Enabled } from './loyalty-page/JoyLoyaltyPage.js';
|
|
3
|
+
export { JoyRedeemCart } from './redeem-cart/JoyRedeemCart.js';
|
|
3
4
|
export { createHeadlessHostAdapter, createJoyDataSource } from './headless-host-adapter.js';
|
|
4
5
|
export { JOY_API_ORIGIN, JOY_CDN_ORIGIN, JOY_CSP_DIRECTIVES, joyCspDirectives } from './csp.js';
|
|
5
6
|
export { JOY_PERSONALIZED_CACHE_CONTROL, isJoyInitialDataPersonalized } from './cache-control.js';
|
|
@@ -33,8 +33,31 @@ export interface WidgetCoreExports {
|
|
|
33
33
|
}) => Promise<unknown[]>;
|
|
34
34
|
getDeeplinkByHash?: (hash: string) => unknown;
|
|
35
35
|
resolveDeeplinkHash?: (param: string | null) => string | null;
|
|
36
|
+
loadRedeemCartCore?: () => Promise<{
|
|
37
|
+
mountRedeemCartCore: MountRedeemCartCore;
|
|
38
|
+
}>;
|
|
36
39
|
[key: string]: unknown;
|
|
37
40
|
}
|
|
41
|
+
export interface RedeemCartCoreHandle {
|
|
42
|
+
update(): void;
|
|
43
|
+
dispose(): void;
|
|
44
|
+
}
|
|
45
|
+
export type MountRedeemCartCore = (el: HTMLElement, options: {
|
|
46
|
+
source: {
|
|
47
|
+
blob: unknown;
|
|
48
|
+
customer: unknown;
|
|
49
|
+
customerKey: string | null;
|
|
50
|
+
translation: Record<string, string>;
|
|
51
|
+
locale: string;
|
|
52
|
+
loginUrl?: string;
|
|
53
|
+
};
|
|
54
|
+
client: unknown;
|
|
55
|
+
cartPort: unknown;
|
|
56
|
+
getSnapshot: () => unknown;
|
|
57
|
+
hooks: {
|
|
58
|
+
navigate: (url: string) => void;
|
|
59
|
+
};
|
|
60
|
+
}) => RedeemCartCoreHandle | Promise<RedeemCartCoreHandle>;
|
|
38
61
|
export interface LoadWidgetCoreOptions {
|
|
39
62
|
assetUrl?: string;
|
|
40
63
|
core?: WidgetCoreManifest | null;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { StorefrontCart } from '../hydrogen-cart-port.js';
|
|
2
|
+
export type RedeemCartLineAllocation = {
|
|
3
|
+
amount: number;
|
|
4
|
+
discount_application: {
|
|
5
|
+
type: string;
|
|
6
|
+
title: string;
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
export type RedeemCartLevelApplication = {
|
|
10
|
+
type: string;
|
|
11
|
+
title: string;
|
|
12
|
+
total_allocated_amount: number;
|
|
13
|
+
};
|
|
14
|
+
export type RedeemCartItem = {
|
|
15
|
+
id: number | null;
|
|
16
|
+
product_id: number | null;
|
|
17
|
+
variant_id: number | null;
|
|
18
|
+
quantity: number;
|
|
19
|
+
original_line_price: number;
|
|
20
|
+
final_line_price: number;
|
|
21
|
+
final_price: number;
|
|
22
|
+
collectionIds: number[];
|
|
23
|
+
};
|
|
24
|
+
export type RedeemCartInfoItem = {
|
|
25
|
+
variant_id: number | null;
|
|
26
|
+
product_id: number | null;
|
|
27
|
+
quantity: number;
|
|
28
|
+
original_line_price: number;
|
|
29
|
+
final_line_price: number;
|
|
30
|
+
line_level_total_discount: number;
|
|
31
|
+
line_level_discount_allocations: RedeemCartLineAllocation[];
|
|
32
|
+
};
|
|
33
|
+
export type RedeemCartInfo = {
|
|
34
|
+
currency: string | null;
|
|
35
|
+
original_total_price: number;
|
|
36
|
+
total_discount: number;
|
|
37
|
+
discount_codes: Array<{
|
|
38
|
+
code: string;
|
|
39
|
+
applicable: boolean;
|
|
40
|
+
}>;
|
|
41
|
+
items?: RedeemCartInfoItem[];
|
|
42
|
+
cart_level_discount_applications?: RedeemCartLevelApplication[];
|
|
43
|
+
};
|
|
44
|
+
export type RedeemCartSnapshot = {
|
|
45
|
+
cartItems: RedeemCartItem[];
|
|
46
|
+
cartInfo: RedeemCartInfo;
|
|
47
|
+
cartStateKnown: boolean;
|
|
48
|
+
collectionIdsKnown: boolean;
|
|
49
|
+
currency: string | null;
|
|
50
|
+
};
|
|
51
|
+
export declare function normalizeRedeemCartSnapshot(cart: StorefrontCart | null | undefined): RedeemCartSnapshot | null;
|
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -390,9 +390,10 @@ export function createWidgetOrchestrator(container, hostAdapter, initialData, ap
|
|
|
390
390
|
});
|
|
391
391
|
if (!built)
|
|
392
392
|
return null;
|
|
393
|
-
const { facade } = built;
|
|
393
|
+
const { facade, renderInput } = built;
|
|
394
394
|
facade.hostAdapter.data = hostAdapter.data;
|
|
395
395
|
facade.widgetEl = element;
|
|
396
|
+
facade._renderInput = renderInput;
|
|
396
397
|
return facade;
|
|
397
398
|
}
|
|
398
399
|
function loadRecentlyViewed() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@joy-loyalty/hydrogen",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Joy Loyalty Widget V4 for any Hydrogen / headless Shopify storefront — host-neutral core embedded through HeadlessHostAdapter. No Weaverse dependency.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "module",
|
|
@@ -95,7 +95,7 @@
|
|
|
95
95
|
}
|
|
96
96
|
},
|
|
97
97
|
"dependencies": {
|
|
98
|
-
"@joy-loyalty/sdk": "^0.
|
|
98
|
+
"@joy-loyalty/sdk": "^0.3.0",
|
|
99
99
|
"dompurify": "^3.1.7"
|
|
100
100
|
},
|
|
101
101
|
"devDependencies": {
|