@disconetwork/shopify 0.0.1 → 0.0.3

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