@veroxm/react-sdk 1.9.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,22 @@
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
+
3
20
  ## 1.9.0
4
21
 
5
22
  - The on-page editor starts a slot that was never published from what the page shows: its empty fields (empty text,
@@ -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;
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
- import { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';
3
+ import { createContext, useCallback, useContext, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';
4
4
  import { createPortal } from 'react-dom';
5
5
  import { EDITOR_HEADER, PREVIEW_COOKIE, ROUTE_BASE } from './constants.js';
6
6
  import { RICH_TEXT_STYLES, RichTextInput } from './rich-text.js';
@@ -9,7 +9,7 @@ import { parseVideoUrl } from '../site/video.js';
9
9
  import { parseMapLink } from '../site/map-math.js';
10
10
  import { CHART_KINDS, chartTableText, parseChartTable } from '../site/chart.js';
11
11
  import { canEditInline, startInlineEdit } from './inline.js';
12
- import { readFallback, seedFromFallback } from './seed.js';
12
+ import { fallbackImage, isEmptyValue, readFallback, sameSiteImage, seedFromFallback } from './seed.js';
13
13
  function asComponentValue(v) {
14
14
  return v && typeof v === 'object' && !Array.isArray(v) && typeof v.component === 'string' ? v : null;
15
15
  }
@@ -91,6 +91,20 @@ function toPayload(fields, values) {
91
91
  }
92
92
  return out;
93
93
  }
94
+ /** What the panel says after starting a slot from the page: which fields came from where. */
95
+ function seedNotice(s, seeded, locale) {
96
+ const label = (f) => s.fields[f]?.label ?? f;
97
+ const fromPage = seeded.map(label).join(', ');
98
+ if (!s.inherited)
99
+ return `Filled from the page’s current content (${fromPage}). Change what you need, then publish.`;
100
+ const rest = Object.keys(s.fields).filter((f) => !seeded.includes(f) && !isEmptyValue(s.values[f]));
101
+ const lang = locale ? ` ${locale}` : '';
102
+ return rest.length
103
+ ? `Nothing saved in${lang} yet. From this page’s${lang} content: ${fromPage}. From the default language’s published copy: ${rest.map(label).join(', ')}.`
104
+ : `Nothing saved in${lang} yet. Filled from this page’s${lang} content (${fromPage}). Change what you need, then publish.`;
105
+ }
106
+ /** What the open panel may do beyond editing (read deep inside the form, by the image fields). */
107
+ const PanelCaps = createContext({ canUploadMedia: false });
94
108
  // -------------------------------------------------------------- singleton
95
109
  const owners = [];
96
110
  const ownerListeners = new Set();
@@ -327,7 +341,7 @@ function Overlay({ onChange, tools }) {
327
341
  const hoverRect = hover && hover !== openEl ? rectOf(hover) : null;
328
342
  const openRect = rectOf(openEl);
329
343
  const fieldRect = openEl && highlightField ? rectOf(openEl.querySelector(`[data-veroxm-field="${CSS.escape(highlightField)}"]`)) : null;
330
- return (_jsxs("div", { ref: rootRef, className: "vx-root", "data-veroxm-overlay": "", children: [_jsx("style", { children: STYLES + RICH_TEXT_STYLES + MENU_STYLES }), hoverRect && _jsx(Outline, { rect: hoverRect, label: hover?.getAttribute('data-veroxm-label') || hover?.getAttribute('data-veroxm-slot') || '' }), openRect && _jsx(Outline, { rect: openRect, active: true }), fieldRect && !inlineHint && _jsx(Outline, { rect: fieldRect, field: true }), inlineHint ? _jsx(InlineHintBar, { hint: inlineHint }) : null, open && session && !ended && (_jsx(SlotPanel, { slot: open, canPublish: session.canPublish, canManageTests: session.canManageTests ?? false, dashboardUrl: session.dashboardUrl ?? null, onClose: () => {
344
+ return (_jsxs("div", { ref: rootRef, className: "vx-root", "data-veroxm-overlay": "", children: [_jsx("style", { children: STYLES + RICH_TEXT_STYLES + MENU_STYLES }), hoverRect && _jsx(Outline, { rect: hoverRect, label: hover?.getAttribute('data-veroxm-label') || hover?.getAttribute('data-veroxm-slot') || '' }), openRect && _jsx(Outline, { rect: openRect, active: true }), fieldRect && !inlineHint && _jsx(Outline, { rect: fieldRect, field: true }), inlineHint ? _jsx(InlineHintBar, { hint: inlineHint }) : null, open && session && !ended && (_jsx(SlotPanel, { slot: open, canPublish: session.canPublish, canManageTests: session.canManageTests ?? false, canUploadMedia: session.canUploadMedia ?? false, dashboardUrl: session.dashboardUrl ?? null, onClose: () => {
331
345
  setOpen(null);
332
346
  setHighlightField(null);
333
347
  }, onFieldFocus: setHighlightField, onSessionError: onSessionError, onChange: onChange, onInline: setInlineHint }, `${open.name}|${open.locale}`)), listOpen && (_jsx(SlotList, { onPick: (s) => {
@@ -362,7 +376,7 @@ function SlotList({ onPick, onClose }) {
362
376
  }, children: [_jsx("p", { className: "vx-list-title", children: "Slots on this page" }), slots.length === 0 ? (_jsx("p", { className: "vx-muted", children: "No slots are visible on this page." })) : (_jsx("ul", { children: slots.map((s, i) => (_jsx("li", { children: _jsxs("button", { type: "button", ref: i === 0 ? firstRef : undefined, onClick: () => onPick(s), children: [_jsx("span", { children: s.label }), s.label !== s.name ? _jsx("code", { children: s.name }) : null, s.locale ? _jsxs("span", { className: "vx-muted", children: [" \u00B7 ", s.locale] }) : null] }) }, `${s.name}|${s.locale}`))) }))] }));
363
377
  }
364
378
  const AUTOSAVE_MS = 800;
365
- function SlotPanel({ slot, canPublish, canManageTests, dashboardUrl, onClose, onFieldFocus, onSessionError, onChange, onInline, }) {
379
+ function SlotPanel({ slot, canPublish, canManageTests, canUploadMedia = false, dashboardUrl, onClose, onFieldFocus, onSessionError, onChange, onInline, }) {
366
380
  const titleId = useId();
367
381
  const panelRef = useRef(null);
368
382
  const returnFocus = useRef(typeof document !== 'undefined' ? document.activeElement : null);
@@ -378,9 +392,13 @@ function SlotPanel({ slot, canPublish, canManageTests, dashboardUrl, onClose, on
378
392
  const timer = useRef(null);
379
393
  const inlineRef = useRef(null);
380
394
  const valuesRef = useRef({});
395
+ const shownRef = useRef({});
381
396
  const latest = useRef(null);
382
397
  // Seeding from the page's fallback happens once per opening, for a slot never published.
383
398
  const seededOnce = useRef(false);
399
+ // Fields changed in this panel (typed, filled from the page). A save sends these from the form and every other
400
+ // field exactly as stored, so a field nobody touched is never written as an empty value.
401
+ const touched = useRef(new Set());
384
402
  const apply = useCallback((next) => {
385
403
  if (!next)
386
404
  return;
@@ -411,13 +429,19 @@ function SlotPanel({ slot, canPublish, canManageTests, dashboardUrl, onClose, on
411
429
  // Never published: start from what the page shows now (its fallback), so the first save stores the real
412
430
  // content instead of empty fields. Not for a test variant (it stores only differences), and never over a
413
431
  // field with stored content.
432
+ // A language with nothing saved yet comes back with the default language's copy: the page's own copy for
433
+ // this language wins wherever it has one, the default language fills the rest.
414
434
  if (position === 0 && !s.version && !seededOnce.current) {
415
435
  seededOnce.current = true;
416
- const { values: seededValues, seeded } = seedFromFallback(s.fields, s.values, readFallback(slotElement(slot.name, slot.locale)));
436
+ const { values: seededValues, seeded } = seedFromFallback(s.fields, s.values, readFallback(slotElement(slot.name, slot.locale)), {
437
+ replace: s.inherited,
438
+ });
417
439
  if (seeded.length) {
440
+ for (const f of seeded)
441
+ touched.current.add(f);
418
442
  setValues(seededValues);
419
443
  latest.current = seededValues;
420
- setNotice('Filled from the page’s current content. Change what you need, then publish.');
444
+ setNotice(seedNotice(s, seeded, res.locale));
421
445
  }
422
446
  }
423
447
  }
@@ -471,7 +495,10 @@ function SlotPanel({ slot, canPublish, canManageTests, dashboardUrl, onClose, on
471
495
  onChange();
472
496
  return true;
473
497
  }
474
- const next = await call(slotPath(slot.name, locale), { method: 'PUT', body: { values: toPayload(data.fields, pending) } });
498
+ // Changed fields from the form; every other field exactly as stored (left out when nothing is stored).
499
+ const stored = data.values;
500
+ const merged = Object.fromEntries(Object.keys(data.fields).map((k) => [k, touched.current.has(k) ? pending[k] : stored[k]]));
501
+ const next = await call(slotPath(slot.name, locale), { method: 'PUT', body: { values: toPayload(data.fields, merged) } });
475
502
  setData(next);
476
503
  setSave({ kind: 'saved', at: new Date() });
477
504
  // While typing on the page the page already shows the text; re-render when done.
@@ -494,6 +521,7 @@ function SlotPanel({ slot, canPublish, canManageTests, dashboardUrl, onClose, on
494
521
  const change = (field, value) => {
495
522
  setNotice(null);
496
523
  setConfirmDiscard(false);
524
+ touched.current.add(field);
497
525
  setValues((prev) => {
498
526
  const next = { ...prev, [field]: value };
499
527
  latest.current = next;
@@ -516,6 +544,9 @@ function SlotPanel({ slot, canPublish, canManageTests, dashboardUrl, onClose, on
516
544
  if (target && def?.type === 'text' && target.el.isConnected && canEditInline(target.el)) {
517
545
  inlineRef.current?.end(true);
518
546
  const before = valuesRef.current[target.field];
547
+ const wasTouched = touched.current.has(target.field);
548
+ // Nothing stored: start from the text the page shows (its fallback), not an empty box.
549
+ const startText = isEmptyValue(before) && typeof shownRef.current[target.field] === 'string' ? shownRef.current[target.field] : undefined;
519
550
  let typed = false;
520
551
  const label = def.label ?? target.field;
521
552
  onFieldFocus(target.field);
@@ -524,6 +555,7 @@ function SlotPanel({ slot, canPublish, canManageTests, dashboardUrl, onClose, on
524
555
  label,
525
556
  max: def.max,
526
557
  point: target.point,
558
+ initialText: startText,
527
559
  onInput: (text) => {
528
560
  typed = true;
529
561
  changeRef.current(target.field, text);
@@ -534,7 +566,16 @@ function SlotPanel({ slot, canPublish, canManageTests, dashboardUrl, onClose, on
534
566
  onInline(null);
535
567
  if (!typed)
536
568
  return;
537
- changeRef.current(target.field, committed ? text : before);
569
+ if (!committed) {
570
+ // Cancelled: back to what was there, and the field counts as untouched again if it was.
571
+ setValues((prev) => ({ ...prev, [target.field]: before }));
572
+ if (latest.current)
573
+ latest.current = { ...latest.current, [target.field]: before };
574
+ if (!wasTouched)
575
+ touched.current.delete(target.field);
576
+ return;
577
+ }
578
+ changeRef.current(target.field, text);
538
579
  void flushRef.current().then(() => onChange());
539
580
  },
540
581
  });
@@ -608,59 +649,77 @@ function SlotPanel({ slot, canPublish, canManageTests, dashboardUrl, onClose, on
608
649
  };
609
650
  // The page's own fallback copy, so empty fields show what visitors see now.
610
651
  const shown = readShown(slot.name, slot.locale);
652
+ shownRef.current = shown;
653
+ const fallback = readFallback(slotElement(slot.name, slot.locale));
654
+ // "Fill empty fields from the page": only when asked, never by itself on a published slot (a list emptied on
655
+ // purpose stays empty). Nothing is saved until the next edit, publish or close.
656
+ const fillable = data && variant === 0 ? seedFromFallback(data.fields, values, fallback).seeded : [];
657
+ const fillFromPage = () => {
658
+ if (!data)
659
+ return;
660
+ const { values: next, seeded } = seedFromFallback(data.fields, values, fallback);
661
+ if (!seeded.length)
662
+ return;
663
+ for (const f of seeded)
664
+ touched.current.add(f);
665
+ setValues(next);
666
+ latest.current = next;
667
+ setConfirmDiscard(false);
668
+ setNotice(`Filled ${seeded.map((f) => data.fields[f]?.label ?? f).join(', ')} from the page. Change what you need, then publish.`);
669
+ };
611
670
  const dirty = Boolean(data?.unpublishedChanges) || save.kind === 'saving' || latest.current !== null;
612
671
  const title = data?.label || slot.name;
613
672
  const approval = data?.approval ?? null;
614
- return (_jsxs("div", { ref: panelRef, className: "vx-panel", role: "dialog", "aria-modal": "false", "aria-labelledby": titleId, onKeyDown: (e) => {
615
- if (e.key === 'Escape') {
616
- e.stopPropagation();
617
- close();
618
- }
619
- }, children: [_jsxs("div", { className: "vx-panel-head", children: [_jsxs("div", { children: [_jsx("h2", { id: titleId, children: title }), _jsxs("p", { className: "vx-muted", children: [title !== slot.name ? _jsx("code", { children: slot.name }) : null, locale ? _jsxs("span", { children: [" \u00B7 ", locale] }) : null, data ? _jsxs("span", { children: [" \u00B7 ", data.version ? `v${data.version} live` : 'never published'] }) : null] })] }), _jsx("button", { type: "button", className: "vx-icon", "aria-label": "Close", onClick: close, children: "\u00D7" })] }), _jsxs("div", { className: "vx-panel-body", children: [loadError ? _jsx("p", { role: "alert", children: loadError }) : null, !data && !loadError ? _jsx("p", { className: "vx-muted", children: "Loading\u2026" }) : null, data?.test ? (_jsxs("div", { className: "vx-test", children: [_jsxs("p", { className: "vx-test-title", children: [TEST_STATUS[data.test.status] ?? 'Test', ": ", data.test.name] }), _jsx("div", { className: "vx-tabs", role: "tablist", "aria-label": "Version to show and edit", onKeyDown: (e) => {
620
- // Arrow keys move between versions (one tab stop for the whole list).
621
- const order = data.test.variants.map((v) => v.position);
622
- const at = order.indexOf(variant);
623
- const next = e.key === 'ArrowRight' || e.key === 'ArrowDown'
624
- ? order[(at + 1) % order.length]
625
- : e.key === 'ArrowLeft' || e.key === 'ArrowUp'
626
- ? order[(at - 1 + order.length) % order.length]
627
- : e.key === 'Home'
628
- ? order[0]
629
- : e.key === 'End'
630
- ? order[order.length - 1]
631
- : undefined;
632
- if (next === undefined)
633
- return;
634
- e.preventDefault();
635
- void selectVariant(next);
636
- e.currentTarget.querySelector(`[data-position="${next}"]`)?.focus();
637
- }, children: data.test.variants.map((v) => (_jsx("button", { type: "button", role: "tab", "data-position": v.position, "aria-selected": variant === v.position, tabIndex: variant === v.position ? 0 : -1, className: "vx-tab", onClick: () => void selectVariant(v.position), children: v.isControl ? 'Published' : v.label }, v.position))) }), variant > 0 ? (_jsx("p", { className: "vx-muted", children: data.test.editable && canManageTests
638
- ? 'The page shows this variant. Edits change only this variant; empty fields use the published version.'
639
- : data.test.editable
640
- ? 'The page shows this variant. Editing variants needs permission to manage experiments.'
641
- : 'The page shows this variant. Variants can’t change once the test has started.' })) : null] })) : null, data?.inherited && locale ? (_jsxs("p", { className: "vx-note", children: ["Nothing saved in ", locale, " yet; you\u2019re starting from the default language\u2019s published copy."] })) : null, data
642
- ? (variant > 0 && !(data.test?.editable && canManageTests) ? [] : Object.entries(data.fields)).map(([name, def]) => (_jsx(FieldInput, { name: name, def: def, value: values[name], shown: shown[name], onChange: (v) => change(name, v), onFocus: () => onFieldFocus(name) }, name)))
643
- : null] }), _jsxs("div", { className: "vx-panel-foot", children: [_jsx("p", { className: "vx-status", role: "status", "aria-live": "polite", children: save.kind === 'saving'
644
- ? variant > 0
645
- ? 'Saving variant…'
646
- : 'Saving draft…'
647
- : save.kind === 'saved'
673
+ return (_jsx(PanelCaps.Provider, { value: { canUploadMedia }, children: _jsxs("div", { ref: panelRef, className: "vx-panel", role: "dialog", "aria-modal": "false", "aria-labelledby": titleId, onKeyDown: (e) => {
674
+ if (e.key === 'Escape') {
675
+ e.stopPropagation();
676
+ close();
677
+ }
678
+ }, children: [_jsxs("div", { className: "vx-panel-head", children: [_jsxs("div", { children: [_jsx("h2", { id: titleId, children: title }), _jsxs("p", { className: "vx-muted", children: [title !== slot.name ? _jsx("code", { children: slot.name }) : null, locale ? _jsxs("span", { children: [" \u00B7 ", locale] }) : null, data ? _jsxs("span", { children: [" \u00B7 ", data.version ? `v${data.version} live` : 'never published'] }) : null] })] }), _jsx("button", { type: "button", className: "vx-icon", "aria-label": "Close", onClick: close, children: "\u00D7" })] }), _jsxs("div", { className: "vx-panel-body", children: [loadError ? _jsx("p", { role: "alert", children: loadError }) : null, !data && !loadError ? _jsx("p", { className: "vx-muted", children: "Loading\u2026" }) : null, data?.test ? (_jsxs("div", { className: "vx-test", children: [_jsxs("p", { className: "vx-test-title", children: [TEST_STATUS[data.test.status] ?? 'Test', ": ", data.test.name] }), _jsx("div", { className: "vx-tabs", role: "tablist", "aria-label": "Version to show and edit", onKeyDown: (e) => {
679
+ // Arrow keys move between versions (one tab stop for the whole list).
680
+ const order = data.test.variants.map((v) => v.position);
681
+ const at = order.indexOf(variant);
682
+ const next = e.key === 'ArrowRight' || e.key === 'ArrowDown'
683
+ ? order[(at + 1) % order.length]
684
+ : e.key === 'ArrowLeft' || e.key === 'ArrowUp'
685
+ ? order[(at - 1 + order.length) % order.length]
686
+ : e.key === 'Home'
687
+ ? order[0]
688
+ : e.key === 'End'
689
+ ? order[order.length - 1]
690
+ : undefined;
691
+ if (next === undefined)
692
+ return;
693
+ e.preventDefault();
694
+ void selectVariant(next);
695
+ e.currentTarget.querySelector(`[data-position="${next}"]`)?.focus();
696
+ }, children: data.test.variants.map((v) => (_jsx("button", { type: "button", role: "tab", "data-position": v.position, "aria-selected": variant === v.position, tabIndex: variant === v.position ? 0 : -1, className: "vx-tab", onClick: () => void selectVariant(v.position), children: v.isControl ? 'Published' : v.label }, v.position))) }), variant > 0 ? (_jsx("p", { className: "vx-muted", children: data.test.editable && canManageTests
697
+ ? 'The page shows this variant. Edits change only this variant; empty fields use the published version.'
698
+ : data.test.editable
699
+ ? 'The page shows this variant. Editing variants needs permission to manage experiments.'
700
+ : 'The page shows this variant. Variants can’t change once the test has started.' })) : null] })) : null, data?.inherited && locale && !touched.current.size ? (_jsxs("p", { className: "vx-note", children: ["Nothing saved in ", locale, " yet; you\u2019re starting from the default language\u2019s published copy."] })) : null, fillable.length ? (_jsxs("div", { className: "vx-fill", children: [_jsxs("p", { className: "vx-muted", children: ["Empty here, but the page shows content for: ", fillable.map((f) => data?.fields[f]?.label ?? f).join(', '), "."] }), _jsx("button", { type: "button", className: "vx-btn", onClick: fillFromPage, children: "Fill empty fields from the page" })] })) : null, data
701
+ ? (variant > 0 && !(data.test?.editable && canManageTests) ? [] : Object.entries(data.fields)).map(([name, def]) => (_jsx(FieldInput, { name: name, def: def, value: values[name], shown: shown[name], fallback: fallback?.[name], onChange: (v) => change(name, v), onFocus: () => onFieldFocus(name) }, name)))
702
+ : null] }), _jsxs("div", { className: "vx-panel-foot", children: [_jsx("p", { className: "vx-status", role: "status", "aria-live": "polite", children: save.kind === 'saving'
648
703
  ? variant > 0
649
- ? 'Variant saved'
650
- : 'Draft saved'
651
- : save.kind === 'error'
652
- ? ''
653
- : latest.current !== null
654
- ? (notice ?? 'Editing… saves in a moment')
655
- : notice ?? (data?.unpublishedChanges ? 'Unpublished changes' : data ? 'No unpublished changes' : '') }), save.kind === 'error' ? (_jsx("ul", { className: "vx-errors", role: "alert", children: save.problems.map((p) => (_jsx("li", { children: p }, p))) })) : null, variant > 0 && data?.test ? (_jsxs("div", { className: "vx-actions", children: [dashboardUrl ? (_jsx("a", { className: "vx-btn", href: `${dashboardUrl}${data.test.dashboardPath}`, target: "_blank", rel: "noopener noreferrer", children: "Test settings and results" })) : null, _jsx("button", { type: "button", className: "vx-btn", onClick: () => void selectVariant(0), children: "Back to published" })] })) : null, variant === 0 && approval?.pending ? (_jsxs("div", { className: "vx-review", role: "group", "aria-label": "Approval", children: [_jsxs("p", { className: "vx-review-title", children: ["Waiting for approval", approval.steps.length > 1 && approval.currentStep !== null
656
- ? ` · step ${approval.steps.findIndex((st) => st.stepOrder === approval.currentStep) + 1} of ${approval.steps.length}`
657
- : ''] }), _jsxs("p", { className: "vx-muted", children: [approval.steps.find((st) => st.stepOrder === approval.currentStep)?.label, approval.submittedByName ? ` · sent by ${approval.submittedByName}` : ''] }), approval.changedSinceSubmission ? (_jsx("p", { className: "vx-muted", children: "Edits made since it was sent aren't part of the request." })) : null, approval.canAct ? (_jsxs(_Fragment, { children: [_jsx("label", { className: "vx-sublabel", htmlFor: `${titleId}-review`, children: "Comment (needed to reject)" }), _jsx("textarea", { id: `${titleId}-review`, className: "vx-review-comment", rows: 2, value: reviewComment, onChange: (e) => setReviewComment(e.target.value) }), _jsxs("div", { className: "vx-actions", children: [_jsx("button", { type: "button", className: "vx-btn vx-primary", disabled: busy !== null, onClick: () => act('approve', { comment: reviewComment }), children: busy === 'approve' ? 'Approving…' : approval.steps[approval.steps.length - 1]?.stepOrder === approval.currentStep ? 'Approve and publish' : 'Approve' }), _jsx("button", { type: "button", className: "vx-btn", disabled: busy !== null || !reviewComment.trim(), onClick: () => act('reject', { comment: reviewComment }), children: busy === 'reject' ? 'Rejecting…' : 'Reject' })] })] })) : approval.isSubmitter ? (_jsx("p", { className: "vx-muted", children: "Someone else on that step's role approves it." })) : null, approval.canWithdraw ? (_jsx("button", { type: "button", className: "vx-btn vx-review-withdraw", disabled: busy !== null, onClick: () => act('withdraw'), children: busy === 'withdraw' ? 'Withdrawing…' : 'Withdraw request' })) : null] })) : null, _jsxs("div", { className: "vx-actions", hidden: variant > 0, children: [canPublish ? (_jsx("button", { type: "button", className: "vx-btn vx-primary", disabled: !data || !dirty || busy !== null || approval?.pending, onClick: () => act('publish'), children: busy === 'publish' ? (approval?.required ? 'Sending…' : 'Publishing…') : approval?.required ? 'Send for approval' : 'Publish' })) : (_jsx("span", { className: "vx-muted", children: "Someone with publish permission can make this live." })), data?.unpublishedChanges && data.version > 0 ? (_jsx("button", { type: "button", className: "vx-btn", disabled: busy !== null, onClick: discard, children: busy === 'discard' ? 'Discarding…' : confirmDiscard ? 'Discard all changes?' : 'Discard changes' })) : null] })] })] }));
704
+ ? 'Saving variant…'
705
+ : 'Saving draft…'
706
+ : save.kind === 'saved'
707
+ ? variant > 0
708
+ ? 'Variant saved'
709
+ : 'Draft saved'
710
+ : save.kind === 'error'
711
+ ? ''
712
+ : latest.current !== null
713
+ ? (notice ?? 'Editing… saves in a moment')
714
+ : notice ?? (data?.unpublishedChanges ? 'Unpublished changes' : data ? 'No unpublished changes' : '') }), save.kind === 'error' ? (_jsx("ul", { className: "vx-errors", role: "alert", children: save.problems.map((p) => (_jsx("li", { children: p }, p))) })) : null, variant > 0 && data?.test ? (_jsxs("div", { className: "vx-actions", children: [dashboardUrl ? (_jsx("a", { className: "vx-btn", href: `${dashboardUrl}${data.test.dashboardPath}`, target: "_blank", rel: "noopener noreferrer", children: "Test settings and results" })) : null, _jsx("button", { type: "button", className: "vx-btn", onClick: () => void selectVariant(0), children: "Back to published" })] })) : null, variant === 0 && approval?.pending ? (_jsxs("div", { className: "vx-review", role: "group", "aria-label": "Approval", children: [_jsxs("p", { className: "vx-review-title", children: ["Waiting for approval", approval.steps.length > 1 && approval.currentStep !== null
715
+ ? ` · step ${approval.steps.findIndex((st) => st.stepOrder === approval.currentStep) + 1} of ${approval.steps.length}`
716
+ : ''] }), _jsxs("p", { className: "vx-muted", children: [approval.steps.find((st) => st.stepOrder === approval.currentStep)?.label, approval.submittedByName ? ` · sent by ${approval.submittedByName}` : ''] }), approval.changedSinceSubmission ? (_jsx("p", { className: "vx-muted", children: "Edits made since it was sent aren't part of the request." })) : null, approval.canAct ? (_jsxs(_Fragment, { children: [_jsx("label", { className: "vx-sublabel", htmlFor: `${titleId}-review`, children: "Comment (needed to reject)" }), _jsx("textarea", { id: `${titleId}-review`, className: "vx-review-comment", rows: 2, value: reviewComment, onChange: (e) => setReviewComment(e.target.value) }), _jsxs("div", { className: "vx-actions", children: [_jsx("button", { type: "button", className: "vx-btn vx-primary", disabled: busy !== null, onClick: () => act('approve', { comment: reviewComment }), children: busy === 'approve' ? 'Approving…' : approval.steps[approval.steps.length - 1]?.stepOrder === approval.currentStep ? 'Approve and publish' : 'Approve' }), _jsx("button", { type: "button", className: "vx-btn", disabled: busy !== null || !reviewComment.trim(), onClick: () => act('reject', { comment: reviewComment }), children: busy === 'reject' ? 'Rejecting…' : 'Reject' })] })] })) : approval.isSubmitter ? (_jsx("p", { className: "vx-muted", children: "Someone else on that step's role approves it." })) : null, approval.canWithdraw ? (_jsx("button", { type: "button", className: "vx-btn vx-review-withdraw", disabled: busy !== null, onClick: () => act('withdraw'), children: busy === 'withdraw' ? 'Withdrawing…' : 'Withdraw request' })) : null] })) : null, _jsxs("div", { className: "vx-actions", hidden: variant > 0, children: [canPublish ? (_jsx("button", { type: "button", className: "vx-btn vx-primary", disabled: !data || !dirty || busy !== null || approval?.pending, onClick: () => act('publish'), children: busy === 'publish' ? (approval?.required ? 'Sending…' : 'Publishing…') : approval?.required ? 'Send for approval' : 'Publish' })) : (_jsx("span", { className: "vx-muted", children: "Someone with publish permission can make this live." })), data?.unpublishedChanges && data.version > 0 ? (_jsx("button", { type: "button", className: "vx-btn", disabled: busy !== null, onClick: discard, children: busy === 'discard' ? 'Discarding…' : confirmDiscard ? 'Discard all changes?' : 'Discard changes' })) : null] })] })] }) }));
658
717
  }
659
718
  // ----------------------------------------------------------------- fields
660
719
  function stripTags(html) {
661
720
  return html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
662
721
  }
663
- function FieldInput({ name, def, value, shown, onChange, onFocus, }) {
722
+ function FieldInput({ name, def, value, shown, fallback, onChange, onFocus, }) {
664
723
  const placeholder = typeof shown === 'string' && shown ? shown : undefined;
665
724
  const id = useId();
666
725
  const label = (_jsxs("label", { htmlFor: id, className: "vx-label", children: [def.label ?? name, def.required ? _jsx("span", { "aria-hidden": "true", children: " *" }) : null] }));
@@ -689,7 +748,7 @@ function FieldInput({ name, def, value, shown, onChange, onFocus, }) {
689
748
  return (_jsxs("fieldset", { className: "vx-field vx-fieldset", children: [_jsxs("legend", { className: "vx-label", children: [def.label ?? name, def.required ? _jsx("span", { "aria-hidden": "true", children: " *" }) : null] }), _jsx("label", { htmlFor: `${id}-label`, className: "vx-sublabel", children: "Text" }), _jsx("input", { id: `${id}-label`, "data-field": name, onFocus: onFocus, type: "text", value: link.label, onChange: (e) => set({ label: e.target.value }) }), _jsx("label", { htmlFor: `${id}-href`, className: "vx-sublabel", children: "Address" }), _jsx("input", { id: `${id}-href`, onFocus: onFocus, type: "text", inputMode: "url", placeholder: "https://\u2026 or /page", value: link.href, onChange: (e) => set({ href: e.target.value }) })] }));
690
749
  }
691
750
  case 'media':
692
- return _jsx(MediaInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
751
+ return _jsx(MediaInput, { name: name, def: def, value: value, fallback: fallback, onChange: onChange, onFocus: onFocus });
693
752
  case 'video':
694
753
  return _jsx(VideoInput, { name: name, def: def, value: value, onChange: onChange, onFocus: onFocus });
695
754
  case 'chart':
@@ -869,7 +928,33 @@ function ListInput({ name, def, value, onChange, onFocus }) {
869
928
  setOpenItem(items.length);
870
929
  }, children: "Add item" }) })] }));
871
930
  }
872
- function MediaInput({ name, def, value, onChange, onFocus }) {
931
+ function MediaInput({ name, def, value, fallback, onChange, onFocus, }) {
932
+ const { canUploadMedia } = useContext(PanelCaps);
933
+ const [importing, setImporting] = useState(false);
934
+ const [importError, setImportError] = useState(null);
935
+ // The page shows an image from the site's own files (no media library id): show it, and offer to import it.
936
+ const fromCode = !value?.url ? fallbackImage(fallback) : null;
937
+ const importable = fromCode && typeof location !== 'undefined' ? sameSiteImage(fromCode.url, location.href) : null;
938
+ const importIntoMedia = async () => {
939
+ if (!importable || !fromCode)
940
+ return;
941
+ setImporting(true);
942
+ setImportError(null);
943
+ try {
944
+ const res = await fetch(importable.href, { credentials: 'same-origin' });
945
+ const blob = res.ok ? await res.blob() : null;
946
+ if (!blob || !blob.type.startsWith('image/'))
947
+ throw new EditorError(res.status, ['That address didn’t return an image.']);
948
+ const m = await call('media', { method: 'POST', body: { fileName: importable.pathname, data: await toBase64(blob), alt: fromCode.alt } });
949
+ onChange({ id: m.id, url: m.url, alt: m.alt });
950
+ }
951
+ catch (err) {
952
+ setImportError(err instanceof EditorError ? err.problems.join(' ') : 'Could not import the image.');
953
+ }
954
+ finally {
955
+ setImporting(false);
956
+ }
957
+ };
873
958
  const [picking, setPicking] = useState(false);
874
959
  const [search, setSearch] = useState('');
875
960
  const [items, setItems] = useState(null);
@@ -889,17 +974,27 @@ function MediaInput({ name, def, value, onChange, onFocus }) {
889
974
  }, 250);
890
975
  return () => clearTimeout(t);
891
976
  }, [picking, search]);
892
- return (_jsxs("div", { className: "vx-field", role: "group", "aria-labelledby": labelId, children: [_jsxs("span", { id: labelId, className: "vx-label", children: [def.label ?? name, def.required ? _jsx("span", { "aria-hidden": "true", children: " *" }) : null] }), value?.url ? _jsx("img", { className: "vx-preview", src: value.url, alt: value.alt ?? '' }) : _jsx("p", { className: "vx-muted", children: "No image chosen." }), _jsxs("div", { className: "vx-actions", children: [_jsx("button", { type: "button", className: "vx-btn", "data-field": name, onFocus: onFocus, "aria-expanded": picking, onClick: () => setPicking((p) => !p), children: picking ? 'Close library' : value ? 'Replace image' : 'Choose image' }), value && !def.required ? (_jsx("button", { type: "button", className: "vx-btn", onClick: () => onChange(null), children: "Remove" })) : null] }), picking ? (_jsxs("div", { className: "vx-picker", children: [_jsx("label", { htmlFor: searchId, className: "vx-sublabel", children: "Search the media library" }), _jsx("input", { id: searchId, type: "search", value: search, onChange: (e) => setSearch(e.target.value) }), error ? _jsx("p", { role: "alert", children: error }) : null, items && items.length === 0 ? _jsx("p", { className: "vx-muted", children: "No images found." }) : null, _jsx("div", { className: "vx-grid", children: (items ?? []).map((m) => (_jsxs("button", { type: "button", "aria-pressed": value?.id === m.id, onClick: () => {
977
+ return (_jsxs("div", { className: "vx-field", role: "group", "aria-labelledby": labelId, children: [_jsxs("span", { id: labelId, className: "vx-label", children: [def.label ?? name, def.required ? _jsx("span", { "aria-hidden": "true", children: " *" }) : null] }), value?.url ? (_jsx("img", { className: "vx-preview", src: value.url, alt: value.alt ?? '' })) : fromCode ? (_jsxs(_Fragment, { children: [_jsx("img", { className: "vx-preview", src: fromCode.url, alt: fromCode.alt }), _jsxs("p", { className: "vx-muted", children: ["Shown from the site\u2019s code. It isn\u2019t in the media library, so it can\u2019t be saved with the slot", canUploadMedia && importable ? ' until you import it' : '', "."] }), canUploadMedia && importable ? (_jsx("div", { className: "vx-actions", children: _jsx("button", { type: "button", className: "vx-btn", disabled: importing, onClick: () => void importIntoMedia(), children: importing ? 'Importing…' : 'Import into Media' }) })) : null, importError ? _jsx("p", { role: "alert", children: importError }) : null] })) : (_jsx("p", { className: "vx-muted", children: "No image chosen." })), _jsxs("div", { className: "vx-actions", children: [_jsx("button", { type: "button", className: "vx-btn", "data-field": name, onFocus: onFocus, "aria-expanded": picking, onClick: () => setPicking((p) => !p), children: picking ? 'Close library' : value ? 'Replace image' : 'Choose image' }), value && !def.required ? (_jsx("button", { type: "button", className: "vx-btn", onClick: () => onChange(null), children: "Remove" })) : null] }), picking ? (_jsxs("div", { className: "vx-picker", children: [_jsx("label", { htmlFor: searchId, className: "vx-sublabel", children: "Search the media library" }), _jsx("input", { id: searchId, type: "search", value: search, onChange: (e) => setSearch(e.target.value) }), error ? _jsx("p", { role: "alert", children: error }) : null, items && items.length === 0 ? _jsx("p", { className: "vx-muted", children: "No images found." }) : null, _jsx("div", { className: "vx-grid", children: (items ?? []).map((m) => (_jsxs("button", { type: "button", "aria-pressed": value?.id === m.id, onClick: () => {
893
978
  onChange({ id: m.id, url: m.url, alt: m.alt });
894
979
  setPicking(false);
895
980
  }, children: [_jsx("img", { src: m.thumbUrl, alt: "" }), _jsx("span", { children: m.alt || m.name })] }, m.id))) })] })) : null] }));
896
981
  }
982
+ /** A file's bytes as base64 (no data: prefix). */
983
+ async function toBase64(blob) {
984
+ const bytes = new Uint8Array(await blob.arrayBuffer());
985
+ let bin = '';
986
+ for (let i = 0; i < bytes.length; i += 0x8000)
987
+ bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
988
+ return btoa(bin);
989
+ }
897
990
  // ----------------------------------------------------------------- styles
898
991
  // Scoped by the vx- prefix and reset at .vx-root so the site's own CSS
899
992
  // neither leaks in much nor gets touched.
900
993
  const STYLES = `
901
994
  .vx-root{all:initial;font:14px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif;color:#18181b}
902
995
  .vx-root *{box-sizing:border-box;font:inherit;color:inherit}
996
+ .vx-root .vx-fill{margin:0 0 12px;padding:8px 10px;border:1px dashed #d4d4d8;border-radius:6px}
997
+ .vx-root .vx-fill p{margin:0 0 6px}
903
998
  .vx-root code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}
904
999
  .vx-outline{position:fixed;z-index:2147483000;pointer-events:none;border:2px dashed #6d28d9;border-radius:6px}
905
1000
  .vx-outline-active{border-style:solid;box-shadow:0 0 0 4px rgba(109,40,217,.15)}
@@ -12,9 +12,21 @@ export declare function isEmptyValue(v: unknown): boolean;
12
12
  * The form's values with every empty field filled from the fallback (when it has something storable), and which fields
13
13
  * were filled. A field with stored content keeps it.
14
14
  */
15
- export declare function seedFromFallback(fields: Record<string, SeedFieldDef>, values: Record<string, unknown>, fallback: Record<string, unknown> | null | undefined): {
15
+ export declare function seedFromFallback(fields: Record<string, SeedFieldDef>, values: Record<string, unknown>, fallback: Record<string, unknown> | null | undefined, options?: {
16
+ replace?: boolean;
17
+ }): {
16
18
  values: Record<string, unknown>;
17
19
  seeded: string[];
18
20
  };
21
+ /**
22
+ * An image the page shows from its own files (a fallback image with no media library id): its address and alt text,
23
+ * or null. Accepts the SDK's media shape ({ url, webpUrl, alt }), { src } or a plain address.
24
+ */
25
+ export declare function fallbackImage(v: unknown): {
26
+ url: string;
27
+ alt: string;
28
+ } | null;
29
+ /** Whether an image address is on this site (so the editor may read it and import it), resolved against `base`. */
30
+ export declare function sameSiteImage(url: string, base: string): URL | null;
19
31
  /** The slot's fallback as the page rendered it (data-veroxm-fallback), or null. Never the shown values: those may be a test variant's. */
20
32
  export declare function readFallback(el: Element | null): Record<string, unknown> | null;
@@ -1,16 +1,20 @@
1
- // Starting the on-page editor from the page's fallback (the site's own copy in code), so the first save stores real
2
- // content instead of empty fields. Pure, so the panel and its tests share it.
1
+ // Starting the on-page editor from the page's fallback (the site's own copy in code), so a save stores real content
2
+ // instead of empty fields. Pure, so the panel and its tests share it.
3
3
  //
4
- // Only for a slot that was never published: its stored values are empty, and the page shows the fallback. Every
5
- // empty field (undefined, null, '' or an empty list) takes the fallback's value. Media is only taken when it is an item
6
- // of the media library (it has an id), because a slot stores media as { id }; inside lists, components and slides,
7
- // media without an id is left empty for the same reason.
4
+ // - A slot never published: every empty field (undefined, null, '' or an empty list) takes the fallback's value.
5
+ // - A language with nothing saved yet (VeroXM answers the default language's published copy): the page's fallback
6
+ // for this language wins for every field it has (`replace`); the default language fills only the rest.
7
+ // - A published slot: only when asked ("Fill empty fields from the page"), and only empty fields.
8
+ // Media is only taken when it is an item of the media library (it has an id), because a slot stores media as { id };
9
+ // inside lists, components and slides, media without an id is left empty for the same reason. An image the page shows
10
+ // from its own files (no id) can be imported into the media library instead (fallbackImage).
8
11
  /** Nothing stored: undefined, null, '' or an empty list. */
9
12
  export function isEmptyValue(v) {
10
13
  return v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0);
11
14
  }
12
15
  const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
13
- const libraryMedia = (v) => isObject(v) && typeof v.id === 'number' && Number.isFinite(v.id);
16
+ // A real media library id is a positive whole number; sites often write { id: 0 } for an image in their own files.
17
+ const libraryMedia = (v) => isObject(v) && typeof v.id === 'number' && Number.isInteger(v.id) && v.id > 0;
14
18
  /** A fallback value as the slot can store it: media only from the library, inside lists and components too. */
15
19
  function storable(def, v) {
16
20
  switch (def.type) {
@@ -43,13 +47,13 @@ function storableValues(fields, values) {
43
47
  * The form's values with every empty field filled from the fallback (when it has something storable), and which fields
44
48
  * were filled. A field with stored content keeps it.
45
49
  */
46
- export function seedFromFallback(fields, values, fallback) {
50
+ export function seedFromFallback(fields, values, fallback, options = {}) {
47
51
  const out = { ...values };
48
52
  const seeded = [];
49
53
  if (!fallback)
50
54
  return { values: out, seeded };
51
55
  for (const [name, def] of Object.entries(fields)) {
52
- if (!isEmptyValue(values[name]) || isEmptyValue(fallback[name]))
56
+ if ((!options.replace && !isEmptyValue(values[name])) || isEmptyValue(fallback[name]))
53
57
  continue;
54
58
  const v = storable(def, fallback[name]);
55
59
  if (isEmptyValue(v))
@@ -59,6 +63,28 @@ export function seedFromFallback(fields, values, fallback) {
59
63
  }
60
64
  return { values: out, seeded };
61
65
  }
66
+ /**
67
+ * An image the page shows from its own files (a fallback image with no media library id): its address and alt text,
68
+ * or null. Accepts the SDK's media shape ({ url, webpUrl, alt }), { src } or a plain address.
69
+ */
70
+ export function fallbackImage(v) {
71
+ if (typeof v === 'string')
72
+ return v.trim() ? { url: v.trim(), alt: '' } : null;
73
+ if (!isObject(v) || libraryMedia(v))
74
+ return null;
75
+ const url = [v.url, v.src, v.webpUrl].find((u) => typeof u === 'string' && u.trim() !== '');
76
+ return url ? { url, alt: typeof v.alt === 'string' ? v.alt : '' } : null;
77
+ }
78
+ /** Whether an image address is on this site (so the editor may read it and import it), resolved against `base`. */
79
+ export function sameSiteImage(url, base) {
80
+ try {
81
+ const u = new URL(url, base);
82
+ return u.origin === new URL(base).origin && (u.protocol === 'http:' || u.protocol === 'https:') ? u : null;
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
62
88
  /** The slot's fallback as the page rendered it (data-veroxm-fallback), or null. Never the shown values: those may be a test variant's. */
63
89
  export function readFallback(el) {
64
90
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veroxm/react-sdk",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "React and Next.js SDK for VeroXM: content hooks, visual slots with A/B tests, the on-page editor, forms and product journeys, llms.txt and structured data.",
5
5
  "keywords": [
6
6
  "veroxm",