@conloca/cms-spa 0.2.3 → 0.2.5

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.
Files changed (176) hide show
  1. package/README.md +2 -1
  2. package/dist/spa/main.css +6 -21
  3. package/dist/ts/.build-inputs.json +38 -28
  4. package/dist/ts/components/CMSDashboard.d.ts.map +1 -1
  5. package/dist/ts/components/CMSDashboard.js +3 -1
  6. package/dist/ts/components/CMSDashboard.js.map +1 -1
  7. package/dist/ts/components/dialogs/DeleteConfirmDialog.d.ts +6 -1
  8. package/dist/ts/components/dialogs/DeleteConfirmDialog.d.ts.map +1 -1
  9. package/dist/ts/components/dialogs/DeleteConfirmDialog.js +2 -2
  10. package/dist/ts/components/dialogs/DeleteConfirmDialog.js.map +1 -1
  11. package/dist/ts/components/dialogs/MakePagesEditableDialog.d.ts +10 -0
  12. package/dist/ts/components/dialogs/MakePagesEditableDialog.d.ts.map +1 -0
  13. package/dist/ts/components/dialogs/MakePagesEditableDialog.js +35 -0
  14. package/dist/ts/components/dialogs/MakePagesEditableDialog.js.map +1 -0
  15. package/dist/ts/components/dialogs/MoveFolderDialog.d.ts +6 -1
  16. package/dist/ts/components/dialogs/MoveFolderDialog.d.ts.map +1 -1
  17. package/dist/ts/components/dialogs/MoveFolderDialog.js +3 -3
  18. package/dist/ts/components/dialogs/MoveFolderDialog.js.map +1 -1
  19. package/dist/ts/components/editor/CMSMDXEditor.d.ts.map +1 -1
  20. package/dist/ts/components/editor/CMSMDXEditor.js +9 -9
  21. package/dist/ts/components/editor/CMSMDXEditor.js.map +1 -1
  22. package/dist/ts/components/editor/DocsPreviewButton.d.ts +6 -0
  23. package/dist/ts/components/editor/DocsPreviewButton.d.ts.map +1 -0
  24. package/dist/ts/components/editor/DocsPreviewButton.js +15 -0
  25. package/dist/ts/components/editor/DocsPreviewButton.js.map +1 -0
  26. package/dist/ts/components/editor/ImagePickerDialog.js +2 -2
  27. package/dist/ts/components/editor/ImagePickerDialog.js.map +1 -1
  28. package/dist/ts/components/editor/MdxPageEditor.d.ts.map +1 -1
  29. package/dist/ts/components/editor/MdxPageEditor.js +2 -1
  30. package/dist/ts/components/editor/MdxPageEditor.js.map +1 -1
  31. package/dist/ts/components/editor/PageEditor.d.ts.map +1 -1
  32. package/dist/ts/components/editor/PageEditor.js +1 -2
  33. package/dist/ts/components/editor/PageEditor.js.map +1 -1
  34. package/dist/ts/components/editor/draft-media-config.d.ts +20 -8
  35. package/dist/ts/components/editor/draft-media-config.d.ts.map +1 -1
  36. package/dist/ts/components/editor/draft-media-config.js +124 -60
  37. package/dist/ts/components/editor/draft-media-config.js.map +1 -1
  38. package/dist/ts/components/editor/preview-availability.d.ts +2 -0
  39. package/dist/ts/components/editor/preview-availability.d.ts.map +1 -1
  40. package/dist/ts/components/editor/preview-availability.js +2 -0
  41. package/dist/ts/components/editor/preview-availability.js.map +1 -1
  42. package/dist/ts/components/editors/DataEditor.d.ts +6 -2
  43. package/dist/ts/components/editors/DataEditor.d.ts.map +1 -1
  44. package/dist/ts/components/editors/DataEditor.js +46 -19
  45. package/dist/ts/components/editors/DataEditor.js.map +1 -1
  46. package/dist/ts/components/fields/ImageField.js +2 -2
  47. package/dist/ts/components/fields/ImageField.js.map +1 -1
  48. package/dist/ts/components/media/AssetCard.d.ts.map +1 -1
  49. package/dist/ts/components/media/AssetCard.js +3 -3
  50. package/dist/ts/components/media/AssetCard.js.map +1 -1
  51. package/dist/ts/components/media/AssetDetailSidebar.d.ts.map +1 -1
  52. package/dist/ts/components/media/AssetDetailSidebar.js +6 -3
  53. package/dist/ts/components/media/AssetDetailSidebar.js.map +1 -1
  54. package/dist/ts/components/media/AssetUsageList.d.ts +13 -0
  55. package/dist/ts/components/media/AssetUsageList.d.ts.map +1 -0
  56. package/dist/ts/components/media/AssetUsageList.js +35 -0
  57. package/dist/ts/components/media/AssetUsageList.js.map +1 -0
  58. package/dist/ts/components/media/MediaLibrary.d.ts.map +1 -1
  59. package/dist/ts/components/media/MediaLibrary.js +6 -4
  60. package/dist/ts/components/media/MediaLibrary.js.map +1 -1
  61. package/dist/ts/components/media/index.d.ts +1 -0
  62. package/dist/ts/components/media/index.d.ts.map +1 -1
  63. package/dist/ts/components/media/index.js +1 -0
  64. package/dist/ts/components/media/index.js.map +1 -1
  65. package/dist/ts/components/pages/DataList.d.ts.map +1 -1
  66. package/dist/ts/components/pages/DataList.js +51 -34
  67. package/dist/ts/components/pages/DataList.js.map +1 -1
  68. package/dist/ts/components/pages/FragmentList.d.ts.map +1 -1
  69. package/dist/ts/components/pages/FragmentList.js +1 -1
  70. package/dist/ts/components/pages/FragmentList.js.map +1 -1
  71. package/dist/ts/components/pages/MediaPage.d.ts.map +1 -1
  72. package/dist/ts/components/pages/MediaPage.js +7 -5
  73. package/dist/ts/components/pages/MediaPage.js.map +1 -1
  74. package/dist/ts/components/pages/NoPagesYet.d.ts +5 -0
  75. package/dist/ts/components/pages/NoPagesYet.d.ts.map +1 -0
  76. package/dist/ts/components/pages/NoPagesYet.js +16 -0
  77. package/dist/ts/components/pages/NoPagesYet.js.map +1 -0
  78. package/dist/ts/components/pages/PageList.d.ts.map +1 -1
  79. package/dist/ts/components/pages/PageList.js +9 -4
  80. package/dist/ts/components/pages/PageList.js.map +1 -1
  81. package/dist/ts/components/sandbox/ContentSandbox.js +3 -3
  82. package/dist/ts/components/sandbox/ContentSandbox.js.map +1 -1
  83. package/dist/ts/convert-pages.d.ts +30 -0
  84. package/dist/ts/convert-pages.d.ts.map +1 -0
  85. package/dist/ts/convert-pages.js +85 -0
  86. package/dist/ts/convert-pages.js.map +1 -0
  87. package/dist/ts/editor-queries.d.ts +24 -0
  88. package/dist/ts/editor-queries.d.ts.map +1 -0
  89. package/dist/ts/editor-queries.js +37 -0
  90. package/dist/ts/editor-queries.js.map +1 -0
  91. package/dist/ts/frame/editor-frame.d.ts +2 -1
  92. package/dist/ts/frame/editor-frame.d.ts.map +1 -1
  93. package/dist/ts/frame/editor-frame.js +14 -2
  94. package/dist/ts/frame/editor-frame.js.map +1 -1
  95. package/dist/ts/frame/media-cache.d.ts +13 -2
  96. package/dist/ts/frame/media-cache.d.ts.map +1 -1
  97. package/dist/ts/frame/media-cache.js +24 -9
  98. package/dist/ts/frame/media-cache.js.map +1 -1
  99. package/dist/ts/frame/protocol.d.ts +13 -1
  100. package/dist/ts/frame/protocol.d.ts.map +1 -1
  101. package/dist/ts/frame/protocol.js +5 -0
  102. package/dist/ts/frame/protocol.js.map +1 -1
  103. package/dist/ts/hooks/index.d.ts +2 -0
  104. package/dist/ts/hooks/index.d.ts.map +1 -1
  105. package/dist/ts/hooks/index.js +1 -0
  106. package/dist/ts/hooks/index.js.map +1 -1
  107. package/dist/ts/hooks/usePageConversion.d.ts +11 -0
  108. package/dist/ts/hooks/usePageConversion.d.ts.map +1 -0
  109. package/dist/ts/hooks/usePageConversion.js +47 -0
  110. package/dist/ts/hooks/usePageConversion.js.map +1 -0
  111. package/dist/ts/hooks/useUploadFlow.d.ts.map +1 -1
  112. package/dist/ts/hooks/useUploadFlow.js +41 -7
  113. package/dist/ts/hooks/useUploadFlow.js.map +1 -1
  114. package/dist/ts/index.d.ts +3 -0
  115. package/dist/ts/index.d.ts.map +1 -1
  116. package/dist/ts/index.js +5 -0
  117. package/dist/ts/index.js.map +1 -1
  118. package/dist/ts/media/prepare-image-upload.d.ts +19 -0
  119. package/dist/ts/media/prepare-image-upload.d.ts.map +1 -0
  120. package/dist/ts/media/prepare-image-upload.js +93 -0
  121. package/dist/ts/media/prepare-image-upload.js.map +1 -0
  122. package/dist/ts/media/use-asset-serve-src.d.ts +7 -0
  123. package/dist/ts/media/use-asset-serve-src.d.ts.map +1 -0
  124. package/dist/ts/media/use-asset-serve-src.js +17 -0
  125. package/dist/ts/media/use-asset-serve-src.js.map +1 -0
  126. package/dist/ts/ui-config.d.ts +13 -3
  127. package/dist/ts/ui-config.d.ts.map +1 -1
  128. package/dist/ts/ui-config.js +14 -0
  129. package/dist/ts/ui-config.js.map +1 -1
  130. package/dist/ts/utils/asset-url.d.ts +3 -0
  131. package/dist/ts/utils/asset-url.d.ts.map +1 -1
  132. package/dist/ts/utils/asset-url.js +4 -0
  133. package/dist/ts/utils/asset-url.js.map +1 -1
  134. package/dist/ts/utils/data-entry-validation.d.ts +11 -0
  135. package/dist/ts/utils/data-entry-validation.d.ts.map +1 -0
  136. package/dist/ts/utils/data-entry-validation.js +15 -0
  137. package/dist/ts/utils/data-entry-validation.js.map +1 -0
  138. package/package.json +6 -7
  139. package/src/components/CMSDashboard.tsx +19 -14
  140. package/src/components/dialogs/DeleteConfirmDialog.tsx +14 -1
  141. package/src/components/dialogs/MakePagesEditableDialog.tsx +112 -0
  142. package/src/components/dialogs/MoveFolderDialog.tsx +9 -2
  143. package/src/components/editor/CMSMDXEditor.tsx +9 -9
  144. package/src/components/editor/DocsPreviewButton.tsx +25 -0
  145. package/src/components/editor/ImagePickerDialog.tsx +2 -2
  146. package/src/components/editor/MdxPageEditor.tsx +2 -0
  147. package/src/components/editor/PageEditor.tsx +1 -5
  148. package/src/components/editor/draft-media-config.ts +121 -65
  149. package/src/components/editor/preview-availability.ts +3 -0
  150. package/src/components/editors/DataEditor.tsx +65 -32
  151. package/src/components/fields/ImageField.tsx +2 -2
  152. package/src/components/media/AssetCard.tsx +4 -4
  153. package/src/components/media/AssetDetailSidebar.tsx +34 -21
  154. package/src/components/media/AssetUsageList.tsx +84 -0
  155. package/src/components/media/MediaLibrary.tsx +6 -4
  156. package/src/components/media/index.ts +1 -0
  157. package/src/components/pages/DataList.tsx +58 -43
  158. package/src/components/pages/FragmentList.tsx +3 -14
  159. package/src/components/pages/MediaPage.tsx +14 -5
  160. package/src/components/pages/NoPagesYet.tsx +41 -0
  161. package/src/components/pages/PageList.tsx +23 -23
  162. package/src/components/sandbox/ContentSandbox.tsx +3 -3
  163. package/src/convert-pages.ts +110 -0
  164. package/src/editor-queries.ts +49 -0
  165. package/src/frame/editor-frame.ts +14 -2
  166. package/src/frame/media-cache.ts +28 -15
  167. package/src/frame/protocol.ts +12 -1
  168. package/src/hooks/index.ts +2 -0
  169. package/src/hooks/usePageConversion.ts +55 -0
  170. package/src/hooks/useUploadFlow.ts +44 -7
  171. package/src/index.ts +5 -0
  172. package/src/media/prepare-image-upload.ts +118 -0
  173. package/src/media/use-asset-serve-src.ts +22 -0
  174. package/src/ui-config.ts +23 -3
  175. package/src/utils/asset-url.ts +6 -0
  176. package/src/utils/data-entry-validation.ts +16 -0
@@ -3,7 +3,7 @@
3
3
  // as the editor internals, avoiding React context isolation issues.
4
4
  import { closeImageDialog$, imageDialogState$, insertImage$, useCellValue, usePublisher } from '@mdxeditor/editor';
5
5
  import type { AssetEntry } from '../../hooks/index.js';
6
- import { buildAssetRef } from '../../utils/asset-url.js';
6
+ import { assetRefOf } from '../../utils/asset-url.js';
7
7
  import { ImagePicker } from '../media/ImagePicker.js';
8
8
 
9
9
  /**
@@ -17,7 +17,7 @@ export function ImagePickerDialog() {
17
17
 
18
18
  const handleSelect = (asset: AssetEntry) => {
19
19
  // Insert image at cursor - no alt text per CONTEXT.md
20
- insertImage({ src: buildAssetRef(asset.folder, asset.filename) });
20
+ insertImage({ src: assetRefOf(asset) });
21
21
  closeDialog();
22
22
  };
23
23
 
@@ -21,6 +21,7 @@ import { ErrorModal } from '../dialogs/ErrorModal.js';
21
21
  import { PageMetadataDialog } from '../dialogs/PageMetadataDialog.js';
22
22
  import { UnsavedChangesDialog } from '../dialogs/UnsavedChangesDialog.js';
23
23
  import { CMSMDXEditor } from './CMSMDXEditor.js';
24
+ import { DocsPreviewButton } from './DocsPreviewButton.js';
24
25
  import { JsxPropsPanel } from './JsxPropsPanel.js';
25
26
  import { LocaleSelector } from './LocaleSelector.js';
26
27
 
@@ -382,6 +383,7 @@ export function MdxPageEditor() {
382
383
  availableLocales={availableLocales}
383
384
  onChange={handleLocaleChange}
384
385
  />
386
+ <DocsPreviewButton />
385
387
  {publishedPathname && (
386
388
  <a
387
389
  // Resolve against the site (siteBaseUrl), not
@@ -285,11 +285,7 @@ export function PageEditor({
285
285
  onReload,
286
286
  onPublish,
287
287
  }: PageEditorProps) {
288
- const draftAssetsBasePath = getUIConfig().draftAssetsBasePath;
289
- const renderConfig = useMemo(
290
- () => withDraftMediaRendering(config, draftAssetsBasePath),
291
- [config, draftAssetsBasePath],
292
- );
288
+ const renderConfig = useMemo(() => withDraftMediaRendering(config), [config]);
293
289
  const [data, setData] = useState(entry.localized.content.puckData);
294
290
  const [saveState, setSaveState] = useState<SaveState>('idle');
295
291
  const [isDirty, setIsDirty] = useState(false);
@@ -1,56 +1,62 @@
1
1
  /** Resolve unpublished draft images for site renderers without changing Puck's persisted data. */
2
2
  /* oxlint-disable anti-slop/no-unsafe-dictionary-type, anti-slop/no-unknown-returns -- block props are whatever the site's components take; this walk only swaps image strings and passes every other value through as it came. */
3
- import { IMAGE_EXTENSION_MIME } from '@conloca/content-api-client';
4
- import type { Config, Field, Fields } from '@puckeditor/core';
3
+ import { draftMediaRefPath, mediaRefPath } from '@conloca/content-api-client';
4
+ import type { Config, Field, Fields, PuckContext } from '@puckeditor/core';
5
5
  import { type ComponentType, createElement, isValidElement } from 'react';
6
- import { loadedMedia, mediaObjectUrl, useMediaCacheVersion } from '../../frame/media-cache.js';
6
+ import { loadedMedia, mediaLoadState, useMediaCacheVersion } from '../../frame/media-cache.js';
7
+ import type { MediaLoadInput } from '../../frame/protocol.js';
7
8
  import { getUIConfig } from '../../ui-config.js';
8
- import { appendAssetUrlPath } from '../../utils/asset-url.js';
9
-
10
- /** What a validated draft image path renders as; `undefined` keeps the canonical value. */
11
- type DraftImageResolver = (path: string) => string | undefined;
12
-
13
- /** The raw media path of a canonical `/assets/<path>` image reference, or `undefined` when it is not a safe image path. */
14
- function draftImagePath(value: string): string | undefined {
15
- if (!value.startsWith('/assets/')) return undefined;
16
- const path = value.slice('/assets/'.length);
17
- if (/[\\?#]/.test(path)) return undefined;
18
- const segments = path.split('/');
19
- for (const part of segments) {
20
- if (
21
- part === '' ||
22
- part === '.' ||
23
- part === '..' ||
24
- [...part].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)
25
- ) {
9
+
10
+ /** A 1×1 transparent GIF: what an image shows until its bytes arrive, and a draft address after a failed load. */
11
+ export const DRAFT_IMAGE_PLACEHOLDER = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
12
+
13
+ /** What a stored image link renders as; `undefined` keeps the stored value. */
14
+ type DraftImageResolver = (source: MediaLoadInput) => string | undefined;
15
+
16
+ /**
17
+ * The one decision of where an image value's bytes come from: a draft address, or a link under the image folder
18
+ * URL (`UIConfig.assetRefBase`, `/assets` by default). A link is URL text, so each segment is decoded once, as
19
+ * the site's static host does; an escape that would change the path (a bad one, or a decoded `/`, `\`, control
20
+ * character, `.` or `..`) makes it no image of ours.
21
+ */
22
+ export function mediaSourceOf(value: string): MediaLoadInput | undefined {
23
+ const draftPath = draftMediaRefPath(value);
24
+ if (draftPath !== undefined) return { route: 'serve', path: draftPath };
25
+ const linked = mediaRefPath(value, getUIConfig().assetRefBase ?? '/assets');
26
+ if (linked === undefined) return undefined;
27
+ const segments: string[] = [];
28
+ for (const segment of linked.split('/')) {
29
+ let part: string;
30
+ try {
31
+ part = decodeURIComponent(segment);
32
+ } catch {
26
33
  return undefined;
27
34
  }
35
+ const control = Array.from(part, (char) => char.charCodeAt(0)).some((code) => code < 32 || code === 127);
36
+ if (part === '.' || part === '..' || /[/\\]/.test(part) || control) return undefined;
37
+ segments.push(part);
28
38
  }
29
- const filename = segments[segments.length - 1] ?? '';
30
- const dot = filename.lastIndexOf('.');
31
- if (dot <= 0) return undefined;
32
- const extension = filename.slice(dot + 1).toLowerCase();
33
- if (!Object.prototype.hasOwnProperty.call(IMAGE_EXTENSION_MIME, extension)) return undefined;
34
- return path;
39
+ return { route: 'repo', path: segments.join('/') };
35
40
  }
36
41
 
37
- function draftImageUrl(path: string, base: string): string {
38
- const encoded = path
39
- .split('/')
40
- .map((part) =>
41
- encodeURIComponent(part).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`),
42
- );
43
- return appendAssetUrlPath(base, encoded.join('/'));
42
+ /** What an image value shows in the canvas once a loader is set: its bytes when loaded, else the placeholder. */
43
+ function shownImage({ route, path }: MediaLoadInput): string {
44
+ const state = mediaLoadState(route, path);
45
+ return state?.status === 'loaded' ? state.url : DRAFT_IMAGE_PLACEHOLDER;
44
46
  }
45
47
 
46
48
  /**
47
- * What the MDX editor canvas shows for an image `src`: the loaded bytes of a draft image, else `src` itself.
49
+ * What the MDX editor canvas shows for an image `src`: the loaded bytes of a draft or repository image, else the
50
+ * placeholder; any other `src` itself, as is a repository link when no loader is set (the site serves it).
48
51
  * The URL is the media cache's own, which a media write or eviction revokes; mdxeditor resolves an image again only
49
52
  * when its `src` changes or it remounts, so a mounted image keeps painting its decoded bytes from a revoked URL.
50
53
  */
51
54
  export async function draftImagePreview(src: string): Promise<string> {
52
- const path = draftImagePath(src);
53
- return (path === undefined ? undefined : (await loadedMedia('draft', path))?.url) ?? src;
55
+ const source = mediaSourceOf(src);
56
+ if (source === undefined) return src;
57
+ const url = (await loadedMedia(source.route, source.path))?.url;
58
+ if (url !== undefined) return url;
59
+ return source.route === 'repo' && !getUIConfig().loadMedia ? src : DRAFT_IMAGE_PLACEHOLDER;
54
60
  }
55
61
 
56
62
  function dataUrl(blob: Blob): Promise<string> {
@@ -71,9 +77,8 @@ function dataUrl(blob: Blob): Promise<string> {
71
77
  // Keyed by the cached Blob, so a cleared or evicted cache entry frees its string too.
72
78
  const dataUrls = new WeakMap<Blob, Promise<string>>();
73
79
 
74
- async function draftImageDataUrl(src: string): Promise<string | undefined> {
75
- const path = draftImagePath(src);
76
- const media = path === undefined ? undefined : await loadedMedia('draft', path);
80
+ async function draftImageDataUrl({ route, path }: MediaLoadInput): Promise<string | undefined> {
81
+ const media = await loadedMedia(route, path);
77
82
  if (!media) return undefined;
78
83
  let url = dataUrls.get(media.blob);
79
84
  if (!url) {
@@ -87,22 +92,27 @@ async function draftImageDataUrl(src: string): Promise<string | undefined> {
87
92
  export const DRAFT_IMAGE_WAIT_MS = 5000;
88
93
 
89
94
  /**
90
- * Data URLs of the draft images a compiled MDX body names, keyed by their canonical `src`, for the
91
- * opaque-origin preview frame, which cannot read this page's blob URLs. Images that fail to load, or are
92
- * still loading after `DRAFT_IMAGE_WAIT_MS`, are left out.
95
+ * Data URLs of the images compiled MDX or sanitized HTML names, keyed by their stored value, for the opaque-origin
96
+ * preview frame, which cannot read this page's blob URLs: an `src`, an HTML `src="…"` attribute or an MDX
97
+ * component's prop. Images that fail to load, or are still loading after `DRAFT_IMAGE_WAIT_MS`, show the placeholder;
98
+ * without a loader a repository link is left out, so the frame loads it from the site.
93
99
  */
94
100
  export async function draftImageData(code: string): Promise<Record<string, string>> {
95
- // shortcut: finds srcs only as plain double-quoted literals, the form the MDX compiler emits for these paths; widen if an escaped path must preview.
96
- const srcs = new Set(code.match(/"\/assets\/[^"\\]*"/g)?.map((literal) => literal.slice(1, -1)));
101
+ // shortcut: finds values only as plain double-quoted literals, the form the MDX compiler and the HTML sanitizer emit; widen if an escaped path must preview.
102
+ const literals = code.match(/"[^"\\]*"/g);
103
+ const srcs = new Set(literals?.map((literal) => literal.slice(1, -1)));
97
104
  const images: Record<string, string> = {};
98
105
  let timer: number | undefined;
99
106
  const expired = new Promise<undefined>((resolve) => {
100
107
  timer = window.setTimeout(resolve, DRAFT_IMAGE_WAIT_MS, undefined);
101
108
  });
109
+ const loader = getUIConfig().loadMedia !== undefined;
102
110
  await Promise.all(
103
111
  [...srcs].map(async (src) => {
104
- const url = await Promise.race([draftImageDataUrl(src).catch(() => undefined), expired]);
105
- if (url !== undefined) images[src] = url;
112
+ const source = mediaSourceOf(src);
113
+ if (source === undefined || (source.route === 'repo' && !loader)) return;
114
+ const url = await Promise.race([draftImageDataUrl(source).catch(() => undefined), expired]);
115
+ images[src] = url ?? DRAFT_IMAGE_PLACEHOLDER;
106
116
  }),
107
117
  );
108
118
  window.clearTimeout(timer);
@@ -115,16 +125,24 @@ function isRecord(value: unknown): value is Record<string, unknown> {
115
125
  return prototype === Object.prototype || prototype === null;
116
126
  }
117
127
 
128
+ /** What the canvas shows for a string: what `resolve` decides when `mediaSourceOf` reads it as an image, else itself. */
129
+ function imageValue(value: string, resolve: DraftImageResolver): string {
130
+ const source = mediaSourceOf(value);
131
+ return source === undefined ? value : (resolve(source) ?? value);
132
+ }
133
+
134
+ /** `items` mapped by `map`, or `items` itself when no item changed. */
135
+ function mapped(items: unknown[], map: (item: unknown) => unknown): unknown[] {
136
+ const next = items.map(map);
137
+ return next.some((item, index) => item !== items[index]) ? next : items;
138
+ }
139
+
118
140
  function fieldValue(value: unknown, field: Field, resolve: DraftImageResolver): unknown {
119
141
  if (field.type === 'slot') return value;
120
- if (typeof value === 'string') {
121
- const path = draftImagePath(value);
122
- return path === undefined ? value : (resolve(path) ?? value);
123
- }
142
+ if (typeof value === 'string') return imageValue(value, resolve);
124
143
  if (field.type === 'object' && isRecord(value)) return fieldProps(value, field.objectFields, resolve);
125
144
  if (field.type === 'array' && Array.isArray(value)) {
126
- const next = value.map((item: unknown) => (isRecord(item) ? fieldProps(item, field.arrayFields, resolve) : item));
127
- return next.some((item, index) => item !== value[index]) ? next : value;
145
+ return mapped(value, (item) => (isRecord(item) ? fieldProps(item, field.arrayFields, resolve) : item));
128
146
  }
129
147
  return value;
130
148
  }
@@ -137,6 +155,7 @@ function fieldProps(
137
155
  let next = props;
138
156
  for (const [name, field] of Object.entries(fields ?? {})) {
139
157
  if (name === 'puck' || name === 'children' || name === 'editMode') continue;
158
+ // biome-ignore lint/suspicious/noPrototypeBuiltins: Object.hasOwn is past this package's ES2020 lib.
140
159
  if (field === undefined || !Object.prototype.hasOwnProperty.call(props, name)) continue;
141
160
  const value = fieldValue(props[name], field, resolve);
142
161
  if (value === props[name]) continue;
@@ -146,18 +165,50 @@ function fieldProps(
146
165
  return next;
147
166
  }
148
167
 
168
+ /** Page settings with every string in them read as a possible image, as the branch save scans them for uploads. */
169
+ function settingsValue(value: unknown, resolve: DraftImageResolver): unknown {
170
+ if (typeof value === 'string') return imageValue(value, resolve);
171
+ if (Array.isArray(value)) return mapped(value, (item) => settingsValue(item, resolve));
172
+ if (!isRecord(value)) return value;
173
+ let next = value;
174
+ for (const [name, item] of Object.entries(value)) {
175
+ const shown = settingsValue(item, resolve);
176
+ if (shown === item) continue;
177
+ if (next === value) next = { ...value };
178
+ next[name] = shown;
179
+ }
180
+ return next;
181
+ }
182
+
183
+ /** The page with its settings' images shown; everything else on it, its Dates included, as given. */
184
+ function pageWithImages(page: unknown, resolve: DraftImageResolver): unknown {
185
+ if (!isRecord(page)) return page;
186
+ const meta = settingsValue(page.meta, resolve);
187
+ return meta === page.meta ? page : { ...page, meta };
188
+ }
189
+
190
+ /**
191
+ * `puck` with the images in the page settings its metadata carries, the page's own and each page its route binds,
192
+ * shown as `resolve` decides: a block such as an article header shows a page setting without a field of its own.
193
+ */
194
+ function puckWithImages(puck: PuckContext, resolve: DraftImageResolver): PuckContext {
195
+ const { metadata } = puck;
196
+ if (!isRecord(metadata)) return puck;
197
+ const page = pageWithImages(metadata.page, resolve);
198
+ const pages = Array.isArray(metadata.pages)
199
+ ? mapped(metadata.pages, (item) => pageWithImages(item, resolve))
200
+ : metadata.pages;
201
+ if (page === metadata.page && pages === metadata.pages) return puck;
202
+ return { ...puck, metadata: { ...metadata, page, pages } };
203
+ }
204
+
149
205
  /**
150
- * Static declared fields bound traversal; dynamic field resolvers and runtime contexts remain untouched.
151
- * With `UIConfig.loadMedia` set, `base` is ignored: draft images show object URLs of the loaded bytes,
152
- * the canonical value until they arrive.
206
+ * Static declared fields bound traversal, plus the page settings in `puck.metadata`; dynamic field resolvers and
207
+ * other runtime contexts remain untouched. Every image value `mediaSourceOf` accepts shows what `shownImage`
208
+ * decides; `config` itself without `UIConfig.loadMedia`, so every value renders as stored.
153
209
  */
154
- export function withDraftMediaRendering(config: Config, base: string | undefined): Config {
155
- const resolve: DraftImageResolver | undefined = getUIConfig().loadMedia
156
- ? (path) => mediaObjectUrl('draft', path)
157
- : base === undefined
158
- ? undefined
159
- : (path) => draftImageUrl(path, base);
160
- if (resolve === undefined) return config;
210
+ export function withDraftMediaRendering(config: Config): Config {
211
+ if (getUIConfig().loadMedia === undefined) return config;
161
212
  const root = config.root;
162
213
  const rootRender = root?.render;
163
214
  return {
@@ -175,7 +226,8 @@ export function withDraftMediaRendering(config: Config, base: string | undefined
175
226
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- see the SAFETY note.
176
227
  return createElement(rootRender as ComponentType<typeof props>, {
177
228
  ...props,
178
- ...fieldProps(props, root.fields, resolve),
229
+ ...fieldProps(props, root.fields, shownImage),
230
+ puck: puckWithImages(props.puck, shownImage),
179
231
  });
180
232
  },
181
233
  },
@@ -188,7 +240,11 @@ export function withDraftMediaRendering(config: Config, base: string | undefined
188
240
  ...component,
189
241
  render: (props: Parameters<typeof component.render>[0]) => {
190
242
  useMediaCacheVersion();
191
- return createElement(component.render, { ...props, ...fieldProps(props, component.fields, resolve) });
243
+ return createElement(component.render, {
244
+ ...props,
245
+ ...fieldProps(props, component.fields, shownImage),
246
+ puck: puckWithImages(props.puck, shownImage),
247
+ });
192
248
  },
193
249
  },
194
250
  ]),
@@ -19,3 +19,6 @@ export const PREVIEW_UNAVAILABLE_TITLE = 'Preview is not available for this bran
19
19
  */
20
20
  export const PREVIEW_UNAVAILABLE_DETAIL =
21
21
  'This branch has no preview server, so there is no preview page to open. Your draft is still saved, and publishing and the live site are unaffected.';
22
+
23
+ /** What the Preview control on a docs (MDX) page says until docs pages render drafts. */
24
+ export const DOCS_PREVIEW_UNAVAILABLE = "Full-page preview isn't available for docs pages yet";
@@ -1,18 +1,27 @@
1
- import { getContentAPIClient, useLocalizedContent, useUpdateLocalized } from '@conloca/content-api-client';
1
+ import {
2
+ type DataCollectionEntry,
3
+ getContentAPIClient,
4
+ useLocalizedContent,
5
+ useUpdateLocalized,
6
+ } from '@conloca/content-api-client';
2
7
  import { AlertCircle, Code2, Loader2, Save } from 'lucide-react';
3
8
  import { useEffect, useRef, useState } from 'react';
4
- import type { HostSchema } from '../../host-schema.js';
9
+ import { type HostSchema, isHostSchema } from '../../host-schema.js';
5
10
  import { contentFailureMessage } from '../../utils/content-failure.js';
11
+ import { validateEntryData } from '../../utils/data-entry-validation.js';
6
12
  import { UnsavedChangesDialog } from '../dialogs/UnsavedChangesDialog.js';
7
13
  import { LocaleSelector } from '../editor/LocaleSelector.js';
8
14
  import { SchemaForm } from '../forms/SchemaForm.js';
9
15
 
10
16
  interface DataEditorProps {
17
+ /** The entry's id, or '' for a new entry, which `create` writes on the first Save. */
11
18
  id: string;
12
19
  collection: string;
13
20
  initialLocale: string;
14
21
  existingLocales: string[];
15
22
  schema: HostSchema | null;
23
+ /** Writes a new entry holding `data`; resolves true once it is created. */
24
+ create?: (data: DataCollectionEntry['data']) => Promise<boolean>;
16
25
  onSave?: () => void;
17
26
  onCancel?: () => void;
18
27
  }
@@ -28,6 +37,7 @@ export function DataEditor({
28
37
  initialLocale,
29
38
  existingLocales,
30
39
  schema,
40
+ create,
31
41
  onSave,
32
42
  onCancel,
33
43
  }: DataEditorProps) {
@@ -47,6 +57,8 @@ export function DataEditor({
47
57
  const [values, setValues] = useState<Record<string, unknown>>({});
48
58
  const [hasChanges, setHasChanges] = useState(false);
49
59
  const [saveError, setSaveError] = useState<string | null>(null);
60
+ const [saving, setSaving] = useState(false);
61
+ const isNew = id === '';
50
62
 
51
63
  // Initialize form values and etag when entry loads
52
64
  useEffect(() => {
@@ -67,28 +79,46 @@ export function DataEditor({
67
79
  setHasChanges(true);
68
80
  };
69
81
 
70
- // Save handler
71
- const handleSave = async () => {
72
- setSaveError(null);
82
+ /**
83
+ * Writes the form once it passes the schema, as the build validates the entry; resolves whether it
84
+ * was written.
85
+ */
86
+ const handleSave = async (): Promise<boolean> => {
87
+ if (saving || !isHostSchema(schema)) return false;
88
+ const invalid = validateEntryData(schema, values);
89
+ setSaveError(invalid);
90
+ if (invalid) return false;
73
91
 
74
- const result = await updateLocalized.mutateAsync({
75
- id,
76
- locale: currentLocale,
77
- data: {
78
- content: { data: values },
79
- },
80
- etag: currentEtag,
81
- });
92
+ setSaving(true);
93
+ try {
94
+ if (isNew) {
95
+ const created = (await create?.(values)) ?? false;
96
+ if (created) onSave?.();
97
+ return created;
98
+ }
82
99
 
83
- if (result.success) {
100
+ const result = await updateLocalized.mutateAsync({
101
+ id,
102
+ locale: currentLocale,
103
+ data: {
104
+ content: { data: values },
105
+ },
106
+ etag: currentEtag,
107
+ });
108
+
109
+ if (!result.success) {
110
+ setSaveError(contentFailureMessage(result, 'Failed to save data'));
111
+ return false;
112
+ }
84
113
  setHasChanges(false);
85
114
  savedValuesRef.current = values;
86
115
  if (result.etag) {
87
116
  setCurrentEtag(result.etag);
88
117
  }
89
118
  onSave?.();
90
- } else {
91
- setSaveError(contentFailureMessage(result, 'Failed to save data'));
119
+ return true;
120
+ } finally {
121
+ setSaving(false);
92
122
  }
93
123
  };
94
124
 
@@ -131,11 +161,12 @@ export function DataEditor({
131
161
  const handleUnsavedDialogSave = async () => {
132
162
  if (!pendingLocaleSwitch) return;
133
163
 
134
- // Save current content first
164
+ // Save current content first; a refused save keeps the locale and the edits, with the reason shown.
135
165
  try {
136
- await handleSave();
166
+ const saved = await handleSave();
137
167
  setShowUnsavedDialog(false);
138
- await switchLocale(pendingLocaleSwitch);
168
+ if (saved) await switchLocale(pendingLocaleSwitch);
169
+ else setPendingLocaleSwitch(null);
139
170
  } catch (error) {
140
171
  // Don't switch if save failed
141
172
  console.error('Failed to save before locale switch:', error);
@@ -196,15 +227,17 @@ export function DataEditor({
196
227
  return (
197
228
  <>
198
229
  <div className="space-y-6">
199
- {/* Locale selector header - only show existing locales */}
200
- <div className="flex items-center gap-3 pb-4 border-b border-grey-09 dark:border-grey-03">
201
- <span className="text-sm text-grey-04 dark:text-grey-07">Locale:</span>
202
- <LocaleSelector
203
- currentLocale={currentLocale}
204
- availableLocales={existingLocales}
205
- onChange={handleLocaleChange}
206
- />
207
- </div>
230
+ {/* Locale selector header - only show existing locales; a new entry has one, the one it is created in */}
231
+ {!isNew && (
232
+ <div className="flex items-center gap-3 pb-4 border-b border-grey-09 dark:border-grey-03">
233
+ <span className="text-sm text-grey-04 dark:text-grey-07">Locale:</span>
234
+ <LocaleSelector
235
+ currentLocale={currentLocale}
236
+ availableLocales={existingLocales}
237
+ onChange={handleLocaleChange}
238
+ />
239
+ </div>
240
+ )}
208
241
 
209
242
  <SchemaForm schema={schema} values={values} onChange={handleChange} />
210
243
 
@@ -220,7 +253,7 @@ export function DataEditor({
220
253
  {hasChanges ? (
221
254
  <span className="text-yellow-05 dark:text-yellow-07">Unsaved changes</span>
222
255
  ) : (
223
- <span>No changes</span>
256
+ <span>{isNew ? 'Not saved yet' : 'No changes'}</span>
224
257
  )}
225
258
  </div>
226
259
 
@@ -229,7 +262,7 @@ export function DataEditor({
229
262
  <button
230
263
  type="button"
231
264
  onClick={onCancel}
232
- disabled={updateLocalized.isPending}
265
+ disabled={saving}
233
266
  className="px-4 py-2 border border-grey-09 dark:border-grey-03 rounded-md hover:bg-grey-11 dark:hover:bg-grey-03 transition-colors disabled:opacity-50"
234
267
  >
235
268
  Cancel
@@ -238,10 +271,10 @@ export function DataEditor({
238
271
  <button
239
272
  type="button"
240
273
  onClick={handleSave}
241
- disabled={!hasChanges || updateLocalized.isPending}
274
+ disabled={(!hasChanges && !isNew) || saving || !isHostSchema(schema)}
242
275
  className="px-4 py-2 bg-azure-04 text-white rounded-md hover:bg-azure-03 transition-colors disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-2"
243
276
  >
244
- {updateLocalized.isPending ? (
277
+ {saving ? (
245
278
  <>
246
279
  <Loader2 className="h-4 w-4 animate-spin" />
247
280
  Saving...
@@ -1,7 +1,7 @@
1
1
  import { FolderOpen } from 'lucide-react';
2
2
  import { useEffect, useState } from 'react';
3
3
  import type { AssetEntry } from '../../hooks/index.js';
4
- import { buildAssetRef } from '../../utils/asset-url.js';
4
+ import { assetRefOf } from '../../utils/asset-url.js';
5
5
  import { ImagePicker } from '../media/ImagePicker.js';
6
6
  import { Input } from '../ui/index.js';
7
7
 
@@ -33,7 +33,7 @@ export function ImageFieldRender({ value, onChange, inputId }: ImageFieldRenderP
33
33
  }, [value]);
34
34
 
35
35
  const handleSelect = (asset: AssetEntry) => {
36
- const assetPath = buildAssetRef(asset.folder, asset.filename);
36
+ const assetPath = assetRefOf(asset);
37
37
  onChange(assetPath);
38
38
  setLocalValue(assetPath);
39
39
  setModalOpen(false);
@@ -1,8 +1,8 @@
1
- import { useAssetServeSrc } from '../../frame/media-cache.js';
2
1
  import type { AssetEntry } from '../../hooks/index.js';
3
2
  import { AssetScopePill } from '../../media/AssetScopePill.js';
4
3
  import { MediaIssueBadge } from '../../media/MediaIssueBadge.js';
5
4
  import { useAssetScope } from '../../media/use-asset-scope.js';
5
+ import { useAssetServeSrc } from '../../media/use-asset-serve-src.js';
6
6
  import { useMediaIssue } from '../../media/use-media-issue.js';
7
7
  import { cn } from '../../utils/cn.js';
8
8
 
@@ -33,7 +33,7 @@ export function AssetCard({
33
33
  // reports. Returns null when the host has no opinion — surfaces
34
34
  // degrade exactly like the scope pill in standalone mounts.
35
35
  const issue = useMediaIssue(asset.filename, asset.folder);
36
- const src = useAssetServeSrc(assetsBasePath, asset.folder, asset.filename);
36
+ const src = useAssetServeSrc(assetsBasePath, asset);
37
37
 
38
38
  const handleClick = () => {
39
39
  onClick?.();
@@ -78,8 +78,8 @@ export function AssetCard({
78
78
 
79
79
  {/* Info - filename only */}
80
80
  <div className="px-2 py-1.5">
81
- <p className="text-xs text-grey-01 dark:text-grey-12 truncate" title={asset.originalName}>
82
- {asset.originalName}
81
+ <p className="text-xs text-grey-01 dark:text-grey-12 truncate" title={asset.filename}>
82
+ {asset.filename}
83
83
  </p>
84
84
  </div>
85
85
  </button>