@veroxm/react-sdk 1.7.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,16 @@
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
+
3
14
  ## 1.7.0
4
15
 
5
16
  - Product journeys: `<VeroxmJourney src="https://buy.example.com/ar/sports-insurance" />` (or `baseUrl` + `journey`)
@@ -9,6 +20,8 @@
9
20
  `onComplete`, `onEvent` (screen ids and steps, never what the person typed). The finish is recorded as
10
21
  `$journey_completed` with the `<VeroxmTrackerProvider>`'s tracker (`track={false}` to skip). The journey must list
11
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.
12
25
 
13
26
  ## 1.6.0
14
27
 
package/README.md CHANGED
@@ -301,6 +301,9 @@ screen ids and steps only, never what the person typed. List your site's origin
301
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
302
  component). The finish is recorded as `$journey_completed` with the `<VeroxmTrackerProvider>`'s tracker.
303
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
+
304
307
  ## Visitor tracking
305
308
 
306
309
  Pair with `@veroxm/sdk`'s `createTracker()` (see that package's README for
package/dist/index.d.ts CHANGED
@@ -44,6 +44,8 @@ export { VeroxmForm, useVeroxmForm } from './form.js';
44
44
  export type { VeroxmFormProps, VeroxmFormOptions, VeroxmFormMode, VeroxmFormHandle } from './form.js';
45
45
  export { VeroxmJourney } from './journey.js';
46
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';
47
49
  export { VeroxmTrackerProvider, useTracker, usePageViews, useExperience, Experience, useContentView, useRecommendations, useSlotImpression, VeroxmSlotImpression, } from './tracking.js';
48
50
  export type { VeroxmTrackerProviderProps, VeroxmTrackerLike, ExperienceDecision, ExperienceState, ExperienceProps, RecommendationsState, VeroxmSlotImpressionProps, } from './tracking.js';
49
51
  export { VeroxmSlot, useSlot, field, configureSlots, loadSlot, mergeSlotValues } from './slots.js';
package/dist/index.js CHANGED
@@ -30,6 +30,8 @@ export { parseVideoUrl, videoEmbedUrl, videoThumbnailUrl } from './site/video.js
30
30
  export { VeroxmForm, useVeroxmForm } from './form.js';
31
31
  // Product journeys: a quote-and-buy journey in your page, in a frame of its hosted page.
32
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';
33
35
  // Experience OS visitor tracking -- pair with @veroxm/sdk's createTracker().
34
36
  export { VeroxmTrackerProvider, useTracker, usePageViews, useExperience, Experience, useContentView, useRecommendations, useSlotImpression, VeroxmSlotImpression, } from './tracking.js';
35
37
  // Visual slots (Experience Layer): named regions marketers edit from VeroXM.
package/dist/journey.d.ts CHANGED
@@ -51,6 +51,12 @@ export interface VeroxmJourneyProps {
51
51
  }>) => void;
52
52
  /** Every event, as it comes. */
53
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;
54
60
  /**
55
61
  * Record the finish as `$journey_completed` (usable as an experience's goal) with the `<VeroxmTrackerProvider>`'s
56
62
  * tracker. Default true; false records nothing.
@@ -61,7 +67,7 @@ export interface VeroxmJourneyProps {
61
67
  * The frame's address: the journey's, with ?embed=1, the language, chrome=0 and the page's own origin (where the
62
68
  * journey sends its events). Null when neither src nor baseUrl + journey make an http(s) address. @internal
63
69
  */
64
- export declare function journeyFrameUrl(p: Pick<VeroxmJourneyProps, 'src' | 'baseUrl' | 'journey' | 'lang' | 'chrome'>, parent: string | null): URL | null;
70
+ export declare function journeyFrameUrl(p: Pick<VeroxmJourneyProps, 'src' | 'baseUrl' | 'journey' | 'lang' | 'chrome'>, parent: string | null, previewToken?: string | null): URL | null;
65
71
  /** A message from the journey's frame, checked: from its origin and window, in the journey's own format. @internal */
66
72
  export declare function journeyEventOf(data: unknown): VeroxmJourneyEvent | null;
67
73
  /**
@@ -73,4 +79,4 @@ export declare function journeyEventOf(data: unknown): VeroxmJourneyEvent | null
73
79
  * onComplete={() => router.push('/thank-you')} />
74
80
  * ```
75
81
  */
76
- export declare function VeroxmJourney({ src, baseUrl, journey, lang, chrome, height, title, className, style, track, ...handlers }: VeroxmJourneyProps): import("react").JSX.Element;
82
+ export declare function VeroxmJourney({ src, baseUrl, journey, lang, chrome, height, title, className, style, track, preview, ...handlers }: VeroxmJourneyProps): import("react").JSX.Element;
package/dist/journey.js CHANGED
@@ -7,7 +7,7 @@ const LANG_PATH = /^\/([a-z]{2,3}(?:-[A-Za-z]{2,4})?)\/([a-z0-9](?:[a-z0-9-]{0,6
7
7
  * The frame's address: the journey's, with ?embed=1, the language, chrome=0 and the page's own origin (where the
8
8
  * journey sends its events). Null when neither src nor baseUrl + journey make an http(s) address. @internal
9
9
  */
10
- export function journeyFrameUrl(p, parent) {
10
+ export function journeyFrameUrl(p, parent, previewToken) {
11
11
  let url;
12
12
  try {
13
13
  if (p.src)
@@ -22,7 +22,17 @@ export function journeyFrameUrl(p, parent) {
22
22
  }
23
23
  if (url.protocol !== 'https:' && url.protocol !== 'http:')
24
24
  return null;
25
- if (p.lang) {
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) {
26
36
  // A readable address carries the language in its path (/ar/sports-insurance); a link takes ?lang=.
27
37
  const at = LANG_PATH.exec(url.pathname);
28
38
  if (at)
@@ -66,12 +76,17 @@ export function journeyEventOf(data) {
66
76
  * onComplete={() => router.push('/thank-you')} />
67
77
  * ```
68
78
  */
69
- export function VeroxmJourney({ src, baseUrl, journey, lang, chrome, height = 760, title = 'Insurance quote', className, style, track = true, ...handlers }) {
79
+ export function VeroxmJourney({ src, baseUrl, journey, lang, chrome, height = 760, title = 'Insurance quote', className, style, track = true, preview = true, ...handlers }) {
70
80
  const frame = useRef(null);
71
81
  // The page's own origin is known only in the browser: the frame is made there.
72
82
  const [parent, setParent] = useState(null);
73
- useEffect(() => setParent(window.location.origin), []);
74
- const url = useMemo(() => (parent ? journeyFrameUrl({ src, baseUrl, journey, lang, chrome }, parent) : null), [src, baseUrl, journey, lang, chrome, parent]);
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]);
75
90
  // Handlers change on every render; the listener calls the latest ones.
76
91
  const latest = useRef({ handlers, track });
77
92
  latest.current = { handlers, track };
@@ -97,7 +112,8 @@ export function VeroxmJourney({ src, baseUrl, journey, lang, chrome, height = 76
97
112
  else if (e.event === 'locale')
98
113
  h.onLocaleChange?.(e);
99
114
  else if (e.event === 'complete') {
100
- if (latest.current.track)
115
+ // A preview's finish isn't a real one.
116
+ if (latest.current.track && !m.data.preview)
101
117
  trackerRef.current.track('$journey_completed', { journey: e.journey });
102
118
  h.onComplete?.(e);
103
119
  }
@@ -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,6 +1,6 @@
1
1
  {
2
2
  "name": "@veroxm/react-sdk",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
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",
@@ -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",