@conloca/cms-spa 0.2.3 → 0.2.4

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 (166) hide show
  1. package/dist/spa/main.css +6 -0
  2. package/dist/ts/.build-inputs.json +36 -27
  3. package/dist/ts/components/CMSDashboard.d.ts.map +1 -1
  4. package/dist/ts/components/CMSDashboard.js +2 -1
  5. package/dist/ts/components/CMSDashboard.js.map +1 -1
  6. package/dist/ts/components/dialogs/DeleteConfirmDialog.d.ts +6 -1
  7. package/dist/ts/components/dialogs/DeleteConfirmDialog.d.ts.map +1 -1
  8. package/dist/ts/components/dialogs/DeleteConfirmDialog.js +2 -2
  9. package/dist/ts/components/dialogs/DeleteConfirmDialog.js.map +1 -1
  10. package/dist/ts/components/dialogs/MakePagesEditableDialog.d.ts +10 -0
  11. package/dist/ts/components/dialogs/MakePagesEditableDialog.d.ts.map +1 -0
  12. package/dist/ts/components/dialogs/MakePagesEditableDialog.js +35 -0
  13. package/dist/ts/components/dialogs/MakePagesEditableDialog.js.map +1 -0
  14. package/dist/ts/components/dialogs/MoveFolderDialog.d.ts +6 -1
  15. package/dist/ts/components/dialogs/MoveFolderDialog.d.ts.map +1 -1
  16. package/dist/ts/components/dialogs/MoveFolderDialog.js +3 -3
  17. package/dist/ts/components/dialogs/MoveFolderDialog.js.map +1 -1
  18. package/dist/ts/components/editor/CMSMDXEditor.d.ts.map +1 -1
  19. package/dist/ts/components/editor/CMSMDXEditor.js +9 -9
  20. package/dist/ts/components/editor/CMSMDXEditor.js.map +1 -1
  21. package/dist/ts/components/editor/DocsPreviewButton.d.ts +6 -0
  22. package/dist/ts/components/editor/DocsPreviewButton.d.ts.map +1 -0
  23. package/dist/ts/components/editor/DocsPreviewButton.js +15 -0
  24. package/dist/ts/components/editor/DocsPreviewButton.js.map +1 -0
  25. package/dist/ts/components/editor/ImagePickerDialog.js +2 -2
  26. package/dist/ts/components/editor/ImagePickerDialog.js.map +1 -1
  27. package/dist/ts/components/editor/MdxPageEditor.d.ts.map +1 -1
  28. package/dist/ts/components/editor/MdxPageEditor.js +2 -1
  29. package/dist/ts/components/editor/MdxPageEditor.js.map +1 -1
  30. package/dist/ts/components/editor/PageEditor.d.ts.map +1 -1
  31. package/dist/ts/components/editor/PageEditor.js +1 -2
  32. package/dist/ts/components/editor/PageEditor.js.map +1 -1
  33. package/dist/ts/components/editor/draft-media-config.d.ts +20 -8
  34. package/dist/ts/components/editor/draft-media-config.d.ts.map +1 -1
  35. package/dist/ts/components/editor/draft-media-config.js +124 -60
  36. package/dist/ts/components/editor/draft-media-config.js.map +1 -1
  37. package/dist/ts/components/editor/preview-availability.d.ts +2 -0
  38. package/dist/ts/components/editor/preview-availability.d.ts.map +1 -1
  39. package/dist/ts/components/editor/preview-availability.js +2 -0
  40. package/dist/ts/components/editor/preview-availability.js.map +1 -1
  41. package/dist/ts/components/editors/DataEditor.d.ts +6 -2
  42. package/dist/ts/components/editors/DataEditor.d.ts.map +1 -1
  43. package/dist/ts/components/editors/DataEditor.js +46 -19
  44. package/dist/ts/components/editors/DataEditor.js.map +1 -1
  45. package/dist/ts/components/fields/ImageField.js +2 -2
  46. package/dist/ts/components/fields/ImageField.js.map +1 -1
  47. package/dist/ts/components/media/AssetCard.d.ts.map +1 -1
  48. package/dist/ts/components/media/AssetCard.js +3 -3
  49. package/dist/ts/components/media/AssetCard.js.map +1 -1
  50. package/dist/ts/components/media/AssetDetailSidebar.d.ts.map +1 -1
  51. package/dist/ts/components/media/AssetDetailSidebar.js +6 -3
  52. package/dist/ts/components/media/AssetDetailSidebar.js.map +1 -1
  53. package/dist/ts/components/media/AssetUsageList.d.ts +13 -0
  54. package/dist/ts/components/media/AssetUsageList.d.ts.map +1 -0
  55. package/dist/ts/components/media/AssetUsageList.js +35 -0
  56. package/dist/ts/components/media/AssetUsageList.js.map +1 -0
  57. package/dist/ts/components/media/MediaLibrary.d.ts.map +1 -1
  58. package/dist/ts/components/media/MediaLibrary.js +6 -4
  59. package/dist/ts/components/media/MediaLibrary.js.map +1 -1
  60. package/dist/ts/components/media/index.d.ts +1 -0
  61. package/dist/ts/components/media/index.d.ts.map +1 -1
  62. package/dist/ts/components/media/index.js +1 -0
  63. package/dist/ts/components/media/index.js.map +1 -1
  64. package/dist/ts/components/pages/DataList.d.ts.map +1 -1
  65. package/dist/ts/components/pages/DataList.js +48 -31
  66. package/dist/ts/components/pages/DataList.js.map +1 -1
  67. package/dist/ts/components/pages/MediaPage.d.ts.map +1 -1
  68. package/dist/ts/components/pages/MediaPage.js +7 -5
  69. package/dist/ts/components/pages/MediaPage.js.map +1 -1
  70. package/dist/ts/components/pages/NoPagesYet.d.ts +5 -0
  71. package/dist/ts/components/pages/NoPagesYet.d.ts.map +1 -0
  72. package/dist/ts/components/pages/NoPagesYet.js +16 -0
  73. package/dist/ts/components/pages/NoPagesYet.js.map +1 -0
  74. package/dist/ts/components/pages/PageList.d.ts.map +1 -1
  75. package/dist/ts/components/pages/PageList.js +9 -4
  76. package/dist/ts/components/pages/PageList.js.map +1 -1
  77. package/dist/ts/components/sandbox/ContentSandbox.js +3 -3
  78. package/dist/ts/components/sandbox/ContentSandbox.js.map +1 -1
  79. package/dist/ts/convert-pages.d.ts +30 -0
  80. package/dist/ts/convert-pages.d.ts.map +1 -0
  81. package/dist/ts/convert-pages.js +85 -0
  82. package/dist/ts/convert-pages.js.map +1 -0
  83. package/dist/ts/frame/editor-frame.d.ts +1 -1
  84. package/dist/ts/frame/editor-frame.d.ts.map +1 -1
  85. package/dist/ts/frame/editor-frame.js +7 -2
  86. package/dist/ts/frame/editor-frame.js.map +1 -1
  87. package/dist/ts/frame/media-cache.d.ts +13 -2
  88. package/dist/ts/frame/media-cache.d.ts.map +1 -1
  89. package/dist/ts/frame/media-cache.js +24 -9
  90. package/dist/ts/frame/media-cache.js.map +1 -1
  91. package/dist/ts/frame/protocol.d.ts +9 -1
  92. package/dist/ts/frame/protocol.d.ts.map +1 -1
  93. package/dist/ts/frame/protocol.js +5 -0
  94. package/dist/ts/frame/protocol.js.map +1 -1
  95. package/dist/ts/hooks/index.d.ts +2 -0
  96. package/dist/ts/hooks/index.d.ts.map +1 -1
  97. package/dist/ts/hooks/index.js +1 -0
  98. package/dist/ts/hooks/index.js.map +1 -1
  99. package/dist/ts/hooks/usePageConversion.d.ts +11 -0
  100. package/dist/ts/hooks/usePageConversion.d.ts.map +1 -0
  101. package/dist/ts/hooks/usePageConversion.js +47 -0
  102. package/dist/ts/hooks/usePageConversion.js.map +1 -0
  103. package/dist/ts/hooks/useUploadFlow.d.ts.map +1 -1
  104. package/dist/ts/hooks/useUploadFlow.js +41 -7
  105. package/dist/ts/hooks/useUploadFlow.js.map +1 -1
  106. package/dist/ts/index.d.ts +2 -0
  107. package/dist/ts/index.d.ts.map +1 -1
  108. package/dist/ts/index.js +3 -0
  109. package/dist/ts/index.js.map +1 -1
  110. package/dist/ts/media/prepare-image-upload.d.ts +19 -0
  111. package/dist/ts/media/prepare-image-upload.d.ts.map +1 -0
  112. package/dist/ts/media/prepare-image-upload.js +93 -0
  113. package/dist/ts/media/prepare-image-upload.js.map +1 -0
  114. package/dist/ts/media/use-asset-serve-src.d.ts +7 -0
  115. package/dist/ts/media/use-asset-serve-src.d.ts.map +1 -0
  116. package/dist/ts/media/use-asset-serve-src.js +17 -0
  117. package/dist/ts/media/use-asset-serve-src.js.map +1 -0
  118. package/dist/ts/ui-config.d.ts +13 -3
  119. package/dist/ts/ui-config.d.ts.map +1 -1
  120. package/dist/ts/ui-config.js +14 -0
  121. package/dist/ts/ui-config.js.map +1 -1
  122. package/dist/ts/utils/asset-url.d.ts +3 -0
  123. package/dist/ts/utils/asset-url.d.ts.map +1 -1
  124. package/dist/ts/utils/asset-url.js +4 -0
  125. package/dist/ts/utils/asset-url.js.map +1 -1
  126. package/dist/ts/utils/data-entry-validation.d.ts +11 -0
  127. package/dist/ts/utils/data-entry-validation.d.ts.map +1 -0
  128. package/dist/ts/utils/data-entry-validation.js +15 -0
  129. package/dist/ts/utils/data-entry-validation.js.map +1 -0
  130. package/package.json +4 -5
  131. package/src/components/CMSDashboard.tsx +16 -8
  132. package/src/components/dialogs/DeleteConfirmDialog.tsx +14 -1
  133. package/src/components/dialogs/MakePagesEditableDialog.tsx +112 -0
  134. package/src/components/dialogs/MoveFolderDialog.tsx +9 -2
  135. package/src/components/editor/CMSMDXEditor.tsx +9 -9
  136. package/src/components/editor/DocsPreviewButton.tsx +25 -0
  137. package/src/components/editor/ImagePickerDialog.tsx +2 -2
  138. package/src/components/editor/MdxPageEditor.tsx +2 -0
  139. package/src/components/editor/PageEditor.tsx +1 -5
  140. package/src/components/editor/draft-media-config.ts +121 -65
  141. package/src/components/editor/preview-availability.ts +3 -0
  142. package/src/components/editors/DataEditor.tsx +65 -32
  143. package/src/components/fields/ImageField.tsx +2 -2
  144. package/src/components/media/AssetCard.tsx +4 -4
  145. package/src/components/media/AssetDetailSidebar.tsx +34 -21
  146. package/src/components/media/AssetUsageList.tsx +84 -0
  147. package/src/components/media/MediaLibrary.tsx +6 -4
  148. package/src/components/media/index.ts +1 -0
  149. package/src/components/pages/DataList.tsx +53 -29
  150. package/src/components/pages/MediaPage.tsx +14 -5
  151. package/src/components/pages/NoPagesYet.tsx +41 -0
  152. package/src/components/pages/PageList.tsx +28 -23
  153. package/src/components/sandbox/ContentSandbox.tsx +3 -3
  154. package/src/convert-pages.ts +110 -0
  155. package/src/frame/editor-frame.ts +6 -2
  156. package/src/frame/media-cache.ts +28 -15
  157. package/src/frame/protocol.ts +10 -1
  158. package/src/hooks/index.ts +2 -0
  159. package/src/hooks/usePageConversion.ts +55 -0
  160. package/src/hooks/useUploadFlow.ts +44 -7
  161. package/src/index.ts +3 -0
  162. package/src/media/prepare-image-upload.ts +118 -0
  163. package/src/media/use-asset-serve-src.ts +22 -0
  164. package/src/ui-config.ts +23 -3
  165. package/src/utils/asset-url.ts +6 -0
  166. package/src/utils/data-entry-validation.ts +16 -0
@@ -1,3 +1,4 @@
1
+ import type { ReactNode } from 'react';
1
2
  import { Button } from '../ui/index.js';
2
3
 
3
4
  interface DeleteConfirmDialogProps {
@@ -8,6 +9,10 @@ interface DeleteConfirmDialogProps {
8
9
  message?: string;
9
10
  itemName?: string;
10
11
  isDeleting?: boolean;
12
+ /** Shown above the warning, e.g. the pages that use what is about to go. */
13
+ children?: ReactNode;
14
+ /** Holds the confirm button until the caller is ready, e.g. until those pages are known. */
15
+ confirmDisabled?: boolean;
11
16
  }
12
17
 
13
18
  export function DeleteConfirmDialog({
@@ -18,6 +23,8 @@ export function DeleteConfirmDialog({
18
23
  message,
19
24
  itemName,
20
25
  isDeleting = false,
26
+ children,
27
+ confirmDisabled = false,
21
28
  }: DeleteConfirmDialogProps) {
22
29
  if (!isOpen) return null;
23
30
 
@@ -35,6 +42,7 @@ export function DeleteConfirmDialog({
35
42
  "{itemName}"
36
43
  </p>
37
44
  )}
45
+ {children}
38
46
  <p className="text-red-04 dark:text-red-08 text-sm mt-3" data-testid="delete-warning-message">
39
47
  This action cannot be undone.
40
48
  </p>
@@ -44,7 +52,12 @@ export function DeleteConfirmDialog({
44
52
  <Button variant="outline" onClick={onCancel} disabled={isDeleting}>
45
53
  Cancel
46
54
  </Button>
47
- <Button variant="destructive" onClick={onConfirm} disabled={isDeleting} className="flex items-center gap-2">
55
+ <Button
56
+ variant="destructive"
57
+ onClick={onConfirm}
58
+ disabled={isDeleting || confirmDisabled}
59
+ className="flex items-center gap-2"
60
+ >
48
61
  {isDeleting ? (
49
62
  <>
50
63
  <span className="inline-block animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
@@ -0,0 +1,112 @@
1
+ import * as Dialog from '@radix-ui/react-dialog';
2
+ import { X } from 'lucide-react';
3
+ import { useState } from 'react';
4
+ import { conversionPrompt } from '../../convert-pages.js';
5
+ import type { PageConversionOffer } from '../../hooks/index.js';
6
+ import { Button, IconButton, Textarea } from '../ui/index.js';
7
+
8
+ interface MakePagesEditableDialogProps {
9
+ open: boolean;
10
+ onOpenChange: (open: boolean) => void;
11
+ offer: PageConversionOffer;
12
+ }
13
+
14
+ /** Lets the person editing choose Astro pages to convert and copy the prompt that has a coding agent convert them. */
15
+ export function MakePagesEditableDialog({ open, onOpenChange, offer }: MakePagesEditableDialogProps) {
16
+ return (
17
+ <Dialog.Root open={open} onOpenChange={onOpenChange}>
18
+ <Dialog.Portal>
19
+ <Dialog.Overlay className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm" />
20
+ <Dialog.Content
21
+ className="fixed top-1/2 left-1/2 z-50 -translate-x-1/2 -translate-y-1/2 bg-overlay rounded-lg shadow-lg p-6 w-full max-w-md mx-4 max-h-[90vh] overflow-y-auto"
22
+ aria-describedby={undefined}
23
+ >
24
+ <div className="flex items-center justify-between mb-4">
25
+ <Dialog.Title className="text-lg font-semibold">Make existing pages editable</Dialog.Title>
26
+ <Dialog.Close asChild>
27
+ <IconButton icon={X} ariaLabel="Close" variant="ghost" />
28
+ </Dialog.Close>
29
+ </div>
30
+ {/* Dialog.Content mounts the picker on every open, so each open starts with nothing chosen. */}
31
+ <RoutePicker offer={offer} />
32
+ </Dialog.Content>
33
+ </Dialog.Portal>
34
+ </Dialog.Root>
35
+ );
36
+ }
37
+
38
+ function RoutePicker({ offer }: { offer: PageConversionOffer }) {
39
+ const { facts, collection, candidates } = offer;
40
+ const [checked, setChecked] = useState<ReadonlySet<string>>(new Set());
41
+ const [copied, setCopied] = useState<'copied' | 'failed' | undefined>();
42
+ const chosen = candidates?.filter((route) => checked.has(route)) ?? [];
43
+ const prompt = conversionPrompt({ facts, collection, routes: chosen.length > 0 ? chosen : undefined });
44
+
45
+ const toggle = (route: string) => {
46
+ const next = new Set(checked);
47
+ if (!next.delete(route)) next.add(route);
48
+ setChecked(next);
49
+ setCopied(undefined);
50
+ };
51
+
52
+ const copy = async () => {
53
+ try {
54
+ await navigator.clipboard.writeText(prompt);
55
+ setCopied('copied');
56
+ } catch {
57
+ setCopied('failed');
58
+ }
59
+ };
60
+
61
+ return (
62
+ <div className="space-y-4 text-sm">
63
+ {candidates === undefined ? (
64
+ <p className="text-grey-04 dark:text-grey-07">
65
+ Conloca doesn't have this site's page list yet. The prompt asks your coding agent to update Conloca first,
66
+ then list the pages so you can choose.
67
+ </p>
68
+ ) : (
69
+ <>
70
+ <p className="text-grey-04 dark:text-grey-07">
71
+ Choose the pages to convert. Pages you don't choose stay as they are.
72
+ </p>
73
+ <ul className="max-h-60 overflow-y-auto space-y-2">
74
+ {candidates.map((route) => (
75
+ <li key={route}>
76
+ <label className="flex items-center gap-2">
77
+ <input
78
+ type="checkbox"
79
+ checked={checked.has(route)}
80
+ onChange={() => toggle(route)}
81
+ className="w-4 h-4 rounded-md border-grey-09 text-azure-04 focus:ring-azure-04"
82
+ />
83
+ <span className="text-sm font-medium text-grey-01 dark:text-grey-12">{route}</span>
84
+ </label>
85
+ </li>
86
+ ))}
87
+ </ul>
88
+ </>
89
+ )}
90
+ <p className="text-grey-04 dark:text-grey-07">
91
+ Copy the prompt, then paste it into your coding agent or send it to your developer. Review the changes, then
92
+ commit, push and deploy; converted pages then show up here.
93
+ </p>
94
+ {/* Only shown when the clipboard refuses, so the prompt can still be copied by hand. */}
95
+ {copied === 'failed' && <Textarea aria-label="Prompt" readOnly value={prompt} rows={6} />}
96
+ <p role="status" className="text-grey-04 dark:text-grey-07 min-h-5">
97
+ {copied === 'copied' && 'Copied. Paste it into your coding agent.'}
98
+ {copied === 'failed' && 'Copying failed. Select the prompt above and copy it yourself.'}
99
+ </p>
100
+ <div className="flex gap-2 pt-4">
101
+ <Button onClick={copy} disabled={candidates !== undefined && chosen.length === 0} className="flex-1">
102
+ Copy prompt
103
+ </Button>
104
+ <Dialog.Close asChild>
105
+ <Button variant="outline" className="flex-1">
106
+ Close
107
+ </Button>
108
+ </Dialog.Close>
109
+ </div>
110
+ </div>
111
+ );
112
+ }
@@ -1,5 +1,5 @@
1
1
  import { Folder, X } from 'lucide-react';
2
- import { useEffect, useRef, useState } from 'react';
2
+ import { type ReactNode, useEffect, useRef, useState } from 'react';
3
3
  import { type FolderTreeNode, useFolderTree } from '../../hooks/index.js';
4
4
  import { cn } from '../../utils/cn.js';
5
5
  import { contentFailureMessage } from '../../utils/content-failure.js';
@@ -13,6 +13,10 @@ interface MoveFolderDialogProps {
13
13
  onMove: (targetFolder: string) => Promise<void>;
14
14
  onCancel: () => void;
15
15
  isMoving?: boolean;
16
+ /** Shown above the folder list, e.g. the pages that link what is about to move. */
17
+ children?: ReactNode;
18
+ /** Holds the Move button until the caller is ready, e.g. until those pages are known. */
19
+ confirmDisabled?: boolean;
16
20
  }
17
21
 
18
22
  interface FolderOptionProps {
@@ -69,6 +73,8 @@ export function MoveFolderDialog({
69
73
  onMove,
70
74
  onCancel,
71
75
  isMoving = false,
76
+ children,
77
+ confirmDisabled = false,
72
78
  }: MoveFolderDialogProps) {
73
79
  const [selectedFolder, setSelectedFolder] = useState<string | null>(null);
74
80
  const [moveError, setMoveError] = useState<string | null>(null);
@@ -117,7 +123,7 @@ export function MoveFolderDialog({
117
123
 
118
124
  if (!isOpen) return null;
119
125
 
120
- const canMove = selectedFolder !== null && selectedFolder !== currentFolder;
126
+ const canMove = selectedFolder !== null && selectedFolder !== currentFolder && !confirmDisabled;
121
127
 
122
128
  return (
123
129
  <div
@@ -134,6 +140,7 @@ export function MoveFolderDialog({
134
140
  <IconButton icon={X} ariaLabel="Cancel" onClick={onCancel} variant="ghost" />
135
141
  </div>
136
142
 
143
+ {children ? <div className="px-6 pt-4">{children}</div> : null}
137
144
  {/* Folder list */}
138
145
  <div className="p-4 max-h-80 overflow-y-auto">
139
146
  {isLoading ? (
@@ -1,4 +1,4 @@
1
- import { useUploadAsset } from '@conloca/content-api-client';
1
+ import { DEFAULT_MAX_FILE_SIZE, useUploadAsset } from '@conloca/content-api-client';
2
2
  import { BaseMDXEditor, type BaseMDXEditorProps } from '@conloca/mdx';
3
3
  // The editor stylesheet; it pulls MDXEditor's own sheet in first. Position
4
4
  // would not decide the cascade anyway: MDXEditor injects its CSS-module
@@ -12,6 +12,7 @@ import { useTheme } from '../../hooks/useTheme.js';
12
12
  import { buildUploadFormData } from '../../hooks/useUpload.js';
13
13
  import { useProbedHostStyles } from '../../host-style-probe.js';
14
14
  import { isJsxDescriptor, toJsxComponentDescriptor, useMdxComponents } from '../../mdx-components.js';
15
+ import { prepareImageUpload } from '../../media/prepare-image-upload.js';
15
16
  import { deriveProseSurfaceStyles } from '../../prose-surface-css.js';
16
17
  import {
17
18
  type SiteStyles,
@@ -22,7 +23,7 @@ import {
22
23
  useSiteStyles,
23
24
  } from '../../site-styles.js';
24
25
  import { getUIConfig, inEditorFrame } from '../../ui-config.js';
25
- import { buildAssetRef } from '../../utils/asset-url.js';
26
+ import { assetRefOf } from '../../utils/asset-url.js';
26
27
  import { draftImagePreview } from './draft-media-config.js';
27
28
  import { GenericBlock } from './GenericBlock.js';
28
29
  import { hostWrapperPlugin } from './host-wrapper-plugin.js';
@@ -221,14 +222,13 @@ export const CMSMDXEditor = forwardRef<MDXEditorMethods, CMSMDXEditorProps>(({ p
221
222
 
222
223
  // Wire paste/drop image uploads to the same backend mutation that powers
223
224
  // the asset library's UploadModal. The library expects a Promise<string>
224
- // resolving to the image src; we hand back the stored reference
225
- // buildAssetRef builds, so it round-trips identically to a path picked
226
- // from the asset browser.
225
+ // resolving to the image src; we hand back the link `assetRefOf` stores,
226
+ // so it round-trips identically to a path picked from the asset browser.
227
227
  const imageUploadHandler = useCallback(
228
228
  async (file: File) => {
229
- const formData = buildUploadFormData(file, undefined, '/');
229
+ const formData = buildUploadFormData(await prepareImageUpload(file, DEFAULT_MAX_FILE_SIZE), undefined, '/');
230
230
  const asset = await uploadAsset.mutateAsync(formData);
231
- return buildAssetRef(asset.folder, asset.filename);
231
+ return assetRefOf(asset);
232
232
  },
233
233
  [uploadAsset],
234
234
  );
@@ -241,8 +241,8 @@ export const CMSMDXEditor = forwardRef<MDXEditorMethods, CMSMDXEditorProps>(({ p
241
241
  disableImageSettingsButton={true}
242
242
  imageButtonRef={insertImageRef}
243
243
  imageUploadHandler={imageUploadHandler}
244
- // The site does not serve branch drafts; with a loader, draft images show their loaded bytes.
245
- imagePreviewHandler={getUIConfig().loadMedia ? draftImagePreview : undefined}
244
+ // The site does not serve branch drafts: draft images show their loaded bytes, draft addresses a placeholder until then.
245
+ imagePreviewHandler={draftImagePreview}
246
246
  jsxComponentDescriptors={jsxComponentDescriptors}
247
247
  extraPlugins={extraPlugins}
248
248
  extraToolbarItems={<InsertMdxComponentButton />}
@@ -0,0 +1,25 @@
1
+ import { getUIConfig } from '../../ui-config.js';
2
+ import { cn } from '../../utils/cn.js';
3
+ import { toast } from '../toast.js';
4
+ import { DOCS_PREVIEW_UNAVAILABLE } from './preview-availability.js';
5
+
6
+ /**
7
+ * The Preview control of a docs page in the workspace editor. Docs pages are prerendered, so a preview link would show
8
+ * the published page: the control stays, focusable and explained, rather than opening something that looks wrong.
9
+ */
10
+ export function DocsPreviewButton() {
11
+ if (getUIConfig().openPreview === undefined) return null;
12
+ return (
13
+ <button
14
+ type="button"
15
+ aria-disabled="true"
16
+ title={DOCS_PREVIEW_UNAVAILABLE}
17
+ aria-label={`Preview unavailable. ${DOCS_PREVIEW_UNAVAILABLE}`}
18
+ onClick={() => toast.info(DOCS_PREVIEW_UNAVAILABLE)}
19
+ className={cn('px-3 py-1.5 text-sm border border-line rounded text-muted cursor-not-allowed')}
20
+ data-testid="mdx-page-preview"
21
+ >
22
+ Preview
23
+ </button>
24
+ );
25
+ }
@@ -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";