@veroxm/react-sdk 0.0.0-stage → 0.1.1
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 +9 -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,21 @@
|
|
|
1
|
+
export declare function safeHref(href: string): boolean;
|
|
2
|
+
/** Rebuilds HTML from the allowlist: other tags are unwrapped (their text kept), attributes dropped except a safe link href. */
|
|
3
|
+
export declare function cleanRichText(html: string): string;
|
|
4
|
+
interface Props {
|
|
5
|
+
id: string;
|
|
6
|
+
value: string;
|
|
7
|
+
onChange(html: string): void;
|
|
8
|
+
onFocus?(): void;
|
|
9
|
+
max?: number;
|
|
10
|
+
required?: boolean;
|
|
11
|
+
labelledBy: string;
|
|
12
|
+
placeholder?: string;
|
|
13
|
+
/** Extra attributes for the editable region (e.g. data-field). */
|
|
14
|
+
regionProps?: Record<string, string>;
|
|
15
|
+
className?: string;
|
|
16
|
+
}
|
|
17
|
+
/** The editor. Styling hooks: .vx-rte, .vx-rte-toolbar, .vx-rte-area (override with your own classes via className). */
|
|
18
|
+
export declare function RichTextInput({ id, value, onChange, onFocus, max, required, labelledBy, placeholder, regionProps, className }: Props): import("react").JSX.Element;
|
|
19
|
+
/** Styles for the editor, using the overlay's vx- tokens. */
|
|
20
|
+
export declare const RICH_TEXT_STYLES = "\n.vx-rte{display:flex;flex-direction:column;gap:4px}\n.vx-rte-toolbar{display:flex;flex-wrap:wrap;gap:2px;border:1px solid #d4d4d8;border-bottom:0;border-radius:8px 8px 0 0;padding:3px;background:#fafafa}\n.vx-rte-btn{appearance:none;border:0;background:transparent;border-radius:6px;padding:3px 7px;font-size:12px;cursor:pointer;min-width:28px;min-height:26px}\n.vx-rte-btn:hover{background:#e4e4e7}\n.vx-rte-btn[aria-pressed=\"true\"]{background:#ede9fe;color:#5b21b6}\n.vx-rte-area{min-height:120px;max-height:320px;overflow:auto;border:1px solid #d4d4d8;border-radius:0 0 8px 8px;padding:8px 10px;background:#fff;line-height:1.5;margin-top:-4px}\n.vx-rte-area:empty::before{content:attr(data-placeholder);color:#a1a1aa}\n.vx-rte-area p,.vx-rte-area ul,.vx-rte-area ol,.vx-rte-area blockquote{margin:0 0 8px}\n.vx-rte-area ul,.vx-rte-area ol{padding-left:22px}\n.vx-rte-area h2{font-size:18px;font-weight:700;margin:4px 0 8px}\n.vx-rte-area h3{font-size:15px;font-weight:700;margin:4px 0 6px}\n.vx-rte-area a{color:#6d28d9;text-decoration:underline}\n.vx-rte-link{border:1px solid #e4e4e7;border-radius:8px;padding:6px 8px}\n.vx-rte-link-row{display:flex;gap:6px}\n.vx-rte-link-row input{flex:1;padding:6px 8px;border:1px solid #d4d4d8;border-radius:8px}\n.vx-rte-error{color:#b91c1c;margin:4px 0 0;font-size:12px}\n.vx-count-over{color:#b91c1c}\n@media (prefers-color-scheme: dark){\n.vx-rte-toolbar{background:#18181b;border-color:#3f3f46}\n.vx-rte-btn:hover{background:#27272a}\n.vx-rte-btn[aria-pressed=\"true\"]{background:#2e1065;color:#ddd6fe}\n.vx-rte-area{background:#09090b;border-color:#3f3f46}\n.vx-rte-area a{color:#c4b5fd}\n.vx-rte-link{border-color:#3f3f46}\n.vx-rte-link-row input{background:#09090b;border-color:#3f3f46}\n.vx-rte-error,.vx-count-over{color:#fca5a5}\n}\n";
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
4
|
+
// A small rich text editor for slot fields declared with field.richText():
|
|
5
|
+
// paragraphs, H2/H3, bold, italic, links and lists -- exactly what VeroXM
|
|
6
|
+
// keeps when it saves (apps/api/src/slots/slot-fields.ts sanitizeRichText),
|
|
7
|
+
// so what an editor sees here is what visitors get. No dependencies: a
|
|
8
|
+
// contentEditable region plus the browser's editing commands, with the
|
|
9
|
+
// output (and anything pasted) cleaned to that allowlist.
|
|
10
|
+
const ALLOWED = new Set(['P', 'BR', 'STRONG', 'EM', 'U', 'S', 'A', 'UL', 'OL', 'LI', 'H2', 'H3', 'H4', 'BLOCKQUOTE', 'SUP', 'SUB']);
|
|
11
|
+
const RENAME = { B: 'STRONG', I: 'EM', DIV: 'P', H1: 'H2', STRIKE: 'S', DEL: 'S' };
|
|
12
|
+
const DROP = new Set(['SCRIPT', 'STYLE', 'IFRAME', 'OBJECT', 'EMBED', 'TEMPLATE', 'NOSCRIPT', 'SVG', 'MATH', 'HEAD', 'TITLE', 'META', 'LINK']);
|
|
13
|
+
export function safeHref(href) {
|
|
14
|
+
return /^(https?:\/\/|mailto:|tel:|\/(?!\/)|#)/i.test(href.trim());
|
|
15
|
+
}
|
|
16
|
+
/** Rebuilds HTML from the allowlist: other tags are unwrapped (their text kept), attributes dropped except a safe link href. */
|
|
17
|
+
export function cleanRichText(html) {
|
|
18
|
+
if (typeof DOMParser === 'undefined')
|
|
19
|
+
return html;
|
|
20
|
+
const doc = new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');
|
|
21
|
+
const out = document.createElement('div');
|
|
22
|
+
const copy = (from, to) => {
|
|
23
|
+
from.childNodes.forEach((child) => {
|
|
24
|
+
if (child.nodeType === Node.TEXT_NODE) {
|
|
25
|
+
to.appendChild(document.createTextNode(child.textContent ?? ''));
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (child.nodeType !== Node.ELEMENT_NODE)
|
|
29
|
+
return;
|
|
30
|
+
const el = child;
|
|
31
|
+
const tag = RENAME[el.tagName] ?? el.tagName;
|
|
32
|
+
if (DROP.has(el.tagName))
|
|
33
|
+
return;
|
|
34
|
+
if (!ALLOWED.has(tag)) {
|
|
35
|
+
copy(el, to); // unwrap, keep the text
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const clean = document.createElement(tag);
|
|
39
|
+
if (tag === 'A') {
|
|
40
|
+
const href = el.getAttribute('href') ?? '';
|
|
41
|
+
if (href && safeHref(href))
|
|
42
|
+
clean.setAttribute('href', href.trim());
|
|
43
|
+
}
|
|
44
|
+
copy(el, clean);
|
|
45
|
+
to.appendChild(clean);
|
|
46
|
+
});
|
|
47
|
+
};
|
|
48
|
+
copy(doc.body, out);
|
|
49
|
+
normaliseBlocks(out);
|
|
50
|
+
// Empty editor leftovers ("<p><br></p>") count as empty.
|
|
51
|
+
return out.textContent?.trim() || out.querySelector('li') ? out.innerHTML.trim() : '';
|
|
52
|
+
}
|
|
53
|
+
const BLOCKS = new Set(['P', 'UL', 'OL', 'H2', 'H3', 'H4', 'BLOCKQUOTE']);
|
|
54
|
+
/** Loose top-level text goes into paragraphs; empty paragraphs and headings go. */
|
|
55
|
+
function normaliseBlocks(root) {
|
|
56
|
+
let run = null;
|
|
57
|
+
for (const child of [...root.childNodes]) {
|
|
58
|
+
const isBlock = child.nodeType === Node.ELEMENT_NODE && BLOCKS.has(child.tagName);
|
|
59
|
+
if (isBlock) {
|
|
60
|
+
run = null;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (child.nodeType === Node.ELEMENT_NODE && child.tagName === 'BR' && !run) {
|
|
64
|
+
child.remove();
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (!run) {
|
|
68
|
+
run = document.createElement('p');
|
|
69
|
+
root.insertBefore(run, child);
|
|
70
|
+
}
|
|
71
|
+
run.appendChild(child);
|
|
72
|
+
}
|
|
73
|
+
root.querySelectorAll('p, h2, h3, h4').forEach((el) => {
|
|
74
|
+
if (!el.textContent?.trim())
|
|
75
|
+
el.remove();
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/** The editor. Styling hooks: .vx-rte, .vx-rte-toolbar, .vx-rte-area (override with your own classes via className). */
|
|
79
|
+
export function RichTextInput({ id, value, onChange, onFocus, max, required, labelledBy, placeholder, regionProps, className }) {
|
|
80
|
+
const areaRef = useRef(null);
|
|
81
|
+
const emitted = useRef(null);
|
|
82
|
+
const savedRange = useRef(null);
|
|
83
|
+
const [active, setActive] = useState({});
|
|
84
|
+
const [linking, setLinking] = useState(false);
|
|
85
|
+
const [href, setHref] = useState('');
|
|
86
|
+
const [linkError, setLinkError] = useState(null);
|
|
87
|
+
const [length, setLength] = useState(value.length);
|
|
88
|
+
// Outside changes (load, discard, restore) replace the content; our own typing doesn't.
|
|
89
|
+
useEffect(() => {
|
|
90
|
+
const el = areaRef.current;
|
|
91
|
+
if (!el || value === emitted.current)
|
|
92
|
+
return;
|
|
93
|
+
el.innerHTML = cleanRichText(value);
|
|
94
|
+
emitted.current = value;
|
|
95
|
+
setLength(value.length);
|
|
96
|
+
}, [value]);
|
|
97
|
+
const emit = useCallback(() => {
|
|
98
|
+
const el = areaRef.current;
|
|
99
|
+
if (!el)
|
|
100
|
+
return;
|
|
101
|
+
const html = cleanRichText(el.innerHTML);
|
|
102
|
+
emitted.current = html;
|
|
103
|
+
setLength(html.length);
|
|
104
|
+
onChange(html);
|
|
105
|
+
}, [onChange]);
|
|
106
|
+
const refreshState = useCallback(() => {
|
|
107
|
+
if (typeof document.queryCommandState !== 'function')
|
|
108
|
+
return;
|
|
109
|
+
const inside = areaRef.current?.contains(document.getSelection()?.anchorNode ?? null);
|
|
110
|
+
if (!inside)
|
|
111
|
+
return;
|
|
112
|
+
const block = String(document.queryCommandValue?.('formatBlock') ?? '').toLowerCase();
|
|
113
|
+
setActive({
|
|
114
|
+
bold: document.queryCommandState('bold'),
|
|
115
|
+
italic: document.queryCommandState('italic'),
|
|
116
|
+
insertUnorderedList: document.queryCommandState('insertUnorderedList'),
|
|
117
|
+
insertOrderedList: document.queryCommandState('insertOrderedList'),
|
|
118
|
+
h2: block === 'h2',
|
|
119
|
+
h3: block === 'h3',
|
|
120
|
+
});
|
|
121
|
+
}, []);
|
|
122
|
+
useEffect(() => {
|
|
123
|
+
document.addEventListener('selectionchange', refreshState);
|
|
124
|
+
return () => document.removeEventListener('selectionchange', refreshState);
|
|
125
|
+
}, [refreshState]);
|
|
126
|
+
const run = (command, arg) => {
|
|
127
|
+
areaRef.current?.focus();
|
|
128
|
+
// New lines become paragraphs, not <div>s.
|
|
129
|
+
document.execCommand?.('defaultParagraphSeparator', false, 'p');
|
|
130
|
+
if (typeof document.execCommand === 'function')
|
|
131
|
+
document.execCommand(command, false, arg);
|
|
132
|
+
emit();
|
|
133
|
+
refreshState();
|
|
134
|
+
};
|
|
135
|
+
const toggleBlock = (tag) => run('formatBlock', active[tag] ? 'p' : tag);
|
|
136
|
+
const startLink = () => {
|
|
137
|
+
const sel = document.getSelection();
|
|
138
|
+
if (sel && sel.rangeCount && areaRef.current?.contains(sel.anchorNode))
|
|
139
|
+
savedRange.current = sel.getRangeAt(0).cloneRange();
|
|
140
|
+
const existing = sel?.anchorNode?.parentElement?.closest('a')?.getAttribute('href') ?? '';
|
|
141
|
+
setHref(existing);
|
|
142
|
+
setLinkError(null);
|
|
143
|
+
setLinking(true);
|
|
144
|
+
};
|
|
145
|
+
const applyLink = () => {
|
|
146
|
+
const url = href.trim();
|
|
147
|
+
if (url && !safeHref(url))
|
|
148
|
+
return setLinkError('Use https://, http://, mailto:, tel:, / or #');
|
|
149
|
+
const sel = document.getSelection();
|
|
150
|
+
areaRef.current?.focus();
|
|
151
|
+
if (savedRange.current && sel) {
|
|
152
|
+
sel.removeAllRanges();
|
|
153
|
+
sel.addRange(savedRange.current);
|
|
154
|
+
}
|
|
155
|
+
if (!url)
|
|
156
|
+
run('unlink');
|
|
157
|
+
else if (sel && sel.isCollapsed)
|
|
158
|
+
run('insertHTML', `<a href="${url.replace(/"/g, '"')}">${url.replace(/[<>&]/g, '')}</a>`);
|
|
159
|
+
else
|
|
160
|
+
run('createLink', url);
|
|
161
|
+
setLinking(false);
|
|
162
|
+
};
|
|
163
|
+
const onPaste = (e) => {
|
|
164
|
+
e.preventDefault();
|
|
165
|
+
const html = e.clipboardData.getData('text/html');
|
|
166
|
+
const text = e.clipboardData.getData('text/plain');
|
|
167
|
+
const clean = html
|
|
168
|
+
? cleanRichText(html)
|
|
169
|
+
: text
|
|
170
|
+
.split(/\n{2,}/)
|
|
171
|
+
.map((p) => `<p>${p.replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' })[c]).replace(/\n/g, '<br>')}</p>`)
|
|
172
|
+
.join('');
|
|
173
|
+
run('insertHTML', clean);
|
|
174
|
+
};
|
|
175
|
+
const onKeyDown = (e) => {
|
|
176
|
+
const mod = e.metaKey || e.ctrlKey;
|
|
177
|
+
if (mod && e.key.toLowerCase() === 'k') {
|
|
178
|
+
e.preventDefault();
|
|
179
|
+
startLink();
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
const button = (key, label, text, onClick, pressed) => (_jsx("button", { type: "button", className: "vx-rte-btn", "aria-label": label, title: label, "aria-pressed": pressed,
|
|
183
|
+
// Keep the selection in the text while clicking the toolbar.
|
|
184
|
+
onMouseDown: (e) => e.preventDefault(), onClick: onClick, children: text }, key));
|
|
185
|
+
const over = max !== undefined && length > max;
|
|
186
|
+
return (_jsxs("div", { className: `vx-rte${className ? ` ${className}` : ''}`, children: [_jsxs("div", { className: "vx-rte-toolbar", role: "toolbar", "aria-label": "Formatting", "aria-controls": id, children: [button('b', 'Bold (Ctrl+B)', _jsx("strong", { children: "B" }), () => run('bold'), active.bold), button('i', 'Italic (Ctrl+I)', _jsx("em", { children: "I" }), () => run('italic'), active.italic), button('h2', 'Heading', 'H2', () => toggleBlock('h2'), active.h2), button('h3', 'Subheading', 'H3', () => toggleBlock('h3'), active.h3), button('ul', 'Bulleted list', '• List', () => run('insertUnorderedList'), active.insertUnorderedList), button('ol', 'Numbered list', '1. List', () => run('insertOrderedList'), active.insertOrderedList), button('a', 'Link (Ctrl+K)', 'Link', startLink), button('x', 'Clear formatting', 'Clear', () => {
|
|
187
|
+
run('removeFormat');
|
|
188
|
+
run('formatBlock', 'p');
|
|
189
|
+
})] }), linking ? (_jsxs("div", { className: "vx-rte-link", children: [_jsx("label", { htmlFor: `${id}-href`, className: "vx-sublabel", children: "Link address (leave empty to remove)" }), _jsxs("div", { className: "vx-rte-link-row", children: [_jsx("input", { id: `${id}-href`, type: "text", inputMode: "url", autoFocus: true, value: href, placeholder: "https://\u2026 or /page", onChange: (e) => setHref(e.target.value), onKeyDown: (e) => {
|
|
190
|
+
if (e.key === 'Enter') {
|
|
191
|
+
e.preventDefault();
|
|
192
|
+
applyLink();
|
|
193
|
+
}
|
|
194
|
+
if (e.key === 'Escape') {
|
|
195
|
+
e.stopPropagation();
|
|
196
|
+
setLinking(false);
|
|
197
|
+
}
|
|
198
|
+
} }), _jsx("button", { type: "button", className: "vx-btn", onClick: applyLink, children: "Apply" })] }), linkError ? _jsx("p", { className: "vx-rte-error", role: "alert", children: linkError }) : null] })) : null, _jsx("div", { ...regionProps, id: id, ref: areaRef, className: "vx-rte-area", contentEditable: true, suppressContentEditableWarning: true, role: "textbox", "aria-multiline": "true", "aria-labelledby": labelledBy, "aria-required": required || undefined, "aria-invalid": over || undefined, "data-placeholder": placeholder, onInput: emit, onBlur: emit, onFocus: () => {
|
|
199
|
+
document.execCommand?.('defaultParagraphSeparator', false, 'p');
|
|
200
|
+
onFocus?.();
|
|
201
|
+
}, onPaste: onPaste, onKeyDown: onKeyDown, onKeyUp: refreshState, onMouseUp: refreshState }), max !== undefined ? (_jsxs("span", { className: `vx-count${over ? ' vx-count-over' : ''}`, children: [length, " / ", max, " characters, including formatting"] })) : null] }));
|
|
202
|
+
}
|
|
203
|
+
/** Styles for the editor, using the overlay's vx- tokens. */
|
|
204
|
+
export const RICH_TEXT_STYLES = `
|
|
205
|
+
.vx-rte{display:flex;flex-direction:column;gap:4px}
|
|
206
|
+
.vx-rte-toolbar{display:flex;flex-wrap:wrap;gap:2px;border:1px solid #d4d4d8;border-bottom:0;border-radius:8px 8px 0 0;padding:3px;background:#fafafa}
|
|
207
|
+
.vx-rte-btn{appearance:none;border:0;background:transparent;border-radius:6px;padding:3px 7px;font-size:12px;cursor:pointer;min-width:28px;min-height:26px}
|
|
208
|
+
.vx-rte-btn:hover{background:#e4e4e7}
|
|
209
|
+
.vx-rte-btn[aria-pressed="true"]{background:#ede9fe;color:#5b21b6}
|
|
210
|
+
.vx-rte-area{min-height:120px;max-height:320px;overflow:auto;border:1px solid #d4d4d8;border-radius:0 0 8px 8px;padding:8px 10px;background:#fff;line-height:1.5;margin-top:-4px}
|
|
211
|
+
.vx-rte-area:empty::before{content:attr(data-placeholder);color:#a1a1aa}
|
|
212
|
+
.vx-rte-area p,.vx-rte-area ul,.vx-rte-area ol,.vx-rte-area blockquote{margin:0 0 8px}
|
|
213
|
+
.vx-rte-area ul,.vx-rte-area ol{padding-left:22px}
|
|
214
|
+
.vx-rte-area h2{font-size:18px;font-weight:700;margin:4px 0 8px}
|
|
215
|
+
.vx-rte-area h3{font-size:15px;font-weight:700;margin:4px 0 6px}
|
|
216
|
+
.vx-rte-area a{color:#6d28d9;text-decoration:underline}
|
|
217
|
+
.vx-rte-link{border:1px solid #e4e4e7;border-radius:8px;padding:6px 8px}
|
|
218
|
+
.vx-rte-link-row{display:flex;gap:6px}
|
|
219
|
+
.vx-rte-link-row input{flex:1;padding:6px 8px;border:1px solid #d4d4d8;border-radius:8px}
|
|
220
|
+
.vx-rte-error{color:#b91c1c;margin:4px 0 0;font-size:12px}
|
|
221
|
+
.vx-count-over{color:#b91c1c}
|
|
222
|
+
@media (prefers-color-scheme: dark){
|
|
223
|
+
.vx-rte-toolbar{background:#18181b;border-color:#3f3f46}
|
|
224
|
+
.vx-rte-btn:hover{background:#27272a}
|
|
225
|
+
.vx-rte-btn[aria-pressed="true"]{background:#2e1065;color:#ddd6fe}
|
|
226
|
+
.vx-rte-area{background:#09090b;border-color:#3f3f46}
|
|
227
|
+
.vx-rte-area a{color:#c4b5fd}
|
|
228
|
+
.vx-rte-link{border-color:#3f3f46}
|
|
229
|
+
.vx-rte-link-row input{background:#09090b;border-color:#3f3f46}
|
|
230
|
+
.vx-rte-error,.vx-count-over{color:#fca5a5}
|
|
231
|
+
}
|
|
232
|
+
`;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { EDITOR_COOKIE, ROUTE_BASE, EDITOR_HEADER } from './constants.js';
|
|
2
|
+
/** Calls VeroXM's on-page editor API with an editor token (server side only). */
|
|
3
|
+
export declare function editorApi(token: string, path: string, init?: RequestInit): Promise<Response>;
|
|
4
|
+
/** A same-site path only ("/pricing?x=1"); anything else becomes "/". */
|
|
5
|
+
export declare function safePath(path: string | null | undefined): string;
|
|
6
|
+
/** The value of one cookie from a Cookie header. */
|
|
7
|
+
export declare function readCookie(header: string | null, name: string): string | undefined;
|
|
8
|
+
/** Seconds until a JWT expires (0 if unreadable or past). Not a signature check -- VeroXM does that. */
|
|
9
|
+
export declare function secondsLeft(token: string, now?: number): number;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { resolveSlotsConfig } from '../slots-core.js';
|
|
2
|
+
export { EDITOR_COOKIE, ROUTE_BASE, EDITOR_HEADER } from './constants.js';
|
|
3
|
+
/** Calls VeroXM's on-page editor API with an editor token (server side only). */
|
|
4
|
+
export async function editorApi(token, path, init = {}) {
|
|
5
|
+
const cfg = resolveSlotsConfig();
|
|
6
|
+
if (!cfg.baseUrl || !cfg.projectId || !cfg.fetch) {
|
|
7
|
+
return new Response(JSON.stringify({ error: 'VEROXM_API_BASE and VEROXM_PROJECT_ID must be set on the site.' }), {
|
|
8
|
+
status: 500,
|
|
9
|
+
headers: { 'Content-Type': 'application/json' },
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
return cfg.fetch(`${cfg.baseUrl}/public/v2/projects/${cfg.projectId}/slot-editor/${path}`, {
|
|
13
|
+
...init,
|
|
14
|
+
cache: 'no-store',
|
|
15
|
+
headers: { ...init.headers, Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
/** A same-site path only ("/pricing?x=1"); anything else becomes "/". */
|
|
19
|
+
export function safePath(path) {
|
|
20
|
+
if (!path || !path.startsWith('/') || path.startsWith('//') || path.includes('\\'))
|
|
21
|
+
return '/';
|
|
22
|
+
return path;
|
|
23
|
+
}
|
|
24
|
+
/** The value of one cookie from a Cookie header. */
|
|
25
|
+
export function readCookie(header, name) {
|
|
26
|
+
for (const part of (header ?? '').split(';')) {
|
|
27
|
+
const i = part.indexOf('=');
|
|
28
|
+
if (i > 0 && part.slice(0, i).trim() === name)
|
|
29
|
+
return decodeURIComponent(part.slice(i + 1).trim());
|
|
30
|
+
}
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
/** Seconds until a JWT expires (0 if unreadable or past). Not a signature check -- VeroXM does that. */
|
|
34
|
+
export function secondsLeft(token, now = Date.now()) {
|
|
35
|
+
try {
|
|
36
|
+
const payload = token.split('.')[1] ?? '';
|
|
37
|
+
const json = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
|
|
38
|
+
return Math.max(0, Math.floor((json.exp ?? 0) - now / 1000));
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return 0;
|
|
42
|
+
}
|
|
43
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown for any GraphQL error response (a non-2xx HTTP status, or a 2xx
|
|
3
|
+
* response whose `errors` array is non-empty) -- wraps graphql-request's
|
|
4
|
+
* own ClientError with a message pulled from the first GraphQL error, the
|
|
5
|
+
* same "surface the server's own message, don't just say 'request
|
|
6
|
+
* failed'" convention @veroxm/sdk's VeroXMApiError follows (see
|
|
7
|
+
* packages/sdk-js/src/errors.ts).
|
|
8
|
+
*/
|
|
9
|
+
export declare class VeroxmGraphQLError extends Error {
|
|
10
|
+
/** The raw GraphQL errors array from the response, if any -- inspect this for a specific error's `extensions.code` (e.g. `QUERY_TOO_COMPLEX`, see apps/api/src/public-api/graphql/complexity.plugin.ts). */
|
|
11
|
+
readonly errors: readonly {
|
|
12
|
+
message: string;
|
|
13
|
+
extensions?: Record<string, unknown>;
|
|
14
|
+
}[];
|
|
15
|
+
/** The HTTP status of the underlying response, when available. */
|
|
16
|
+
readonly status: number | undefined;
|
|
17
|
+
private constructor();
|
|
18
|
+
/** Wraps whatever graphql-request's client.request() threw -- a ClientError for a GraphQL-level failure, or rethrows anything else (a network error, say) unchanged so it isn't misreported as a GraphQL error. */
|
|
19
|
+
static from(cause: unknown): Error;
|
|
20
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { ClientError } from 'graphql-request';
|
|
2
|
+
/**
|
|
3
|
+
* Thrown for any GraphQL error response (a non-2xx HTTP status, or a 2xx
|
|
4
|
+
* response whose `errors` array is non-empty) -- wraps graphql-request's
|
|
5
|
+
* own ClientError with a message pulled from the first GraphQL error, the
|
|
6
|
+
* same "surface the server's own message, don't just say 'request
|
|
7
|
+
* failed'" convention @veroxm/sdk's VeroXMApiError follows (see
|
|
8
|
+
* packages/sdk-js/src/errors.ts).
|
|
9
|
+
*/
|
|
10
|
+
export class VeroxmGraphQLError extends Error {
|
|
11
|
+
constructor(message, errors, status) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = 'VeroxmGraphQLError';
|
|
14
|
+
this.errors = errors;
|
|
15
|
+
this.status = status;
|
|
16
|
+
}
|
|
17
|
+
/** Wraps whatever graphql-request's client.request() threw -- a ClientError for a GraphQL-level failure, or rethrows anything else (a network error, say) unchanged so it isn't misreported as a GraphQL error. */
|
|
18
|
+
static from(cause) {
|
|
19
|
+
if (cause instanceof ClientError) {
|
|
20
|
+
const errors = cause.response?.errors ?? [];
|
|
21
|
+
const message = errors[0]?.message ?? cause.message;
|
|
22
|
+
return new VeroxmGraphQLError(message, errors, cause.response?.status);
|
|
23
|
+
}
|
|
24
|
+
return cause instanceof Error ? cause : new Error(String(cause));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { VeroxmCache } from '../cache.js';
|
|
2
|
+
export interface QueryState<T> {
|
|
3
|
+
data: T | undefined;
|
|
4
|
+
error: Error | undefined;
|
|
5
|
+
/** True only while there is no data at all yet for the current query (first load, or after switching to a key with nothing cached). Never true again once this query has resolved once, even while a background revalidation runs -- see isValidating for that. */
|
|
6
|
+
loading: boolean;
|
|
7
|
+
/** True while a request is in flight for the CURRENT cache key, whether that's the very first load (loading is also true then) or a background revalidation of already-cached data (loading is false then -- `data` stays the last-known-good value throughout, see §5.3). */
|
|
8
|
+
isValidating: boolean;
|
|
9
|
+
/** Re-runs the query immediately, without waiting for a dependency to change -- e.g. a manual "retry"/"refresh" button. */
|
|
10
|
+
refetch: () => void;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Internal cache-aware fetch helper shared by every hook in this
|
|
14
|
+
* directory -- not part of this package's public API (see ../index.ts,
|
|
15
|
+
* which does not export this). Supersedes Phase 3's use-query-state.ts:
|
|
16
|
+
* same loading/error/stale-response bookkeeping, plus §5.3's caching --
|
|
17
|
+
* a cache hit returns immediately (synchronously, on the same render
|
|
18
|
+
* that reads it) and, if stale, triggers a background revalidation
|
|
19
|
+
* rather than a user-visible loading state.
|
|
20
|
+
*/
|
|
21
|
+
export declare function useCachedQuery<T>(cache: VeroxmCache, cacheKey: string, tags: readonly string[], queryFn: () => Promise<T>): QueryState<T>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
2
|
+
/**
|
|
3
|
+
* Internal cache-aware fetch helper shared by every hook in this
|
|
4
|
+
* directory -- not part of this package's public API (see ../index.ts,
|
|
5
|
+
* which does not export this). Supersedes Phase 3's use-query-state.ts:
|
|
6
|
+
* same loading/error/stale-response bookkeeping, plus §5.3's caching --
|
|
7
|
+
* a cache hit returns immediately (synchronously, on the same render
|
|
8
|
+
* that reads it) and, if stale, triggers a background revalidation
|
|
9
|
+
* rather than a user-visible loading state.
|
|
10
|
+
*/
|
|
11
|
+
export function useCachedQuery(cache, cacheKey, tags, queryFn) {
|
|
12
|
+
const [data, setData] = useState(() => cache.get(cacheKey));
|
|
13
|
+
const [error, setError] = useState(undefined);
|
|
14
|
+
const [isValidating, setIsValidating] = useState(false);
|
|
15
|
+
// Guards against a slow, now-stale request overwriting a newer one's
|
|
16
|
+
// result if the cache key changes again (or refetch() is called again)
|
|
17
|
+
// before the first resolves.
|
|
18
|
+
const requestId = useRef(0);
|
|
19
|
+
const run = useCallback(() => {
|
|
20
|
+
const id = ++requestId.current;
|
|
21
|
+
setIsValidating(true);
|
|
22
|
+
setError(undefined);
|
|
23
|
+
cache.dedupe(cacheKey, queryFn).then((result) => {
|
|
24
|
+
if (id !== requestId.current)
|
|
25
|
+
return;
|
|
26
|
+
cache.set(cacheKey, result, tags);
|
|
27
|
+
setData(result);
|
|
28
|
+
setIsValidating(false);
|
|
29
|
+
}, (err) => {
|
|
30
|
+
if (id !== requestId.current)
|
|
31
|
+
return;
|
|
32
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
33
|
+
setIsValidating(false);
|
|
34
|
+
});
|
|
35
|
+
// deps is caller-controlled via the closure below, not this hook's
|
|
36
|
+
// business -- see use-query-state.ts's Phase 3 precedent for the
|
|
37
|
+
// same intentionally-non-exhaustive pattern.
|
|
38
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
39
|
+
}, [cache, cacheKey, queryFn]);
|
|
40
|
+
useEffect(() => {
|
|
41
|
+
// Read (and apply) whatever this NEW key's cache holds immediately,
|
|
42
|
+
// rather than leaving the previous key's `data` on screen -- without
|
|
43
|
+
// this, switching e.g. useEntry(..., 1) to useEntry(..., 2) would
|
|
44
|
+
// show entry 1's data mislabeled as "loaded" while entry 2 is still
|
|
45
|
+
// in flight.
|
|
46
|
+
const cached = cache.get(cacheKey);
|
|
47
|
+
setData(cached);
|
|
48
|
+
if (cached === undefined || cache.isStale(cacheKey))
|
|
49
|
+
run();
|
|
50
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
51
|
+
}, [cacheKey]);
|
|
52
|
+
return {
|
|
53
|
+
data,
|
|
54
|
+
error,
|
|
55
|
+
loading: data === undefined && isValidating,
|
|
56
|
+
isValidating,
|
|
57
|
+
refetch: run,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type QueryState } from './use-cached-query.js';
|
|
2
|
+
import type { CollectionMeta } from '../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* A collection's field list (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
|
|
5
|
+
* §5.2) -- build dynamic forms/renderers against a collection without
|
|
6
|
+
* hardcoding its shape, the same reflection use case the dashboard's own
|
|
7
|
+
* Field Manager exists for. `data` is `null` (once `loading` is false)
|
|
8
|
+
* when no collection with that slug exists on this project.
|
|
9
|
+
*/
|
|
10
|
+
export declare function useCollection(slug: string): QueryState<CollectionMeta | null>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { useVeroxmClient } from '../provider.js';
|
|
2
|
+
import { useCachedQuery } from './use-cached-query.js';
|
|
3
|
+
import { collectionKey, collectionTag } from '../query-keys.js';
|
|
4
|
+
/**
|
|
5
|
+
* A collection's field list (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
|
|
6
|
+
* §5.2) -- build dynamic forms/renderers against a collection without
|
|
7
|
+
* hardcoding its shape, the same reflection use case the dashboard's own
|
|
8
|
+
* Field Manager exists for. `data` is `null` (once `loading` is false)
|
|
9
|
+
* when no collection with that slug exists on this project.
|
|
10
|
+
*/
|
|
11
|
+
export function useCollection(slug) {
|
|
12
|
+
const client = useVeroxmClient();
|
|
13
|
+
return useCachedQuery(client.cache, collectionKey(slug), [collectionTag(slug)], () => client.getCollection(slug));
|
|
14
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type QueryState } from './use-cached-query.js';
|
|
2
|
+
import type { EntriesQueryOptions, EntryConnection } from '../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* A page of entries (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md §5.2)
|
|
5
|
+
* -- mirrors ListOptions from @veroxm/sdk/the REST v2 API (see
|
|
6
|
+
* ../types.ts's EntriesQueryOptions), so porting REST-based fetching code
|
|
7
|
+
* to this hook is mostly a name-and-shape swap, not a rewrite.
|
|
8
|
+
*
|
|
9
|
+
* `options` is compared by VALUE (via a stable JSON key), not by
|
|
10
|
+
* reference -- pass a fresh object literal on every render, same as any
|
|
11
|
+
* other data-fetching hook; you don't need to useMemo() it yourself.
|
|
12
|
+
*
|
|
13
|
+
* Respects <VeroxmPreviewProvider>'s draft mode: when active AND you
|
|
14
|
+
* didn't pass an explicit `state`, this hook requests `state:
|
|
15
|
+
* 'only_draft'` instead of the default published-only (§5.4). An
|
|
16
|
+
* explicit `state` you pass always wins over draft mode.
|
|
17
|
+
*/
|
|
18
|
+
export declare function useEntries<T = Record<string, unknown>>(collection: string, options?: EntriesQueryOptions): QueryState<EntryConnection<T>>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { useVeroxmClient } from '../provider.js';
|
|
2
|
+
import { useDraftMode } from '../preview.js';
|
|
3
|
+
import { useCachedQuery } from './use-cached-query.js';
|
|
4
|
+
import { entriesKey, entryTags } from '../query-keys.js';
|
|
5
|
+
/**
|
|
6
|
+
* A page of entries (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md §5.2)
|
|
7
|
+
* -- mirrors ListOptions from @veroxm/sdk/the REST v2 API (see
|
|
8
|
+
* ../types.ts's EntriesQueryOptions), so porting REST-based fetching code
|
|
9
|
+
* to this hook is mostly a name-and-shape swap, not a rewrite.
|
|
10
|
+
*
|
|
11
|
+
* `options` is compared by VALUE (via a stable JSON key), not by
|
|
12
|
+
* reference -- pass a fresh object literal on every render, same as any
|
|
13
|
+
* other data-fetching hook; you don't need to useMemo() it yourself.
|
|
14
|
+
*
|
|
15
|
+
* Respects <VeroxmPreviewProvider>'s draft mode: when active AND you
|
|
16
|
+
* didn't pass an explicit `state`, this hook requests `state:
|
|
17
|
+
* 'only_draft'` instead of the default published-only (§5.4). An
|
|
18
|
+
* explicit `state` you pass always wins over draft mode.
|
|
19
|
+
*/
|
|
20
|
+
export function useEntries(collection, options = {}) {
|
|
21
|
+
const client = useVeroxmClient();
|
|
22
|
+
const { isDraftMode } = useDraftMode();
|
|
23
|
+
const effectiveOptions = options.state === undefined && isDraftMode ? { ...options, state: 'only_draft' } : options;
|
|
24
|
+
return useCachedQuery(client.cache, entriesKey(collection, effectiveOptions), entryTags(collection, effectiveOptions.locale), () => client.listEntries(collection, effectiveOptions));
|
|
25
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type QueryState } from './use-cached-query.js';
|
|
2
|
+
import type { Entry } from '../types.js';
|
|
3
|
+
export interface UseEntryOptions {
|
|
4
|
+
/** Include created_at/updated_at/published_at on the returned entry. */
|
|
5
|
+
timestamps?: boolean;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* A single entry by id (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
|
|
9
|
+
* §5.2). `data` is `null` (once `loading` is false) when no entry with
|
|
10
|
+
* that id exists in this collection -- see VeroxmClient.getEntry()'s own
|
|
11
|
+
* comment for why that's not an error.
|
|
12
|
+
*
|
|
13
|
+
* Unlike useEntries(), this hook does NOT respect
|
|
14
|
+
* <VeroxmPreviewProvider>'s draft mode -- the underlying `entry` GraphQL
|
|
15
|
+
* query takes no `state` argument at all and only ever resolves a
|
|
16
|
+
* PUBLISHED row (same restriction packages/sdk-js's ContentResource.get()
|
|
17
|
+
* documents for the REST API). To preview a specific unpublished entry,
|
|
18
|
+
* use useEntries() with `state: 'only_draft'` plus a `where` filter that
|
|
19
|
+
* identifies it (e.g. by `slug`) instead.
|
|
20
|
+
*/
|
|
21
|
+
export declare function useEntry<T = Record<string, unknown>>(collection: string, id: number, options?: UseEntryOptions): QueryState<Entry<T> | null>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { useVeroxmClient } from '../provider.js';
|
|
2
|
+
import { useCachedQuery } from './use-cached-query.js';
|
|
3
|
+
import { entryKey, entryTags } from '../query-keys.js';
|
|
4
|
+
/**
|
|
5
|
+
* A single entry by id (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
|
|
6
|
+
* §5.2). `data` is `null` (once `loading` is false) when no entry with
|
|
7
|
+
* that id exists in this collection -- see VeroxmClient.getEntry()'s own
|
|
8
|
+
* comment for why that's not an error.
|
|
9
|
+
*
|
|
10
|
+
* Unlike useEntries(), this hook does NOT respect
|
|
11
|
+
* <VeroxmPreviewProvider>'s draft mode -- the underlying `entry` GraphQL
|
|
12
|
+
* query takes no `state` argument at all and only ever resolves a
|
|
13
|
+
* PUBLISHED row (same restriction packages/sdk-js's ContentResource.get()
|
|
14
|
+
* documents for the REST API). To preview a specific unpublished entry,
|
|
15
|
+
* use useEntries() with `state: 'only_draft'` plus a `where` filter that
|
|
16
|
+
* identifies it (e.g. by `slug`) instead.
|
|
17
|
+
*/
|
|
18
|
+
export function useEntry(collection, id, options = {}) {
|
|
19
|
+
const client = useVeroxmClient();
|
|
20
|
+
const { timestamps = false } = options;
|
|
21
|
+
return useCachedQuery(client.cache, entryKey(collection, id, timestamps), entryTags(collection, undefined), () => client.getEntry(collection, id, { timestamps }));
|
|
22
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type QueryState } from './use-cached-query.js';
|
|
2
|
+
import type { MediaView } from '../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* A single media item by id (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
|
|
5
|
+
* §5.2). `data` is `null` (once `loading` is false) when no media with
|
|
6
|
+
* that id exists on this project. Pairs with <VeroxmImage> (§5.6), which
|
|
7
|
+
* consumes this same shape.
|
|
8
|
+
*/
|
|
9
|
+
export declare function useMedia(id: number): QueryState<MediaView | null>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { useVeroxmClient } from '../provider.js';
|
|
2
|
+
import { useCachedQuery } from './use-cached-query.js';
|
|
3
|
+
import { mediaKey, mediaTag } from '../query-keys.js';
|
|
4
|
+
/**
|
|
5
|
+
* A single media item by id (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
|
|
6
|
+
* §5.2). `data` is `null` (once `loading` is false) when no media with
|
|
7
|
+
* that id exists on this project. Pairs with <VeroxmImage> (§5.6), which
|
|
8
|
+
* consumes this same shape.
|
|
9
|
+
*/
|
|
10
|
+
export function useMedia(id) {
|
|
11
|
+
const client = useVeroxmClient();
|
|
12
|
+
return useCachedQuery(client.cache, mediaKey(id), [mediaTag(id)], () => client.getMedia(id));
|
|
13
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ReactElement, ReactNode } from 'react';
|
|
2
|
+
import type { VeroxmHydrationEntry } from './ssr.js';
|
|
3
|
+
export interface VeroxmHydrationBoundaryProps {
|
|
4
|
+
/** One or more server-fetched results to seed this subtree's cache with -- pass the `hydration` value each fetchX() helper in ./ssr.ts returns (an array when a page made more than one server-side fetch). */
|
|
5
|
+
state: VeroxmHydrationEntry | VeroxmHydrationEntry[];
|
|
6
|
+
children: ReactNode;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Seeds the nearest <VeroxmProvider>'s cache with already-fetched data
|
|
10
|
+
* BEFORE this subtree's own hooks (§5.2) mount, so a hook whose query
|
|
11
|
+
* matches one of `state`'s keys sees it as already-fresh and skips an
|
|
12
|
+
* immediate client-side refetch (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-
|
|
13
|
+
* PLAN.md §5.5) -- the "no double-fetch" piece of SSR support. Typical
|
|
14
|
+
* Next.js usage: fetch server-side with ./ssr.ts's helpers, pass the
|
|
15
|
+
* data down as normal props/RSC payload for your own rendering, AND pass
|
|
16
|
+
* each result's `hydration` here so the client-side useEntries()/
|
|
17
|
+
* useEntry()/etc. for that same query doesn't re-fetch on mount:
|
|
18
|
+
*
|
|
19
|
+
* ```tsx
|
|
20
|
+
* const { data, hydration } = await fetchEntries(client, 'posts');
|
|
21
|
+
* return (
|
|
22
|
+
* <VeroxmHydrationBoundary state={hydration}>
|
|
23
|
+
* <PostsList initialPosts={data} />
|
|
24
|
+
* </VeroxmHydrationBoundary>
|
|
25
|
+
* );
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* Seeding happens synchronously during render (not inside a useEffect),
|
|
29
|
+
* so it's in place before any descendant hook's own mount-time effect
|
|
30
|
+
* runs. Seeding is idempotent and cheap, so this runs unconditionally on
|
|
31
|
+
* every render, not just the first -- a re-render with the same
|
|
32
|
+
* server-fetched props just means "this data is still fresh", which is
|
|
33
|
+
* exactly what it should mean.
|
|
34
|
+
*/
|
|
35
|
+
export declare function VeroxmHydrationBoundary(props: VeroxmHydrationBoundaryProps): ReactElement;
|