@veroxm/react-sdk 1.8.0 → 1.10.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,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.10.0
4
+
5
+ - A language with nothing saved yet (VeroXM answers the default language's published copy) starts from the page's own
6
+ fallback for that language wherever it has one; the default language fills only the rest, and the panel names the
7
+ source of each field.
8
+ - "Fill empty fields from the page": a button in the panel when a field is empty and the page's fallback has content
9
+ for it, for published slots too. It runs only when clicked (a list emptied on purpose stays empty), and nothing is
10
+ saved until the next edit, publish or close.
11
+ - Saving sends the changed fields from the form and every other field exactly as stored, so a field nobody touched is
12
+ never saved as empty.
13
+ - Media fields show an image the page takes from the site's own files ("Shown from the site's code"), with
14
+ **Import into Media** for users who can manage media: the editor reads the image from the site and adds it to the
15
+ media library, then the field holds its `{ id }`. A fallback image with `id: 0` is not treated as a library item.
16
+ The route handler relays `POST media` (needs a VeroXM server with the editor's media import).
17
+ - Typing on the page into a field with nothing stored starts from the text the page shows; Enter (or leaving) with
18
+ nothing changed is a cancel.
19
+
20
+ ## 1.9.0
21
+
22
+ - The on-page editor starts a slot that was never published from what the page shows: its empty fields (empty text,
23
+ nothing chosen, an empty list) are filled from the slot's `fallback`, and the panel says so ("Filled from the page's
24
+ current content"). Editing one field and publishing then stores the rest of the page's content too, instead of
25
+ empty fields: a list of tabs or cards no longer disappears after the first edit. Media is taken only when it is an
26
+ item of the media library (it has an `id`). A published slot, a field with content and a test variant are never
27
+ filled.
28
+ - `mergeSlotValues(fields, fallback, values, { neverPublished: true })`: an empty list in the draft of a slot never
29
+ published is treated as not set, so the fallback's list shows. `<VeroxmSlot>` in draft mode
30
+ (`@veroxm/react-sdk/next`) passes it. Once a slot is published, an empty list stays empty.
31
+
3
32
  ## 1.8.0
4
33
 
5
34
  - App translations: `const { t, dir, ready } = useTranslations('ar')` reads a locale's whole bundle from VeroXM in one
@@ -1,5 +1,5 @@
1
1
  import { type ReactNode } from 'react';
2
- import { field, type SlotFieldDefs, type SlotInfo, type SlotValues } from './slots-core.js';
2
+ import { field, type SlotFallback, type SlotFieldDefs, type SlotInfo, type SlotValues } from './slots-core.js';
3
3
  export { field };
4
4
  export type { SlotFieldDefs, SlotValues, SlotInfo };
5
5
  /** True while this browser is in an "Edit on page" session. */
@@ -10,7 +10,7 @@ export declare function configureClientSlots(options: {
10
10
  }): void;
11
11
  export interface ClientSlotOptions<F extends SlotFieldDefs> {
12
12
  fields: F;
13
- fallback?: Partial<SlotValues<F>>;
13
+ fallback?: SlotFallback<F>;
14
14
  label?: string;
15
15
  locale?: string;
16
16
  }
package/dist/client.d.ts CHANGED
@@ -1,6 +1,16 @@
1
1
  import { type RequestControl } from '@veroxm/sdk';
2
2
  import { VeroxmCache, type CacheOptions } from './cache.js';
3
3
  import type { CollectionMeta, Entry, EntryConnection, EntriesQueryOptions, MediaView } from './types.js';
4
+ /** A live design system's values (GET /public/v2/design-systems/:slug). */
5
+ export interface DesignSystemTokens {
6
+ slug: string;
7
+ name: string;
8
+ version: number | null;
9
+ hash: string;
10
+ modes: Array<'light' | 'dark' | 'rtl'>;
11
+ tokens: Partial<Record<'light' | 'dark' | 'rtl', Record<string, string>>>;
12
+ own: string[];
13
+ }
4
14
  /** GraphQL variables: any object. */
5
15
  type Variables = object;
6
16
  export interface VeroxmClientOptions {
@@ -85,6 +95,16 @@ export declare class VeroxmClient {
85
95
  }): Promise<Entry<T> | null>;
86
96
  /** A page of entries -- see EntriesQueryOptions for the full filter/sort/pagination vocabulary. */
87
97
  listEntries<T = Record<string, unknown>>(collection: string, options?: EntriesQueryOptions): Promise<EntryConnection<T>>;
98
+ /**
99
+ * A live design system's CSS (`:root` variables named `--vx-color-action` and so on, dark ones under
100
+ * `[data-vx-theme="dark"]`, right-to-left ones under `[dir="rtl"]`), for <VeroxmDesignSystem>. `slug`: one of the
101
+ * tenant's design systems, `"default"` (the project's default, or VeroXM's own) or `"veroxm"`. `null`: no such
102
+ * design system is live.
103
+ */
104
+ getDesignSystemCss(slug?: string, control?: RequestControl): Promise<string | null>;
105
+ /** The same design system as values: each mode's tokens by name, and the names it sets itself (`own`). */
106
+ getDesignSystem(slug?: string, control?: RequestControl): Promise<DesignSystemTokens | null>;
107
+ private designSystemFile;
88
108
  /** A single media item by id. `null` means no media with that id exists on this project. */
89
109
  getMedia(id: number): Promise<MediaView | null>;
90
110
  }
package/dist/client.js CHANGED
@@ -133,6 +133,35 @@ export class VeroxmClient {
133
133
  });
134
134
  return data.entries;
135
135
  }
136
+ /**
137
+ * A live design system's CSS (`:root` variables named `--vx-color-action` and so on, dark ones under
138
+ * `[data-vx-theme="dark"]`, right-to-left ones under `[dir="rtl"]`), for <VeroxmDesignSystem>. `slug`: one of the
139
+ * tenant's design systems, `"default"` (the project's default, or VeroXM's own) or `"veroxm"`. `null`: no such
140
+ * design system is live.
141
+ */
142
+ async getDesignSystemCss(slug = 'default', control = {}) {
143
+ return this.designSystemFile(`${slug}.css`, control, (res) => res.text());
144
+ }
145
+ /** The same design system as values: each mode's tokens by name, and the names it sets itself (`own`). */
146
+ async getDesignSystem(slug = 'default', control = {}) {
147
+ return this.designSystemFile(slug, control, (res) => res.json());
148
+ }
149
+ async designSystemFile(file, control, read) {
150
+ if (!/^[a-z0-9][a-z0-9-]{0,62}(\.css)?$/.test(file))
151
+ throw new Error(`"${file}" is not a design system's slug`);
152
+ const token = (this.getAccessToken ? await this.getAccessToken() : null) || this.apiKey;
153
+ const timeout = control.timeoutMs ?? this.timeoutMs;
154
+ const signals = [control.signal, timeout ? AbortSignal.timeout(timeout) : undefined].filter((x) => !!x);
155
+ const res = await (this.fetchImpl ?? fetch)(`${this.apiBase.replace(/\/$/, '')}/public/v2/design-systems/${file}`, {
156
+ headers: { Authorization: `Bearer ${token}`, Accept: file.endsWith('.css') ? 'text/css' : 'application/json' },
157
+ ...(signals.length ? { signal: signals.length === 1 ? signals[0] : AbortSignal.any(signals) } : {}),
158
+ });
159
+ if (res.status === 404)
160
+ return null;
161
+ if (!res.ok)
162
+ throw new Error(`VeroXM answered ${res.status} for the design system ${file}`);
163
+ return read(res);
164
+ }
136
165
  /** A single media item by id. `null` means no media with that id exists on this project. */
137
166
  async getMedia(id) {
138
167
  const data = await this.request(`query Media($id: Int!) { media(id: $id) { ${MEDIA_FIELDS} } }`, { id });
@@ -0,0 +1,4 @@
1
+ /** @experimental A site building block: it can still change in a minor release (see SDK-STABILITY.md). */
2
+ export declare function VeroxmDesignSystem({ css }: {
3
+ css: string | null | undefined;
4
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,16 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // Design systems: a tenant's brand as CSS variables on the page (--vx-color-action, --vx-radius-control...). Fetch the
3
+ // CSS with client.getDesignSystemCss() (on the server, in a root layout) and render it once:
4
+ //
5
+ // const css = await client.getDesignSystemCss('default');
6
+ // <VeroxmDesignSystem css={css} />
7
+ //
8
+ // VeroXM's site blocks (<VeroxmSiteStyles />) take their colours and corners from it; your own CSS can read the same
9
+ // variables. Dark values apply inside [data-vx-theme="dark"], right-to-left ones inside [dir="rtl"].
10
+ /** @experimental A site building block: it can still change in a minor release (see SDK-STABILITY.md). */
11
+ export function VeroxmDesignSystem({ css }) {
12
+ if (!css)
13
+ return null;
14
+ // As text in a <style> element: a "<" can't end the element early.
15
+ return _jsx("style", { id: "veroxm-design-system", dangerouslySetInnerHTML: { __html: css.replace(/</g, '\\3c ') } });
16
+ }
@@ -218,6 +218,8 @@ export function createEditorHandler(hooks = {}) {
218
218
  if (method === 'PUT' && action === 'slots' && name && verb === 'variants' && /^\d{1,2}$/.test(rest[0] ?? '') && rest.length === 1) {
219
219
  return relay(request, `slots/${encodeURIComponent(name)}/variants/${rest[0]}`, 'PUT');
220
220
  }
221
+ if (method === 'POST' && action === 'media' && !name)
222
+ return relay(request, 'media', 'POST');
221
223
  if (method === 'POST' && action === 'slots' && name && POST_VERBS.has(verb) && !rest.length) {
222
224
  return relay(request, `slots/${encodeURIComponent(name)}/${verb}`, 'POST');
223
225
  }
@@ -3,6 +3,8 @@ export interface InlineEditOptions {
3
3
  max?: number;
4
4
  /** Accessible name while editing, e.g. "Headline". */
5
5
  label: string;
6
+ /** Text to start from when the element shows none (nothing stored: the page's fallback). */
7
+ initialText?: string;
6
8
  /** Where the click landed, to put the caret there. */
7
9
  point?: {
8
10
  x: number;
@@ -11,8 +11,8 @@
11
11
  // ends up holding that same node again, with the new text, before React
12
12
  // re-renders -- so React's next update finds the node it expects.
13
13
  // - One line, plain text: Enter saves, Escape restores the original,
14
- // leaving the element (blur) saves. A field's max length is enforced as
15
- // you type.
14
+ // leaving the element (blur) saves; Enter with nothing changed cancels.
15
+ // A field's max length is enforced as you type.
16
16
  /** Whether an element can be edited in place: a single text node, nothing nested, not inside a button. */
17
17
  export function canEditInline(el) {
18
18
  if (!el || !(el instanceof HTMLElement))
@@ -29,6 +29,10 @@ function plainText(el) {
29
29
  export function startInlineEdit(el, opts) {
30
30
  const node = el.firstChild;
31
31
  const original = node.nodeValue ?? '';
32
+ // Never an empty box when the page has text for it: start from that text.
33
+ if (!original.trim() && opts.initialText)
34
+ node.nodeValue = opts.initialText;
35
+ const start = node.nodeValue ?? '';
32
36
  let finished = false;
33
37
  const prev = {
34
38
  contenteditable: el.getAttribute('contenteditable'),
@@ -97,6 +101,9 @@ export function startInlineEdit(el, opts) {
97
101
  el.removeEventListener('keydown', onKeyDown);
98
102
  el.removeEventListener('blur', onBlur);
99
103
  el.removeEventListener('paste', onPaste);
104
+ // Enter (or leaving) with nothing changed is a cancel: nothing to save.
105
+ if (commit && clamp(plainText(el)) === start)
106
+ commit = false;
100
107
  const text = commit ? clamp(plainText(el)) : original;
101
108
  // Hand React back exactly the node it rendered, holding the final text.
102
109
  node.nodeValue = text;
@@ -13,11 +13,13 @@ export declare const menuOps: {
13
13
  /** Becomes the next item after its parent, one level up. */
14
14
  outdent: (items: SlotMenuItem[], path: Path) => SlotMenuItem[];
15
15
  };
16
- export declare function MenuInput({ name, label, required, depth, value, onChange, onFocus, }: {
16
+ export declare function MenuInput({ name, label, required, depth, icons, value, onChange, onFocus, }: {
17
17
  name: string;
18
18
  label: string;
19
19
  required?: boolean;
20
20
  depth: number;
21
+ /** The icons an item may have (the menu field's), by name. */
22
+ icons?: string[];
21
23
  value: unknown;
22
24
  onChange(v: SlotMenuItem[] | null): void;
23
25
  onFocus(): void;
@@ -4,6 +4,8 @@ import { useId } from 'react';
4
4
  // compact enough for the side panel. Each item has a label, a link and
5
5
  // "new tab"; items move up and down, in under the item above, and out a
6
6
  // level. An item with sub-items may have no link: it just opens them.
7
+ // Each item may also have a badge ("New"), a description and, when the
8
+ // developer declared icons for the menu, an icon.
7
9
  export const MAX_MENU_ITEMS = 100;
8
10
  export function countItems(items) {
9
11
  return items.reduce((n, i) => n + 1 + countItems(i.children ?? []), 0);
@@ -73,7 +75,7 @@ export const menuOps = {
73
75
  return withList(removed, grand, (l) => [...l.slice(0, p + 1), item, ...l.slice(p + 1)]);
74
76
  },
75
77
  };
76
- export function MenuInput({ name, label, required, depth, value, onChange, onFocus, }) {
78
+ export function MenuInput({ name, label, required, depth, icons, value, onChange, onFocus, }) {
77
79
  const id = useId();
78
80
  const items = Array.isArray(value) ? value : [];
79
81
  const total = countItems(items);
@@ -83,7 +85,7 @@ export function MenuInput({ name, label, required, depth, value, onChange, onFoc
83
85
  const level = path.length;
84
86
  const title = item.label.trim() || `item ${i + 1}`;
85
87
  const canIndent = i > 0 && level + depthOf(item) <= depth;
86
- return (_jsxs("li", { className: "vx-menu-item", children: [_jsxs("div", { className: "vx-menu-row", children: [_jsx("input", { type: "text", "data-field": level === 1 && i === 0 ? name : undefined, onFocus: onFocus, value: item.label, maxLength: 80, placeholder: "Label", "aria-label": `Label of ${title}`, onChange: (e) => set(menuOps.update(items, path, { label: e.target.value })) }), _jsx("input", { type: "text", inputMode: "url", onFocus: onFocus, value: item.href, placeholder: item.children?.length ? 'Link (optional)' : '/page or https://…', "aria-label": `Link of ${title}`, onChange: (e) => set(menuOps.update(items, path, { href: e.target.value })) })] }), _jsxs("div", { className: "vx-menu-tools", children: [_jsxs("label", { className: "vx-menu-tab", children: [_jsx("input", { type: "checkbox", checked: !!item.newTab, onChange: (e) => set(menuOps.update(items, path, { newTab: e.target.checked || undefined })) }), "New tab"] }), _jsx("button", { type: "button", className: "vx-mini", disabled: i === 0, "aria-label": `Move ${title} up`, onClick: () => set(menuOps.move(items, path, -1)), children: "\u2191" }), _jsx("button", { type: "button", className: "vx-mini", disabled: i === list.length - 1, "aria-label": `Move ${title} down`, onClick: () => set(menuOps.move(items, path, 1)), children: "\u2193" }), depth > 1 ? (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "vx-mini", disabled: level === 1, "aria-label": `Move ${title} out a level`, onClick: () => set(menuOps.outdent(items, path)), children: "\u2190" }), _jsx("button", { type: "button", className: "vx-mini", disabled: !canIndent, "aria-label": `Move ${title} under the item above`, onClick: () => set(menuOps.indent(items, path)), children: "\u2192" })] })) : null, level < depth ? (_jsx("button", { type: "button", className: "vx-mini", disabled: total >= MAX_MENU_ITEMS, "aria-label": `Add a sub-item under ${title}`, onClick: () => set(menuOps.add(items, path)), children: "+ Sub" })) : null, _jsx("button", { type: "button", className: "vx-mini", "aria-label": `Remove ${title}${item.children?.length ? ' and its sub-items' : ''}`, onClick: () => set(menuOps.remove(items, path)), children: "Remove" })] }), item.children?.length ? _jsx("ul", { className: "vx-menu-list vx-menu-sub", children: rows(item.children, path) }) : null] }, path.join('-')));
88
+ return (_jsxs("li", { className: "vx-menu-item", children: [_jsxs("div", { className: "vx-menu-row", children: [_jsx("input", { type: "text", "data-field": level === 1 && i === 0 ? name : undefined, onFocus: onFocus, value: item.label, maxLength: 80, placeholder: "Label", "aria-label": `Label of ${title}`, onChange: (e) => set(menuOps.update(items, path, { label: e.target.value })) }), _jsx("input", { type: "text", inputMode: "url", onFocus: onFocus, value: item.href, placeholder: item.children?.length ? 'Link (optional)' : '/page or https://…', "aria-label": `Link of ${title}`, onChange: (e) => set(menuOps.update(items, path, { href: e.target.value })) })] }), _jsxs("div", { className: "vx-menu-row", children: [icons?.length ? (_jsxs("select", { "aria-label": `Icon of ${title}`, onFocus: onFocus, value: item.icon ?? '', onChange: (e) => set(menuOps.update(items, path, { icon: e.target.value || undefined })), children: [_jsx("option", { value: "", children: "No icon" }), icons.map((icon) => (_jsx("option", { value: icon, children: icon }, icon)))] })) : null, _jsx("input", { type: "text", onFocus: onFocus, value: item.badge ?? '', maxLength: 24, placeholder: "Badge (optional)", "aria-label": `Badge of ${title}`, onChange: (e) => set(menuOps.update(items, path, { badge: e.target.value || undefined })) }), _jsx("input", { type: "text", onFocus: onFocus, value: item.description ?? '', maxLength: 160, placeholder: "Description (optional)", "aria-label": `Description of ${title}`, onChange: (e) => set(menuOps.update(items, path, { description: e.target.value || undefined })) })] }), _jsxs("div", { className: "vx-menu-tools", children: [_jsxs("label", { className: "vx-menu-tab", children: [_jsx("input", { type: "checkbox", checked: !!item.newTab, onChange: (e) => set(menuOps.update(items, path, { newTab: e.target.checked || undefined })) }), "New tab"] }), _jsx("button", { type: "button", className: "vx-mini", disabled: i === 0, "aria-label": `Move ${title} up`, onClick: () => set(menuOps.move(items, path, -1)), children: "\u2191" }), _jsx("button", { type: "button", className: "vx-mini", disabled: i === list.length - 1, "aria-label": `Move ${title} down`, onClick: () => set(menuOps.move(items, path, 1)), children: "\u2193" }), depth > 1 ? (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "vx-mini", disabled: level === 1, "aria-label": `Move ${title} out a level`, onClick: () => set(menuOps.outdent(items, path)), children: "\u2190" }), _jsx("button", { type: "button", className: "vx-mini", disabled: !canIndent, "aria-label": `Move ${title} under the item above`, onClick: () => set(menuOps.indent(items, path)), children: "\u2192" })] })) : null, level < depth ? (_jsx("button", { type: "button", className: "vx-mini", disabled: total >= MAX_MENU_ITEMS, "aria-label": `Add a sub-item under ${title}`, onClick: () => set(menuOps.add(items, path)), children: "+ Sub" })) : null, _jsx("button", { type: "button", className: "vx-mini", "aria-label": `Remove ${title}${item.children?.length ? ' and its sub-items' : ''}`, onClick: () => set(menuOps.remove(items, path)), children: "Remove" })] }), item.children?.length ? _jsx("ul", { className: "vx-menu-list vx-menu-sub", children: rows(item.children, path) }) : null] }, path.join('-')));
87
89
  });
88
90
  return (_jsxs("fieldset", { className: "vx-field vx-fieldset", "aria-describedby": `${id}-count`, children: [_jsxs("legend", { className: "vx-label", children: [label, required ? _jsx("span", { "aria-hidden": "true", children: " *" }) : null] }), _jsxs("span", { id: `${id}-count`, className: "vx-count", children: [total, " / ", MAX_MENU_ITEMS, " items \u00B7 ", depth === 1 ? 'one level' : `up to ${depth} levels`] }), items.length ? _jsx("ul", { className: "vx-menu-list", children: rows(items, []) }) : _jsx("p", { className: "vx-muted", children: "No items yet: the site shows its own menu." }), _jsx("div", { className: "vx-actions", children: _jsx("button", { type: "button", className: "vx-btn", "data-field": items.length ? undefined : name, onFocus: onFocus, disabled: total >= MAX_MENU_ITEMS, onClick: () => set(menuOps.add(items, [])), children: "Add item" }) })] }));
89
91
  }