@veroxm/react-sdk 0.0.0-stage → 0.1.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 +5 -0
- package/LICENSE +21 -0
- package/README.md +295 -2
- package/dist/cache.d.ts +69 -0
- package/dist/cache.js +89 -0
- package/dist/client-slots.d.ts +35 -0
- package/dist/client-slots.js +169 -0
- package/dist/client.d.ts +65 -0
- package/dist/client.js +87 -0
- package/dist/editor/constants.d.ts +12 -0
- package/dist/editor/constants.js +12 -0
- package/dist/editor/handler.d.ts +16 -0
- package/dist/editor/handler.js +175 -0
- package/dist/editor/inline.d.ts +25 -0
- package/dist/editor/inline.js +149 -0
- package/dist/editor/menu-input.d.ts +26 -0
- package/dist/editor/menu-input.js +110 -0
- package/dist/editor/overlay.d.ts +31 -0
- package/dist/editor/overlay.js +856 -0
- package/dist/editor/rich-text.d.ts +21 -0
- package/dist/editor/rich-text.js +232 -0
- package/dist/editor/server.d.ts +9 -0
- package/dist/editor/server.js +43 -0
- package/dist/errors.d.ts +20 -0
- package/dist/errors.js +26 -0
- package/dist/hooks/use-cached-query.d.ts +21 -0
- package/dist/hooks/use-cached-query.js +59 -0
- package/dist/hooks/use-collection.d.ts +10 -0
- package/dist/hooks/use-collection.js +14 -0
- package/dist/hooks/use-entries.d.ts +18 -0
- package/dist/hooks/use-entries.js +25 -0
- package/dist/hooks/use-entry.d.ts +21 -0
- package/dist/hooks/use-entry.js +22 -0
- package/dist/hooks/use-media.d.ts +9 -0
- package/dist/hooks/use-media.js +13 -0
- package/dist/hydration-boundary.d.ts +35 -0
- package/dist/hydration-boundary.js +38 -0
- package/dist/image.d.ts +34 -0
- package/dist/image.js +39 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +32 -0
- package/dist/next/cache-components.d.ts +15 -0
- package/dist/next/cache-components.js +25 -0
- package/dist/next/cached.d.ts +9 -0
- package/dist/next/cached.js +20 -0
- package/dist/next/edge-slot.d.ts +21 -0
- package/dist/next/edge-slot.js +29 -0
- package/dist/next/editor.d.ts +7 -0
- package/dist/next/editor.js +13 -0
- package/dist/next/index.d.ts +17 -0
- package/dist/next/index.js +21 -0
- package/dist/next/llms.d.ts +2 -0
- package/dist/next/llms.js +44 -0
- package/dist/next/route.d.ts +12 -0
- package/dist/next/route.js +16 -0
- package/dist/next/slot.d.ts +21 -0
- package/dist/next/slot.js +160 -0
- package/dist/node.d.ts +43 -0
- package/dist/node.js +67 -0
- package/dist/preview.d.ts +35 -0
- package/dist/preview.js +46 -0
- package/dist/provider.d.ts +29 -0
- package/dist/provider.js +37 -0
- package/dist/query-keys.d.ts +19 -0
- package/dist/query-keys.js +49 -0
- package/dist/site/chart-view.d.ts +14 -0
- package/dist/site/chart-view.js +44 -0
- package/dist/site/chart.d.ts +127 -0
- package/dist/site/chart.js +639 -0
- package/dist/site/map-embed.d.ts +32 -0
- package/dist/site/map-embed.js +139 -0
- package/dist/site/map-math.d.ts +27 -0
- package/dist/site/map-math.js +89 -0
- package/dist/site/nav-menu.d.ts +19 -0
- package/dist/site/nav-menu.js +76 -0
- package/dist/site/site-parts.d.ts +87 -0
- package/dist/site/site-parts.js +46 -0
- package/dist/site/slider.d.ts +17 -0
- package/dist/site/slider.js +78 -0
- package/dist/site/styles.d.ts +3 -0
- package/dist/site/styles.js +155 -0
- package/dist/site/video-embed.d.ts +15 -0
- package/dist/site/video-embed.js +27 -0
- package/dist/site/video.d.ts +18 -0
- package/dist/site/video.js +73 -0
- package/dist/slots-core.d.ts +397 -0
- package/dist/slots-core.js +367 -0
- package/dist/slots.d.ts +13 -0
- package/dist/slots.js +30 -0
- package/dist/ssr.d.ts +20 -0
- package/dist/ssr.js +35 -0
- package/dist/structured-data.d.ts +13 -0
- package/dist/structured-data.js +36 -0
- package/dist/tracking.d.ts +142 -0
- package/dist/tracking.js +152 -0
- package/dist/types.d.ts +106 -0
- package/dist/types.js +6 -0
- package/package.json +95 -4
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { cookies, draftMode } from 'next/headers';
|
|
3
|
+
import { after } from 'next/server';
|
|
4
|
+
import { Suspense } from 'react';
|
|
5
|
+
import { fallbackValues, loadPublishedSlot, loadSlotFor, loadSlotForVisitor, mergeSlotValues, reportSlot, resolveSlotsConfig, } from '../slots-core.js';
|
|
6
|
+
import { PREVIEW_COOKIE, VISITOR_COOKIE } from '../editor/constants.js';
|
|
7
|
+
import { EDITOR_COOKIE, editorApi } from '../editor/server.js';
|
|
8
|
+
import { VeroxmEditor } from './editor.js';
|
|
9
|
+
import { EdgeSlot } from './edge-slot.js';
|
|
10
|
+
/**
|
|
11
|
+
* <VeroxmSlot> for Next.js App Router. Outside draft mode it shows the
|
|
12
|
+
* published content (cached) -- or, when the slot is under a live A/B test
|
|
13
|
+
* and the visitor has the tracker's visitor cookie, that visitor's variant.
|
|
14
|
+
* In draft mode -- after "Edit on page" in VeroXM -- it renders the slot's
|
|
15
|
+
* draft, marks it for the on-page editor, and mounts the editor overlay.
|
|
16
|
+
*/
|
|
17
|
+
export function VeroxmSlot(props) {
|
|
18
|
+
return slotWith(props, loadPublishedSlot, false);
|
|
19
|
+
}
|
|
20
|
+
/** Sends slot definitions once the response is done (a timer may never fire while a page is prerendered). */
|
|
21
|
+
const afterResponse = (send) => after(send);
|
|
22
|
+
/** Shared by this entry and '@veroxm/react-sdk/next/cache-components' (which passes a cached loader). */
|
|
23
|
+
export async function slotWith(props, load, cached) {
|
|
24
|
+
const { isEnabled } = await draftMode();
|
|
25
|
+
const token = isEnabled ? (await cookies()).get(EDITOR_COOKIE)?.value : undefined;
|
|
26
|
+
if (!token) {
|
|
27
|
+
if (cacheComponents && !cached) {
|
|
28
|
+
// Uncached reads must not block a Cache Components route: stream the
|
|
29
|
+
// slot in, with your fallback in the static shell.
|
|
30
|
+
warnCacheComponents();
|
|
31
|
+
return (_jsx(Suspense, { fallback: render(props, null), children: _jsx(Published, { props: props, load: load, cached: cached }) }));
|
|
32
|
+
}
|
|
33
|
+
return Published({ props, load, cached });
|
|
34
|
+
}
|
|
35
|
+
const { name, children, fields, fallback, label, locale, path } = props;
|
|
36
|
+
const site = fallbackValues(fields, fallback);
|
|
37
|
+
reportSlot(name, fields, label, path, afterResponse, { values: site, locale });
|
|
38
|
+
const preview = (await cookies()).get(PREVIEW_COOKIE)?.value ?? '';
|
|
39
|
+
const variant = preview.startsWith(`${name}:`) ? preview.slice(name.length + 1) : undefined;
|
|
40
|
+
const draft = await loadDraft(token, name, locale, variant);
|
|
41
|
+
const slot = {
|
|
42
|
+
name,
|
|
43
|
+
version: draft?.version ?? null,
|
|
44
|
+
source: draft ? 'draft' : 'fallback',
|
|
45
|
+
editing: true,
|
|
46
|
+
edit: (fieldName) => ({ 'data-veroxm-field': fieldName }),
|
|
47
|
+
};
|
|
48
|
+
const values = mergeSlotValues(fields, fallback, draft?.values ?? null);
|
|
49
|
+
return (_jsxs(_Fragment, { children: [_jsx("div", { "data-veroxm-slot": name, "data-veroxm-label": label ?? '', "data-veroxm-locale": locale ?? '', "data-veroxm-shown": JSON.stringify(values), "data-veroxm-fallback": JSON.stringify(site), style: { display: 'contents' }, children: children(values, slot) }), _jsx(VeroxmEditor, {})] }));
|
|
50
|
+
}
|
|
51
|
+
const cacheComponents = Boolean(process.env.__NEXT_CACHE_COMPONENTS);
|
|
52
|
+
function render({ name, children, fields, fallback }, data) {
|
|
53
|
+
// A personalised version hid the slot for this person.
|
|
54
|
+
if (data?.hidden)
|
|
55
|
+
return null;
|
|
56
|
+
const slot = {
|
|
57
|
+
name,
|
|
58
|
+
version: data?.version || null,
|
|
59
|
+
source: data && (data.version || data.test) ? 'published' : 'fallback',
|
|
60
|
+
test: data?.test ?? null,
|
|
61
|
+
editing: false,
|
|
62
|
+
edit: () => ({}),
|
|
63
|
+
};
|
|
64
|
+
return children(mergeSlotValues(fields, fallback, data?.values ?? null), slot);
|
|
65
|
+
}
|
|
66
|
+
/** The published version plus every variant, for the edge worker (see edge-slot.tsx). */
|
|
67
|
+
function edgeShell(props, data) {
|
|
68
|
+
const t = data.variants;
|
|
69
|
+
return (_jsx(EdgeSlot, { name: props.name, experienceId: t.experienceId, locale: props.locale, shown: render(props, data), variants: t.variants.map((v) => ({
|
|
70
|
+
variantId: v.variantId,
|
|
71
|
+
node: render(props, { ...data, values: v.values, test: { experienceId: t.experienceId, variantId: v.variantId, label: v.label, isControl: false } }),
|
|
72
|
+
})) }));
|
|
73
|
+
}
|
|
74
|
+
let warned = false;
|
|
75
|
+
function warnCacheComponents() {
|
|
76
|
+
if (warned)
|
|
77
|
+
return;
|
|
78
|
+
warned = true;
|
|
79
|
+
console.warn("[veroxm] cacheComponents is on: import VeroxmSlot from '@veroxm/react-sdk/next/cache-components' so slot content is cached and part of the static shell.");
|
|
80
|
+
}
|
|
81
|
+
/** Published values -- or this visitor's A/B variant when the slot is under a live test. */
|
|
82
|
+
async function Published({ props, load, cached }) {
|
|
83
|
+
const { name, fields, label, locale, path } = props;
|
|
84
|
+
const shown = fallbackValues(fields, props.fallback);
|
|
85
|
+
// The cached loader reports inside its cache scope; otherwise report once the response is done.
|
|
86
|
+
if (!cached)
|
|
87
|
+
reportSlot(name, fields, label, path, afterResponse, { values: shown, locale });
|
|
88
|
+
const data = cached ? await load(name, locale, { fields, label, path, shown }) : await load(name, locale);
|
|
89
|
+
if (data?.personalised && props.person) {
|
|
90
|
+
// Personalised versions: this person's, read for this request (with their A/B variant when under a test).
|
|
91
|
+
let visitorId;
|
|
92
|
+
if (data.testing) {
|
|
93
|
+
try {
|
|
94
|
+
visitorId = (await cookies()).get(VISITOR_COOKIE)?.value;
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
// Static page: no visitor cookie; the person's version still applies.
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return render(props, (await loadSlotFor(name, { visitorId, person: props.person }, locale)) ?? data);
|
|
101
|
+
}
|
|
102
|
+
if (!data?.testing)
|
|
103
|
+
return render(props, data);
|
|
104
|
+
// Edge delivery: every variant in the page, for the edge worker to pick from.
|
|
105
|
+
const shell = resolveSlotsConfig().edge && data.variants?.variants.length ? edgeShell(props, data) : render(props, data);
|
|
106
|
+
if (cacheComponents) {
|
|
107
|
+
// The published version is the static shell; the visitor's variant
|
|
108
|
+
// (which needs their cookie) streams in at request time. Behind the
|
|
109
|
+
// edge worker the shell already shows it, so the swap changes nothing.
|
|
110
|
+
return (_jsx(Suspense, { fallback: shell, children: _jsx(VisitorVariant, { props: props, base: data, shell: shell }) }));
|
|
111
|
+
}
|
|
112
|
+
// Only slots under a test read the cookie (which makes the page per-request).
|
|
113
|
+
// A page Next.js rendered statically can't read it: there everyone sees
|
|
114
|
+
// the published version (see warnStatic).
|
|
115
|
+
let visitorId;
|
|
116
|
+
try {
|
|
117
|
+
visitorId = (await cookies()).get(VISITOR_COOKIE)?.value;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
// Static page: the edge worker can still show each visitor their variant.
|
|
121
|
+
if (shell !== null && resolveSlotsConfig().edge && data.variants?.variants.length)
|
|
122
|
+
return shell;
|
|
123
|
+
warnStatic(name);
|
|
124
|
+
return render(props, data);
|
|
125
|
+
}
|
|
126
|
+
return render(props, visitorId ? ((await loadSlotForVisitor(name, visitorId, locale)) ?? data) : data);
|
|
127
|
+
}
|
|
128
|
+
const warnedStatic = new Set();
|
|
129
|
+
function warnStatic(name) {
|
|
130
|
+
if (warnedStatic.has(name))
|
|
131
|
+
return;
|
|
132
|
+
warnedStatic.add(name);
|
|
133
|
+
console.warn(`[veroxm] slot "${name}" has a live A/B test, but this page is rendered statically, so every visitor sees the published version. ` +
|
|
134
|
+
"Turn on cacheComponents (and import VeroxmSlot from '@veroxm/react-sdk/next/cache-components'), or make the page dynamic.");
|
|
135
|
+
}
|
|
136
|
+
/** Cache Components: the visitor's variant, streamed in behind the published static shell. */
|
|
137
|
+
async function VisitorVariant({ props, base, shell }) {
|
|
138
|
+
const visitorId = (await cookies()).get(VISITOR_COOKIE)?.value;
|
|
139
|
+
const mine = visitorId ? await loadSlotForVisitor(props.name, visitorId, props.locale) : null;
|
|
140
|
+
// No answer of our own: keep the shell (in edge mode the edge worker
|
|
141
|
+
// fills this streamed copy too, so it can't undo the edge's variant).
|
|
142
|
+
return mine ? render(props, mine) : shell;
|
|
143
|
+
}
|
|
144
|
+
async function loadDraft(token, name, locale, variant) {
|
|
145
|
+
const qs = new URLSearchParams({ names: name });
|
|
146
|
+
if (locale)
|
|
147
|
+
qs.set('locale', locale);
|
|
148
|
+
if (variant && /^\d{1,2}$/.test(variant))
|
|
149
|
+
qs.set('variant', variant);
|
|
150
|
+
try {
|
|
151
|
+
const res = await editorApi(token, `slots?${qs}`);
|
|
152
|
+
if (!res.ok)
|
|
153
|
+
return null;
|
|
154
|
+
const body = (await res.json());
|
|
155
|
+
return body.slots?.[name] ?? null;
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
}
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type SlotFieldDefs, type SlotsConfig } from './slots-core.js';
|
|
2
|
+
interface NodeRequest extends AsyncIterable<Uint8Array | string> {
|
|
3
|
+
method?: string;
|
|
4
|
+
url?: string;
|
|
5
|
+
originalUrl?: string;
|
|
6
|
+
headers: Record<string, string | string[] | undefined>;
|
|
7
|
+
socket?: unknown;
|
|
8
|
+
}
|
|
9
|
+
interface NodeResponse {
|
|
10
|
+
statusCode: number;
|
|
11
|
+
setHeader(name: string, value: string | string[]): unknown;
|
|
12
|
+
end(body?: string | Uint8Array): unknown;
|
|
13
|
+
}
|
|
14
|
+
type Next = (err?: unknown) => void;
|
|
15
|
+
export interface VeroxmMiddlewareOptions extends SlotsConfig {
|
|
16
|
+
/** Trust X-Forwarded-Proto/Host from a proxy in front (nginx, a load balancer). Default true. */
|
|
17
|
+
trustProxy?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** A slot definition shared by the client components and the server. */
|
|
20
|
+
export interface SlotDefinition {
|
|
21
|
+
name: string;
|
|
22
|
+
fields: SlotFieldDefs;
|
|
23
|
+
label?: string;
|
|
24
|
+
/** Page path where it appears, shown in VeroXM and used by "Edit on page". */
|
|
25
|
+
path?: string;
|
|
26
|
+
/** The content the site shows before anything is published, so VeroXM's dashboard can show it in empty fields. */
|
|
27
|
+
fallback?: Record<string, unknown>;
|
|
28
|
+
/** The locale `fallback` is in (omit for the site's default). */
|
|
29
|
+
locale?: string;
|
|
30
|
+
}
|
|
31
|
+
/** Express/Connect middleware for the /api/veroxm routes. Mount it at exactly '/api/veroxm'. */
|
|
32
|
+
export declare function veroxmMiddleware(options?: VeroxmMiddlewareOptions): (req: NodeRequest, res: NodeResponse, next?: Next) => Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Reports slot definitions to VeroXM from the server (call once at
|
|
35
|
+
* startup), so they appear in the dashboard and can be edited before
|
|
36
|
+
* anyone renders them. Client-rendered pages never report: they have no key.
|
|
37
|
+
*/
|
|
38
|
+
export declare function registerSlots(definitions: SlotDefinition[], options?: SlotsConfig): void;
|
|
39
|
+
export { configureSlots, field } from './slots-core.js';
|
|
40
|
+
export type { SlotsConfig, SlotFieldDefs } from './slots-core.js';
|
|
41
|
+
/** The fetch-style handler behind veroxmMiddleware, for other servers (Hono, Remix, workers...). */
|
|
42
|
+
export { createEditorHandler } from './editor/handler.js';
|
|
43
|
+
export type { EditorHandler, EditorHandlerHooks } from './editor/handler.js';
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { configureSlots, fallbackValues, reportSlot } from './slots-core.js';
|
|
2
|
+
import { createEditorHandler } from './editor/handler.js';
|
|
3
|
+
const header = (h) => (Array.isArray(h) ? h[0] : h);
|
|
4
|
+
/** Express/Connect middleware for the /api/veroxm routes. Mount it at exactly '/api/veroxm'. */
|
|
5
|
+
export function veroxmMiddleware(options = {}) {
|
|
6
|
+
const { trustProxy = true, ...config } = options;
|
|
7
|
+
if (Object.keys(config).length)
|
|
8
|
+
configureSlots(config);
|
|
9
|
+
const handle = createEditorHandler({ servePublished: true });
|
|
10
|
+
return async function veroxm(req, res, next) {
|
|
11
|
+
try {
|
|
12
|
+
const proto = (trustProxy && header(req.headers['x-forwarded-proto'])?.split(',')[0].trim()) || (req.socket?.encrypted ? 'https' : 'http');
|
|
13
|
+
const host = (trustProxy && header(req.headers['x-forwarded-host'])) || header(req.headers.host) || 'localhost';
|
|
14
|
+
const url = new URL(req.originalUrl ?? req.url ?? '/', `${proto}://${host}`);
|
|
15
|
+
const headers = new Headers();
|
|
16
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
17
|
+
if (v === undefined)
|
|
18
|
+
continue;
|
|
19
|
+
for (const one of Array.isArray(v) ? v : [v])
|
|
20
|
+
headers.append(k, one);
|
|
21
|
+
}
|
|
22
|
+
const method = (req.method ?? 'GET').toUpperCase();
|
|
23
|
+
let body;
|
|
24
|
+
if (method === 'PUT' || method === 'POST') {
|
|
25
|
+
let text = '';
|
|
26
|
+
const decoder = new TextDecoder();
|
|
27
|
+
for await (const chunk of req)
|
|
28
|
+
text += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
|
|
29
|
+
body = text + decoder.decode();
|
|
30
|
+
}
|
|
31
|
+
const response = await handle(new Request(url, { method, headers, body }));
|
|
32
|
+
if (response.status === 404 && next)
|
|
33
|
+
return next();
|
|
34
|
+
res.statusCode = response.status;
|
|
35
|
+
response.headers.forEach((value, key) => {
|
|
36
|
+
if (key.toLowerCase() !== 'set-cookie')
|
|
37
|
+
res.setHeader(key, value);
|
|
38
|
+
});
|
|
39
|
+
const cookies = response.headers.getSetCookie?.() ?? [];
|
|
40
|
+
if (cookies.length)
|
|
41
|
+
res.setHeader('Set-Cookie', cookies);
|
|
42
|
+
res.end(response.body ? new Uint8Array(await response.arrayBuffer()) : undefined);
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
if (next)
|
|
46
|
+
return next(err);
|
|
47
|
+
res.statusCode = 500;
|
|
48
|
+
res.end('VeroXM middleware error');
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Reports slot definitions to VeroXM from the server (call once at
|
|
54
|
+
* startup), so they appear in the dashboard and can be edited before
|
|
55
|
+
* anyone renders them. Client-rendered pages never report: they have no key.
|
|
56
|
+
*/
|
|
57
|
+
export function registerSlots(definitions, options = {}) {
|
|
58
|
+
if (Object.keys(options).length)
|
|
59
|
+
configureSlots(options);
|
|
60
|
+
for (const d of definitions) {
|
|
61
|
+
const shown = d.fallback ? { values: fallbackValues(d.fields, d.fallback), locale: d.locale } : undefined;
|
|
62
|
+
reportSlot(d.name, d.fields, d.label, d.path, undefined, shown);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
export { configureSlots, field } from './slots-core.js';
|
|
66
|
+
/** The fetch-style handler behind veroxmMiddleware, for other servers (Hono, Remix, workers...). */
|
|
67
|
+
export { createEditorHandler } from './editor/handler.js';
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type ReactElement, type ReactNode } from 'react';
|
|
2
|
+
export interface DraftModeState {
|
|
3
|
+
isDraftMode: boolean;
|
|
4
|
+
enableDraftMode: () => void;
|
|
5
|
+
disableDraftMode: () => void;
|
|
6
|
+
}
|
|
7
|
+
export interface VeroxmPreviewProviderProps {
|
|
8
|
+
children: ReactNode;
|
|
9
|
+
/**
|
|
10
|
+
* Start already in draft mode -- e.g. because your Next.js route
|
|
11
|
+
* handler already resolved Next's own `draftMode().isEnabled`
|
|
12
|
+
* server-side before rendering this (docs/REACT-SDK-GRAPHQL-
|
|
13
|
+
* IMPLEMENTATION-PLAN.md §5.4/§5.5). Defaults to false.
|
|
14
|
+
*/
|
|
15
|
+
initialDraftMode?: boolean;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Supplies live-preview/draft-mode state to useDraftMode() and, through
|
|
19
|
+
* it, to useEntries() (§5.2), which requests unpublished content while
|
|
20
|
+
* active. Optional: an app that never uses preview mode doesn't need to
|
|
21
|
+
* mount this at all -- useDraftMode() reports `isDraftMode: false`
|
|
22
|
+
* without one.
|
|
23
|
+
*/
|
|
24
|
+
export declare function VeroxmPreviewProvider(props: VeroxmPreviewProviderProps): ReactElement;
|
|
25
|
+
/**
|
|
26
|
+
* Reads draft-mode state -- see <VeroxmPreviewProvider>. Safe to call
|
|
27
|
+
* without one mounted: reports `isDraftMode: false` and a no-op
|
|
28
|
+
* disableDraftMode() (already disabled), so an app that never uses
|
|
29
|
+
* preview mode doesn't need to wrap anything just to call useEntries().
|
|
30
|
+
* enableDraftMode() without a provider throws, rather than silently
|
|
31
|
+
* doing nothing, since that call means the caller specifically wants
|
|
32
|
+
* draft mode ON and would otherwise get no feedback that it didn't take
|
|
33
|
+
* effect.
|
|
34
|
+
*/
|
|
35
|
+
export declare function useDraftMode(): DraftModeState;
|
package/dist/preview.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, useContext, useMemo, useState } from 'react';
|
|
3
|
+
const DraftModeContext = createContext(null);
|
|
4
|
+
// A stable, module-level constant (not recreated per render/call) for
|
|
5
|
+
// the no-provider-mounted case -- see useDraftMode()'s own comment on
|
|
6
|
+
// why that's the right default rather than throwing.
|
|
7
|
+
const DISABLED_DRAFT_MODE = {
|
|
8
|
+
isDraftMode: false,
|
|
9
|
+
enableDraftMode: () => {
|
|
10
|
+
throw new Error('enableDraftMode() has no effect -- mount a <VeroxmPreviewProvider> above this component first.');
|
|
11
|
+
},
|
|
12
|
+
disableDraftMode: () => {
|
|
13
|
+
/* already disabled; a no-op provider has nothing to disable */
|
|
14
|
+
},
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Supplies live-preview/draft-mode state to useDraftMode() and, through
|
|
18
|
+
* it, to useEntries() (§5.2), which requests unpublished content while
|
|
19
|
+
* active. Optional: an app that never uses preview mode doesn't need to
|
|
20
|
+
* mount this at all -- useDraftMode() reports `isDraftMode: false`
|
|
21
|
+
* without one.
|
|
22
|
+
*/
|
|
23
|
+
export function VeroxmPreviewProvider(props) {
|
|
24
|
+
const { children, initialDraftMode = false } = props;
|
|
25
|
+
const [isDraftMode, setIsDraftMode] = useState(initialDraftMode);
|
|
26
|
+
const value = useMemo(() => ({
|
|
27
|
+
isDraftMode,
|
|
28
|
+
enableDraftMode: () => setIsDraftMode(true),
|
|
29
|
+
disableDraftMode: () => setIsDraftMode(false),
|
|
30
|
+
}), [isDraftMode]);
|
|
31
|
+
return _jsx(DraftModeContext.Provider, { value: value, children: children });
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Reads draft-mode state -- see <VeroxmPreviewProvider>. Safe to call
|
|
35
|
+
* without one mounted: reports `isDraftMode: false` and a no-op
|
|
36
|
+
* disableDraftMode() (already disabled), so an app that never uses
|
|
37
|
+
* preview mode doesn't need to wrap anything just to call useEntries().
|
|
38
|
+
* enableDraftMode() without a provider throws, rather than silently
|
|
39
|
+
* doing nothing, since that call means the caller specifically wants
|
|
40
|
+
* draft mode ON and would otherwise get no feedback that it didn't take
|
|
41
|
+
* effect.
|
|
42
|
+
*/
|
|
43
|
+
export function useDraftMode() {
|
|
44
|
+
const ctx = useContext(DraftModeContext);
|
|
45
|
+
return ctx ?? DISABLED_DRAFT_MODE;
|
|
46
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type ReactElement, type ReactNode } from 'react';
|
|
2
|
+
import { VeroxmClient, type VeroxmClientOptions } from './client.js';
|
|
3
|
+
export interface VeroxmProviderProps extends Partial<VeroxmClientOptions> {
|
|
4
|
+
children: ReactNode;
|
|
5
|
+
/**
|
|
6
|
+
* Reuse an already-constructed VeroxmClient instead of having the
|
|
7
|
+
* provider build its own from apiBase/apiKey/projectUuid -- e.g. a
|
|
8
|
+
* client built server-side for SSR that you want the client-side hooks
|
|
9
|
+
* to keep using after hydration (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-
|
|
10
|
+
* PLAN.md §5.5, a later phase). When passed, apiBase/apiKey/projectUuid
|
|
11
|
+
* are ignored.
|
|
12
|
+
*/
|
|
13
|
+
client?: VeroxmClient;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Supplies a VeroxmClient to every hook in ./hooks via context -- the
|
|
17
|
+
* React counterpart to @veroxm/sdk's VeroXMApp.initializeApp()
|
|
18
|
+
* (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md §5.1). Mount once near
|
|
19
|
+
* your app's root:
|
|
20
|
+
*
|
|
21
|
+
* ```tsx
|
|
22
|
+
* <VeroxmProvider apiBase="https://cms.example.com" apiKey={process.env.VEROXM_API_KEY!}>
|
|
23
|
+
* <App />
|
|
24
|
+
* </VeroxmProvider>
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function VeroxmProvider(props: VeroxmProviderProps): ReactElement;
|
|
28
|
+
/** Reads the VeroxmClient supplied by the nearest <VeroxmProvider> -- throws if none is mounted, same fail-loud philosophy as @veroxm/sdk's own methods (see packages/sdk-js/src/errors.ts's VeroXMNotAuthenticatedError). Every hook in ./hooks calls this rather than reading context directly. */
|
|
29
|
+
export declare function useVeroxmClient(): VeroxmClient;
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, useContext, useMemo } from 'react';
|
|
3
|
+
import { VeroxmClient } from './client.js';
|
|
4
|
+
const VeroxmContext = createContext(null);
|
|
5
|
+
/**
|
|
6
|
+
* Supplies a VeroxmClient to every hook in ./hooks via context -- the
|
|
7
|
+
* React counterpart to @veroxm/sdk's VeroXMApp.initializeApp()
|
|
8
|
+
* (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md §5.1). Mount once near
|
|
9
|
+
* your app's root:
|
|
10
|
+
*
|
|
11
|
+
* ```tsx
|
|
12
|
+
* <VeroxmProvider apiBase="https://cms.example.com" apiKey={process.env.VEROXM_API_KEY!}>
|
|
13
|
+
* <App />
|
|
14
|
+
* </VeroxmProvider>
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
export function VeroxmProvider(props) {
|
|
18
|
+
const { children, client, apiBase, apiKey, projectUuid, cache } = props;
|
|
19
|
+
const value = useMemo(() => {
|
|
20
|
+
if (client)
|
|
21
|
+
return client;
|
|
22
|
+
if (!apiBase || !apiKey) {
|
|
23
|
+
throw new Error('<VeroxmProvider> needs either a `client` prop or both `apiBase` and `apiKey`.');
|
|
24
|
+
}
|
|
25
|
+
return new VeroxmClient({ apiBase, apiKey, projectUuid, cache });
|
|
26
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
27
|
+
}, [client, apiBase, apiKey, projectUuid, cache]);
|
|
28
|
+
return _jsx(VeroxmContext.Provider, { value: value, children: children });
|
|
29
|
+
}
|
|
30
|
+
/** Reads the VeroxmClient supplied by the nearest <VeroxmProvider> -- throws if none is mounted, same fail-loud philosophy as @veroxm/sdk's own methods (see packages/sdk-js/src/errors.ts's VeroXMNotAuthenticatedError). Every hook in ./hooks calls this rather than reading context directly. */
|
|
31
|
+
export function useVeroxmClient() {
|
|
32
|
+
const client = useContext(VeroxmContext);
|
|
33
|
+
if (!client) {
|
|
34
|
+
throw new Error('useVeroxmClient() was called outside a <VeroxmProvider> -- mount one near your app root.');
|
|
35
|
+
}
|
|
36
|
+
return client;
|
|
37
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { EntriesQueryOptions } from './types.js';
|
|
2
|
+
export declare function collectionKey(slug: string): string;
|
|
3
|
+
export declare function collectionsKey(): string;
|
|
4
|
+
export declare function entryKey(collection: string, id: number, timestamps: boolean): string;
|
|
5
|
+
export declare function entriesKey(collection: string, options: EntriesQueryOptions): string;
|
|
6
|
+
export declare function mediaKey(id: number): string;
|
|
7
|
+
/** Tag a cached collection-meta entry so invalidateCollection() drops it too. */
|
|
8
|
+
export declare function collectionTag(slug: string): string;
|
|
9
|
+
export declare function mediaTag(id: number): string;
|
|
10
|
+
/**
|
|
11
|
+
* Every cached query that reads FROM a collection (a list or a single
|
|
12
|
+
* entry) is tagged with both the collection slug and, when one was
|
|
13
|
+
* given, the locale -- the "tag = collection slug + locale" scheme
|
|
14
|
+
* described in §5.3, letting an app invalidate either dimension
|
|
15
|
+
* (VeroxmCache.invalidateCollection() / invalidateLocale()) without the
|
|
16
|
+
* other.
|
|
17
|
+
*/
|
|
18
|
+
export declare function entryTags(collection: string, locale: string | undefined): string[];
|
|
19
|
+
export declare function localeTag(locale: string): string;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Canonical cache-key/tag builders -- shared by the hooks (./hooks) and
|
|
2
|
+
// the SSR helpers (./ssr.ts) so a server-fetched result and the
|
|
3
|
+
// client-side hook for "the same query" always land on the identical
|
|
4
|
+
// cache key. Never construct a key/tag string by hand anywhere else in
|
|
5
|
+
// this package (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md §5.3/§5.5).
|
|
6
|
+
export function collectionKey(slug) {
|
|
7
|
+
return `collection:${slug}`;
|
|
8
|
+
}
|
|
9
|
+
export function collectionsKey() {
|
|
10
|
+
return 'collections';
|
|
11
|
+
}
|
|
12
|
+
export function entryKey(collection, id, timestamps) {
|
|
13
|
+
return `entry:${collection}:${id}:${timestamps}`;
|
|
14
|
+
}
|
|
15
|
+
// EntriesQueryOptions is plain JSON-serializable data (see types.ts), so
|
|
16
|
+
// JSON.stringify is an exact, dependency-free way to fold the whole
|
|
17
|
+
// filter/sort/pagination shape into one key -- same reasoning
|
|
18
|
+
// hooks/use-entries.ts used before this phase, just centralized here now
|
|
19
|
+
// that ssr.ts needs the identical key too.
|
|
20
|
+
export function entriesKey(collection, options) {
|
|
21
|
+
return `entries:${collection}:${JSON.stringify(options)}`;
|
|
22
|
+
}
|
|
23
|
+
export function mediaKey(id) {
|
|
24
|
+
return `media:${id}`;
|
|
25
|
+
}
|
|
26
|
+
/** Tag a cached collection-meta entry so invalidateCollection() drops it too. */
|
|
27
|
+
export function collectionTag(slug) {
|
|
28
|
+
return `collection:${slug}`;
|
|
29
|
+
}
|
|
30
|
+
export function mediaTag(id) {
|
|
31
|
+
return `media:${id}`;
|
|
32
|
+
}
|
|
33
|
+
function localeTags(locale) {
|
|
34
|
+
return locale ? [`locale:${locale}`] : [];
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Every cached query that reads FROM a collection (a list or a single
|
|
38
|
+
* entry) is tagged with both the collection slug and, when one was
|
|
39
|
+
* given, the locale -- the "tag = collection slug + locale" scheme
|
|
40
|
+
* described in §5.3, letting an app invalidate either dimension
|
|
41
|
+
* (VeroxmCache.invalidateCollection() / invalidateLocale()) without the
|
|
42
|
+
* other.
|
|
43
|
+
*/
|
|
44
|
+
export function entryTags(collection, locale) {
|
|
45
|
+
return [collectionTag(collection), ...localeTags(locale)];
|
|
46
|
+
}
|
|
47
|
+
export function localeTag(locale) {
|
|
48
|
+
return `locale:${locale}`;
|
|
49
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type ChartValue } from './chart.js';
|
|
2
|
+
export interface ChartProps {
|
|
3
|
+
chart: ChartValue | null | undefined;
|
|
4
|
+
/** Pixels. Default 320 (220 for a key figure). */
|
|
5
|
+
height?: number;
|
|
6
|
+
/** Number and date formatting. Default: the reader's browser. */
|
|
7
|
+
locale?: string;
|
|
8
|
+
/** Offer the numbers as a table under the chart. Default true. */
|
|
9
|
+
showTable?: boolean;
|
|
10
|
+
className?: string;
|
|
11
|
+
/** Spread on the figure, e.g. slot.edit('chart') for VeroXM's on-page editor. */
|
|
12
|
+
editProps?: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
export declare function Chart({ chart, height, locale, showTable, className, editProps }: ChartProps): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useId, useLayoutEffect, useRef, useState } from 'react';
|
|
4
|
+
import { chartSummary, chartSvg, formatChartNumber } from './chart.js';
|
|
5
|
+
const COLORS = ['#2a78d6', '#eb6834', '#1baf7a', '#eda100', '#e87ba4', '#008300'];
|
|
6
|
+
export function Chart({ chart, height, locale, showTable = true, className, editProps }) {
|
|
7
|
+
const id = useId();
|
|
8
|
+
const boxRef = useRef(null);
|
|
9
|
+
const [width, setWidth] = useState(640);
|
|
10
|
+
const [tip, setTip] = useState(null);
|
|
11
|
+
useLayoutEffect(() => {
|
|
12
|
+
const el = boxRef.current;
|
|
13
|
+
if (!el)
|
|
14
|
+
return;
|
|
15
|
+
const measure = () => {
|
|
16
|
+
if (el.clientWidth)
|
|
17
|
+
setWidth(Math.round(el.clientWidth));
|
|
18
|
+
};
|
|
19
|
+
measure();
|
|
20
|
+
if (typeof ResizeObserver === 'undefined')
|
|
21
|
+
return;
|
|
22
|
+
const ro = new ResizeObserver(measure);
|
|
23
|
+
ro.observe(el);
|
|
24
|
+
return () => ro.disconnect();
|
|
25
|
+
}, []);
|
|
26
|
+
if (!chart)
|
|
27
|
+
return null;
|
|
28
|
+
const h = height ?? (chart.kind === 'kpi' ? 220 : 320);
|
|
29
|
+
const svg = chartSvg(chart, { width, height: h, locale });
|
|
30
|
+
if (!svg)
|
|
31
|
+
return null;
|
|
32
|
+
const series = chart.series.filter((s) => s.values.some((v) => typeof v === 'number'));
|
|
33
|
+
const fmt = (v) => formatChartNumber(v, chart.format, { locale });
|
|
34
|
+
const pie = chart.kind === 'pie' || chart.kind === 'donut';
|
|
35
|
+
return (_jsxs("figure", { className: `vxs-chart${className ? ` ${className}` : ''}`, "aria-labelledby": chart.title ? `${id}-title` : undefined, ...editProps, children: [chart.title ? (_jsx("p", { id: `${id}-title`, className: "vxs-chart-title", children: chart.title })) : null, _jsxs("div", { ref: boxRef, className: "vxs-chart-box", style: { height: h }, onPointerMove: (e) => {
|
|
36
|
+
const hit = e.target.closest?.('[data-x]');
|
|
37
|
+
const i = hit ? Number(hit.getAttribute('data-x')) : NaN;
|
|
38
|
+
if (!hit || !Number.isInteger(i) || i < 0)
|
|
39
|
+
return setTip(null);
|
|
40
|
+
const r = e.currentTarget.getBoundingClientRect();
|
|
41
|
+
const cx = hit.getAttribute('data-cx');
|
|
42
|
+
setTip({ i, x: e.clientX - r.left, y: e.clientY - r.top, ...(cx ? { cx: Number(cx) } : {}) });
|
|
43
|
+
}, onPointerLeave: () => setTip(null), children: [_jsx("div", { role: "img", "aria-label": chartSummary(chart, locale), dangerouslySetInnerHTML: { __html: svg } }), tip && tip.cx !== undefined ? _jsx("div", { className: "vxs-chart-cross", style: { left: tip.cx }, "aria-hidden": "true" }) : null, tip ? (_jsxs("div", { className: "vxs-chart-tip", style: { left: Math.min(tip.x + 12, width - 180), top: Math.max(4, tip.y - 12) }, "aria-hidden": "true", children: [_jsx("span", { className: "vxs-chart-tip-label", children: chart.labels[tip.i] ?? tip.i + 1 }), (pie ? series.slice(0, 1) : series).map((s, k) => (_jsxs("span", { className: "vxs-chart-tip-row", children: [series.length > 1 ? _jsx("i", { style: { background: `var(--vxc-${k + 1}, ${COLORS[k]})` } }) : null, series.length > 1 ? `${s.name}: ` : '', _jsx("b", { children: fmt(s.values[tip.i] ?? null) })] }, k)))] })) : null] }), chart.caption ? _jsx("figcaption", { className: "vxs-chart-caption", children: chart.caption }) : null, showTable && chart.labels.length ? (_jsxs("details", { className: "vxs-chart-data", children: [_jsx("summary", { children: "Show the numbers" }), _jsx("div", { className: "vxs-chart-table", children: _jsxs("table", { children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: chart.kind === 'kpi' ? 'Period' : '' }), series.map((s, k) => (_jsx("th", { scope: "col", children: s.name }, k)))] }) }), _jsx("tbody", { children: chart.labels.map((l, i) => (_jsxs("tr", { children: [_jsx("th", { scope: "row", children: l }), series.map((s, k) => (_jsx("td", { children: fmt(s.values[i] ?? null) }, k)))] }, i))) })] }) })] })) : null] }));
|
|
44
|
+
}
|