@veroxm/react-sdk 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.8.0
4
+
5
+ - App translations: `const { t, dir, ready } = useTranslations('ar')` reads a locale's whole bundle from VeroXM in one
6
+ request, shared by every component asking for it. `t('checkout.pay', { amount })` fills `{{placeholders}}`, plural
7
+ forms by `count` and `$t(other.key)`; keys not translated yet show the default locale's text. `dir` (`rtl`/`ltr`) and
8
+ `nativeName` ("العربية") come with it. Mount `<VeroxmTranslationsProvider baseUrl projectId apiKey locale>` once (a
9
+ browser key is enough), or pass the same as the hook's options. `initial` takes bundles fetched on the server with
10
+ `fetchTranslations()`, so the first render has the words; `applyToDocument` sets `<html lang dir>`. While another
11
+ locale loads, `t` keeps the previous one's texts. For i18next, use `@veroxm/sdk`'s `VeroxmI18nextBackend`. Needs
12
+ `@veroxm/sdk` 1.13 and a VeroXM server with app translations.
13
+
14
+ ## 1.7.0
15
+
16
+ - Product journeys: `<VeroxmJourney src="https://buy.example.com/ar/sports-insurance" />` (or `baseUrl` + `journey`)
17
+ shows a VeroXM quote-and-buy journey in your page, as published: its screens, shared blocks, brand and colours. It
18
+ runs in a frame of the hosted page, so prices, eligibility and payment links stay with VeroXM. `lang`, `chrome={false}`
19
+ (only the journey, for a page with its own header), `height`, and `onReady`, `onScreen`, `onLocaleChange`,
20
+ `onComplete`, `onEvent` (screen ids and steps, never what the person typed). The finish is recorded as
21
+ `$journey_completed` with the `<VeroxmTrackerProvider>`'s tracker (`track={false}` to skip). The journey must list
22
+ your site under Embedding; needs the VeroXM version with embeddable journeys (2026-10-27).
23
+ - Draft previews: a page opened from the builder's "Preview in your app" (`?veroxm_journey_preview=<token>`) shows the
24
+ journey's draft with test answers in the same `<VeroxmJourney>`; `preview={false}` always shows the published one.
25
+
3
26
  ## 1.6.0
4
27
 
5
28
  - Query text: `useEntries(collection, { q })`, `listEntries` and the server helpers take `q`, one readable line instead
package/README.md CHANGED
@@ -282,6 +282,28 @@ function Account() {
282
282
  </SignedIn>;
283
283
  ```
284
284
 
285
+ ## Product journeys
286
+
287
+ A VeroXM quote-and-buy journey in your page, as published (its screens, shared blocks, brand and colours):
288
+
289
+ ```tsx
290
+ import { VeroxmJourney } from '@veroxm/react-sdk';
291
+
292
+ <VeroxmJourney src="https://buy.example.com/ar/sports-insurance" />
293
+
294
+ // Or by its link, without the brand around it, for a page with its own header:
295
+ <VeroxmJourney baseUrl="https://cms.example.com" journey="j_Ab3dEf7hJk9mNpQr2sTu" lang="en" chrome={false}
296
+ height={720} onScreen={(e) => console.log(e.step)} onComplete={() => router.push('/thank-you')} />
297
+ ```
298
+
299
+ It runs in a frame of the hosted journey: prices, eligibility and payment links stay with VeroXM, and events carry
300
+ screen ids and steps only, never what the person typed. List your site's origin under **Embedding** in the journey's
301
+ Look and brand (or in its page layout), or the browser refuses to show it. Works the same in Next.js (a client
302
+ component). The finish is recorded as `$journey_completed` with the `<VeroxmTrackerProvider>`'s tracker.
303
+
304
+ Opened from the builder's **Preview in your app**, the page's address carries `?veroxm_journey_preview=…`, and the
305
+ same component shows the draft (test answers, nothing sent); pass `preview={false}` to always show the published one.
306
+
285
307
  ## Visitor tracking
286
308
 
287
309
  Pair with `@veroxm/sdk`'s `createTracker()` (see that package's README for
@@ -46,7 +46,7 @@ let routeBase = ROUTE_BASE;
46
46
  /** Where the server mounted veroxmMiddleware. Default '/api/veroxm'. */
47
47
  export function configureClientSlots(options) {
48
48
  if (options.routeBase)
49
- routeBase = options.routeBase.replace(/\/+$/, '');
49
+ routeBase = withoutTrailingSlashes(options.routeBase);
50
50
  }
51
51
  const pending = new Map();
52
52
  let scheduled = false;
@@ -170,3 +170,10 @@ export function resetClientSlotsForTests() {
170
170
  routeBase = ROUTE_BASE;
171
171
  resetSentFallbacksForTests();
172
172
  }
173
+ /** `url` without trailing slashes (a loop: /\/+$/ goes over a long run of slashes again from each position). */
174
+ function withoutTrailingSlashes(url) {
175
+ let end = url.length;
176
+ while (end > 0 && url[end - 1] === '/')
177
+ end--;
178
+ return url.slice(0, end);
179
+ }
package/dist/index.d.ts CHANGED
@@ -42,6 +42,10 @@ export type { VideoRef, VideoProvider } from './site/video.js';
42
42
  export type { CollectionFieldMeta, CollectionMeta, Entry, EntryConnection, EntriesQueryOptions, MediaView, MediaHotspot, WhereClause, } from './types.js';
43
43
  export { VeroxmForm, useVeroxmForm } from './form.js';
44
44
  export type { VeroxmFormProps, VeroxmFormOptions, VeroxmFormMode, VeroxmFormHandle } from './form.js';
45
+ export { VeroxmJourney } from './journey.js';
46
+ export type { VeroxmJourneyProps, VeroxmJourneyEvent } from './journey.js';
47
+ export { VeroxmTranslationsProvider, useTranslations } from './translations.js';
48
+ export type { VeroxmTranslationsProviderProps, TranslationsSource, TranslationsState, UseTranslationsOptions } from './translations.js';
45
49
  export { VeroxmTrackerProvider, useTracker, usePageViews, useExperience, Experience, useContentView, useRecommendations, useSlotImpression, VeroxmSlotImpression, } from './tracking.js';
46
50
  export type { VeroxmTrackerProviderProps, VeroxmTrackerLike, ExperienceDecision, ExperienceState, ExperienceProps, RecommendationsState, VeroxmSlotImpressionProps, } from './tracking.js';
47
51
  export { VeroxmSlot, useSlot, field, configureSlots, loadSlot, mergeSlotValues } from './slots.js';
package/dist/index.js CHANGED
@@ -28,6 +28,10 @@ export { chartSvg, chartSummary, formatChartNumber, chartFromRows, chartDataFrom
28
28
  export { parseVideoUrl, videoEmbedUrl, videoThumbnailUrl } from './site/video.js';
29
29
  // Forms: inline, popup, full page or toast, through the embed script of your VeroXM address.
30
30
  export { VeroxmForm, useVeroxmForm } from './form.js';
31
+ // Product journeys: a quote-and-buy journey in your page, in a frame of its hosted page.
32
+ export { VeroxmJourney } from './journey.js';
33
+ // App translations: a locale's bundle in one request, t() and its writing direction. (i18next: @veroxm/sdk's VeroxmI18nextBackend.)
34
+ export { VeroxmTranslationsProvider, useTranslations } from './translations.js';
31
35
  // Experience OS visitor tracking -- pair with @veroxm/sdk's createTracker().
32
36
  export { VeroxmTrackerProvider, useTracker, usePageViews, useExperience, Experience, useContentView, useRecommendations, useSlotImpression, VeroxmSlotImpression, } from './tracking.js';
33
37
  // Visual slots (Experience Layer): named regions marketers edit from VeroXM.
@@ -0,0 +1,82 @@
1
+ import { type CSSProperties } from 'react';
2
+ /** What the journey tells your page (never what the person typed). */
3
+ export type VeroxmJourneyEvent = {
4
+ event: 'ready';
5
+ journey: string;
6
+ locale: string;
7
+ } | {
8
+ event: 'screen';
9
+ journey: string;
10
+ screen: string;
11
+ step: string | null;
12
+ dialog: string | null;
13
+ } | {
14
+ event: 'locale';
15
+ journey: string;
16
+ locale: string;
17
+ } | {
18
+ event: 'complete';
19
+ journey: string;
20
+ };
21
+ export interface VeroxmJourneyProps {
22
+ /**
23
+ * The journey's address: its readable one (`https://buy.example.com/en/sports-insurance`) or its link
24
+ * (`https://cms.example.com/j/j_Ab3dEf7hJk9mNpQr2sTu`).
25
+ */
26
+ src?: string;
27
+ /** Or your VeroXM address and the journey's public id (j_...). */
28
+ baseUrl?: string;
29
+ journey?: string;
30
+ /** The language to show ("ar"), when the journey has it; otherwise the address's, then the visitor's browser's. */
31
+ lang?: string;
32
+ /** false: only the journey -- no logo, side stepper, footer links or top icons -- for a page with its own header. */
33
+ chrome?: boolean;
34
+ /** The frame's height: pixels or any CSS length (default 760). `"100%"` fills a sized parent. */
35
+ height?: number | string;
36
+ /** The frame's name for screen readers (default "Insurance quote"). */
37
+ title?: string;
38
+ className?: string;
39
+ style?: CSSProperties;
40
+ onReady?: (e: Extract<VeroxmJourneyEvent, {
41
+ event: 'ready';
42
+ }>) => void;
43
+ onScreen?: (e: Extract<VeroxmJourneyEvent, {
44
+ event: 'screen';
45
+ }>) => void;
46
+ onLocaleChange?: (e: Extract<VeroxmJourneyEvent, {
47
+ event: 'locale';
48
+ }>) => void;
49
+ onComplete?: (e: Extract<VeroxmJourneyEvent, {
50
+ event: 'complete';
51
+ }>) => void;
52
+ /** Every event, as it comes. */
53
+ onEvent?: (e: VeroxmJourneyEvent) => void;
54
+ /**
55
+ * Show the journey's draft when the page is opened from the builder's "Preview in your app" (the page's address has
56
+ * `?veroxm_journey_preview=<token>`): test answers, nothing is sent, and parts can be picked to edit in the builder.
57
+ * Default true; false always shows the published journey.
58
+ */
59
+ preview?: boolean;
60
+ /**
61
+ * Record the finish as `$journey_completed` (usable as an experience's goal) with the `<VeroxmTrackerProvider>`'s
62
+ * tracker. Default true; false records nothing.
63
+ */
64
+ track?: boolean;
65
+ }
66
+ /**
67
+ * The frame's address: the journey's, with ?embed=1, the language, chrome=0 and the page's own origin (where the
68
+ * journey sends its events). Null when neither src nor baseUrl + journey make an http(s) address. @internal
69
+ */
70
+ export declare function journeyFrameUrl(p: Pick<VeroxmJourneyProps, 'src' | 'baseUrl' | 'journey' | 'lang' | 'chrome'>, parent: string | null, previewToken?: string | null): URL | null;
71
+ /** A message from the journey's frame, checked: from its origin and window, in the journey's own format. @internal */
72
+ export declare function journeyEventOf(data: unknown): VeroxmJourneyEvent | null;
73
+ /**
74
+ * A VeroXM product journey in your page.
75
+ *
76
+ * ```tsx
77
+ * <VeroxmJourney src="https://buy.example.com/ar/sports-insurance" />
78
+ * <VeroxmJourney baseUrl="https://cms.example.com" journey="j_Ab3dEf7hJk9mNpQr2sTu" lang="en" chrome={false}
79
+ * onComplete={() => router.push('/thank-you')} />
80
+ * ```
81
+ */
82
+ export declare function VeroxmJourney({ src, baseUrl, journey, lang, chrome, height, title, className, style, track, preview, ...handlers }: VeroxmJourneyProps): import("react").JSX.Element;
@@ -0,0 +1,130 @@
1
+ 'use client';
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { useEffect, useMemo, useRef, useState } from 'react';
4
+ import { useTracker } from './tracking.js';
5
+ const LANG_PATH = /^\/([a-z]{2,3}(?:-[A-Za-z]{2,4})?)\/([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)\/?$/;
6
+ /**
7
+ * The frame's address: the journey's, with ?embed=1, the language, chrome=0 and the page's own origin (where the
8
+ * journey sends its events). Null when neither src nor baseUrl + journey make an http(s) address. @internal
9
+ */
10
+ export function journeyFrameUrl(p, parent, previewToken) {
11
+ let url;
12
+ try {
13
+ if (p.src)
14
+ url = new URL(p.src);
15
+ else if (p.baseUrl && p.journey && /^j_[A-Za-z0-9]{20}$/.test(p.journey))
16
+ url = new URL(`/j/${p.journey}`, p.baseUrl);
17
+ else
18
+ return null;
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
24
+ return null;
25
+ if (previewToken) {
26
+ // The draft, on the same VeroXM address: /j/preview?token=…
27
+ const preview = new URL('/j/preview', url.origin);
28
+ preview.searchParams.set('token', previewToken);
29
+ const at = LANG_PATH.exec(url.pathname);
30
+ const lang = p.lang ?? (at ? at[1] : url.searchParams.get('lang'));
31
+ if (lang)
32
+ preview.searchParams.set('lang', lang);
33
+ url = preview;
34
+ }
35
+ else if (p.lang) {
36
+ // A readable address carries the language in its path (/ar/sports-insurance); a link takes ?lang=.
37
+ const at = LANG_PATH.exec(url.pathname);
38
+ if (at)
39
+ url.pathname = `/${p.lang}/${at[2]}`;
40
+ else
41
+ url.searchParams.set('lang', p.lang);
42
+ }
43
+ url.searchParams.set('embed', '1');
44
+ if (p.chrome === false)
45
+ url.searchParams.set('chrome', '0');
46
+ if (parent)
47
+ url.searchParams.set('parent', parent);
48
+ return url;
49
+ }
50
+ /** A message from the journey's frame, checked: from its origin and window, in the journey's own format. @internal */
51
+ export function journeyEventOf(data) {
52
+ const d = data;
53
+ if (!d || typeof d !== 'object' || d.source !== 'veroxm-journey' || d.version !== 1 || typeof d.journey !== 'string')
54
+ return null;
55
+ const journey = d.journey;
56
+ const str = (v) => (typeof v === 'string' ? v : null);
57
+ switch (d.event) {
58
+ case 'ready':
59
+ return { event: 'ready', journey, locale: str(d.locale) ?? '' };
60
+ case 'screen':
61
+ return typeof d.screen === 'string' ? { event: 'screen', journey, screen: d.screen, step: str(d.step), dialog: str(d.dialog) } : null;
62
+ case 'locale':
63
+ return { event: 'locale', journey, locale: str(d.locale) ?? '' };
64
+ case 'complete':
65
+ return { event: 'complete', journey };
66
+ default:
67
+ return null;
68
+ }
69
+ }
70
+ /**
71
+ * A VeroXM product journey in your page.
72
+ *
73
+ * ```tsx
74
+ * <VeroxmJourney src="https://buy.example.com/ar/sports-insurance" />
75
+ * <VeroxmJourney baseUrl="https://cms.example.com" journey="j_Ab3dEf7hJk9mNpQr2sTu" lang="en" chrome={false}
76
+ * onComplete={() => router.push('/thank-you')} />
77
+ * ```
78
+ */
79
+ export function VeroxmJourney({ src, baseUrl, journey, lang, chrome, height = 760, title = 'Insurance quote', className, style, track = true, preview = true, ...handlers }) {
80
+ const frame = useRef(null);
81
+ // The page's own origin is known only in the browser: the frame is made there.
82
+ const [parent, setParent] = useState(null);
83
+ const [previewToken, setPreviewToken] = useState(null);
84
+ useEffect(() => {
85
+ setParent(window.location.origin);
86
+ const t = new URLSearchParams(window.location.search).get('veroxm_journey_preview');
87
+ setPreviewToken(t && t.length <= 4096 ? t : null);
88
+ }, []);
89
+ const url = useMemo(() => (parent ? journeyFrameUrl({ src, baseUrl, journey, lang, chrome }, parent, preview ? previewToken : null) : null), [src, baseUrl, journey, lang, chrome, parent, preview, previewToken]);
90
+ // Handlers change on every render; the listener calls the latest ones.
91
+ const latest = useRef({ handlers, track });
92
+ latest.current = { handlers, track };
93
+ const tracker = useTracker();
94
+ const trackerRef = useRef(tracker);
95
+ trackerRef.current = tracker;
96
+ const origin = url?.origin;
97
+ useEffect(() => {
98
+ if (!origin)
99
+ return;
100
+ const onMessage = (m) => {
101
+ if (m.origin !== origin || m.source !== frame.current?.contentWindow)
102
+ return;
103
+ const e = journeyEventOf(m.data);
104
+ if (!e)
105
+ return;
106
+ const h = latest.current.handlers;
107
+ h.onEvent?.(e);
108
+ if (e.event === 'ready')
109
+ h.onReady?.(e);
110
+ else if (e.event === 'screen')
111
+ h.onScreen?.(e);
112
+ else if (e.event === 'locale')
113
+ h.onLocaleChange?.(e);
114
+ else if (e.event === 'complete') {
115
+ // A preview's finish isn't a real one.
116
+ if (latest.current.track && !m.data.preview)
117
+ trackerRef.current.track('$journey_completed', { journey: e.journey });
118
+ h.onComplete?.(e);
119
+ }
120
+ };
121
+ window.addEventListener('message', onMessage);
122
+ return () => window.removeEventListener('message', onMessage);
123
+ }, [origin]);
124
+ const box = { display: 'block', width: '100%', height: typeof height === 'number' ? `${height}px` : height, border: 0, ...style };
125
+ if (!url)
126
+ return _jsx("div", { className: className, style: box, "data-veroxm-journey-box": "" });
127
+ return (_jsx("iframe", { ref: frame, src: url.toString(), title: title, className: className, style: box,
128
+ // Payment links open in a new tab; copy-link buttons use the clipboard.
129
+ allow: "clipboard-write", sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", referrerPolicy: "strict-origin-when-cross-origin", "data-veroxm-journey": "" }));
130
+ }
@@ -17,7 +17,8 @@ const round6 = (v) => Math.round(v * 1e6) / 1e6;
17
17
  */
18
18
  export function parseMapLink(input) {
19
19
  const text = input.trim();
20
- const pair = /^(-?\d{1,2}(?:\.\d+)?)\s*[,\s]\s*(-?\d{1,3}(?:\.\d+)?)$/.exec(text);
20
+ // "lat, lng" or "lat lng": a comma with any spaces, or spaces alone (one way to match each, so no slow backtracking).
21
+ const pair = /^(-?\d{1,2}(?:\.\d+)?)(?:\s*,\s*|\s+)(-?\d{1,3}(?:\.\d+)?)$/.exec(text);
21
22
  if (pair) {
22
23
  const lat = Number(pair[1]);
23
24
  const lng = Number(pair[2]);
@@ -12,7 +12,7 @@ export function isSafeMenuHref(href) {
12
12
  const samePage = (href, current) => {
13
13
  if (!current || !href.startsWith('/'))
14
14
  return false;
15
- const clean = (p) => p.split(/[?#]/)[0].replace(/\/+$/, '') || '/';
15
+ const clean = (p) => withoutTrailingSlashes(p.split(/[?#]/)[0]) || '/';
16
16
  return clean(href) === clean(current);
17
17
  };
18
18
  function MenuLink({ item, currentPath, Link, onNavigate }) {
@@ -79,3 +79,10 @@ export function NavMenu({ items, label = 'Main', currentPath, linkComponent = 'a
79
79
  return null;
80
80
  return (_jsxs("nav", { ref: navRef, "aria-label": label, className: `vxs-nav${className ? ` ${className}` : ''}`, ...editProps, children: [_jsxs("button", { type: "button", className: "vxs-nav-toggle", "aria-expanded": mobileOpen, "aria-controls": `${id}-list`, onClick: () => setMobileOpen((v) => !v), children: [_jsx("span", { className: "vxs-burger", "aria-hidden": "true" }), _jsx("span", { className: "vxs-nav-toggle-text", children: toggleLabel })] }), list(items, '', 1)] }));
81
81
  }
82
+ /** `url` without trailing slashes (a loop: /\/+$/ goes over a long run of slashes again from each position). */
83
+ function withoutTrailingSlashes(url) {
84
+ let end = url.length;
85
+ while (end > 0 && url[end - 1] === '/')
86
+ end--;
87
+ return url.slice(0, end);
88
+ }
@@ -62,7 +62,7 @@ function env(name) {
62
62
  }
63
63
  /** The effective slots configuration (configureSlots over environment variables). */
64
64
  export function resolveSlotsConfig() {
65
- const baseUrl = (config.baseUrl ?? env('VEROXM_API_BASE') ?? '').replace(/\/+$/, '');
65
+ const baseUrl = withoutTrailingSlashes(config.baseUrl ?? env('VEROXM_API_BASE') ?? '');
66
66
  const projectId = config.projectId ?? env('VEROXM_PROJECT_ID') ?? '';
67
67
  const apiKey = config.apiKey ?? env('VEROXM_API_KEY') ?? '';
68
68
  return {
@@ -423,3 +423,10 @@ export function resetSlotsForTests() {
423
423
  flushScheduled = false;
424
424
  reportScheduled = false;
425
425
  }
426
+ /** `url` without trailing slashes (a loop: /\/+$/ goes over a long run of slashes again from each position). */
427
+ function withoutTrailingSlashes(url) {
428
+ let end = url.length;
429
+ while (end > 0 && url[end - 1] === '/')
430
+ end--;
431
+ return url.slice(0, end);
432
+ }
@@ -0,0 +1,54 @@
1
+ import { type ReactElement, type ReactNode } from 'react';
2
+ import { type TranslationBundle, type Translator } from '@veroxm/sdk';
3
+ /** Where the bundles come from. */
4
+ export interface TranslationsSource {
5
+ /** Your VeroXM deployment's origin, e.g. "https://cms.example.com". */
6
+ baseUrl: string;
7
+ /** The project's UUID. */
8
+ projectId: string;
9
+ /** Any key of the project; a browser key is enough. */
10
+ apiKey: string;
11
+ /** The fetch to send with. Default: the global fetch. */
12
+ fetch?: typeof fetch;
13
+ }
14
+ export interface VeroxmTranslationsProviderProps extends TranslationsSource {
15
+ children: ReactNode;
16
+ /** The locale `useTranslations()` uses when it isn't given one. */
17
+ locale?: string;
18
+ /** Bundles you already have (fetched on the server): used at once, with no request. */
19
+ initial?: TranslationBundle | TranslationBundle[];
20
+ /** Fill keys a locale doesn't have yet from the default locale. Default: true. */
21
+ fallback?: boolean;
22
+ /** Set `<html lang>` and `<html dir>` from the provider's `locale` once its bundle is in, so the layout flips for right-to-left languages. Default: false. */
23
+ applyToDocument?: boolean;
24
+ }
25
+ /** Supplies the bundles' source (and a default locale) to `useTranslations()` below it. */
26
+ export declare function VeroxmTranslationsProvider(props: VeroxmTranslationsProviderProps): ReactElement;
27
+ export interface UseTranslationsOptions extends Partial<TranslationsSource> {
28
+ /** Fill keys not translated yet from the default locale. Default: the provider's, or true. */
29
+ fallback?: boolean;
30
+ }
31
+ export interface TranslationsState {
32
+ /** `t('checkout.pay', { amount })`: the text with its placeholders filled, or the key while it loads. */
33
+ t: Translator;
34
+ /** The locale answered (`ar` for `ar-SA` when the project has only `ar`), once loaded. */
35
+ locale: string | undefined;
36
+ /** Writing direction: put it on your root element (`<div dir={dir}>`). `ltr` until the bundle is in. */
37
+ dir: 'rtl' | 'ltr';
38
+ /** The language's own name ("العربية"), once loaded. */
39
+ nativeName: string | undefined;
40
+ /** The project's translations version of the bundle shown. */
41
+ version: number | undefined;
42
+ /** The whole bundle, with `fallback` (keys shown in the default locale). */
43
+ bundle: TranslationBundle | undefined;
44
+ /** True once the requested locale's bundle is in. While another locale loads, `t` keeps the previous one's texts. */
45
+ ready: boolean;
46
+ error: Error | undefined;
47
+ /** Fetch the bundle again (after the texts change, for example). */
48
+ reload: () => Promise<void>;
49
+ }
50
+ /**
51
+ * A locale's app translations: `const { t, dir, ready } = useTranslations('ar')`. Without a locale, the provider's.
52
+ * Every component asking for the same locale shares one request.
53
+ */
54
+ export declare function useTranslations(locale?: string, options?: UseTranslationsOptions): TranslationsState;
@@ -0,0 +1,130 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
4
+ import { createTranslator, fetchTranslations } from '@veroxm/sdk';
5
+ /** Loaded bundles and the requests in flight, per locale. */
6
+ class BundleStore {
7
+ constructor(source, fallback, initial) {
8
+ this.source = source;
9
+ this.fallback = fallback;
10
+ this.bundles = new Map();
11
+ this.pending = new Map();
12
+ for (const b of initial ? (Array.isArray(initial) ? initial : [initial]) : [])
13
+ this.bundles.set(b.locale.toLowerCase(), b);
14
+ }
15
+ peek(locale) {
16
+ return this.bundles.get(locale.toLowerCase());
17
+ }
18
+ load(locale, reload = false) {
19
+ const key = locale.toLowerCase();
20
+ if (!reload) {
21
+ const have = this.bundles.get(key);
22
+ if (have)
23
+ return Promise.resolve(have);
24
+ const inFlight = this.pending.get(key);
25
+ if (inFlight)
26
+ return inFlight;
27
+ }
28
+ const p = fetchTranslations({ ...this.source, locale, fallback: this.fallback })
29
+ .then((b) => {
30
+ this.bundles.set(key, b);
31
+ // A request for "ar-SA" answered by "ar": keep it under both.
32
+ this.bundles.set(b.locale.toLowerCase(), b);
33
+ return b;
34
+ })
35
+ .finally(() => this.pending.delete(key));
36
+ this.pending.set(key, p);
37
+ return p;
38
+ }
39
+ }
40
+ const TranslationsContext = createContext(null);
41
+ /** Supplies the bundles' source (and a default locale) to `useTranslations()` below it. */
42
+ export function VeroxmTranslationsProvider(props) {
43
+ const { children, baseUrl, projectId, apiKey, fetch: fetchFn, locale, initial, fallback = true, applyToDocument = false } = props;
44
+ const store = useMemo(() => new BundleStore({ baseUrl, projectId, apiKey, fetch: fetchFn }, fallback, initial),
45
+ // `initial` seeds the store once; later values are ignored, like a useState initial value.
46
+ // eslint-disable-next-line react-hooks/exhaustive-deps
47
+ [baseUrl, projectId, apiKey, fetchFn, fallback]);
48
+ const value = useMemo(() => ({ store, locale }), [store, locale]);
49
+ return (_jsxs(TranslationsContext.Provider, { value: value, children: [applyToDocument && locale ? _jsx(DocumentLanguage, { locale: locale }) : null, children] }));
50
+ }
51
+ function DocumentLanguage({ locale }) {
52
+ const { bundle } = useTranslations(locale);
53
+ useEffect(() => {
54
+ if (!bundle || typeof document === 'undefined')
55
+ return;
56
+ document.documentElement.lang = bundle.locale;
57
+ document.documentElement.dir = bundle.dir;
58
+ }, [bundle]);
59
+ return null;
60
+ }
61
+ const standalone = new Map();
62
+ function storeFor(context, options) {
63
+ const { baseUrl, projectId, apiKey } = options;
64
+ if (baseUrl && projectId && apiKey) {
65
+ const fallback = options.fallback ?? context?.store.fallback ?? true;
66
+ if (context && context.store.source.baseUrl === baseUrl && context.store.source.projectId === projectId && context.store.source.apiKey === apiKey && context.store.fallback === fallback) {
67
+ return context.store;
68
+ }
69
+ const key = `${baseUrl}|${projectId}|${apiKey}|${fallback ? 1 : 0}`;
70
+ let store = standalone.get(key);
71
+ if (!store) {
72
+ store = new BundleStore({ baseUrl, projectId, apiKey, fetch: options.fetch }, fallback);
73
+ standalone.set(key, store);
74
+ }
75
+ return store;
76
+ }
77
+ if (context)
78
+ return context.store;
79
+ throw new Error('useTranslations() needs a <VeroxmTranslationsProvider> above it, or { baseUrl, projectId, apiKey }.');
80
+ }
81
+ const EMPTY = createTranslator({});
82
+ /**
83
+ * A locale's app translations: `const { t, dir, ready } = useTranslations('ar')`. Without a locale, the provider's.
84
+ * Every component asking for the same locale shares one request.
85
+ */
86
+ export function useTranslations(locale, options = {}) {
87
+ const context = useContext(TranslationsContext);
88
+ const store = storeFor(context, options);
89
+ const wanted = locale ?? context?.locale;
90
+ if (!wanted)
91
+ throw new Error('useTranslations() needs a locale, or a <VeroxmTranslationsProvider locale="...">.');
92
+ const [state, setState] = useState(() => {
93
+ const have = store.peek(wanted);
94
+ return { bundle: have, for: have ? wanted.toLowerCase() : undefined, error: undefined };
95
+ });
96
+ useEffect(() => {
97
+ let live = true;
98
+ const have = store.peek(wanted);
99
+ if (have) {
100
+ setState((s) => (s.bundle === have && s.for === wanted.toLowerCase() ? s : { bundle: have, for: wanted.toLowerCase(), error: undefined }));
101
+ return;
102
+ }
103
+ store.load(wanted).then((b) => live && setState({ bundle: b, for: wanted.toLowerCase(), error: undefined }), (e) => live && setState((s) => ({ ...s, error: e instanceof Error ? e : new Error(String(e)) })));
104
+ return () => {
105
+ live = false;
106
+ };
107
+ }, [store, wanted]);
108
+ const reload = useCallback(async () => {
109
+ try {
110
+ const b = await store.load(wanted, true);
111
+ setState({ bundle: b, for: wanted.toLowerCase(), error: undefined });
112
+ }
113
+ catch (e) {
114
+ setState((s) => ({ ...s, error: e instanceof Error ? e : new Error(String(e)) }));
115
+ }
116
+ }, [store, wanted]);
117
+ const { bundle } = state;
118
+ const t = useMemo(() => (bundle ? createTranslator(bundle.translations, { locale: bundle.locale }) : EMPTY), [bundle]);
119
+ return {
120
+ t,
121
+ locale: bundle?.locale,
122
+ dir: bundle?.dir ?? 'ltr',
123
+ nativeName: bundle?.nativeName,
124
+ version: bundle?.version,
125
+ bundle,
126
+ ready: !!bundle && state.for === wanted.toLowerCase(),
127
+ error: state.error,
128
+ reload,
129
+ };
130
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@veroxm/react-sdk",
3
- "version": "1.6.0",
4
- "description": "React and Next.js SDK for VeroXM: content hooks, visual slots with A/B tests, the on-page editor, llms.txt and structured data.",
3
+ "version": "1.8.0",
4
+ "description": "React and Next.js SDK for VeroXM: content hooks, visual slots with A/B tests, the on-page editor, forms and product journeys, llms.txt and structured data.",
5
5
  "keywords": [
6
6
  "veroxm",
7
7
  "react",
@@ -71,7 +71,7 @@
71
71
  "api:report": "node ../../scripts/api-report.mjs . --write"
72
72
  },
73
73
  "dependencies": {
74
- "@veroxm/sdk": "^1.10.0"
74
+ "@veroxm/sdk": "^1.13.0"
75
75
  },
76
76
  "peerDependencies": {
77
77
  "react": "^18.0.0 || ^19.0.0",