@frak-labs/components 1.4.0 → 1.5.0-beta.d6248982

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.
Files changed (48) hide show
  1. package/cdn/Ambassador.Cmb0kX5D.js +519 -0
  2. package/cdn/Banner.2WJ4pT6E.js +227 -0
  3. package/cdn/{ButtonShare.C7A2tEvB.js → ButtonShare.DSGvJfJ-.js} +1 -1
  4. package/cdn/{ButtonWallet.Cg2OK1di.js → ButtonWallet.DHpHCl4c.js} +2 -2
  5. package/cdn/GiftIcon.DYg5xgHg.js +1 -0
  6. package/cdn/InstallQr.CHImaq56.js +1 -0
  7. package/cdn/{OpenInAppButton.Djz_cb9Y.js → OpenInAppButton.CxBzRNKw.js} +1 -1
  8. package/cdn/PostPurchase.C75q-9BM.js +124 -0
  9. package/cdn/RewardReminder.C6o8lgak.js +369 -0
  10. package/cdn/components.js +1 -1
  11. package/cdn/format.D2Ai5cCn.js +1 -0
  12. package/cdn/{GiftIcon.CW1SwrXH.js → icons.CdzHzZIJ.js} +1 -1
  13. package/cdn/jsxRuntime.module.7FJBZ9bf.js +58 -0
  14. package/cdn/loader.js +21 -16
  15. package/cdn/mountRewardReminder.BlmSRJDe.js +1 -0
  16. package/cdn/previewSummary.DxyobqED.js +1 -0
  17. package/cdn/replay-V6FXES7X.CgBxdfNp.js +1 -0
  18. package/cdn/rewardSummaryStore.DyjI-vPH.js +1 -0
  19. package/cdn/{rewards.t-rH9M3s.js → rewards.CeNLrK54.js} +1 -1
  20. package/cdn/useGlobalComponents.CNnOzerU.js +1 -0
  21. package/cdn/{useLightDomStyles.B72V1WPK.js → useLightDomStyles.557xWurb.js} +1 -1
  22. package/cdn/usePlacement.DYgmdkfr.js +1 -0
  23. package/cdn/{useReward.D2kXQbtD.js → useReward.BzUL3ijd.js} +1 -1
  24. package/dist/GiftIcon-Csu31jtf.js +62 -0
  25. package/dist/InstallQr-kpb44cfg.js +84 -0
  26. package/dist/ambassador.d.ts +16 -1
  27. package/dist/ambassador.js +534 -178
  28. package/dist/banner.d.ts +20 -6
  29. package/dist/banner.js +235 -13
  30. package/dist/format-zGdbUoX_.js +283 -0
  31. package/dist/i18n/defaults.d.ts +72 -0
  32. package/dist/i18n/defaults.js +108 -6
  33. package/dist/{GiftIcon-B9k_syq6.js → icons-iN3qH_Bv.js} +1 -61
  34. package/dist/postPurchase.d.ts +6 -1
  35. package/dist/postPurchase.js +187 -33
  36. package/dist/previewSummary-CMc6q8vI.js +37 -0
  37. package/dist/rewardReminder.d.ts +50 -0
  38. package/dist/rewardReminder.js +809 -0
  39. package/dist/sharedBaseCss.css-48sBApvf.js +3 -0
  40. package/package.json +18 -12
  41. package/cdn/Ambassador.BDu4aVZ9.js +0 -392
  42. package/cdn/Banner.BqfCxKs3.js +0 -208
  43. package/cdn/PostPurchase.DIZneqoT.js +0 -102
  44. package/cdn/jsxRuntime.module.DWH-kRVd.js +0 -58
  45. package/cdn/replay-V6FXES7X.efKsNT6s.js +0 -1
  46. package/cdn/useGlobalComponents.DVgSWfOp.js +0 -1
  47. package/cdn/usePlacement.DEOEf5_6.js +0 -1
  48. package/dist/sharedBaseCss.css-nYy9vlzH.js +0 -3
package/dist/banner.d.ts CHANGED
@@ -49,6 +49,18 @@ type BannerProps = {
49
49
  * Override the in-app browser banner CTA button text.
50
50
  */
51
51
  inappCta?: string;
52
+ /**
53
+ * Override the pending banner title. Supports `{REWARD}`, `{DAYS}`, `{DATE}`.
54
+ */
55
+ pendingTitle?: string;
56
+ /**
57
+ * Override the pending banner description. Supports the same placeholders.
58
+ */
59
+ pendingDescription?: string;
60
+ /**
61
+ * Override the pending banner CTA text. Supports the same placeholders.
62
+ */
63
+ pendingCta?: string;
52
64
  /**
53
65
  * Override the image displayed on the left of the referral banner.
54
66
  * Accepts an image URL. Falls back to the built-in gift icon when omitted.
@@ -62,10 +74,10 @@ type BannerProps = {
62
74
  */
63
75
  preview?: string;
64
76
  /**
65
- * Which banner variant to preview: "referral" or "inapp".
77
+ * Which banner variant to preview: "referral", "inapp" or "pending".
66
78
  * Only used when {@link preview} is set. Defaults to "referral".
67
79
  */
68
- previewMode?: "referral" | "inapp";
80
+ previewMode?: "referral" | "inapp" | "pending";
69
81
  /**
70
82
  * When `true` (default `false`), the banner is allowed to switch to
71
83
  * in-app browser mode (Instagram / Facebook WebView) and prompt the
@@ -85,8 +97,7 @@ type BannerProps = {
85
97
  /**
86
98
  * Auto-detecting notification banner component.
87
99
  *
88
- * Renders an inline banner on the merchant page with one of two distinct
89
- * visual styles depending on the detected mode:
100
+ * Renders an inline banner on the merchant page with one of three modes:
90
101
  *
91
102
  * - **Referral mode** (white): Shown after a successful referral link
92
103
  * processing. Displays a gift icon, reward copy, and a "Got it" CTA.
@@ -95,7 +106,10 @@ type BannerProps = {
95
106
  * Offers an inline link to redirect to the default browser plus a
96
107
  * close button to dismiss.
97
108
  *
98
- * In-app browser mode takes priority over referral mode.
109
+ * - **Pending mode** (white): Shown to a visitor with unclaimed rewards and no
110
+ * Frak wallet yet; see {@link PendingBanner}.
111
+ *
112
+ * Priority: in-app browser, then referral, then pending.
99
113
  * Uses Light DOM + vanilla-extract styles from `@frak-labs/design-system`.
100
114
  *
101
115
  * @group components
@@ -112,7 +126,7 @@ type BannerProps = {
112
126
  * <frak-banner classname="my-custom-banner"></frak-banner>
113
127
  * ```
114
128
  */
115
- export declare function Banner({ placement: placementId, classname, interaction, products, referralTitle: propReferralTitle, referralDescription: propReferralDescription, referralCta: propReferralCta, inappTitle: propInappTitle, inappDescription: propInappDescription, inappCta: propInappCta, imageUrl: propImageUrl, preview, previewMode, allowInappRedirect }: BannerProps): import("preact").JSX.Element | null;
129
+ export declare function Banner({ placement: placementId, classname, interaction, products, referralTitle: propReferralTitle, referralDescription: propReferralDescription, referralCta: propReferralCta, inappTitle: propInappTitle, inappDescription: propInappDescription, inappCta: propInappCta, pendingTitle, pendingDescription, pendingCta, imageUrl: propImageUrl, preview, previewMode, allowInappRedirect }: BannerProps): import("preact").JSX.Element | null;
116
130
  /**
117
131
  * Custom element interface for `<frak-banner>`.
118
132
  * Combines standard {@link HTMLElement} with {@link BannerProps}.
package/dist/banner.js CHANGED
@@ -1,14 +1,17 @@
1
1
  import { a as useClientReady, o as registerWebComponent, r as useLang } from "./sharedCss-SKmJGZgN.js";
2
2
  import { i as w } from "./rewards-BuNthAR2.js";
3
- import { a as CloseCircleIcon, i as ExternalLinkIcon, n as WarningIcon, r as LogoFrakWithName, t as GiftIcon } from "./GiftIcon-B9k_syq6.js";
3
+ import { i as CloseCircleIcon, n as LogoFrakWithName, r as ExternalLinkIcon, t as WarningIcon } from "./icons-iN3qH_Bv.js";
4
4
  import { t as useGlobalComponents } from "./useGlobalComponents-BF47jsBt.js";
5
5
  import { t as useLightDomStyles } from "./useLightDomStyles-wGaNXHqN.js";
6
6
  import { t as usePlacement } from "./usePlacement-Dd7itnCf.js";
7
7
  import { t as useReward } from "./useReward-cQ54x8q-.js";
8
8
  import { componentDefaults } from "./i18n/defaults.js";
9
- import { t as cssSource$4 } from "./sharedBaseCss.css-nYy9vlzH.js";
9
+ import { t as cssSource$4 } from "./sharedBaseCss.css-48sBApvf.js";
10
+ import { t as GiftIcon } from "./GiftIcon-Csu31jtf.js";
11
+ import { a as resolveRewardCurrency, c as isClaimable, d as useInlineReminderRegistration, f as useReminderDismissed, l as markClaimStarted, n as formatFiat, o as getRewardCountdown, p as dismissReminder, r as formatRewardDate, s as useRewardSummary, t as fillReminderText } from "./format-zGdbUoX_.js";
12
+ import { n as getCountdownLabel, t as getPreviewPending } from "./previewSummary-CMc6q8vI.js";
10
13
  import { isInAppBrowser, redirectToExternalBrowser, sanitizeProductDetailsList, trackEvent } from "@frak-labs/core-sdk";
11
- import { REFERRAL_SUCCESS_EVENT, getMergeToken } from "@frak-labs/core-sdk/actions";
14
+ import { REFERRAL_SUCCESS_EVENT, getInstallUrl, getMergeToken } from "@frak-labs/core-sdk/actions";
12
15
  import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
13
16
  import { jsx, jsxs } from "preact/jsx-runtime";
14
17
  // \0ve-inline:../../packages/design-system/src/keyframes.css.ts.vanilla.js
@@ -273,7 +276,26 @@ const cssSource$1 = `.Banner_rootBase__1gnumzi0 {
273
276
  display: inline-block;
274
277
  }
275
278
 
276
- .Banner_frakLogo__1gnumzi9 {
279
+ .Banner_pendingCta__1gnumzi9 {
280
+ text-decoration: none;
281
+ }
282
+
283
+ .Banner_pendingBody__1gnumzia {
284
+ padding-right: 24px;
285
+ }
286
+
287
+ .Banner_pendingClose__1gnumzib {
288
+ color: #979797;
289
+ width: 24px;
290
+ height: 24px;
291
+ font-size: 18px;
292
+ line-height: 24px;
293
+ position: absolute;
294
+ top: 8px;
295
+ right: 8px;
296
+ }
297
+
298
+ .Banner_frakLogo__1gnumzic {
277
299
  pointer-events: none;
278
300
  position: absolute;
279
301
  bottom: 12px;
@@ -281,8 +303,11 @@ const cssSource$1 = `.Banner_rootBase__1gnumzi0 {
281
303
  }
282
304
  `;
283
305
  // src/components/Banner/Banner.css.ts
284
- var frakLogo = "Banner_frakLogo__1gnumzi9";
306
+ var frakLogo = "Banner_frakLogo__1gnumzic";
285
307
  var iconSvg = "Banner_iconSvg__1gnumzi1";
308
+ var pendingBody = "Banner_pendingBody__1gnumzia";
309
+ var pendingClose = "Banner_pendingClose__1gnumzib sharedBaseCss_buttonReset__7cswil0";
310
+ var pendingCta = "Banner_pendingCta__1gnumzi9 Banner_referralCta__1gnumzi8 sharedBaseCss_buttonReset__7cswil0";
286
311
  var referral = "Banner_referral__1gnumzi2 reset_base__1831jhd0 Banner_rootBase__1gnumzi0";
287
312
  var referralBody = "Banner_referralBody__1gnumzi5";
288
313
  var referralCta = "Banner_referralCta__1gnumzi8 sharedBaseCss_buttonReset__7cswil0";
@@ -291,12 +316,187 @@ var referralIconWrapper = "Banner_referralIconWrapper__1gnumzi3";
291
316
  var referralImage = "Banner_referralImage__1gnumzi4";
292
317
  var referralTitle = "Banner_referralTitle__1gnumzi6 reset_base__1831jhd0";
293
318
  const cssSource = cssSource$3 + cssSource$2 + cssSource$1;
319
+ // src/components/Banner/PendingBanner.tsx
320
+ function pickDate(date, lang) {
321
+ return date ? formatRewardDate(date, lang) : void 0;
322
+ }
323
+ /** Banner for a visitor with unclaimed rewards and no Frak wallet: amount, days left, link to the wallet install page. */
324
+ function PendingBanner({ pending, isPreview, isClientReady, placementId, classname, imageUrl, config, overrides }) {
325
+ const lang = useLang();
326
+ const [installUrl, setInstallUrl] = useState(void 0);
327
+ const trackedImpressionRef = useRef(false);
328
+ const countdown = useMemo(() => getRewardCountdown(pending.expiresAt), [pending.expiresAt]);
329
+ const daysLeft = countdown?.days;
330
+ const locked = pending.lockedCount > 0;
331
+ useInlineReminderRegistration(!isPreview);
332
+ const track = useCallback((event) => {
333
+ if (isPreview) return;
334
+ trackEvent(window.FrakSetup?.client, event, {
335
+ surface: "banner",
336
+ placement: placementId,
337
+ days_left: daysLeft,
338
+ locked
339
+ });
340
+ }, [
341
+ isPreview,
342
+ placementId,
343
+ daysLeft,
344
+ locked
345
+ ]);
346
+ useEffect(() => {
347
+ if (isPreview || !isClientReady) return;
348
+ let cancelled = false;
349
+ getInstallUrl().then((url) => {
350
+ if (!cancelled) setInstallUrl(url);
351
+ }).catch(() => {});
352
+ return () => {
353
+ cancelled = true;
354
+ };
355
+ }, [isPreview, isClientReady]);
356
+ useEffect(() => {
357
+ if (isPreview || !isClientReady || trackedImpressionRef.current) return;
358
+ trackedImpressionRef.current = true;
359
+ track("reward_reminder_impression");
360
+ }, [
361
+ isPreview,
362
+ isClientReady,
363
+ track
364
+ ]);
365
+ const texts = (() => {
366
+ const defaults = componentDefaults[lang].banner;
367
+ const unlockAt = pending.nextUnlockAt ? new Date(pending.nextUnlockAt) : void 0;
368
+ const allLocked = pending.lockedCount >= pending.count && unlockAt !== void 0 && !Number.isNaN(unlockAt.getTime());
369
+ const values = {
370
+ reward: formatFiat(pending.total, resolveRewardCurrency()),
371
+ days: countdown?.days,
372
+ date: pickDate(allLocked ? unlockAt : countdown?.date, lang)
373
+ };
374
+ const defaultDescription = [allLocked ? defaults.pendingDescriptionLocked : defaults.pendingDescription, countdown && `${getCountdownLabel(countdown.days, lang)}.`].filter(Boolean).join(" ");
375
+ const fill = (template) => fillReminderText(template, values);
376
+ return {
377
+ title: fill(overrides.title ?? config?.pendingTitle ?? defaults.pendingTitle),
378
+ description: fill(overrides.description ?? config?.pendingDescription ?? defaultDescription),
379
+ cta: fill(overrides.cta ?? config?.pendingCta ?? defaults.pendingCta)
380
+ };
381
+ })();
382
+ const onClaim = useCallback((event) => {
383
+ if (isPreview) return;
384
+ if (!installUrl) {
385
+ event.preventDefault();
386
+ return;
387
+ }
388
+ markClaimStarted();
389
+ trackEvent(window.FrakSetup?.client, "banner_resolved", {
390
+ placement: placementId,
391
+ variant: "pending",
392
+ outcome: "clicked"
393
+ });
394
+ track("reward_reminder_claim_clicked");
395
+ }, [
396
+ isPreview,
397
+ installUrl,
398
+ placementId,
399
+ track
400
+ ]);
401
+ const onDismiss = useCallback(() => {
402
+ if (isPreview) return;
403
+ trackEvent(window.FrakSetup?.client, "banner_resolved", {
404
+ placement: placementId,
405
+ variant: "pending",
406
+ outcome: "dismissed"
407
+ });
408
+ track("reward_reminder_dismissed");
409
+ dismissReminder();
410
+ }, [
411
+ isPreview,
412
+ placementId,
413
+ track
414
+ ]);
415
+ const inert = !isPreview && !installUrl;
416
+ const bannerClass = [
417
+ referral,
418
+ "frak-banner",
419
+ "frak-banner--pending",
420
+ classname
421
+ ].filter(Boolean).join(" ");
422
+ return /* @__PURE__ */ jsxs("section", {
423
+ class: bannerClass,
424
+ "aria-label": texts.title,
425
+ children: [
426
+ /* @__PURE__ */ jsx("div", {
427
+ class: `${referralIconWrapper} frak-banner__icon`,
428
+ children: imageUrl ? /* @__PURE__ */ jsx("img", {
429
+ src: imageUrl,
430
+ alt: "",
431
+ class: referralImage
432
+ }) : /* @__PURE__ */ jsx(GiftIcon, { class: iconSvg })
433
+ }),
434
+ /* @__PURE__ */ jsxs("div", {
435
+ class: `${referralBody} ${pendingBody} frak-banner__text`,
436
+ children: [
437
+ /* @__PURE__ */ jsx("p", {
438
+ class: `${referralTitle} frak-banner__title`,
439
+ children: texts.title
440
+ }),
441
+ /* @__PURE__ */ jsx("p", {
442
+ class: `${referralDescription} frak-banner__description`,
443
+ children: texts.description
444
+ }),
445
+ /* @__PURE__ */ jsx("a", {
446
+ class: `${pendingCta} frak-banner__cta`,
447
+ href: isPreview ? "#" : installUrl,
448
+ target: isPreview ? void 0 : "_blank",
449
+ rel: "noopener",
450
+ role: inert ? "link" : void 0,
451
+ tabIndex: inert ? 0 : void 0,
452
+ "aria-disabled": inert ? "true" : void 0,
453
+ onClick: onClaim,
454
+ children: texts.cta
455
+ })
456
+ ]
457
+ }),
458
+ /* @__PURE__ */ jsx("button", {
459
+ type: "button",
460
+ class: `${pendingClose} frak-banner__close`,
461
+ "aria-label": componentDefaults[lang].banner.dismissLabel,
462
+ onClick: onDismiss,
463
+ children: "×"
464
+ }),
465
+ /* @__PURE__ */ jsx(LogoFrakWithName, {
466
+ class: `${frakLogo} frak-banner__logo`,
467
+ width: 42,
468
+ height: 24
469
+ })
470
+ ]
471
+ });
472
+ }
473
+ // src/components/Banner/usePendingSummary.ts
474
+ /**
475
+ * The pending rewards the banner can show. `baseMode` is the mode already decided
476
+ * by the page (in-app, referral, or a previewed pending): the summary is only
477
+ * fetched while none applies, so the other modes keep their priority.
478
+ */
479
+ function usePendingSummary(baseMode, canFetch) {
480
+ const dismissed = useReminderDismissed();
481
+ const { summary } = useRewardSummary(baseMode === null && canFetch);
482
+ return useMemo(() => {
483
+ if (baseMode === "pending") return getPreviewPending();
484
+ if (baseMode !== null || dismissed) return null;
485
+ return isClaimable(summary) ? summary.pending : null;
486
+ }, [
487
+ baseMode,
488
+ dismissed,
489
+ summary
490
+ ]);
491
+ }
294
492
  // src/components/Banner/Banner.tsx
493
+ function toPreviewMode(value) {
494
+ return value === "inapp" || value === "pending" ? value : "referral";
495
+ }
295
496
  /**
296
497
  * Auto-detecting notification banner component.
297
498
  *
298
- * Renders an inline banner on the merchant page with one of two distinct
299
- * visual styles depending on the detected mode:
499
+ * Renders an inline banner on the merchant page with one of three modes:
300
500
  *
301
501
  * - **Referral mode** (white): Shown after a successful referral link
302
502
  * processing. Displays a gift icon, reward copy, and a "Got it" CTA.
@@ -305,7 +505,10 @@ const cssSource = cssSource$3 + cssSource$2 + cssSource$1;
305
505
  * Offers an inline link to redirect to the default browser plus a
306
506
  * close button to dismiss.
307
507
  *
308
- * In-app browser mode takes priority over referral mode.
508
+ * - **Pending mode** (white): Shown to a visitor with unclaimed rewards and no
509
+ * Frak wallet yet; see {@link PendingBanner}.
510
+ *
511
+ * Priority: in-app browser, then referral, then pending.
309
512
  * Uses Light DOM + vanilla-extract styles from `@frak-labs/design-system`.
310
513
  *
311
514
  * @group components
@@ -322,19 +525,21 @@ const cssSource = cssSource$3 + cssSource$2 + cssSource$1;
322
525
  * <frak-banner classname="my-custom-banner"></frak-banner>
323
526
  * ```
324
527
  */
325
- function Banner({ placement: placementId, classname = "", interaction, products, referralTitle: propReferralTitle, referralDescription: propReferralDescription, referralCta: propReferralCta, inappTitle: propInappTitle, inappDescription: propInappDescription, inappCta: propInappCta, imageUrl: propImageUrl, preview, previewMode, allowInappRedirect }) {
528
+ function Banner({ placement: placementId, classname = "", interaction, products, referralTitle: propReferralTitle, referralDescription: propReferralDescription, referralCta: propReferralCta, inappTitle: propInappTitle, inappDescription: propInappDescription, inappCta: propInappCta, pendingTitle, pendingDescription, pendingCta, imageUrl: propImageUrl, preview, previewMode, allowInappRedirect }) {
326
529
  const isPreview = !!preview;
327
530
  const lang = useLang();
328
- const resolvedPreviewMode = previewMode === "inapp" ? "inapp" : "referral";
531
+ const resolvedPreviewMode = toPreviewMode(previewMode);
329
532
  const isInappRedirectAllowed = allowInappRedirect === true || allowInappRedirect === "true";
330
533
  const placement = usePlacement(placementId);
331
534
  const { shouldRender, isHidden, isClientReady } = useClientReady();
332
535
  useLightDomStyles("frak-banner", placementId, placement?.components?.banner?.css, cssSource, cssSource$4);
333
536
  const [dismissed, setDismissed] = useState(false);
334
- const [mode, setMode] = useState(() => {
537
+ const [baseMode, setMode] = useState(() => {
335
538
  if (isPreview) return resolvedPreviewMode;
336
539
  return isInappRedirectAllowed && isInAppBrowser ? "inapp" : null;
337
540
  });
541
+ const pending = usePendingSummary(baseMode, !isPreview && isClientReady && shouldRender && !isHidden);
542
+ const mode = baseMode ?? (pending ? "pending" : null);
338
543
  const trackedImpressionModeRef = useRef(null);
339
544
  useEffect(() => {
340
545
  if (isPreview) setMode(resolvedPreviewMode);
@@ -369,11 +574,11 @@ function Banner({ placement: placementId, classname = "", interaction, products,
369
574
  placementId
370
575
  ]);
371
576
  useEffect(() => {
372
- if (isPreview || mode === "inapp") return;
577
+ if (isPreview || baseMode === "inapp") return;
373
578
  const handler = () => setMode("referral");
374
579
  window.addEventListener(REFERRAL_SUCCESS_EVENT, handler);
375
580
  return () => window.removeEventListener(REFERRAL_SUCCESS_EVENT, handler);
376
- }, [isPreview, mode]);
581
+ }, [isPreview, baseMode]);
377
582
  const handleAction = useCallback(async () => {
378
583
  if (isPreview) return;
379
584
  trackEvent(window.FrakSetup?.client, "banner_resolved", {
@@ -446,6 +651,20 @@ function Banner({ placement: placementId, classname = "", interaction, products,
446
651
  propInappCta
447
652
  ]);
448
653
  if (!mode || !isPreview && (!shouldRender || isHidden || dismissed)) return null;
654
+ if (pending) return /* @__PURE__ */ jsx(PendingBanner, {
655
+ pending,
656
+ isPreview,
657
+ isClientReady,
658
+ placementId,
659
+ classname,
660
+ imageUrl,
661
+ config: bannerConfig,
662
+ overrides: {
663
+ title: pendingTitle,
664
+ description: pendingDescription,
665
+ cta: pendingCta
666
+ }
667
+ });
449
668
  const bannerClass = [
450
669
  referral,
451
670
  "frak-banner",
@@ -523,6 +742,9 @@ registerWebComponent(Banner, "frak-banner", [
523
742
  "inappTitle",
524
743
  "inappDescription",
525
744
  "inappCta",
745
+ "pendingTitle",
746
+ "pendingDescription",
747
+ "pendingCta",
526
748
  "preview",
527
749
  "previewMode",
528
750
  "imageUrl",
@@ -0,0 +1,283 @@
1
+ import { formatAmount, getClientId, getSupportedCurrency, isIOS, sdkConfigStore } from "@frak-labs/core-sdk";
2
+ import { REFERRAL_SUCCESS_EVENT, getRewardSummary } from "@frak-labs/core-sdk/actions";
3
+ import { useEffect } from "preact/hooks";
4
+ import { useSyncExternalStore } from "preact/compat";
5
+ // src/rewards/dismissal.ts
6
+ const KEY_PREFIX = "frak-reward-reminder-dismissed-";
7
+ const DISMISS_EVENT = "frak:reward-reminder-dismissed";
8
+ function storageKey() {
9
+ return `${KEY_PREFIX}${sdkConfigStore.getConfig().merchantId ?? "unknown"}`;
10
+ }
11
+ /** Dismissal lasts for the browser session only, and is shared by every reminder surface. */
12
+ function isReminderDismissed() {
13
+ try {
14
+ return window.sessionStorage.getItem(storageKey()) === "1";
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+ function dismissReminder() {
20
+ try {
21
+ window.sessionStorage.setItem(storageKey(), "1");
22
+ } catch {}
23
+ window.dispatchEvent(new CustomEvent(DISMISS_EVENT));
24
+ }
25
+ function subscribeReminderDismissal(listener) {
26
+ window.addEventListener(DISMISS_EVENT, listener);
27
+ return () => window.removeEventListener(DISMISS_EVENT, listener);
28
+ }
29
+ // src/rewards/inlineSurfaces.ts
30
+ const surfaces = /* @__PURE__ */ new Set();
31
+ const listeners$1 = /* @__PURE__ */ new Set();
32
+ function notify() {
33
+ for (const listener of listeners$1) listener();
34
+ }
35
+ /** An inline surface currently showing the claim prompt; the floating pill stays hidden meanwhile. */
36
+ function registerInlineReminder() {
37
+ const token = Symbol("inline-reminder");
38
+ surfaces.add(token);
39
+ notify();
40
+ return () => {
41
+ if (surfaces.delete(token)) notify();
42
+ };
43
+ }
44
+ function hasInlineReminder() {
45
+ return surfaces.size > 0;
46
+ }
47
+ function subscribeInlineReminders(listener) {
48
+ listeners$1.add(listener);
49
+ return () => listeners$1.delete(listener);
50
+ }
51
+ // src/hooks/useInlineReminder.ts
52
+ /** Call from an inline surface while it shows the claim prompt, so the floating pill steps aside. */
53
+ function useInlineReminderRegistration(active) {
54
+ useEffect(() => {
55
+ if (!active) return;
56
+ return registerInlineReminder();
57
+ }, [active]);
58
+ }
59
+ function useHasInlineReminder() {
60
+ return useSyncExternalStore(subscribeInlineReminders, hasInlineReminder);
61
+ }
62
+ function useReminderDismissed() {
63
+ return useSyncExternalStore(subscribeReminderDismissal, isReminderDismissed);
64
+ }
65
+ // src/rewards/rewardSummaryStore.ts
66
+ const CACHE_PREFIX = "frak-reward-summary-";
67
+ /** Something is waiting: it can be claimed, unlocked or paid any minute. */
68
+ const PENDING_TTL_MS = 6e5;
69
+ /** Nothing waiting: only a referral invalidates, so a purchase or share shows up once this expires. */
70
+ const IDLE_TTL_MS = 36e5;
71
+ let state = {
72
+ status: "idle",
73
+ summary: null
74
+ };
75
+ let inflight = null;
76
+ let generation = 0;
77
+ let invalidationBound = false;
78
+ let claimRefreshBound = false;
79
+ let claimStarted = false;
80
+ const listeners = /* @__PURE__ */ new Set();
81
+ function setState(next) {
82
+ state = next;
83
+ for (const listener of listeners) listener();
84
+ }
85
+ function cacheKey(merchantId) {
86
+ const clientId = getClientId();
87
+ return clientId ? `${CACHE_PREFIX}${merchantId}-${clientId}` : void 0;
88
+ }
89
+ function storageFor(summary) {
90
+ return summary.pending ? window.sessionStorage : window.localStorage;
91
+ }
92
+ function readCache(merchantId) {
93
+ const key = cacheKey(merchantId);
94
+ if (!key) return null;
95
+ for (const [storage, ttl] of [[window.sessionStorage, PENDING_TTL_MS], [window.localStorage, IDLE_TTL_MS]]) try {
96
+ const raw = storage.getItem(key);
97
+ if (!raw) continue;
98
+ const entry = JSON.parse(raw);
99
+ if (Date.now() - entry.at < ttl) return entry.summary;
100
+ storage.removeItem(key);
101
+ } catch {}
102
+ return null;
103
+ }
104
+ function writeCache(merchantId, summary) {
105
+ const key = cacheKey(merchantId);
106
+ if (!key) return;
107
+ try {
108
+ const entry = {
109
+ at: Date.now(),
110
+ summary
111
+ };
112
+ storageFor(summary).setItem(key, JSON.stringify(entry));
113
+ } catch {}
114
+ }
115
+ function clearCache() {
116
+ for (const storage of [window.sessionStorage, window.localStorage]) try {
117
+ const keys = [];
118
+ for (let index = 0; index < storage.length; index++) {
119
+ const key = storage.key(index);
120
+ if (key?.startsWith(CACHE_PREFIX)) keys.push(key);
121
+ }
122
+ for (const key of keys) storage.removeItem(key);
123
+ } catch {}
124
+ }
125
+ function bindInvalidation() {
126
+ if (invalidationBound || typeof window === "undefined") return;
127
+ invalidationBound = true;
128
+ window.addEventListener(REFERRAL_SUCCESS_EVENT, invalidateRewardSummary);
129
+ }
130
+ function refreshAfterClaim() {
131
+ if (!claimStarted || document.visibilityState === "hidden") return;
132
+ claimStarted = false;
133
+ invalidateRewardSummary();
134
+ }
135
+ function onPageShow(event) {
136
+ if (event.persisted) refreshAfterClaim();
137
+ }
138
+ /** A claim CTA was clicked: the next time the page is visible again the summary is refetched. */
139
+ function markClaimStarted() {
140
+ claimStarted = true;
141
+ if (claimRefreshBound || typeof window === "undefined") return;
142
+ claimRefreshBound = true;
143
+ document.addEventListener("visibilitychange", refreshAfterClaim);
144
+ window.addEventListener("pageshow", onPageShow);
145
+ }
146
+ /**
147
+ * Load the visitor's reward summary once per page, through a session/local cache.
148
+ * Failures are not cached: the next page asks again.
149
+ */
150
+ function loadRewardSummary() {
151
+ bindInvalidation();
152
+ if (state.status === "ready") return Promise.resolve(state.summary);
153
+ if (inflight) return inflight;
154
+ const currentGeneration = generation;
155
+ setState({
156
+ status: "loading",
157
+ summary: state.summary
158
+ });
159
+ inflight = (async () => {
160
+ const merchantId = await sdkConfigStore.resolveMerchantId();
161
+ const cached = merchantId ? readCache(merchantId) : null;
162
+ const summary = cached ?? (merchantId ? await getRewardSummary({ merchantId }) : null);
163
+ if (currentGeneration === generation) {
164
+ if (summary && merchantId && !cached) writeCache(merchantId, summary);
165
+ setState({
166
+ status: "ready",
167
+ summary
168
+ });
169
+ }
170
+ return summary;
171
+ })().catch(() => {
172
+ if (currentGeneration === generation) setState({
173
+ status: "ready",
174
+ summary: null
175
+ });
176
+ return null;
177
+ }).finally(() => {
178
+ if (currentGeneration === generation) inflight = null;
179
+ });
180
+ return inflight;
181
+ }
182
+ /** Drop the cache after anything that can create or pay a reward; the next read refetches. */
183
+ function invalidateRewardSummary() {
184
+ generation += 1;
185
+ inflight = null;
186
+ clearCache();
187
+ setState({
188
+ status: "idle",
189
+ summary: state.summary
190
+ });
191
+ }
192
+ function getRewardSummaryState() {
193
+ return state;
194
+ }
195
+ function subscribeRewardSummary(listener) {
196
+ listeners.add(listener);
197
+ return () => listeners.delete(listener);
198
+ }
199
+ function isExpired(expiresAt) {
200
+ return expiresAt !== null && Date.parse(expiresAt) <= Date.now();
201
+ }
202
+ function isClaimable(summary) {
203
+ return !!summary && !summary.linked && !!summary.pending && summary.pending.count > 0 && !isExpired(summary.pending.expiresAt);
204
+ }
205
+ // src/hooks/useRewardSummary.ts
206
+ /**
207
+ * The visitor's reward summary at this merchant, shared by every component on the
208
+ * page. Fetches only once `enabled` (client ready, component visible), and again
209
+ * after an invalidation.
210
+ */
211
+ function useRewardSummary(enabled) {
212
+ const snapshot = useSyncExternalStore(subscribeRewardSummary, getRewardSummaryState);
213
+ useEffect(() => {
214
+ if (enabled && snapshot.status === "idle") loadRewardSummary();
215
+ }, [enabled, snapshot.status]);
216
+ return snapshot;
217
+ }
218
+ // src/rewards/countdown.ts
219
+ const DAY_MS = 864e5;
220
+ /** Safari, and every iOS browser or web view, since all of them run WebKit's tracking prevention. */
221
+ function isStorageCappedBrowser(userAgent = typeof navigator === "undefined" ? "" : navigator.userAgent, ios = isIOS) {
222
+ if (ios) return true;
223
+ return /AppleWebKit/i.test(userAgent) && !/(Chrome|Chromium|CriOS|Edg|OPR|Android)/i.test(userAgent);
224
+ }
225
+ /** Days between local calendar dates, so the count agrees with the date shown beside it. */
226
+ function calendarDaysUntil(deadline, now) {
227
+ const dayOf = (ms) => {
228
+ const date = new Date(ms);
229
+ return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());
230
+ };
231
+ return Math.max(0, Math.round((dayOf(deadline) - dayOf(now)) / DAY_MS));
232
+ }
233
+ /**
234
+ * Countdown shown with an unclaimed reward. On WebKit it never exceeds 7 days, even
235
+ * without a deadline, since the visitor's storage would not outlive it; elsewhere a
236
+ * reward without a deadline gets no countdown.
237
+ */
238
+ function getRewardCountdown(expiresAt, { now = Date.now(), capped = isStorageCappedBrowser() } = {}) {
239
+ const deadline = expiresAt ? Date.parse(expiresAt) : NaN;
240
+ const days = Number.isFinite(deadline) ? calendarDaysUntil(deadline, now) : void 0;
241
+ if (!capped) return days === void 0 ? void 0 : {
242
+ days,
243
+ date: new Date(deadline)
244
+ };
245
+ if (days !== void 0 && days <= 7) return {
246
+ days,
247
+ date: new Date(deadline)
248
+ };
249
+ return {
250
+ days: 7,
251
+ date: new Date(now + 7 * DAY_MS)
252
+ };
253
+ }
254
+ // src/rewards/format.ts
255
+ /** Backend config first, then the page's static SDK config. */
256
+ function resolveRewardCurrency() {
257
+ return sdkConfigStore.getConfig().currency ?? window.FrakSetup?.config?.metadata?.currency;
258
+ }
259
+ function pickFiat(amounts, currency) {
260
+ switch (getSupportedCurrency(currency)) {
261
+ case "usd": return amounts.usdAmount;
262
+ case "gbp": return amounts.gbpAmount;
263
+ default: return amounts.eurAmount;
264
+ }
265
+ }
266
+ function formatFiat(amounts, currency) {
267
+ return formatAmount(pickFiat(amounts, currency), currency);
268
+ }
269
+ /** Short day + month in the component's language, e.g. "5 Dec" / "5 déc.". */
270
+ function formatRewardDate(date, lang) {
271
+ return date.toLocaleDateString(lang === "fr" ? "fr-FR" : "en-GB", {
272
+ day: "numeric",
273
+ month: "short"
274
+ });
275
+ }
276
+ /** Fills `{REWARD}`, `{DAYS}`, `{DATE}` and `{BRAND}`; a missing value leaves an empty slot. */
277
+ function fillReminderText(template, values) {
278
+ return template.replaceAll("{REWARD}", () => values.reward ?? "").replaceAll("{DAYS}", () => values.days === void 0 ? "" : String(values.days)).replace(/\{DATE\}(\.?)/g, (_, dot) => {
279
+ const date = values.date ?? "";
280
+ return date.endsWith(".") ? date : date + dot;
281
+ }).replaceAll("{BRAND}", () => values.brand ?? "");
282
+ }
283
+ export { resolveRewardCurrency as a, isClaimable as c, useInlineReminderRegistration as d, useReminderDismissed as f, pickFiat as i, markClaimStarted as l, formatFiat as n, getRewardCountdown as o, dismissReminder as p, formatRewardDate as r, useRewardSummary as s, fillReminderText as t, useHasInlineReminder as u };