@disconetwork/shopify 0.0.7 → 0.0.8

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.
@@ -1,1819 +0,0 @@
1
- import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";
2
- import { createContext } from "preact";
3
- import { cloneElement, createContext as createContext$1, createElement, isValidElement, useCallback as useCallback$1, useContext as useContext$1, useEffect as useEffect$1, useMemo as useMemo$1, useState as useState$1 } from "preact/compat";
4
- import { withImpressionDedupe } from "@disconetwork/core";
5
- import { jsx } from "preact/jsx-runtime";
6
- import { INTERNAL_BASE_URL, InternalDiscoClient, parseScreens } from "@disconetwork/core/internal";
7
- import { Fragment, jsx as jsx$1, jsxs } from "preact/jsx-runtime";
8
- import { useApi, useBillingAddress, useCartLines, useCheckoutToken, useCustomer, useDiscountCodes, useEmail, usePhone, usePurchasingCompany, useShippingAddress, useShop, useSubscription, useTotalAmount } from "@shopify/ui-extensions/checkout/preact";
9
- import { useApi as useApi$1, useBillingAddress as useBillingAddress$1, useCartLines as useCartLines$1, useCustomer as useCustomer$1, useDiscountCodes as useDiscountCodes$1, useEmail as useEmail$1, useOrder, usePhone as usePhone$1, usePurchasingCompany as usePurchasingCompany$1, useShippingAddress as useShippingAddress$1, useShop as useShop$1, useSubscription as useSubscription$1, useTotalAmount as useTotalAmount$1 } from "@shopify/ui-extensions/customer-account/preact";
10
- //#region ../react-shared/dist/createHeadlessBindings-CPuF5wZQ.js
11
- /**
12
- * Build a self-contained set of headless React bindings for one client type.
13
- *
14
- * Returns the client context (for a backing-specific `DiscoProvider` to provide
15
- * into), the `useDiscoClient` accessor, the `Disco.Root` controller, and the
16
- * `useDiscoRecommendations` / `useDiscoTracker` / `useFetchRecommendations`
17
- * hooks — all concretely typed to `TRequest` / `TResponse`. Call this once per
18
- * backing at module load; the returned components/hooks are stable references.
19
- */
20
- function createHeadlessBindings() {
21
- /**
22
- * Holds the client built by the backing's `<DiscoProvider>`. Read it with
23
- * `useDiscoClient` to fetch recommendations or create trackers.
24
- */
25
- const DiscoClientContext = createContext$1(null);
26
- /**
27
- * Read the client configured by the surrounding `<DiscoProvider>`.
28
- *
29
- * Returns the single, stable, provider-configured instance — use this rather
30
- * than constructing a client in a component (which would create a new one each
31
- * render and risk drifting from the provider's auth/env). Throws if used
32
- * outside a provider.
33
- */
34
- function useDiscoClient() {
35
- const client = useContext$1(DiscoClientContext);
36
- if (!client) throw new Error("useDiscoClient must be used inside a <DiscoProvider>.");
37
- return client;
38
- }
39
- const LOADING = {
40
- status: "loading",
41
- data: void 0,
42
- error: void 0
43
- };
44
- /**
45
- * Fetch-on-mount state machine for a recommendations surface.
46
- *
47
- * Owns the request lifecycle — fetch on mount, refetch when the request
48
- * changes or `refetch` is called, abort in-flight requests on unmount/change —
49
- * and derives the session-bound tracker from each response. Renders nothing and
50
- * knows nothing about the `Disco.*` contexts; `<Disco.Root>` adapts its result.
51
- *
52
- * Exported from each backing's `/headless` entry as the shared fetch
53
- * primitive: `<Disco.Root>` builds on it. Reach for it directly only when
54
- * building a custom surface that needs the fetch lifecycle without the
55
- * `Disco.*` contexts.
56
- */
57
- function useFetchRecommendations(request) {
58
- const client = useDiscoClient();
59
- const [state, setState] = useState$1(LOADING);
60
- const [tracker, setTracker] = useState$1(null);
61
- const requestKey = useMemo$1(() => JSON.stringify(request), [request]);
62
- const [reloadCount, setReloadCount] = useState$1(0);
63
- const refetch = useCallback$1(() => setReloadCount((n) => n + 1), []);
64
- useEffect$1(() => {
65
- const controller = new AbortController();
66
- setState(LOADING);
67
- setTracker(null);
68
- client.getRecommendationsWithTracker(request, { signal: controller.signal }).then(({ data, tracker }) => {
69
- if (controller.signal.aborted) return;
70
- setState({
71
- status: "success",
72
- data,
73
- error: void 0
74
- });
75
- setTracker(withImpressionDedupe(tracker));
76
- }).catch((error) => {
77
- if (controller.signal.aborted) return;
78
- setState({
79
- status: "error",
80
- data: void 0,
81
- error
82
- });
83
- });
84
- return () => controller.abort();
85
- }, [
86
- client,
87
- requestKey,
88
- reloadCount
89
- ]);
90
- return {
91
- state,
92
- tracker,
93
- refetch
94
- };
95
- }
96
- const DiscoContext = createContext$1(null);
97
- /**
98
- * Read the recommendations fetch state, the session-bound tracker, and
99
- * `refetch` from the surrounding `<Disco.Root>`. The tracker is non-null only
100
- * once `status === "success"`; for consumers that only need the tracker and
101
- * render inside a success branch, {@link useDiscoTracker} returns a non-null
102
- * tracker and throws if used before success. Throws if used outside a
103
- * `<Disco.Root>`.
104
- */
105
- function useDiscoRecommendations() {
106
- const ctx = useContext$1(DiscoContext);
107
- if (!ctx) throw new Error("useDiscoRecommendations must be used inside a <Disco.Root>.");
108
- return ctx;
109
- }
110
- /**
111
- * Read the session-bound {@link EventTracker} for the surrounding
112
- * `<Disco.Root>`.
113
- *
114
- * The tracker exists only once recommendations have loaded (its session comes
115
- * from the response). Render tracking UI inside the `success` branch and this
116
- * hook returns a ready tracker; it throws if used before `success`, surfacing
117
- * misuse loudly rather than silently dropping events. Throws if used outside a
118
- * `<Disco.Root>`.
119
- */
120
- function useDiscoTracker() {
121
- const ctx = useContext$1(DiscoContext);
122
- if (!ctx) throw new Error("useDiscoTracker must be used inside a <Disco.Root>.");
123
- if (!ctx.tracker) throw new Error("useDiscoTracker is only available after recommendations have loaded — render tracking UI inside the <Disco.Root> success branch.");
124
- return ctx.tracker;
125
- }
126
- /**
127
- * Headless controller for a Disco recommendations surface — the root of the
128
- * `Disco.*` compound. Fetches via `useFetchRecommendations` and provides the
129
- * fetch state (read with `useDiscoRecommendations`) and the session-bound
130
- * tracker (read with `useDiscoTracker`) to its subtree. Renders no UI of its
131
- * own; aborts in-flight requests on unmount or request change.
132
- */
133
- function DiscoRoot({ request, children }) {
134
- const { state, tracker, refetch } = useFetchRecommendations(request);
135
- const value = useMemo$1(() => ({
136
- ...state,
137
- tracker,
138
- refetch
139
- }), [
140
- state,
141
- tracker,
142
- refetch
143
- ]);
144
- return /* @__PURE__ */ jsx(DiscoContext.Provider, {
145
- value,
146
- children
147
- });
148
- }
149
- return {
150
- DiscoClientContext,
151
- useDiscoClient,
152
- useDiscoRecommendations,
153
- useDiscoTracker,
154
- useFetchRecommendations,
155
- DiscoRoot
156
- };
157
- }
158
- //#endregion
159
- //#region ../react-shared/dist/bindings-D-XXI0bV.js
160
- const bindings = createHeadlessBindings();
161
- const DiscoClientContext = bindings.DiscoClientContext;
162
- const useDiscoClient = bindings.useDiscoClient;
163
- bindings.DiscoRoot;
164
- const useFetchRecommendations = bindings.useFetchRecommendations;
165
- bindings.useDiscoRecommendations;
166
- bindings.useDiscoTracker;
167
- //#endregion
168
- //#region ../react-shared/dist/headless-C9iZrlrk.js
169
- const RendererContext = createContext$1(null);
170
- function useRendererContext() {
171
- const ctx = useContext$1(RendererContext);
172
- if (!ctx) throw new Error("useRendererContext must be used within a ScreensRenderer");
173
- return ctx;
174
- }
175
- function generateNodes({ nodes, path, renderers }) {
176
- return nodes.map((node, idx) => {
177
- const generator = renderers[node.type];
178
- if (!generator) throw new Error(`No renderer found for node type: "${node.type}"`);
179
- const nodePath = `${path}.${node.type}.${idx}`;
180
- const reactNode = generator({
181
- node,
182
- nodesToJSX: (args) => generateNodes({
183
- nodes: args.nodes,
184
- path: nodePath,
185
- renderers
186
- })
187
- });
188
- if (isValidElement(reactNode)) return cloneElement(reactNode, { key: nodePath });
189
- return reactNode;
190
- });
191
- }
192
- function ScreensRenderer({ jsonContent, renderers, fallback = null }) {
193
- const screens = useMemo$1(() => parseScreens(jsonContent), [jsonContent]);
194
- if (!screens) return fallback;
195
- return createElement(ScreensNavigator, {
196
- screens,
197
- renderers
198
- });
199
- }
200
- function ScreensNavigator({ screens, renderers }) {
201
- const [currentScreenId, setCurrentScreenId] = useState$1(() => screens[0]?.id ?? "default");
202
- useEffect$1(() => {
203
- setCurrentScreenId(screens[0]?.id ?? "default");
204
- }, [screens]);
205
- const activeScreen = screens.find((screen) => screen.id === currentScreenId) ?? screens[0];
206
- if (!activeScreen) return null;
207
- return createElement(RendererContext.Provider, { value: {
208
- screens,
209
- currentScreenId: activeScreen.id,
210
- setCurrentScreenId
211
- } }, generateNodes({
212
- nodes: activeScreen.children,
213
- path: activeScreen.id,
214
- renderers
215
- }));
216
- }
217
- //#endregion
218
- //#region src/managers/RecommendationsTrackingManager/index.tsx
219
- const RecommendationsTrackingManagerContext = createContext(null);
220
- function RecommendationsTrackingManager({ children, tracker }) {
221
- return /* @__PURE__ */ jsx$1(RecommendationsTrackingManagerContext.Provider, {
222
- value: tracker,
223
- children
224
- });
225
- }
226
- function useEventTracker() {
227
- const ctx = useContext(RecommendationsTrackingManagerContext);
228
- if (!ctx) throw new Error("useEventTracker must be used inside RecommendationsTrackingManager");
229
- return ctx;
230
- }
231
- //#endregion
232
- //#region src/hooks/usePayload.tsx
233
- const usePayload = () => {
234
- const data = useContext(PayloadContext);
235
- if (!data) throw new Error("No wrapper Payload context found");
236
- return data;
237
- };
238
- //#endregion
239
- //#region src/utils/dataManagerUtils.ts
240
- const getShopIdentifier = (shopGid) => {
241
- return shopGid.replace("gid://shopify/Shop/", "");
242
- };
243
- const shopifyOrderIdFormatter = (inp) => typeof inp === "string" ? inp.replace("gid://shopify/Order/", "") : inp;
244
- const getRecommendationsRequest = ({ payload, widgetId }) => {
245
- return {
246
- user: {
247
- email: payload.buyerEmail,
248
- firstName: payload.extrapolatedFirstName,
249
- lastName: payload.customerLastName,
250
- phone: payload.extrapolatedPhone
251
- },
252
- placement: {
253
- displayMode: "INLINE",
254
- view: payload.target,
255
- widgetId
256
- },
257
- order: {
258
- amount: payload.totalCost,
259
- currencyCode: payload.currencyCode,
260
- id: shopifyOrderIdFormatter(payload.orderId) ?? void 0
261
- },
262
- purchases: payload.cartLines.map((cartLine) => {
263
- return {
264
- name: cartLine.merchandise.title,
265
- type: cartLine.merchandise.product.productType,
266
- variant: cartLine.merchandise.subtitle,
267
- quantity: cartLine.quantity,
268
- amount: cartLine.cost.totalAmount.amount,
269
- currencyCode: cartLine.cost.totalAmount.currencyCode,
270
- productId: cartLine.merchandise.product.id.replace("gid://shopify/Product/", "")
271
- };
272
- })
273
- };
274
- };
275
- //#endregion
276
- //#region src/components/CardContainer.tsx
277
- const CardContainer = ({ children, ...rest }) => {
278
- return /* @__PURE__ */ jsx$1("s-box", {
279
- border: "base",
280
- borderWidth: "base",
281
- borderRadius: "large",
282
- ...rest,
283
- children
284
- });
285
- };
286
- //#endregion
287
- //#region src/components/RecommendationsWidget/RecommendationsWidgetSkeleton.tsx
288
- const WIDE = "@container (inline-size > 450px)";
289
- const TILE_COUNT = 4;
290
- const Block = ({ blockSize }) => /* @__PURE__ */ jsx$1("s-box", {
291
- blockSize,
292
- inlineSize: "100%",
293
- background: "subdued",
294
- borderRadius: "base"
295
- });
296
- const HeroOfferSkeleton = () => /* @__PURE__ */ jsx$1("s-box", {
297
- padding: "base",
298
- border: "base",
299
- borderWidth: "none none base none",
300
- children: /* @__PURE__ */ jsxs("s-stack", {
301
- gap: "small-400",
302
- children: [/* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Thank you for your purchase:" }), /* @__PURE__ */ jsxs("s-stack", {
303
- gap: "base",
304
- children: [/* @__PURE__ */ jsxs("s-stack", {
305
- gap: "small-200",
306
- children: [/* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Exclusive offer from a brand you'll love" }), /* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Get a special discount on your next order" })]
307
- }), /* @__PURE__ */ jsx$1("s-stack", {
308
- direction: `${WIDE} inline, block`,
309
- gap: "base",
310
- children: [0, 1].map((index) => /* @__PURE__ */ jsx$1("s-box", {
311
- inlineSize: `${WIDE} 160px, 100%`,
312
- children: /* @__PURE__ */ jsx$1(Block, { blockSize: "44px" })
313
- }, index))
314
- })]
315
- })]
316
- })
317
- });
318
- const OfferRowSkeleton = () => /* @__PURE__ */ jsx$1("s-box", {
319
- padding: "base",
320
- border: "base",
321
- borderWidth: "none none base none",
322
- children: /* @__PURE__ */ jsx$1("s-grid", {
323
- gridTemplateColumns: "repeat(4, minmax(0, 1fr))",
324
- gap: "small-200",
325
- children: Array.from({ length: TILE_COUNT }, (_, index) => /* @__PURE__ */ jsxs("s-stack", {
326
- gap: "small-400",
327
- children: [/* @__PURE__ */ jsx$1("s-image", {
328
- aspectRatio: "1",
329
- inlineSize: "fill",
330
- border: "base",
331
- borderRadius: "small",
332
- accessibilityRole: "presentation"
333
- }), /* @__PURE__ */ jsxs("s-stack", {
334
- gap: "none",
335
- children: [/* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Brand" }), /* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Offer" })]
336
- })]
337
- }, index))
338
- })
339
- });
340
- const RecommendationsWidgetSkeleton = () => /* @__PURE__ */ jsx$1("s-box", {
341
- accessibilityRole: "status",
342
- accessibilityLabel: "Loading recommendations",
343
- children: /* @__PURE__ */ jsx$1(CardContainer, {
344
- background: "base",
345
- children: /* @__PURE__ */ jsxs("s-query-container", { children: [
346
- /* @__PURE__ */ jsx$1(HeroOfferSkeleton, {}),
347
- /* @__PURE__ */ jsx$1(OfferRowSkeleton, {}),
348
- /* @__PURE__ */ jsx$1("s-stack", {
349
- padding: "small-200 base",
350
- alignItems: "end",
351
- children: /* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Privacy Policy" })
352
- })
353
- ] })
354
- })
355
- });
356
- //#endregion
357
- //#region src/sdkIdentity.ts
358
- const SDK_IDENTITY = {
359
- name: "@disconetwork/shopify",
360
- version: "0.0.7"
361
- };
362
- //#endregion
363
- //#region ../react-shared/dist/sdk-internals.js
364
- /** @internal Bind SDK identity to a provider using the legacy backend proxy. */
365
- function createProxySdkProvider(sdk) {
366
- return function ProxySdkProvider({ children, ...auth }) {
367
- const apiKey = "apiKey" in auth ? auth.apiKey : void 0;
368
- const surface = "surface" in auth ? auth.surface : void 0;
369
- const shopGid = "shopGid" in auth ? auth.shopGid : void 0;
370
- const env = "env" in auth ? auth.env : void 0;
371
- const client = useMemo$1(() => apiKey !== void 0 ? new InternalDiscoClient({
372
- apiKey,
373
- surface,
374
- sdk
375
- }) : new InternalDiscoClient({
376
- shopGid,
377
- env,
378
- sdk
379
- }), [
380
- apiKey,
381
- surface,
382
- shopGid,
383
- env
384
- ]);
385
- return /* @__PURE__ */ jsx(DiscoClientContext.Provider, {
386
- value: client,
387
- children
388
- });
389
- };
390
- }
391
- //#endregion
392
- //#region src/managers/DataManager.tsx
393
- const ShopifySdkProvider = createProxySdkProvider(SDK_IDENTITY);
394
- const DataManager = ({ auth, widgetId, request, children }) => {
395
- const payload = usePayload();
396
- return /* @__PURE__ */ jsx$1(ShopifySdkProvider, {
397
- ..."apiKey" in auth ? {
398
- apiKey: auth.apiKey,
399
- surface: "shopify"
400
- } : {
401
- shopGid: payload.shopGid,
402
- env: auth.env
403
- },
404
- children: /* @__PURE__ */ jsx$1(RecommendationsContent, {
405
- request: request ?? getRecommendationsRequest({
406
- payload,
407
- widgetId
408
- }),
409
- children
410
- })
411
- });
412
- };
413
- const RecommendationsContent = ({ children, request }) => {
414
- const { state: recommendations, tracker } = useFetchRecommendations(request);
415
- if (recommendations.status === "error") return null;
416
- if (recommendations.status === "loading" || !tracker) return /* @__PURE__ */ jsx$1(RecommendationsWidgetSkeleton, {});
417
- return /* @__PURE__ */ jsx$1(RecommendationsDataContext.Provider, {
418
- value: recommendations.data,
419
- children: /* @__PURE__ */ jsx$1(RecommendationsTrackingManager, {
420
- tracker,
421
- children
422
- })
423
- });
424
- };
425
- //#endregion
426
- //#region src/managers/PayloadManager.tsx
427
- const GenericPayloadProvider = ({ target, children, payload, additionalPayload, isB2BPurchase }) => {
428
- useEffect(() => {
429
- if (!isB2BPurchase) return;
430
- throw new Error("[Disco]: Disabling for B2B purchase");
431
- }, [isB2BPurchase]);
432
- if (isB2BPurchase) return null;
433
- return /* @__PURE__ */ jsx$1(PayloadContext.Provider, {
434
- value: {
435
- ...payload,
436
- ...additionalPayload || {},
437
- target
438
- },
439
- children
440
- });
441
- };
442
- function createGenericPayload({ buyerPhone, buyerEmail, customer, shippingAddress, billingAddress, totalAmount, cartLines, checkoutToken, discountCodes, shopGid, extensionTarget }) {
443
- const derivedFirstName = billingAddress?.firstName || shippingAddress?.firstName;
444
- return {
445
- buyerPhone,
446
- buyerEmail,
447
- customerId: customer?.id,
448
- customerFirstName: customer?.firstName,
449
- customerLastName: customer?.lastName,
450
- customerFullName: customer?.fullName,
451
- derivedFirstName,
452
- billingFirstName: billingAddress?.firstName,
453
- billingLastName: billingAddress?.lastName,
454
- billingZipCode: billingAddress?.zip,
455
- shippingZipCode: shippingAddress?.zip,
456
- extrapolatedFirstName: customer?.firstName || derivedFirstName,
457
- extrapolatedPhone: buyerPhone || shippingAddress?.phone || billingAddress?.phone || "",
458
- totalCost: totalAmount.amount,
459
- currencyCode: totalAmount.currencyCode,
460
- cartLines,
461
- checkoutToken,
462
- discountCodes,
463
- shopGid,
464
- target: PAYLOAD_MANAGER_TARGET.GENERIC,
465
- extensionTarget
466
- };
467
- }
468
- const ThankYouPayloadManager = ({ children }) => {
469
- const target = PAYLOAD_MANAGER_TARGET.THANK_YOU;
470
- const customer = useCustomer();
471
- const buyerEmail = useEmail();
472
- const buyerPhone = usePhone();
473
- const purchasingCompany = usePurchasingCompany();
474
- const shippingAddress = useShippingAddress();
475
- const billingAddress = useBillingAddress();
476
- const totalAmount = useTotalAmount();
477
- const cartLines = useCartLines();
478
- const checkoutToken = useCheckoutToken();
479
- const discountCodes = useDiscountCodes();
480
- const shop = useShop();
481
- const api = useApi();
482
- const orderId = useSubscription(api.orderConfirmation).order.id.split("/").pop();
483
- if (!orderId) console.warn("[Disco]: Order ID not found in thank you page");
484
- return /* @__PURE__ */ jsx$1(GenericPayloadProvider, {
485
- target,
486
- payload: createGenericPayload({
487
- buyerPhone,
488
- buyerEmail,
489
- customer,
490
- shippingAddress,
491
- billingAddress,
492
- totalAmount,
493
- cartLines,
494
- checkoutToken,
495
- discountCodes,
496
- shopGid: shop.id,
497
- extensionTarget: api.extension.target
498
- }),
499
- additionalPayload: {
500
- orderId,
501
- target
502
- },
503
- isB2BPurchase: Boolean(purchasingCompany?.company),
504
- children
505
- });
506
- };
507
- const OrderStatusPayloadManager = ({ children }) => {
508
- const target = PAYLOAD_MANAGER_TARGET.ORDER_STATUS;
509
- const customer = useCustomer$1();
510
- const buyerEmail = useEmail$1();
511
- const buyerPhone = usePhone$1();
512
- const purchasingCompany = usePurchasingCompany$1();
513
- const shippingAddress = useShippingAddress$1();
514
- const billingAddress = useBillingAddress$1();
515
- const totalAmount = useTotalAmount$1();
516
- const cartLines = useCartLines$1();
517
- const discountCodes = useDiscountCodes$1();
518
- const shop = useShop$1();
519
- const order = useOrder();
520
- const api = useApi$1();
521
- return /* @__PURE__ */ jsx$1(GenericPayloadProvider, {
522
- target,
523
- payload: createGenericPayload({
524
- buyerPhone,
525
- buyerEmail,
526
- customer,
527
- shippingAddress,
528
- billingAddress,
529
- totalAmount,
530
- cartLines,
531
- checkoutToken: useSubscription$1(api.checkoutToken),
532
- discountCodes,
533
- shopGid: shop.id,
534
- extensionTarget: api.extension.target
535
- }),
536
- additionalPayload: {
537
- orderId: order?.id,
538
- orderName: order?.name,
539
- target
540
- },
541
- isB2BPurchase: Boolean(purchasingCompany?.company),
542
- children
543
- });
544
- };
545
- const PAYLOAD_MANAGER_TARGET = {
546
- GENERIC: "GENERIC",
547
- ORDER_STATUS: "ORDER_STATUS",
548
- THANK_YOU: "THANK_YOU"
549
- };
550
- const EXTENSION_TARGETS = {
551
- "purchase.thank-you.block.render": PAYLOAD_MANAGER_TARGET.THANK_YOU,
552
- "customer-account.order-status.block.render": PAYLOAD_MANAGER_TARGET.ORDER_STATUS
553
- };
554
- const getExtensionTarget = () => globalThis.shopify?.extension?.target;
555
- const PayloadManager = ({ children }) => {
556
- const extensionTarget = getExtensionTarget();
557
- const target = extensionTarget && EXTENSION_TARGETS[extensionTarget];
558
- if (target === PAYLOAD_MANAGER_TARGET.THANK_YOU) return /* @__PURE__ */ jsx$1(ThankYouPayloadManager, { children });
559
- if (target === PAYLOAD_MANAGER_TARGET.ORDER_STATUS) return /* @__PURE__ */ jsx$1(OrderStatusPayloadManager, { children });
560
- throw new Error(`[Disco]: Unsupported extension target ${extensionTarget ?? "(none)"}`);
561
- };
562
- //#endregion
563
- //#region src/managers/UserManager.tsx
564
- const UserManager = ({ children }) => {
565
- const { buyerEmail, customerFirstName, customerLastName, customerFullName, derivedFirstName, extrapolatedFirstName } = usePayload();
566
- const [user, setUser] = useState({
567
- email: buyerEmail,
568
- firstName: customerFirstName,
569
- lastName: customerLastName,
570
- fullName: customerFullName,
571
- derivedFirstName,
572
- extrapolatedFirstName
573
- });
574
- const hasIdentity = useMemo(() => !!user?.email, [user]);
575
- return /* @__PURE__ */ jsx$1(UserContext.Provider, {
576
- value: {
577
- user,
578
- setUser,
579
- hasIdentity
580
- },
581
- children
582
- });
583
- };
584
- //#endregion
585
- //#region src/managers/index.ts
586
- const RecommendationsDataContext = createContext(null);
587
- const PayloadContext = createContext(null);
588
- const UserContext = createContext(null);
589
- //#endregion
590
- //#region src/hooks/useRecommendationsData.tsx
591
- function useRecommendationsData() {
592
- const ctx = useContext(RecommendationsDataContext);
593
- if (!ctx) throw new Error("useRecommendationsData must be used inside RecommendationsDataContext");
594
- return ctx;
595
- }
596
- //#endregion
597
- //#region src/hooks/useCounter.tsx
598
- const useCounter = ({ start = 0, min = 0, max = Infinity, resetOnMax = false, disabled = false } = {}) => {
599
- const [counter, setCounter] = useState(start);
600
- const incrementCounter = useCallback((counter) => Math.min(max, counter + 1) % (resetOnMax ? max : Infinity), [max, resetOnMax]);
601
- const increment = useCallback(() => disabled ? null : setCounter(incrementCounter), [incrementCounter, disabled]);
602
- const decrementCounter = useCallback((counter) => Math.max(min, counter - 1), [min]);
603
- const decrement = useCallback(() => disabled ? null : setCounter(decrementCounter), [decrementCounter, disabled]);
604
- const nextCounter = useMemo(() => incrementCounter(counter), [incrementCounter, counter]);
605
- const prevCounter = useMemo(() => decrementCounter(counter), [decrementCounter, counter]);
606
- const isMin = useMemo(() => counter === min, [min, counter]);
607
- const isMax = useMemo(() => counter === max, [max, counter]);
608
- const procValue = useCallback((value) => Math.max(min, Math.min(max, value)), [max, min]);
609
- return {
610
- counter,
611
- setCounter: useCallback((cb) => {
612
- if (disabled) return;
613
- setCounter((counter) => procValue(typeof cb === "function" ? cb(counter) : cb));
614
- }, [procValue, disabled]),
615
- increment,
616
- decrement,
617
- nextCounter,
618
- prevCounter,
619
- isMin,
620
- isMax
621
- };
622
- };
623
- //#endregion
624
- //#region src/components/RecommendationsWidget/HeroOfferProvider.tsx
625
- const HeroContext = createContext(null);
626
- const HeroOfferProvider = ({ children, recommendationGroup, loop }) => {
627
- const [claimedOffers, setClaimedOffers] = useState([]);
628
- const { recommendations } = recommendationGroup;
629
- const { counter: activeRecommendationIdx, increment: nextOffer, decrement: prevOffer, isMin: isFirstOffer, isMax: isLastOffer } = useCounter(loop ? {
630
- start: 0,
631
- min: 0,
632
- max: recommendations.length,
633
- resetOnMax: true
634
- } : {
635
- start: 0,
636
- min: 0,
637
- max: recommendations.length - 1
638
- });
639
- const activeRecommendation = recommendations[activeRecommendationIdx];
640
- const handleOfferClaim = () => {
641
- setClaimedOffers((claimedOffers) => [...claimedOffers, activeRecommendation.id]);
642
- };
643
- const value = {
644
- activeRecommendation,
645
- activeOfferIndex: activeRecommendationIdx,
646
- nextOffer,
647
- prevOffer,
648
- isOfferClaimed: claimedOffers.includes(activeRecommendation.id),
649
- handleOfferClaim,
650
- TOTAL_NUM_OFFERS: recommendations.length,
651
- isFirstOffer,
652
- isLastOffer,
653
- claimedOffers,
654
- recommendations
655
- };
656
- return /* @__PURE__ */ jsx$1(HeroContext.Provider, {
657
- value,
658
- children
659
- });
660
- };
661
- const useHeroOffer = () => {
662
- const context = useContext(HeroContext);
663
- if (!context) throw new Error("useHeroOffer must be used within a HeroOfferProvider");
664
- return context;
665
- };
666
- //#endregion
667
- //#region src/components/RecommendationsWidget/ScrollableSlotProvider.tsx
668
- const ScrollableSlotContext = createContext(null);
669
- const ScrollableSlotProvider = ({ children, scrollableRecommendationGroup }) => {
670
- const value = { hasScrollableSlot: !!scrollableRecommendationGroup };
671
- return /* @__PURE__ */ jsx$1(ScrollableSlotContext.Provider, {
672
- value,
673
- children
674
- });
675
- };
676
- const useScrollableSlot = () => {
677
- const context = useContext(ScrollableSlotContext);
678
- if (!context) throw new Error("useScrollableSlot must be used within a ScrollableSlotProvider");
679
- return context;
680
- };
681
- //#endregion
682
- //#region src/hooks/useIdentity.tsx
683
- const useIdentity = () => {
684
- const data = useContext(UserContext);
685
- if (!data) throw new Error("No wrapper User manager found");
686
- return data;
687
- };
688
- //#endregion
689
- //#region src/hooks/useCustomization.ts
690
- const CUSTOMIZATION_TYPE = {
691
- CHECKOUT: "checkout",
692
- UPFRONT: "upfront"
693
- };
694
- //#endregion
695
- //#region src/hooks/useRecommendationsCustomization.tsx
696
- const useRecommendationsCustomization = ({ type = CUSTOMIZATION_TYPE.CHECKOUT } = {}) => {
697
- const customization = useRecommendationsData()?.publisherCustomization?.[type] || null;
698
- const hasCustomization = (detail) => {
699
- if (!customization || typeof customization !== "object" || !detail) return false;
700
- return !!customization[detail];
701
- };
702
- const getCustomization = (detail) => {
703
- if (!hasCustomization(detail) || !customization) return null;
704
- return customization[detail];
705
- };
706
- const applyCustomizationOrFallback = (detail, fallback = null) => {
707
- if (!hasCustomization(detail)) return fallback;
708
- return getCustomization(detail);
709
- };
710
- return { applyCustomizationOrFallback };
711
- };
712
- //#endregion
713
- //#region src/components/RecommendationsWidget/useFirstOfferHeading.ts
714
- const useFirstOfferHeading = () => {
715
- const { user } = useIdentity();
716
- const { applyCustomizationOrFallback } = useRecommendationsCustomization();
717
- const firstName = user?.extrapolatedFirstName;
718
- return applyCustomizationOrFallback("widget_heading", `${firstName ? `${firstName}, thank you` : "Thank you"} for your purchase:`);
719
- };
720
- //#endregion
721
- //#region src/conf/env_conf.ts
722
- const BUCKET_NAME = {
723
- production: "coopcommerce",
724
- staging: "coopcommerce-staging"
725
- };
726
- const IMAGE_HANDLING_CLOUDFRONT_DOMAIN = {
727
- production: "https://d1t86rpuyqggut.cloudfront.net/",
728
- staging: "https://dn9o42i1jy6mo.cloudfront.net/"
729
- };
730
- //#endregion
731
- //#region src/utils/getImgUrl.ts
732
- /**
733
- * Parses a cloudfront image URL and extracts the key from its BASE64-encoded payload.
734
- * Returns the key if the URL is a valid cloudfront URL, otherwise returns null.
735
- */
736
- function parseKeyFromCloudfrontUrl(url, env) {
737
- const domain = IMAGE_HANDLING_CLOUDFRONT_DOMAIN[env];
738
- if (!url.startsWith(domain)) return null;
739
- try {
740
- const base64Path = url.slice(domain.length).split("?")[0];
741
- if (!base64Path) return null;
742
- const decodedPayload = atob(base64Path);
743
- return JSON.parse(decodedPayload).key ?? null;
744
- } catch {
745
- return null;
746
- }
747
- }
748
- const getCloudfrontImageSources = ({ env, key, edits, width, height }) => {
749
- const imgPayload = JSON.stringify({
750
- bucket: BUCKET_NAME[env],
751
- key,
752
- edits: {
753
- ...edits,
754
- resize: {
755
- fit: "fill",
756
- withoutEnlargement: true
757
- }
758
- }
759
- });
760
- return getImageVariants(`${IMAGE_HANDLING_CLOUDFRONT_DOMAIN[env]}${btoa(imgPayload)}`, {
761
- width: width || 350,
762
- height: height || 350
763
- });
764
- };
765
- /**
766
- * Square image sources for `url`. A cloudfront image-handler URL is re-encoded
767
- * at `size` with 1x-4x variants; any other URL is used as-is.
768
- */
769
- function getImageSources(url, { env, size }) {
770
- const key = parseKeyFromCloudfrontUrl(url, env);
771
- return key ? getCloudfrontImageSources({
772
- env,
773
- key,
774
- width: size,
775
- height: size
776
- }) : { src: url };
777
- }
778
- function getImageVariants(imgUrl, dimensions) {
779
- const { width: cssWidth, height: cssHeight } = dimensions;
780
- const getTransformedDimension = (resolution, dimension) => {
781
- const STEP = 32;
782
- return Math.ceil(dimension * resolution / STEP) * STEP;
783
- };
784
- const getTransformedImageUrl = (resolution) => {
785
- return `${imgUrl}?width=${getTransformedDimension(resolution, cssWidth)}&height=${getTransformedDimension(resolution, cssHeight)}`;
786
- };
787
- const variants = [
788
- 1,
789
- 2,
790
- 3,
791
- 4
792
- ].map((resolution) => ({
793
- resolution,
794
- url: getTransformedImageUrl(resolution)
795
- }));
796
- return {
797
- src: getTransformedImageUrl(1),
798
- srcSet: variants.map(({ resolution, url }) => `${url} ${resolution}x`).join(", ")
799
- };
800
- }
801
- //#endregion
802
- //#region src/hooks/useDiscoEnv.ts
803
- const useDiscoEnv = () => useDiscoClient().env;
804
- //#endregion
805
- //#region src/components/Essential/generation/LinkGenerator.tsx
806
- function InternalLink({ targetScreenId, children }) {
807
- const ctx = useRendererContext();
808
- return /* @__PURE__ */ jsx$1("s-link", {
809
- tone: "neutral",
810
- onClick: () => ctx.setCurrentScreenId(targetScreenId),
811
- children
812
- });
813
- }
814
- const LinkGenerator = { link: ({ node, nodesToJSX }) => {
815
- const children = nodesToJSX({ nodes: node.children });
816
- if ("targetScreenId" in node.attributes) return /* @__PURE__ */ jsx$1(InternalLink, {
817
- targetScreenId: node.attributes.targetScreenId,
818
- children
819
- });
820
- const href = node.attributes.to;
821
- const external = node.attributes.external;
822
- return /* @__PURE__ */ jsx$1("s-link", {
823
- tone: "neutral",
824
- href,
825
- target: external ? "_blank" : "auto",
826
- children
827
- });
828
- } };
829
- //#endregion
830
- //#region src/components/Essential/generation/ParagraphGenerator.tsx
831
- const ParagraphGenerator = { paragraph: ({ node, nodesToJSX }) => {
832
- return /* @__PURE__ */ jsx$1("s-paragraph", {
833
- color: "subdued",
834
- children: /* @__PURE__ */ jsx$1("s-text", {
835
- type: "strong",
836
- children: nodesToJSX({ nodes: node.children })
837
- })
838
- });
839
- } };
840
- //#endregion
841
- //#region src/components/Essential/generation/ScrollViewGenerator.tsx
842
- const DEFAULT_MAX_BLOCK_SIZE = 300;
843
- const ScrollViewGenerator = { scrollview: ({ node, nodesToJSX }) => {
844
- const children = nodesToJSX({ nodes: node.children });
845
- return /* @__PURE__ */ jsx$1("s-scroll-box", {
846
- maxBlockSize: `${node.attributes?.maxBlockSize ?? DEFAULT_MAX_BLOCK_SIZE}px`,
847
- children
848
- });
849
- } };
850
- //#endregion
851
- //#region src/components/Essential/EssentialOfferContent.tsx
852
- const renderers = {
853
- text: ({ node }) => {
854
- return node.text;
855
- },
856
- ...LinkGenerator,
857
- ...ParagraphGenerator,
858
- ...ScrollViewGenerator
859
- };
860
- const EssentialOfferContent = ({ heading: offerHeading, subheading: offerSubheading, jsonContent: incentiveJson }) => {
861
- return /* @__PURE__ */ jsxs("s-stack", {
862
- gap: "small-200",
863
- children: [/* @__PURE__ */ jsx$1("s-heading", { children: offerHeading }), /* @__PURE__ */ jsx$1(ScreensRenderer, {
864
- jsonContent: incentiveJson,
865
- renderers,
866
- fallback: /* @__PURE__ */ jsx$1("s-paragraph", {
867
- color: "subdued",
868
- children: /* @__PURE__ */ jsx$1("s-text", {
869
- type: "strong",
870
- children: offerSubheading || ""
871
- })
872
- })
873
- })]
874
- });
875
- };
876
- //#endregion
877
- //#region src/components/RecommendationsWidget/Essential/EssentialLayoutType.tsx
878
- const EssentialLayoutType = ({ onLastOffer, compact }) => {
879
- const { isFirstOffer, activeRecommendation: recommendation } = useHeroOffer();
880
- const renderBrandLogo = recommendation.offer.metadata.layoutType === "FEATURED_IMAGE";
881
- return /* @__PURE__ */ jsx$1("s-query-container", { children: /* @__PURE__ */ jsx$1("s-box", {
882
- padding: compact ? "none" : "base",
883
- children: /* @__PURE__ */ jsxs("s-stack", {
884
- gap: "small-400",
885
- children: [
886
- renderBrandLogo && /* @__PURE__ */ jsx$1("s-box", {
887
- display: "@container (inline-size > 450px) none, auto",
888
- children: /* @__PURE__ */ jsx$1("s-stack", {
889
- alignItems: "center",
890
- children: /* @__PURE__ */ jsx$1(AdvertiserLogo, { recommendation })
891
- })
892
- }),
893
- isFirstOffer && !compact && /* @__PURE__ */ jsx$1(FirstOfferHeading, {}),
894
- /* @__PURE__ */ jsxs("s-grid", {
895
- gridTemplateColumns: renderBrandLogo ? "@container (inline-size > 450px) 1fr auto, 1fr" : "1fr",
896
- gap: "base",
897
- alignItems: "center",
898
- children: [/* @__PURE__ */ jsxs("s-stack", {
899
- gap: "base",
900
- children: [/* @__PURE__ */ jsx$1(EssentialOfferContent, {
901
- heading: recommendation.offer.heading || "",
902
- subheading: recommendation.offer.subheading || "",
903
- jsonContent: recommendation.offer.jsonContent
904
- }), /* @__PURE__ */ jsxs("s-stack", {
905
- direction: "@container (inline-size > 450px) inline, block",
906
- gap: "base",
907
- children: [/* @__PURE__ */ jsx$1("s-box", {
908
- inlineSize: "@container (inline-size > 450px) auto, 100%",
909
- children: /* @__PURE__ */ jsx$1(PrimaryButton, {})
910
- }), /* @__PURE__ */ jsx$1("s-box", {
911
- inlineSize: "@container (inline-size > 450px) auto, 100%",
912
- children: /* @__PURE__ */ jsx$1(SecondaryButton, { onLastOffer })
913
- })]
914
- })]
915
- }), renderBrandLogo && /* @__PURE__ */ jsx$1("s-box", {
916
- display: "@container (inline-size > 450px) auto, none",
917
- children: /* @__PURE__ */ jsx$1(AdvertiserLogo, { recommendation })
918
- })]
919
- })
920
- ]
921
- })
922
- }) });
923
- };
924
- function AdvertiserLogo({ recommendation }) {
925
- const { advertiser } = recommendation;
926
- const env = useDiscoEnv();
927
- const imageSize = 140;
928
- const image = getImageSources(advertiser.logoUrl, {
929
- env,
930
- size: imageSize
931
- });
932
- return /* @__PURE__ */ jsx$1("s-box", {
933
- blockSize: `${imageSize}px`,
934
- inlineSize: `${imageSize}px`,
935
- children: /* @__PURE__ */ jsx$1("s-image", {
936
- aspectRatio: "1",
937
- src: image.src,
938
- srcSet: image.srcSet,
939
- alt: `${advertiser.name} Logo`,
940
- inlineSize: "fill"
941
- })
942
- });
943
- }
944
- function PrimaryButton() {
945
- const { track } = useEventTracker();
946
- const { handleOfferClaim, isOfferClaimed, activeRecommendation: recommendation } = useHeroOffer();
947
- const handleClick = () => {
948
- track({
949
- type: "BRAND_CLICK",
950
- target: "INLINE_ACTION_BUTTON",
951
- brand: {
952
- offerId: recommendation.offer.id,
953
- advertiserId: recommendation.advertiser.id,
954
- insertionId: recommendation.insertionId
955
- }
956
- });
957
- handleOfferClaim();
958
- };
959
- return /* @__PURE__ */ jsx$1("s-button", {
960
- href: recommendation.offer.targetUrl,
961
- target: "_blank",
962
- inlineSize: "fill",
963
- variant: isOfferClaimed ? "secondary" : "primary",
964
- onClick: handleClick,
965
- children: recommendation.offer.ctaDetails.acceptCopy
966
- });
967
- }
968
- function SecondaryButton({ onLastOffer }) {
969
- const { track } = useEventTracker();
970
- const { hasScrollableSlot } = useScrollableSlot();
971
- const { isOfferClaimed, nextOffer, isLastOffer, activeRecommendation: recommendation } = useHeroOffer();
972
- const handleClick = () => {
973
- track({
974
- type: "ELEMENT_CLICK",
975
- target: "INLINE_NAV_FORWARD",
976
- brand: {
977
- offerId: recommendation.offer.id,
978
- advertiserId: recommendation.advertiser.id,
979
- insertionId: recommendation.insertionId
980
- }
981
- });
982
- if (isLastOffer) {
983
- onLastOffer();
984
- return;
985
- }
986
- nextOffer();
987
- };
988
- const buttonText = isOfferClaimed ? isLastOffer ? hasScrollableSlot ? "See more" : "Close" : "Next offer" : recommendation.offer.ctaDetails.declineCopy || "No thanks";
989
- return /* @__PURE__ */ jsx$1("s-button", {
990
- inlineSize: "fill",
991
- variant: isOfferClaimed ? "primary" : "secondary",
992
- onClick: handleClick,
993
- children: buttonText
994
- });
995
- }
996
- function FirstOfferHeading() {
997
- return /* @__PURE__ */ jsx$1("s-text", {
998
- tone: "info",
999
- children: useFirstOfferHeading()
1000
- });
1001
- }
1002
- //#endregion
1003
- //#region src/components/RecommendationsWidget/DotIndicators.tsx
1004
- const DotIndicators = ({ totalCount, activeIndex }) => {
1005
- if (totalCount <= 1) return null;
1006
- return /* @__PURE__ */ jsx$1("s-stack", {
1007
- padding: "small-200 none",
1008
- alignItems: "center",
1009
- children: /* @__PURE__ */ jsx$1("s-stack", {
1010
- direction: "inline",
1011
- gap: "small-200",
1012
- children: Array.from({ length: totalCount }, (_, i) => /* @__PURE__ */ jsx$1("s-badge", {
1013
- size: "small",
1014
- color: i === activeIndex ? "base" : "subdued",
1015
- children: `${i + 1}`
1016
- }, i))
1017
- })
1018
- });
1019
- };
1020
- //#endregion
1021
- //#region src/conf/index.ts
1022
- const getLeadGenRegisterUrl = (env) => `${INTERNAL_BASE_URL[env]}/lead_gen/register_lead/`;
1023
- const PRIVACY_POLICY_URL = "https://www.disconetwork.com/privacy-policy";
1024
- //#endregion
1025
- //#region src/components/PrivacyLink.tsx
1026
- const PrivacyLink = ({ onPress }) => {
1027
- return /* @__PURE__ */ jsx$1("s-text", {
1028
- color: "subdued",
1029
- children: /* @__PURE__ */ jsx$1("s-link", {
1030
- href: PRIVACY_POLICY_URL,
1031
- target: "_blank",
1032
- tone: "neutral",
1033
- onClick: onPress,
1034
- children: "Privacy Policy"
1035
- })
1036
- });
1037
- };
1038
- //#endregion
1039
- //#region src/components/RecommendationsWidget/Footer.tsx
1040
- function Footer() {
1041
- const { track } = useEventTracker();
1042
- const handlePrivacyClick = () => {
1043
- track({
1044
- type: "ELEMENT_CLICK",
1045
- target: "INLINE_FOOTER_PRIVACY"
1046
- });
1047
- };
1048
- return /* @__PURE__ */ jsx$1("s-stack", {
1049
- padding: "small-200 base",
1050
- alignItems: "end",
1051
- children: /* @__PURE__ */ jsx$1(PrivacyLink, { onPress: handlePrivacyClick })
1052
- });
1053
- }
1054
- //#endregion
1055
- //#region src/components/RecommendationsWidget/Cover/index.tsx
1056
- const CoverRecommendationsWidget = ({ heroRecommendationGroup }) => {
1057
- const { track } = useEventTracker();
1058
- useEffect(() => {
1059
- track({ type: "WIDGET_LOAD" });
1060
- }, [track]);
1061
- return /* @__PURE__ */ jsx$1(HeroOfferProvider, {
1062
- recommendationGroup: heroRecommendationGroup,
1063
- loop: true,
1064
- children: /* @__PURE__ */ jsx$1(CoverRecommendationsWidgetContent, {})
1065
- });
1066
- };
1067
- const CoverRecommendationsWidgetContent = () => {
1068
- const { track } = useEventTracker();
1069
- const firstOfferHeading = useFirstOfferHeading();
1070
- const modalHeading = typeof firstOfferHeading === "string" ? firstOfferHeading : "Your rewards";
1071
- const { TOTAL_NUM_OFFERS, activeOfferIndex, nextOffer, activeRecommendation } = useHeroOffer();
1072
- const [modalOpen, setModalOpen] = useState(false);
1073
- const { insertionId, offer, advertiser } = activeRecommendation;
1074
- useEffect(() => {
1075
- if (!modalOpen) return;
1076
- track({
1077
- type: "BRAND_DISPLAY",
1078
- target: "INLINE_SLOT",
1079
- brand: {
1080
- offerId: offer.id,
1081
- advertiserId: advertiser.id,
1082
- insertionId
1083
- }
1084
- });
1085
- }, [
1086
- modalOpen,
1087
- track,
1088
- insertionId,
1089
- offer.id,
1090
- advertiser.id
1091
- ]);
1092
- const subtitle = `You've unlocked ${TOTAL_NUM_OFFERS} exclusive offer${TOTAL_NUM_OFFERS !== 1 ? "s" : ""} with your purchase — don't let them go to waste!`;
1093
- return /* @__PURE__ */ jsx$1(CardContainer, {
1094
- background: "transparent",
1095
- children: /* @__PURE__ */ jsx$1("s-box", {
1096
- padding: "base",
1097
- children: /* @__PURE__ */ jsxs("s-stack", {
1098
- gap: "base",
1099
- children: [
1100
- /* @__PURE__ */ jsx$1("s-heading", { children: "Your purchase comes with rewards!" }),
1101
- /* @__PURE__ */ jsx$1("s-text", {
1102
- color: "subdued",
1103
- children: subtitle
1104
- }),
1105
- /* @__PURE__ */ jsx$1("s-button", {
1106
- variant: "primary",
1107
- command: "--show",
1108
- commandFor: "cover-modal",
1109
- onClick: () => track({
1110
- type: "ELEMENT_CLICK",
1111
- target: "OPEN_OVERLAY"
1112
- }),
1113
- children: "View my rewards"
1114
- }),
1115
- /* @__PURE__ */ jsxs("s-modal", {
1116
- id: "cover-modal",
1117
- padding: "base",
1118
- heading: modalHeading,
1119
- size: "large",
1120
- onShow: () => {
1121
- setModalOpen(true);
1122
- track({ type: "WIDGET_DISPLAY" });
1123
- },
1124
- onHide: () => {
1125
- setModalOpen(false);
1126
- track({
1127
- type: "ELEMENT_CLICK",
1128
- target: "CLOSE_BUTTON"
1129
- });
1130
- },
1131
- children: [
1132
- /* @__PURE__ */ jsx$1(ScrollableSlotProvider, { children: /* @__PURE__ */ jsx$1(EssentialLayoutType, {
1133
- onLastOffer: nextOffer,
1134
- compact: true
1135
- }) }),
1136
- /* @__PURE__ */ jsx$1(DotIndicators, {
1137
- totalCount: TOTAL_NUM_OFFERS,
1138
- activeIndex: activeOfferIndex
1139
- }),
1140
- /* @__PURE__ */ jsx$1("s-divider", {}),
1141
- /* @__PURE__ */ jsx$1(Footer, {})
1142
- ]
1143
- })
1144
- ]
1145
- })
1146
- })
1147
- });
1148
- };
1149
- //#endregion
1150
- //#region src/components/DiscoFeed/DiscoFeedProduct.tsx
1151
- function ProductTile({ targetUrl, trackClick, image, productName }) {
1152
- return /* @__PURE__ */ jsx$1("s-box", {
1153
- inlineSize: "100%",
1154
- children: /* @__PURE__ */ jsxs("s-stack", {
1155
- alignItems: "stretch",
1156
- gap: "none",
1157
- children: [/* @__PURE__ */ jsx$1("s-link", {
1158
- target: "_blank",
1159
- tone: "neutral",
1160
- href: targetUrl,
1161
- onClick: trackClick,
1162
- children: /* @__PURE__ */ jsx$1("s-box", {
1163
- inlineSize: "100%",
1164
- children: /* @__PURE__ */ jsx$1("s-image", {
1165
- aspectRatio: "1",
1166
- src: image.src,
1167
- srcSet: image.srcSet,
1168
- alt: productName,
1169
- inlineSize: "fill",
1170
- border: "base",
1171
- borderRadius: "small"
1172
- })
1173
- })
1174
- }), /* @__PURE__ */ jsx$1("s-stack", {
1175
- maxBlockSize: "50px",
1176
- maxInlineSize: "100%",
1177
- padding: "small-400 none none none",
1178
- overflow: "hidden",
1179
- children: /* @__PURE__ */ jsx$1("s-text", {
1180
- type: "strong",
1181
- color: "subdued",
1182
- children: /* @__PURE__ */ jsx$1("s-link", {
1183
- target: "_blank",
1184
- tone: "neutral",
1185
- href: targetUrl,
1186
- onClick: trackClick,
1187
- children: productName
1188
- })
1189
- })
1190
- })]
1191
- })
1192
- });
1193
- }
1194
- //#endregion
1195
- //#region src/components/RecommendationsWidget/RecommendationsOfferRow.tsx
1196
- const PAGE_SIZE = 4;
1197
- const PRODUCT_IMAGE_SOURCE_SIZE = 256;
1198
- const RecommendationsOfferRow = ({ recommendations, padding }) => {
1199
- return /* @__PURE__ */ jsx$1(RecommendationsPager, {
1200
- recommendations: recommendations.filter((recommendation) => recommendation.offer.assets.length > 0),
1201
- padding
1202
- });
1203
- };
1204
- function RecommendationsPager({ recommendations, padding }) {
1205
- const [page, setPage] = useState(0);
1206
- const pageCount = Math.ceil(recommendations.length / PAGE_SIZE);
1207
- const currentPage = Math.min(page, Math.max(pageCount - 1, 0));
1208
- const pageRecommendations = recommendations.slice(currentPage * PAGE_SIZE, (currentPage + 1) * PAGE_SIZE);
1209
- useEffect(() => {
1210
- if (page !== currentPage) setPage(currentPage);
1211
- }, [page, currentPage]);
1212
- if (pageRecommendations.length === 0) return null;
1213
- return /* @__PURE__ */ jsx$1("s-box", {
1214
- padding,
1215
- children: /* @__PURE__ */ jsxs("s-stack", {
1216
- gap: "base",
1217
- children: [/* @__PURE__ */ jsx$1("s-grid", {
1218
- gridTemplateColumns: "repeat(4, minmax(0, 1fr))",
1219
- gap: "small-200",
1220
- children: pageRecommendations.map((recommendation) => /* @__PURE__ */ jsx$1("s-box", {
1221
- inlineSize: "100%",
1222
- children: /* @__PURE__ */ jsx$1(RecommendationsOfferRowTile, { recommendation })
1223
- }, recommendation.id))
1224
- }), pageCount > 1 && /* @__PURE__ */ jsxs("s-stack", {
1225
- direction: "inline",
1226
- justifyContent: "center",
1227
- alignItems: "center",
1228
- gap: "small-200",
1229
- children: [
1230
- /* @__PURE__ */ jsx$1("s-clickable", {
1231
- accessibilityLabel: "Previous recommendations page",
1232
- disabled: currentPage === 0,
1233
- inlineSize: "32px",
1234
- blockSize: "32px",
1235
- border: "base",
1236
- borderRadius: "base",
1237
- onClick: () => setPage(currentPage - 1),
1238
- children: /* @__PURE__ */ jsx$1("s-stack", {
1239
- blockSize: "100%",
1240
- alignItems: "center",
1241
- justifyContent: "center",
1242
- children: /* @__PURE__ */ jsx$1("s-icon", {
1243
- type: "chevron-left",
1244
- size: "small",
1245
- tone: currentPage === 0 ? "neutral" : "auto"
1246
- })
1247
- })
1248
- }),
1249
- /* @__PURE__ */ jsxs("s-text", {
1250
- type: "small",
1251
- tone: "neutral",
1252
- color: "base",
1253
- children: [
1254
- currentPage + 1,
1255
- " / ",
1256
- pageCount
1257
- ]
1258
- }),
1259
- /* @__PURE__ */ jsx$1("s-clickable", {
1260
- accessibilityLabel: "Next recommendations page",
1261
- disabled: currentPage === pageCount - 1,
1262
- inlineSize: "32px",
1263
- blockSize: "32px",
1264
- border: "base",
1265
- borderRadius: "base",
1266
- onClick: () => setPage(currentPage + 1),
1267
- children: /* @__PURE__ */ jsx$1("s-stack", {
1268
- blockSize: "100%",
1269
- alignItems: "center",
1270
- justifyContent: "center",
1271
- children: /* @__PURE__ */ jsx$1("s-icon", {
1272
- type: "chevron-right",
1273
- size: "small",
1274
- tone: currentPage === pageCount - 1 ? "neutral" : "auto"
1275
- })
1276
- })
1277
- })
1278
- ]
1279
- })]
1280
- })
1281
- });
1282
- }
1283
- function RecommendationsOfferRowTile({ recommendation }) {
1284
- const { track } = useEventTracker();
1285
- const env = useDiscoEnv();
1286
- const offerId = recommendation.offer.id;
1287
- const advertiserId = recommendation.advertiser.id;
1288
- const insertionId = recommendation.insertionId;
1289
- useEffect(() => {
1290
- track({
1291
- type: "BRAND_DISPLAY",
1292
- target: "SCROLLABLE_SLOT",
1293
- brand: {
1294
- offerId,
1295
- advertiserId,
1296
- insertionId
1297
- }
1298
- });
1299
- }, [
1300
- track,
1301
- offerId,
1302
- advertiserId,
1303
- insertionId
1304
- ]);
1305
- const trackClick = () => {
1306
- track({
1307
- type: "BRAND_CLICK",
1308
- target: "SCROLLABLE_SLOT_TILE",
1309
- brand: {
1310
- offerId,
1311
- advertiserId,
1312
- insertionId
1313
- }
1314
- });
1315
- };
1316
- const targetUrl = recommendation.offer.targetUrl;
1317
- const productName = `${recommendation.offer.heading} ${recommendation.offer.subheading}`;
1318
- const offerImageAsset = recommendation.offer.assets[0];
1319
- if (!offerImageAsset) return null;
1320
- return /* @__PURE__ */ jsx$1(ProductTile, {
1321
- targetUrl,
1322
- trackClick,
1323
- image: getImageSources(offerImageAsset.imageUrl, {
1324
- env,
1325
- size: PRODUCT_IMAGE_SOURCE_SIZE
1326
- }),
1327
- productName
1328
- });
1329
- }
1330
- //#endregion
1331
- //#region src/components/RecommendationsWidget/Essential/index.tsx
1332
- const EssentialRecommendationsWidget = ({ heroRecommendationGroup, scrollableRecommendationGroup }) => {
1333
- const [showOfferSlot, setShowOfferSlot] = useState(!!heroRecommendationGroup);
1334
- const { track } = useEventTracker();
1335
- const { applyCustomizationOrFallback } = useRecommendationsCustomization();
1336
- useEffect(() => {
1337
- track({ type: "WIDGET_LOAD" });
1338
- track({ type: "WIDGET_DISPLAY" });
1339
- }, [track]);
1340
- const hideOfferSlot = () => setShowOfferSlot(false);
1341
- const heading = applyCustomizationOrFallback("widget_bottom_slot_heading", "Trending brands we think you'll love");
1342
- if (!showOfferSlot && !scrollableRecommendationGroup) return null;
1343
- return /* @__PURE__ */ jsx$1(ScrollableSlotProvider, {
1344
- scrollableRecommendationGroup,
1345
- children: /* @__PURE__ */ jsxs(CardContainer, {
1346
- background: "base",
1347
- children: [
1348
- showOfferSlot && heroRecommendationGroup ? /* @__PURE__ */ jsx$1("s-box", {
1349
- border: "base",
1350
- borderWidth: "none none base none",
1351
- children: /* @__PURE__ */ jsx$1(HeroOfferProvider, {
1352
- recommendationGroup: heroRecommendationGroup,
1353
- children: /* @__PURE__ */ jsx$1(TrackedEssentialLayout, { onLastOffer: hideOfferSlot })
1354
- })
1355
- }) : /* @__PURE__ */ jsx$1("s-box", {
1356
- padding: "base base none base",
1357
- children: /* @__PURE__ */ jsx$1("s-heading", { children: heading })
1358
- }),
1359
- scrollableRecommendationGroup && /* @__PURE__ */ jsx$1("s-box", {
1360
- padding: "base none",
1361
- border: "base",
1362
- borderWidth: "none none base none",
1363
- children: /* @__PURE__ */ jsx$1(RecommendationsOfferRow, {
1364
- recommendations: scrollableRecommendationGroup.recommendations,
1365
- padding: "none base"
1366
- })
1367
- }),
1368
- /* @__PURE__ */ jsx$1(Footer, {})
1369
- ]
1370
- })
1371
- });
1372
- };
1373
- const TrackedEssentialLayout = ({ onLastOffer }) => {
1374
- const { track } = useEventTracker();
1375
- const { activeRecommendation } = useHeroOffer();
1376
- const { insertionId, offer, advertiser } = activeRecommendation;
1377
- useEffect(() => {
1378
- track({
1379
- type: "BRAND_DISPLAY",
1380
- target: "INLINE_SLOT",
1381
- brand: {
1382
- offerId: offer.id,
1383
- advertiserId: advertiser.id,
1384
- insertionId
1385
- }
1386
- });
1387
- }, [
1388
- track,
1389
- insertionId,
1390
- offer.id,
1391
- advertiser.id
1392
- ]);
1393
- return /* @__PURE__ */ jsx$1(EssentialLayoutType, { onLastOffer });
1394
- };
1395
- //#endregion
1396
- //#region src/components/RecommendationsWidget/LeadGen/LeadGenHeader.tsx
1397
- const LeadGenHeader = () => {
1398
- const { claimedOffers } = useHeroOffer();
1399
- const { applyCustomizationOrFallback } = useRecommendationsCustomization();
1400
- const hasClaimedAnOffer = claimedOffers.length > 0;
1401
- const heading = applyCustomizationOrFallback("widget_heading", !hasClaimedAnOffer ? `Special offers just for you` : `Your special offer is claimed!`);
1402
- const subheading = applyCustomizationOrFallback("widget_subheading", !hasClaimedAnOffer ? `As a thank you for your recent purchase` : "Discover more deals to save on top brands");
1403
- return /* @__PURE__ */ jsxs("s-stack", {
1404
- gap: "none",
1405
- padding: "large-200",
1406
- children: [/* @__PURE__ */ jsx$1("s-heading", { children: heading }), /* @__PURE__ */ jsx$1("s-text", {
1407
- color: "subdued",
1408
- children: subheading
1409
- })]
1410
- });
1411
- };
1412
- //#endregion
1413
- //#region src/components/RecommendationsWidget/LeadGen/LeadGenBrand.tsx
1414
- const LeadGenAssetTile = ({ asset }) => {
1415
- const env = useDiscoEnv();
1416
- const image = getImageSources(asset.imageUrl, {
1417
- env,
1418
- size: 400
1419
- });
1420
- return /* @__PURE__ */ jsx$1("s-image", {
1421
- aspectRatio: "1",
1422
- src: image.src,
1423
- srcSet: image.srcSet,
1424
- alt: "Offer product",
1425
- inlineSize: "fill",
1426
- border: "base",
1427
- borderRadius: "base",
1428
- loading: "lazy"
1429
- });
1430
- };
1431
- const LeadGenBrandProducts = () => {
1432
- const { activeRecommendation } = useHeroOffer();
1433
- const assets = activeRecommendation.offer.assets.slice(0, 4);
1434
- if (assets.length === 0) return null;
1435
- return /* @__PURE__ */ jsx$1("s-query-container", { children: /* @__PURE__ */ jsx$1("s-grid", {
1436
- gridTemplateColumns: "@container (inline-size > 450px) repeat(4, 1fr), repeat(3, 1fr)",
1437
- gap: "small-200",
1438
- children: assets.map((asset) => /* @__PURE__ */ jsx$1(LeadGenAssetTile, { asset }, asset.id))
1439
- }) });
1440
- };
1441
- const LeadGenBrand = () => {
1442
- const { activeRecommendation } = useHeroOffer();
1443
- const { advertiser } = activeRecommendation;
1444
- const env = useDiscoEnv();
1445
- const logoSize = 56;
1446
- const logo = getImageSources(advertiser.logoUrl, {
1447
- env,
1448
- size: logoSize
1449
- });
1450
- return /* @__PURE__ */ jsxs("s-stack", {
1451
- gap: "small-200",
1452
- padding: "base large-200",
1453
- children: [/* @__PURE__ */ jsxs("s-grid", {
1454
- gridTemplateColumns: `1fr ${logoSize}px`,
1455
- gap: "small-200",
1456
- alignItems: "start",
1457
- children: [/* @__PURE__ */ jsxs("s-stack", {
1458
- gap: "none",
1459
- children: [/* @__PURE__ */ jsx$1("s-text", {
1460
- type: "strong",
1461
- children: advertiser.name
1462
- }), /* @__PURE__ */ jsx$1("s-paragraph", { children: advertiser.description })]
1463
- }), /* @__PURE__ */ jsx$1("s-box", {
1464
- inlineSize: `${logoSize}px`,
1465
- blockSize: `${logoSize}px`,
1466
- children: /* @__PURE__ */ jsx$1("s-image", {
1467
- aspectRatio: "1",
1468
- src: logo.src,
1469
- srcSet: logo.srcSet,
1470
- alt: `${advertiser.name} logo`,
1471
- inlineSize: "fill",
1472
- border: "base",
1473
- borderRadius: "max"
1474
- })
1475
- })]
1476
- }), /* @__PURE__ */ jsx$1(LeadGenBrandProducts, {})]
1477
- });
1478
- };
1479
- //#endregion
1480
- //#region src/hooks/useResource.tsx
1481
- const initialResource = {
1482
- loading: false,
1483
- error: false,
1484
- data: null,
1485
- headers: null
1486
- };
1487
- const useResource = (options, autoLoad = true, debug = false) => {
1488
- const [shouldLoad, setShouldLoad] = useState(autoLoad);
1489
- const [resource, setResource] = useState(initialResource);
1490
- const reset = useCallback(() => {
1491
- setResource(initialResource);
1492
- setShouldLoad(false);
1493
- }, []);
1494
- const log = useCallback((...msg) => {
1495
- if (debug) console.log(...msg);
1496
- }, [debug]);
1497
- const mounted = useRef(true);
1498
- useEffect(() => {
1499
- mounted.current = true;
1500
- return () => {
1501
- mounted.current = false;
1502
- };
1503
- }, []);
1504
- const startLoad = useCallback(() => setShouldLoad(true), []);
1505
- const load = useCallback(async () => {
1506
- log("[uR]: Load called ");
1507
- if (resource.loading || !shouldLoad || !options?.url) {
1508
- log("[uR]: Load stopped ");
1509
- return;
1510
- }
1511
- log("[uR]: Load started ");
1512
- setShouldLoad(false);
1513
- let resp;
1514
- setResource({
1515
- loading: true,
1516
- error: false,
1517
- data: null,
1518
- headers: null
1519
- });
1520
- try {
1521
- let reqOptions = {
1522
- headers: { "Content-Type": "application/json" },
1523
- method: "GET",
1524
- ...options
1525
- };
1526
- if ((options?.method === "POST" || options?.method === "PUT") && options.data) reqOptions = {
1527
- ...reqOptions,
1528
- body: JSON.stringify(options.data)
1529
- };
1530
- resp = await fetch(options.url, reqOptions);
1531
- if (resp.status !== 200 && resp.status !== 201) throw new Error("RESP_ERR");
1532
- try {
1533
- resp = await resp.json();
1534
- } catch {
1535
- throw new Error("JSON_ERR");
1536
- }
1537
- } catch (e) {
1538
- if (typeof e === "string") {
1539
- log(`[uR]: Load error! String => ${e}`);
1540
- return;
1541
- } else if (!(e instanceof Error)) {
1542
- log(`[uR]: Load error! Unknown error =>`, e);
1543
- return;
1544
- }
1545
- const { message: errMessage } = e;
1546
- log(`[uR]: Load error! ${errMessage}`);
1547
- if (mounted.current) return setResource({
1548
- loading: false,
1549
- error: errMessage === "RESP_ERR" || errMessage === "JSON_ERR" ? "An unknown error occured" : "Could not connect to the server",
1550
- data: null
1551
- });
1552
- else return log("[uR]: Load error but NOT MOUNTED ");
1553
- }
1554
- if (mounted.current) {
1555
- log("[uR]: Load complete:", resp);
1556
- setResource({
1557
- loading: false,
1558
- error: false,
1559
- data: resp,
1560
- headers: null
1561
- });
1562
- } else log("[uR]: Load complete but NOT MOUNTED ");
1563
- }, [
1564
- options,
1565
- resource.loading,
1566
- shouldLoad,
1567
- log
1568
- ]);
1569
- useEffect(() => {
1570
- if (!resource.loading && shouldLoad) load();
1571
- }, [
1572
- resource.loading,
1573
- shouldLoad,
1574
- load
1575
- ]);
1576
- return [
1577
- resource,
1578
- startLoad,
1579
- reset
1580
- ];
1581
- };
1582
- //#endregion
1583
- //#region src/hooks/useSendOfferEmail.ts
1584
- const useSendOfferEmail = ({ shopGid, offerRemoteId, displayedOfferRemoteIds, sessionId }) => {
1585
- const payload = usePayload();
1586
- return useResource({
1587
- url: getLeadGenRegisterUrl(useDiscoEnv()),
1588
- method: "POST",
1589
- data: {
1590
- email: payload.buyerEmail,
1591
- first_name: payload.billingFirstName || "",
1592
- last_name: payload.billingLastName || "",
1593
- shop_gid: shopGid,
1594
- offer_id: offerRemoteId,
1595
- displayed_offer_ids: displayedOfferRemoteIds,
1596
- session_id: sessionId,
1597
- shopify_order_id: shopifyOrderIdFormatter(payload.orderId || null)
1598
- }
1599
- }, false);
1600
- };
1601
- //#endregion
1602
- //#region src/components/RecommendationsWidget/LeadGen/LeadGenActionButton.tsx
1603
- function LeadGenActionButton() {
1604
- const { activeRecommendation, isOfferClaimed, handleOfferClaim, recommendations } = useHeroOffer();
1605
- const { track } = useEventTracker();
1606
- const buttonText = useGetButtonText();
1607
- const data = useRecommendationsData();
1608
- const payload = usePayload();
1609
- const [, sendOfferEmail] = useSendOfferEmail({
1610
- shopGid: getShopIdentifier(payload.shopGid),
1611
- displayedOfferRemoteIds: recommendations.map((recommendation) => recommendation.offer.id),
1612
- offerRemoteId: activeRecommendation.offer.id,
1613
- sessionId: data.sessionId
1614
- });
1615
- const handleClick = () => {
1616
- track({
1617
- type: "BRAND_CLICK",
1618
- target: "INLINE_ACTION_BUTTON",
1619
- brand: {
1620
- offerId: activeRecommendation.offer.id,
1621
- advertiserId: activeRecommendation.advertiser.id,
1622
- insertionId: activeRecommendation.insertionId
1623
- }
1624
- });
1625
- if (isOfferClaimed) return;
1626
- if (payload.buyerEmail) sendOfferEmail();
1627
- handleOfferClaim();
1628
- };
1629
- return /* @__PURE__ */ jsx$1("s-button", {
1630
- href: activeRecommendation.offer.targetUrl,
1631
- target: "_blank",
1632
- inlineSize: "fill",
1633
- variant: isOfferClaimed ? "secondary" : "primary",
1634
- onClick: handleClick,
1635
- children: buttonText
1636
- }, "lead-action-button");
1637
- }
1638
- function useGetButtonText() {
1639
- const { activeRecommendation, isOfferClaimed } = useHeroOffer();
1640
- const { applyCustomizationOrFallback } = useRecommendationsCustomization();
1641
- if (activeRecommendation.offer.metadata.type === "NO_PROMO_CODE") {
1642
- if (isOfferClaimed) return applyCustomizationOrFallback("widget_claimed_no_promo_cta_text", "Redeem onsite");
1643
- return applyCustomizationOrFallback("widget_unclaimed_no_promo_cta_text", "Redeem onsite");
1644
- }
1645
- if (isOfferClaimed) return applyCustomizationOrFallback("widget_claimed_promo_cta_text", "Visit shop");
1646
- return applyCustomizationOrFallback("widget_unclaimed_promo_cta_text", "Claim offer");
1647
- }
1648
- //#endregion
1649
- //#region src/components/RecommendationsWidget/LeadGen/LeadGenOfferRow.tsx
1650
- const LeadGenOfferRow = ({ recommendations }) => {
1651
- const { applyCustomizationOrFallback } = useRecommendationsCustomization();
1652
- return /* @__PURE__ */ jsxs("s-stack", {
1653
- gap: "small-200",
1654
- padding: "base none",
1655
- children: [/* @__PURE__ */ jsx$1("s-box", {
1656
- padding: "none large-200",
1657
- children: /* @__PURE__ */ jsx$1("s-text", {
1658
- type: "strong",
1659
- children: applyCustomizationOrFallback("widget_bottom_slot_heading", "Trending brands we think you'll love")
1660
- })
1661
- }), /* @__PURE__ */ jsx$1(RecommendationsOfferRow, {
1662
- recommendations,
1663
- padding: "small-400 large-200"
1664
- })]
1665
- });
1666
- };
1667
- //#endregion
1668
- //#region src/components/RecommendationsWidget/LeadGen/index.tsx
1669
- const LeadGen = ({ heroRecommendationGroup, scrollableRecommendationGroup }) => {
1670
- const { track } = useEventTracker();
1671
- useEffect(() => {
1672
- track({ type: "WIDGET_LOAD" });
1673
- track({ type: "WIDGET_DISPLAY" });
1674
- }, [track]);
1675
- return /* @__PURE__ */ jsxs(CardContainer, {
1676
- background: "base",
1677
- padding: "none none large-200 none",
1678
- children: [
1679
- heroRecommendationGroup && /* @__PURE__ */ jsxs(HeroOfferProvider, {
1680
- recommendationGroup: heroRecommendationGroup,
1681
- children: [
1682
- /* @__PURE__ */ jsx$1(LeadGenHeader, {}),
1683
- /* @__PURE__ */ jsx$1("s-divider", {}),
1684
- /* @__PURE__ */ jsx$1("s-box", {
1685
- minBlockSize: "230px",
1686
- children: /* @__PURE__ */ jsx$1(LeadGenBrand, {})
1687
- }),
1688
- /* @__PURE__ */ jsxs("s-stack", {
1689
- padding: "none large-200 large-200 large-200",
1690
- gap: "base",
1691
- children: [/* @__PURE__ */ jsx$1(LeadGenActionOffer, {}), /* @__PURE__ */ jsx$1(LeadGenActionNav, {})]
1692
- }),
1693
- /* @__PURE__ */ jsx$1("s-divider", {})
1694
- ]
1695
- }),
1696
- scrollableRecommendationGroup && /* @__PURE__ */ jsx$1(LeadGenOfferRow, { recommendations: scrollableRecommendationGroup.recommendations }),
1697
- /* @__PURE__ */ jsx$1(Footer, {})
1698
- ]
1699
- });
1700
- };
1701
- function LeadGenActionOffer() {
1702
- const { activeRecommendation, isOfferClaimed } = useHeroOffer();
1703
- const { heading, subheading, metadata } = activeRecommendation.offer;
1704
- const primaryHeading = isOfferClaimed ? `You've got ${heading}` : heading;
1705
- const secondaryHeading = isOfferClaimed && metadata.type === "PROMO_CODE" ? /* @__PURE__ */ jsxs(Fragment, { children: ["Use code: ", /* @__PURE__ */ jsx$1("s-text", {
1706
- type: "strong",
1707
- children: metadata.code
1708
- })] }) : subheading || "On your next purchase";
1709
- return /* @__PURE__ */ jsxs("s-stack", {
1710
- padding: "base",
1711
- background: "subdued",
1712
- border: "base base dashed",
1713
- borderRadius: "base",
1714
- gap: "base",
1715
- children: [/* @__PURE__ */ jsxs("s-stack", {
1716
- gap: "none",
1717
- children: [/* @__PURE__ */ jsx$1("s-heading", { children: primaryHeading }), /* @__PURE__ */ jsx$1("s-text", { children: secondaryHeading })]
1718
- }), /* @__PURE__ */ jsx$1(LeadGenActionButton, {})]
1719
- });
1720
- }
1721
- function LeadGenActionNav() {
1722
- const { activeRecommendation, nextOffer, prevOffer, isFirstOffer, isLastOffer, isOfferClaimed, TOTAL_NUM_OFFERS } = useHeroOffer();
1723
- const { track } = useEventTracker();
1724
- const { applyCustomizationOrFallback } = useRecommendationsCustomization();
1725
- if (TOTAL_NUM_OFFERS <= 1) return null;
1726
- const showPrevious = !isFirstOffer;
1727
- const showNext = !isLastOffer;
1728
- const hasSingleButton = !showNext || !showPrevious;
1729
- const trackNavigation = () => ({
1730
- offerId: activeRecommendation.offer.id,
1731
- advertiserId: activeRecommendation.advertiser.id,
1732
- insertionId: activeRecommendation.insertionId
1733
- });
1734
- const handleNext = () => {
1735
- track({
1736
- type: "ELEMENT_CLICK",
1737
- target: "INLINE_NAV_FORWARD",
1738
- brand: trackNavigation()
1739
- });
1740
- nextOffer();
1741
- };
1742
- const handlePrevious = () => {
1743
- track({
1744
- type: "ELEMENT_CLICK",
1745
- target: "INLINE_NAV_BACKWARD",
1746
- brand: trackNavigation()
1747
- });
1748
- prevOffer();
1749
- };
1750
- return /* @__PURE__ */ jsxs("s-grid", {
1751
- gridTemplateColumns: hasSingleButton ? "1fr" : "1fr 11px 1fr",
1752
- gap: "base",
1753
- children: [
1754
- showPrevious && /* @__PURE__ */ jsx$1("s-button", {
1755
- variant: !isOfferClaimed || showNext ? "secondary" : "primary",
1756
- onClick: handlePrevious,
1757
- children: applyCustomizationOrFallback("widget_nav_backward_cta_text", "Previous offer")
1758
- }),
1759
- !hasSingleButton && /* @__PURE__ */ jsx$1("s-box", {}),
1760
- showNext && /* @__PURE__ */ jsx$1("s-button", {
1761
- variant: isOfferClaimed ? "primary" : "secondary",
1762
- onClick: handleNext,
1763
- children: applyCustomizationOrFallback("widget_nav_forward_cta_text", showPrevious ? "Next offer" : "No thanks")
1764
- })
1765
- ]
1766
- });
1767
- }
1768
- //#endregion
1769
- //#region src/components/RecommendationsWidget/index.tsx
1770
- const ESSENTIAL_LAYOUT_IDS = ["SHOPIFY_NATIVE_ESSENTIAL", "SHOPIFY_NATIVE_ESSENTIAL_0.22"];
1771
- const Widget = () => {
1772
- const recommendationsData = useRecommendationsData();
1773
- const heroRecommendationGroup = recommendationsData.recommendationGroups.find((group) => group.slotContext === "HERO");
1774
- const scrollableRecommendationGroup = recommendationsData.recommendationGroups.find((group) => group.slotContext === "SCROLLABLE");
1775
- if (!heroRecommendationGroup && !scrollableRecommendationGroup) return null;
1776
- const layoutId = recommendationsData.layoutId;
1777
- if (ESSENTIAL_LAYOUT_IDS.includes(layoutId)) return /* @__PURE__ */ jsx$1(EssentialRecommendationsWidget, {
1778
- heroRecommendationGroup,
1779
- scrollableRecommendationGroup
1780
- });
1781
- if (layoutId === "SHOPIFY_NATIVE_COVER") {
1782
- if (!heroRecommendationGroup) return null;
1783
- return /* @__PURE__ */ jsx$1(CoverRecommendationsWidget, { heroRecommendationGroup });
1784
- }
1785
- return /* @__PURE__ */ jsx$1(LeadGen, {
1786
- heroRecommendationGroup,
1787
- scrollableRecommendationGroup
1788
- });
1789
- };
1790
- //#endregion
1791
- //#region src/DiscoRecommendations.tsx
1792
- /**
1793
- * Disco post-purchase recommendations for a Shopify UI extension.
1794
- *
1795
- * Render it from a `purchase.thank-you.block.render` or
1796
- * `customer-account.order-status.block.render` target; the order and buyer
1797
- * details are read from that target's API.
1798
- */
1799
- function DiscoRecommendations({ apiKey, ...source }) {
1800
- return /* @__PURE__ */ jsx$1(Recommendations, {
1801
- auth: { apiKey },
1802
- ...source
1803
- });
1804
- }
1805
- /**
1806
- * The widget tree shared by the public (`apiKey`) and internal (`shop_gid`)
1807
- * entry points.
1808
- */
1809
- function Recommendations({ auth, ...source }) {
1810
- return /* @__PURE__ */ jsx$1(PayloadManager, { children: /* @__PURE__ */ jsx$1(DataManager, {
1811
- auth,
1812
- ...source,
1813
- children: /* @__PURE__ */ jsx$1(UserManager, { children: /* @__PURE__ */ jsx$1(Widget, {}) })
1814
- }) });
1815
- }
1816
- //#endregion
1817
- export { Recommendations as n, DiscoRecommendations as t };
1818
-
1819
- //# sourceMappingURL=DiscoRecommendations-DTYhXMfG.js.map