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