@conloca/cms-spa 0.1.4-rc.1 → 0.1.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.
@@ -0,0 +1,1499 @@
1
+ import { BlockTypeSelect, BoldItalicUnderlineToggles, CreateLink, DiffSourceToggleWrapper, InsertCodeBlock, InsertImage, InsertTable, InsertThematicBreak, ListsToggle, MDXEditor, Separator, UndoRedo, closeImageDialog$, codeBlockPlugin, codeMirrorPlugin, diffSourcePlugin, frontmatterPlugin, headingsPlugin, imageDialogState$, imagePlugin, insertImage$, jsxPlugin, linkDialogPlugin, linkPlugin, listsPlugin, markdownShortcutPlugin, quotePlugin, tablePlugin, thematicBreakPlugin, toolbarPlugin, useCellValue, usePublisher } from "@mdxeditor/editor";
2
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
+ import "@mdxeditor/editor/style.css";
4
+ import { Folder, FolderPlus, Search, Upload, X } from "lucide-react";
5
+ import { useAssetFolders, useAssetUsage, useCreateFolder, useDeleteAsset, useFolderTree as useFolderTree$1, useImportAssetUrl, useMoveAssets, useUpdateAssetMetadata, useUploadAsset } from "@conloca/content-api-client";
6
+ import { clsx } from "clsx";
7
+ import { twMerge } from "tailwind-merge";
8
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
+ import { useMDXEvaluation } from "@conloca/mdx";
10
+
11
+ //#region src/hooks/useClickOutside.ts
12
+ /**
13
+ * Hook that triggers a callback when clicking outside the referenced element.
14
+ * Useful for closing dropdowns, modals, etc.
15
+ */
16
+ function useClickOutside(ref, callback, enabled = true) {
17
+ useEffect(() => {
18
+ if (!enabled) return;
19
+ const handleClickOutside = (event) => {
20
+ if (ref.current && !ref.current.contains(event.target)) callback();
21
+ };
22
+ document.addEventListener("mousedown", handleClickOutside);
23
+ return () => document.removeEventListener("mousedown", handleClickOutside);
24
+ }, [
25
+ ref,
26
+ callback,
27
+ enabled
28
+ ]);
29
+ }
30
+
31
+ //#endregion
32
+ //#region src/hooks/useDialogState.ts
33
+ /**
34
+ * Generic hook for managing dialog state with open/close functionality.
35
+ * Reduces boilerplate for dialogs that need to track additional data alongside isOpen.
36
+ *
37
+ * @param initialData - The initial state for dialog data (excluding isOpen)
38
+ * @returns Tuple of [state, open, close] where state includes isOpen
39
+ *
40
+ * @example
41
+ * const [deleteDialog, openDeleteDialog, closeDeleteDialog] = useDialogState({
42
+ * entryId: '',
43
+ * entryTitle: '',
44
+ * });
45
+ *
46
+ * // Open with data
47
+ * openDeleteDialog({ entryId: '123', entryTitle: 'My Entry' });
48
+ *
49
+ * // Close (resets to initial state)
50
+ * closeDeleteDialog();
51
+ */
52
+ function useDialogState(initialData) {
53
+ const [state, setState] = useState({
54
+ ...initialData,
55
+ isOpen: false
56
+ });
57
+ return [
58
+ state,
59
+ useCallback((data) => {
60
+ setState({
61
+ ...initialData,
62
+ ...data,
63
+ isOpen: true
64
+ });
65
+ }, [initialData]),
66
+ useCallback(() => {
67
+ setState({
68
+ ...initialData,
69
+ isOpen: false
70
+ });
71
+ }, [initialData])
72
+ ];
73
+ }
74
+
75
+ //#endregion
76
+ //#region src/hooks/useErrorModal.tsx
77
+ function useErrorModal() {
78
+ const [errorModal, setErrorModal] = useState({
79
+ isOpen: false,
80
+ message: ""
81
+ });
82
+ const showError = (message, error, actions) => {
83
+ setErrorModal({
84
+ isOpen: true,
85
+ message,
86
+ error,
87
+ actions
88
+ });
89
+ };
90
+ const hideError = useCallback(() => {
91
+ setErrorModal({
92
+ isOpen: false,
93
+ message: "",
94
+ error: void 0,
95
+ actions: void 0
96
+ });
97
+ }, []);
98
+ return {
99
+ errorModal,
100
+ showError,
101
+ showStaleWriteError: useCallback((error) => {
102
+ showError("This entry has been modified by someone else. Would you like to reload and try again?", error, [{
103
+ label: "Reload",
104
+ onClick: () => window.location.reload(),
105
+ variant: "primary"
106
+ }, {
107
+ label: "Cancel",
108
+ onClick: hideError,
109
+ variant: "secondary"
110
+ }]);
111
+ }, [hideError]),
112
+ hideError,
113
+ errorModalProps: {
114
+ isOpen: errorModal.isOpen,
115
+ onClose: hideError,
116
+ message: errorModal.message,
117
+ error: errorModal.error,
118
+ actions: errorModal.actions
119
+ }
120
+ };
121
+ }
122
+
123
+ //#endregion
124
+ //#region src/ui-config.ts
125
+ const defaultConfig = {
126
+ basename: "/__cms",
127
+ apiBaseUrl: "/__cms/api",
128
+ siteBaseUrl: "",
129
+ enableDevtools: false,
130
+ queryClientOptions: { defaultOptions: { queries: {
131
+ staleTime: 1e3 * 60 * 5,
132
+ retry: 1
133
+ } } }
134
+ };
135
+ let config = { ...defaultConfig };
136
+ function configureUI(options) {
137
+ config = {
138
+ ...defaultConfig,
139
+ ...options
140
+ };
141
+ if (typeof window !== "undefined") window.__UI_CONFIG__ = config;
142
+ }
143
+ function getUIConfig() {
144
+ if (typeof window === "undefined") return config;
145
+ if (window.__UI_CONFIG__) return window.__UI_CONFIG__;
146
+ if (window.location.pathname === "/") return {
147
+ ...defaultConfig,
148
+ basename: void 0,
149
+ enableDevtools: true
150
+ };
151
+ return config;
152
+ }
153
+ if (typeof window !== "undefined") window.configureUI = configureUI;
154
+
155
+ //#endregion
156
+ //#region src/lib/utils.ts
157
+ /**
158
+ * Build a full URL from the site base URL and a path
159
+ * @param path The path to append (e.g., '/about')
160
+ * @returns The full URL (e.g., 'https://example.com/docs/about' or '/docs/about')
161
+ */
162
+ function buildSiteUrl(path) {
163
+ const siteBaseUrl = getUIConfig().siteBaseUrl || "";
164
+ if (!siteBaseUrl) return path;
165
+ if (siteBaseUrl.includes("://")) return `${siteBaseUrl.endsWith("/") ? siteBaseUrl.slice(0, -1) : siteBaseUrl}${path.startsWith("/") ? path : `/${path}`}`;
166
+ const prefix = siteBaseUrl.startsWith("/") ? siteBaseUrl : `/${siteBaseUrl}`;
167
+ return `${prefix.endsWith("/") ? prefix.slice(0, -1) : prefix}${path.startsWith("/") ? path : `/${path}`}`;
168
+ }
169
+ /**
170
+ * Extract the path from a full URL, removing the site base URL
171
+ * @param url The full URL (e.g., 'https://example.com/docs/about' or '/docs/about')
172
+ * @returns The path without base URL (e.g., '/about')
173
+ */
174
+ function extractPathFromUrl(url) {
175
+ const siteBaseUrl = getUIConfig().siteBaseUrl || "";
176
+ if (!siteBaseUrl) return url;
177
+ if (siteBaseUrl.includes("://") && url.startsWith(siteBaseUrl)) {
178
+ const withoutBase = url.slice(siteBaseUrl.length);
179
+ return withoutBase.startsWith("/") ? withoutBase : `/${withoutBase}`;
180
+ }
181
+ const prefix = siteBaseUrl.startsWith("/") ? siteBaseUrl : `/${siteBaseUrl}`;
182
+ const cleanPrefix = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
183
+ if (url.startsWith(cleanPrefix)) {
184
+ const withoutPrefix = url.slice(cleanPrefix.length);
185
+ return withoutPrefix.startsWith("/") ? withoutPrefix : `/${withoutPrefix}`;
186
+ }
187
+ return url;
188
+ }
189
+
190
+ //#endregion
191
+ //#region src/hooks/useSiteBaseUrl.ts
192
+ /**
193
+ * Hook to access and use the site base URL configuration
194
+ */
195
+ function useSiteBaseUrl() {
196
+ return {
197
+ siteBaseUrl: getUIConfig().siteBaseUrl || "",
198
+ buildUrl: buildSiteUrl,
199
+ extractPath: extractPathFromUrl
200
+ };
201
+ }
202
+
203
+ //#endregion
204
+ //#region src/hooks/useUpload.ts
205
+ /** Read image dimensions from a File using the browser Image API */
206
+ function getImageDimensions(file) {
207
+ return new Promise((resolve, reject) => {
208
+ if (!file.type.startsWith("image/")) {
209
+ reject(/* @__PURE__ */ new Error("File is not an image"));
210
+ return;
211
+ }
212
+ const url = URL.createObjectURL(file);
213
+ const img = new Image();
214
+ img.onload = () => {
215
+ resolve({
216
+ width: img.naturalWidth,
217
+ height: img.naturalHeight
218
+ });
219
+ URL.revokeObjectURL(url);
220
+ };
221
+ img.onerror = () => {
222
+ URL.revokeObjectURL(url);
223
+ reject(/* @__PURE__ */ new Error("Failed to load image for dimension reading"));
224
+ };
225
+ img.src = url;
226
+ });
227
+ }
228
+ /** Build FormData for asset upload, reading dimensions client-side */
229
+ async function buildUploadFormData(file, alt, folder) {
230
+ const formData = new FormData();
231
+ formData.append("file", file);
232
+ if (alt) formData.append("alt", alt);
233
+ if (folder && folder !== "/") formData.append("folder", folder);
234
+ try {
235
+ const { width, height } = await getImageDimensions(file);
236
+ formData.append("width", String(width));
237
+ formData.append("height", String(height));
238
+ } catch {}
239
+ return formData;
240
+ }
241
+
242
+ //#endregion
243
+ //#region src/utils/cn.ts
244
+ function cn$1(...inputs) {
245
+ return twMerge(clsx(inputs));
246
+ }
247
+
248
+ //#endregion
249
+ //#region src/components/dialogs/CreateFolderDialog.tsx
250
+ function CreateFolderDialog({ open, isPending, onClose, onCreate }) {
251
+ const [folderName, setFolderName] = useState("");
252
+ const inputRef = useRef(null);
253
+ useEffect(() => {
254
+ if (open) {
255
+ setFolderName("");
256
+ setTimeout(() => inputRef.current?.focus(), 50);
257
+ }
258
+ }, [open]);
259
+ const handleCreate = () => {
260
+ const name = folderName.trim();
261
+ if (!name) return;
262
+ onCreate(name);
263
+ };
264
+ const handleKeyDown = (e) => {
265
+ if (e.key === "Escape") onClose();
266
+ else if (e.key === "Enter" && folderName.trim()) handleCreate();
267
+ };
268
+ if (!open) return null;
269
+ const isValid = folderName.trim().length > 0;
270
+ return /* @__PURE__ */ jsx("div", {
271
+ className: "fixed inset-0 bg-black/50 flex items-center justify-center z-50",
272
+ role: "dialog",
273
+ onKeyDown: handleKeyDown,
274
+ children: /* @__PURE__ */ jsxs("div", {
275
+ className: "bg-white rounded-lg p-6 w-full max-w-md",
276
+ "data-testid": "create-folder-dialog",
277
+ children: [
278
+ /* @__PURE__ */ jsx("h2", {
279
+ className: "text-xl font-semibold text-grey-01 mb-4",
280
+ children: "Create New Folder"
281
+ }),
282
+ /* @__PURE__ */ jsxs("div", {
283
+ className: "mb-4",
284
+ children: [/* @__PURE__ */ jsx("label", {
285
+ htmlFor: "folder-name",
286
+ className: "block text-sm font-medium text-grey-01 mb-2",
287
+ children: "Folder Name"
288
+ }), /* @__PURE__ */ jsx("input", {
289
+ ref: inputRef,
290
+ id: "folder-name",
291
+ type: "text",
292
+ value: folderName,
293
+ onChange: (e) => setFolderName(e.target.value),
294
+ placeholder: "Enter folder name",
295
+ className: "w-full px-3 py-2 border border-grey-09 rounded focus:outline-none focus:ring-2 focus:ring-azure-04",
296
+ "data-testid": "folder-name-input"
297
+ })]
298
+ }),
299
+ /* @__PURE__ */ jsxs("div", {
300
+ className: "flex justify-end gap-3",
301
+ children: [/* @__PURE__ */ jsx("button", {
302
+ type: "button",
303
+ onClick: onClose,
304
+ className: "px-4 py-2 border border-grey-09 rounded hover:bg-grey-11 transition-colors",
305
+ children: "Cancel"
306
+ }), /* @__PURE__ */ jsx("button", {
307
+ type: "button",
308
+ onClick: handleCreate,
309
+ disabled: !isValid || isPending,
310
+ className: "px-4 py-2 bg-azure-04 text-white rounded hover:bg-azure-03 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",
311
+ "data-testid": "create-folder-submit",
312
+ children: isPending ? "Creating..." : "Create"
313
+ })]
314
+ })
315
+ ]
316
+ })
317
+ });
318
+ }
319
+
320
+ //#endregion
321
+ //#region src/components/media/FolderTreeSidebar.tsx
322
+ function FolderNode({ node, depth, currentFolder, dropTargetFolder, onFolderSelect }) {
323
+ const isActive = node.path === currentFolder;
324
+ const isDropTarget = node.path === dropTargetFolder;
325
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("button", {
326
+ type: "button",
327
+ onClick: () => onFolderSelect(node.path),
328
+ className: cn$1("w-full flex items-center gap-2 py-1.5 px-3 rounded text-sm transition-colors text-left", {
329
+ "bg-azure-11 text-azure-01": isActive,
330
+ "hover:bg-grey-11": !isActive,
331
+ "ring-2 ring-azure-04": isDropTarget
332
+ }),
333
+ style: { paddingLeft: `${depth * 16 + 12}px` },
334
+ children: [
335
+ /* @__PURE__ */ jsx(Folder, { className: "w-4 h-4 flex-shrink-0" }),
336
+ /* @__PURE__ */ jsx("span", {
337
+ className: "truncate flex-1",
338
+ children: node.name
339
+ }),
340
+ /* @__PURE__ */ jsxs("span", {
341
+ className: "text-grey-05 text-xs",
342
+ children: [
343
+ "(",
344
+ node.assetCount,
345
+ ")"
346
+ ]
347
+ })
348
+ ]
349
+ }), node.children.map((child) => /* @__PURE__ */ jsx(FolderNode, {
350
+ node: child,
351
+ depth: depth + 1,
352
+ currentFolder,
353
+ dropTargetFolder,
354
+ onFolderSelect
355
+ }, child.path))] });
356
+ }
357
+ function FolderTreeSidebar({ currentFolder, onFolderSelect, dropTargetFolder }) {
358
+ const [showCreateFolderDialog, setShowCreateFolderDialog] = useState(false);
359
+ const { data, isLoading } = useFolderTree$1();
360
+ const createFolder = useCreateFolder();
361
+ const rawTree = data?.tree ?? [];
362
+ const tree = rawTree.length === 1 && rawTree[0].path === "/" ? rawTree[0].children : rawTree;
363
+ const handleCreateFolder = (name) => {
364
+ const folderPath = `/${name}`;
365
+ createFolder.mutate(folderPath, { onSuccess: () => {
366
+ setShowCreateFolderDialog(false);
367
+ } });
368
+ };
369
+ const rootAssetCount = rawTree.length === 1 && rawTree[0].path === "/" ? rawTree[0].assetCount : tree.reduce((sum, node) => sum + node.assetCount, 0);
370
+ return /* @__PURE__ */ jsxs("div", {
371
+ className: "w-56 flex-shrink-0 border-r border-grey-09 bg-white",
372
+ children: [
373
+ /* @__PURE__ */ jsxs("div", {
374
+ className: "flex items-center justify-between px-4 py-3 border-b border-grey-09",
375
+ children: [/* @__PURE__ */ jsx("h3", {
376
+ className: "font-semibold text-grey-01",
377
+ children: "Folders"
378
+ }), /* @__PURE__ */ jsx("button", {
379
+ type: "button",
380
+ onClick: () => setShowCreateFolderDialog(true),
381
+ className: "p-1.5 rounded hover:bg-grey-11 transition-colors",
382
+ title: "New Folder",
383
+ children: /* @__PURE__ */ jsx(FolderPlus, { className: "w-4 h-4 text-grey-04" })
384
+ })]
385
+ }),
386
+ /* @__PURE__ */ jsx("div", {
387
+ className: "p-2 overflow-y-auto",
388
+ style: { maxHeight: "calc(100vh - 200px)" },
389
+ children: isLoading ? /* @__PURE__ */ jsx("div", {
390
+ className: "text-sm text-grey-05 px-3 py-2",
391
+ children: "Loading..."
392
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("button", {
393
+ type: "button",
394
+ onClick: () => onFolderSelect("/"),
395
+ className: cn$1("w-full flex items-center gap-2 py-1.5 px-3 rounded text-sm transition-colors text-left", {
396
+ "bg-azure-11 text-azure-01": currentFolder === "/",
397
+ "hover:bg-grey-11": currentFolder !== "/",
398
+ "ring-2 ring-azure-04": dropTargetFolder === "/"
399
+ }),
400
+ children: [
401
+ /* @__PURE__ */ jsx(Folder, { className: "w-4 h-4 flex-shrink-0" }),
402
+ /* @__PURE__ */ jsx("span", {
403
+ className: "truncate flex-1",
404
+ children: "Root"
405
+ }),
406
+ /* @__PURE__ */ jsxs("span", {
407
+ className: "text-grey-05 text-xs",
408
+ children: [
409
+ "(",
410
+ rootAssetCount,
411
+ ")"
412
+ ]
413
+ })
414
+ ]
415
+ }), tree.length > 0 ? tree.map((node) => /* @__PURE__ */ jsx(FolderNode, {
416
+ node,
417
+ depth: 1,
418
+ currentFolder,
419
+ dropTargetFolder,
420
+ onFolderSelect
421
+ }, node.path)) : /* @__PURE__ */ jsx("div", {
422
+ className: "text-sm text-grey-05 px-3 py-2",
423
+ children: "No folders yet"
424
+ })] })
425
+ }),
426
+ /* @__PURE__ */ jsx(CreateFolderDialog, {
427
+ open: showCreateFolderDialog,
428
+ isPending: createFolder.isPending,
429
+ onClose: () => setShowCreateFolderDialog(false),
430
+ onCreate: handleCreateFolder
431
+ })
432
+ ]
433
+ });
434
+ }
435
+
436
+ //#endregion
437
+ //#region src/components/media/AssetCard.tsx
438
+ function AssetCard({ asset, isSelected, onClick, onDoubleClick, assetsBasePath = "/__cms/api/assets/serve" }) {
439
+ const handleClick = () => {
440
+ onClick?.();
441
+ };
442
+ const handleDoubleClick = () => {
443
+ onDoubleClick?.();
444
+ };
445
+ return /* @__PURE__ */ jsxs("div", {
446
+ onClick: handleClick,
447
+ onDoubleClick: handleDoubleClick,
448
+ onKeyDown: (e) => {
449
+ if (e.key === "Enter" || e.key === " ") {
450
+ e.preventDefault();
451
+ handleClick();
452
+ }
453
+ },
454
+ role: "button",
455
+ tabIndex: 0,
456
+ className: cn$1("group relative rounded overflow-hidden cursor-pointer transition-colors", "bg-white hover:border-azure-04", isSelected ? "border-2 border-azure-04" : "border border-grey-09"),
457
+ children: [/* @__PURE__ */ jsx("div", {
458
+ className: "aspect-square bg-grey-11 flex items-center justify-center overflow-hidden",
459
+ children: /* @__PURE__ */ jsx("img", {
460
+ src: `${assetsBasePath}/${asset.folder && asset.folder !== "/" ? `${asset.folder.replace(/^\//, "")}/${asset.filename}` : asset.filename}`,
461
+ alt: asset.alt || asset.originalName,
462
+ className: "w-full h-full object-contain",
463
+ loading: "lazy"
464
+ })
465
+ }), /* @__PURE__ */ jsx("div", {
466
+ className: "px-2 py-1.5",
467
+ children: /* @__PURE__ */ jsx("p", {
468
+ className: "text-xs text-grey-01 truncate",
469
+ title: asset.originalName,
470
+ children: asset.originalName
471
+ })
472
+ })]
473
+ });
474
+ }
475
+
476
+ //#endregion
477
+ //#region src/components/media/MediaToolbar.tsx
478
+ function MediaToolbar({ search, onSearchChange, fileType, onFileTypeChange, sort, onSortChange, isSelectMode, onEnterSelectMode, onExitSelectMode, onUploadClick }) {
479
+ return /* @__PURE__ */ jsxs("div", {
480
+ className: "flex items-center gap-3 flex-wrap",
481
+ children: [
482
+ /* @__PURE__ */ jsxs("div", {
483
+ className: "relative flex-1 min-w-[200px]",
484
+ children: [/* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-grey-04" }), /* @__PURE__ */ jsx("input", {
485
+ type: "text",
486
+ value: search,
487
+ onChange: (e) => onSearchChange(e.target.value),
488
+ placeholder: "Search files...",
489
+ className: "w-full pl-9 pr-3 py-2 border border-grey-09 rounded text-sm focus:outline-none focus:ring-2 focus:ring-azure-04 focus:border-azure-04"
490
+ })]
491
+ }),
492
+ /* @__PURE__ */ jsxs("select", {
493
+ value: fileType,
494
+ onChange: (e) => onFileTypeChange(e.target.value),
495
+ className: "px-3 py-2 border border-grey-09 rounded text-sm bg-white hover:bg-grey-11 transition-colors",
496
+ children: [
497
+ /* @__PURE__ */ jsx("option", {
498
+ value: "all",
499
+ children: "All types"
500
+ }),
501
+ /* @__PURE__ */ jsx("option", {
502
+ value: "images",
503
+ children: "Images"
504
+ }),
505
+ /* @__PURE__ */ jsx("option", {
506
+ value: "svg",
507
+ children: "SVG"
508
+ })
509
+ ]
510
+ }),
511
+ /* @__PURE__ */ jsxs("select", {
512
+ value: sort,
513
+ onChange: (e) => onSortChange(e.target.value),
514
+ className: "px-3 py-2 border border-grey-09 rounded text-sm bg-white hover:bg-grey-11 transition-colors",
515
+ children: [
516
+ /* @__PURE__ */ jsx("option", {
517
+ value: "date-newest",
518
+ children: "Date (newest)"
519
+ }),
520
+ /* @__PURE__ */ jsx("option", {
521
+ value: "date-oldest",
522
+ children: "Date (oldest)"
523
+ }),
524
+ /* @__PURE__ */ jsx("option", {
525
+ value: "name-asc",
526
+ children: "Name (A-Z)"
527
+ }),
528
+ /* @__PURE__ */ jsx("option", {
529
+ value: "name-desc",
530
+ children: "Name (Z-A)"
531
+ }),
532
+ /* @__PURE__ */ jsx("option", {
533
+ value: "size-largest",
534
+ children: "Size (largest)"
535
+ }),
536
+ /* @__PURE__ */ jsx("option", {
537
+ value: "size-smallest",
538
+ children: "Size (smallest)"
539
+ })
540
+ ]
541
+ }),
542
+ isSelectMode ? /* @__PURE__ */ jsx("button", {
543
+ type: "button",
544
+ onClick: onExitSelectMode,
545
+ className: "px-3 py-2 bg-azure-04 text-white rounded text-sm hover:bg-azure-03 transition-colors",
546
+ children: "Done"
547
+ }) : onEnterSelectMode && /* @__PURE__ */ jsx("button", {
548
+ type: "button",
549
+ onClick: onEnterSelectMode,
550
+ className: "px-3 py-2 border border-grey-09 rounded text-sm bg-white hover:bg-grey-11 transition-colors",
551
+ children: "Select"
552
+ }),
553
+ onUploadClick && /* @__PURE__ */ jsxs("button", {
554
+ type: "button",
555
+ onClick: onUploadClick,
556
+ className: "flex items-center gap-2 px-3 py-2 bg-azure-04 text-white rounded text-sm hover:bg-azure-03 transition-colors",
557
+ children: [/* @__PURE__ */ jsx(Upload, { className: "w-4 h-4" }), "Upload"]
558
+ })
559
+ ]
560
+ });
561
+ }
562
+
563
+ //#endregion
564
+ //#region src/components/media/MediaLibrary.tsx
565
+ function MediaLibrary({ folder: initialFolder = "/", onFolderChange, showToolbar = true, mode = "page", assetsBasePath, selectedAssets, onToggleSelect, onAssetClick, onAssetDoubleClick, onSelect, selectedAsset, search: externalSearch, fileType: externalFileType, sort: externalSort }) {
566
+ const [internalSearch, setInternalSearch] = useState("");
567
+ const [internalFileType, setInternalFileType] = useState("all");
568
+ const [internalSort, setInternalSort] = useState("date-newest");
569
+ const search = externalSearch ?? internalSearch;
570
+ const fileType = externalFileType ?? internalFileType;
571
+ const sort = externalSort ?? internalSort;
572
+ const [showCreateFolderDialog, setShowCreateFolderDialog] = useState(false);
573
+ const { data, isLoading } = useAssetFolders(initialFolder);
574
+ const createFolder = useCreateFolder();
575
+ const assets = data?.assets ?? [];
576
+ const filteredAssets = useMemo(() => {
577
+ let result = assets;
578
+ if (search.trim()) {
579
+ const q = search.toLowerCase();
580
+ result = result.filter((a) => a.originalName.toLowerCase().includes(q) || a.filename.toLowerCase().includes(q) || a.alt?.toLowerCase().includes(q));
581
+ }
582
+ if (fileType !== "all") result = result.filter((a) => {
583
+ if (fileType === "images") return a.mimeType.startsWith("image/") && a.mimeType !== "image/svg+xml";
584
+ if (fileType === "svg") return a.mimeType === "image/svg+xml";
585
+ return true;
586
+ });
587
+ return result;
588
+ }, [
589
+ assets,
590
+ search,
591
+ fileType
592
+ ]);
593
+ const sortedAssets = useMemo(() => {
594
+ const sorted = [...filteredAssets];
595
+ switch (sort) {
596
+ case "date-newest":
597
+ sorted.sort((a, b) => new Date(b.uploadedAt).getTime() - new Date(a.uploadedAt).getTime());
598
+ break;
599
+ case "date-oldest":
600
+ sorted.sort((a, b) => new Date(a.uploadedAt).getTime() - new Date(b.uploadedAt).getTime());
601
+ break;
602
+ case "name-asc":
603
+ sorted.sort((a, b) => a.originalName.localeCompare(b.originalName));
604
+ break;
605
+ case "name-desc":
606
+ sorted.sort((a, b) => b.originalName.localeCompare(a.originalName));
607
+ break;
608
+ case "size-largest":
609
+ sorted.sort((a, b) => b.size - a.size);
610
+ break;
611
+ case "size-smallest":
612
+ sorted.sort((a, b) => a.size - b.size);
613
+ break;
614
+ }
615
+ return sorted;
616
+ }, [filteredAssets, sort]);
617
+ const handleAssetClick = (asset) => {
618
+ if (mode === "picker") onSelect?.(asset);
619
+ else onAssetClick?.(asset);
620
+ };
621
+ const handleAssetDoubleClick = (asset) => {
622
+ onAssetDoubleClick?.(asset);
623
+ };
624
+ const handleCreateFolder = (name) => {
625
+ const folderPath = initialFolder === "/" ? `/${name}` : `${initialFolder}/${name}`;
626
+ createFolder.mutate(folderPath, { onSuccess: () => {
627
+ setShowCreateFolderDialog(false);
628
+ onFolderChange?.(folderPath);
629
+ } });
630
+ };
631
+ return /* @__PURE__ */ jsxs("div", {
632
+ className: "flex flex-col gap-4",
633
+ children: [
634
+ showToolbar && externalSearch === void 0 && /* @__PURE__ */ jsx(MediaToolbar, {
635
+ search: internalSearch,
636
+ onSearchChange: setInternalSearch,
637
+ fileType: internalFileType,
638
+ onFileTypeChange: setInternalFileType,
639
+ sort: internalSort,
640
+ onSortChange: setInternalSort
641
+ }),
642
+ isLoading ? /* @__PURE__ */ jsx("div", {
643
+ className: "text-center py-12 text-grey-04",
644
+ children: "Loading assets..."
645
+ }) : /* @__PURE__ */ jsx(Fragment, { children: sortedAssets.length === 0 ? /* @__PURE__ */ jsx("div", {
646
+ className: "text-center py-12 text-grey-04",
647
+ children: assets.length === 0 ? "No assets yet. Click Upload to add your first image." : "No assets match your filter."
648
+ }) : /* @__PURE__ */ jsx("div", {
649
+ className: "grid gap-4",
650
+ style: { gridTemplateColumns: "repeat(auto-fit, minmax(120px, 150px))" },
651
+ children: sortedAssets.map((asset) => /* @__PURE__ */ jsx(AssetCard, {
652
+ asset,
653
+ isSelected: selectedAssets?.has(asset.filename) ?? selectedAsset?.filename === asset.filename,
654
+ onClick: () => handleAssetClick(asset),
655
+ onDoubleClick: () => handleAssetDoubleClick(asset),
656
+ assetsBasePath
657
+ }, asset.filename))
658
+ }) }),
659
+ mode === "picker" && /* @__PURE__ */ jsx(CreateFolderDialog, {
660
+ open: showCreateFolderDialog,
661
+ isPending: createFolder.isPending,
662
+ onClose: () => setShowCreateFolderDialog(false),
663
+ onCreate: handleCreateFolder
664
+ })
665
+ ]
666
+ });
667
+ }
668
+
669
+ //#endregion
670
+ //#region src/components/media/UploadModal.tsx
671
+ const ACCEPTED_TYPES = "image/jpeg,image/png,image/gif,image/webp,image/svg+xml,image/avif";
672
+ function UploadModal({ isOpen, onClose, folder, onUploadComplete }) {
673
+ const [activeTab, setActiveTab] = useState("file");
674
+ const [isDragOver, setIsDragOver] = useState(false);
675
+ const [pendingFile, setPendingFile] = useState(null);
676
+ const [altText, setAltText] = useState("");
677
+ const [customName, setCustomName] = useState("");
678
+ const [importUrl, setImportUrl] = useState("");
679
+ const [uploadProgress, setUploadProgress] = useState(null);
680
+ const fileInputRef = useRef(null);
681
+ const uploadMutation = useUploadAsset();
682
+ const importMutation = useImportAssetUrl();
683
+ const isUploading = uploadMutation.isPending || importMutation.isPending || (uploadProgress?.inProgress ?? false);
684
+ const error = uploadMutation.error || importMutation.error;
685
+ const resetState = useCallback(() => {
686
+ setPendingFile(null);
687
+ setAltText("");
688
+ setCustomName("");
689
+ setImportUrl("");
690
+ setUploadProgress(null);
691
+ setActiveTab("file");
692
+ setIsDragOver(false);
693
+ if (fileInputRef.current) fileInputRef.current.value = "";
694
+ }, []);
695
+ useEffect(() => {
696
+ if (!isOpen) return;
697
+ const handleKeyDown = (e) => {
698
+ if (e.key === "Escape") onClose();
699
+ };
700
+ document.addEventListener("keydown", handleKeyDown);
701
+ return () => document.removeEventListener("keydown", handleKeyDown);
702
+ }, [isOpen, onClose]);
703
+ useEffect(() => {
704
+ if (!isOpen) resetState();
705
+ }, [isOpen, resetState]);
706
+ const handleSingleFile = useCallback((file) => {
707
+ setPendingFile(file);
708
+ setAltText("");
709
+ setCustomName("");
710
+ }, []);
711
+ const handleMultipleFiles = useCallback(async (files) => {
712
+ if (files.length === 0) return;
713
+ if (files.length === 1) {
714
+ handleSingleFile(files[0]);
715
+ return;
716
+ }
717
+ setUploadProgress({
718
+ total: files.length,
719
+ completed: 0,
720
+ failed: 0,
721
+ inProgress: true
722
+ });
723
+ const uploadPromises = files.map(async (file) => {
724
+ const formData = await buildUploadFormData(file, void 0, folder);
725
+ return uploadMutation.mutateAsync(formData);
726
+ });
727
+ const results = await Promise.allSettled(uploadPromises);
728
+ const completed = results.filter((r) => r.status === "fulfilled").length;
729
+ const failed = results.filter((r) => r.status === "rejected").length;
730
+ setUploadProgress({
731
+ total: files.length,
732
+ completed,
733
+ failed,
734
+ inProgress: false
735
+ });
736
+ setTimeout(() => {
737
+ if (completed > 0) onUploadComplete?.();
738
+ onClose();
739
+ }, 2e3);
740
+ }, [
741
+ folder,
742
+ uploadMutation,
743
+ handleSingleFile,
744
+ onUploadComplete,
745
+ onClose
746
+ ]);
747
+ const handleFiles = useCallback((fileList) => {
748
+ if (!fileList || fileList.length === 0) return;
749
+ handleMultipleFiles(Array.from(fileList));
750
+ }, [handleMultipleFiles]);
751
+ const handleDragOver = useCallback((e) => {
752
+ e.preventDefault();
753
+ setIsDragOver(true);
754
+ }, []);
755
+ const handleDragLeave = useCallback((e) => {
756
+ e.preventDefault();
757
+ setIsDragOver(false);
758
+ }, []);
759
+ const handleDrop = useCallback((e) => {
760
+ e.preventDefault();
761
+ setIsDragOver(false);
762
+ handleFiles(e.dataTransfer.files);
763
+ }, [handleFiles]);
764
+ const handleUpload = async () => {
765
+ if (!pendingFile) return;
766
+ const formData = await buildUploadFormData(pendingFile, altText || void 0, folder);
767
+ uploadMutation.mutate(formData, { onSuccess: () => {
768
+ onUploadComplete?.();
769
+ onClose();
770
+ } });
771
+ };
772
+ const handleImportUrl = () => {
773
+ if (!importUrl.trim()) return;
774
+ importMutation.mutate({
775
+ url: importUrl.trim(),
776
+ alt: altText || void 0,
777
+ folder
778
+ }, { onSuccess: () => {
779
+ onUploadComplete?.();
780
+ onClose();
781
+ } });
782
+ };
783
+ const handleCancel = () => {
784
+ setPendingFile(null);
785
+ setAltText("");
786
+ setCustomName("");
787
+ if (fileInputRef.current) fileInputRef.current.value = "";
788
+ };
789
+ if (!isOpen) return null;
790
+ return /* @__PURE__ */ jsx("div", {
791
+ className: "fixed inset-0 bg-black/50 flex items-center justify-center z-50",
792
+ onClick: (e) => {
793
+ if (e.target === e.currentTarget) onClose();
794
+ },
795
+ children: /* @__PURE__ */ jsxs("div", {
796
+ className: "bg-white rounded-lg w-full max-w-md mx-4 shadow-xl",
797
+ children: [
798
+ /* @__PURE__ */ jsxs("div", {
799
+ className: "flex items-center justify-between px-6 py-4 border-b border-grey-09",
800
+ children: [/* @__PURE__ */ jsx("h2", {
801
+ className: "text-lg font-semibold text-grey-01",
802
+ children: "Upload Assets"
803
+ }), /* @__PURE__ */ jsx("button", {
804
+ type: "button",
805
+ onClick: onClose,
806
+ className: "p-1 text-grey-04 hover:text-grey-01 transition-colors rounded hover:bg-grey-11",
807
+ children: /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
808
+ })]
809
+ }),
810
+ /* @__PURE__ */ jsxs("div", {
811
+ className: "p-6",
812
+ children: [
813
+ /* @__PURE__ */ jsxs("div", {
814
+ className: "flex gap-2 mb-4",
815
+ children: [/* @__PURE__ */ jsx("button", {
816
+ type: "button",
817
+ onClick: () => setActiveTab("file"),
818
+ className: cn$1("px-3 py-1.5 text-sm rounded transition-colors", activeTab === "file" ? "bg-azure-04 text-white" : "bg-white border border-grey-09 text-grey-04 hover:bg-grey-11"),
819
+ children: "Upload File"
820
+ }), /* @__PURE__ */ jsx("button", {
821
+ type: "button",
822
+ onClick: () => setActiveTab("url"),
823
+ className: cn$1("px-3 py-1.5 text-sm rounded transition-colors", activeTab === "url" ? "bg-azure-04 text-white" : "bg-white border border-grey-09 text-grey-04 hover:bg-grey-11"),
824
+ children: "Import URL"
825
+ })]
826
+ }),
827
+ activeTab === "file" && /* @__PURE__ */ jsxs(Fragment, { children: [uploadProgress && /* @__PURE__ */ jsxs("div", {
828
+ className: "mb-4 p-3 bg-grey-11 rounded border border-grey-09",
829
+ children: [
830
+ /* @__PURE__ */ jsx("p", {
831
+ className: "text-sm font-medium text-grey-01",
832
+ children: uploadProgress.inProgress ? `Uploading ${uploadProgress.total} files...` : `Upload complete: ${uploadProgress.completed}/${uploadProgress.total} succeeded`
833
+ }),
834
+ uploadProgress.failed > 0 && /* @__PURE__ */ jsxs("p", {
835
+ className: "text-sm text-red-04 mt-1",
836
+ children: [uploadProgress.failed, " file(s) failed to upload"]
837
+ }),
838
+ /* @__PURE__ */ jsx("div", {
839
+ className: "mt-2 h-2 bg-grey-09 rounded overflow-hidden",
840
+ children: /* @__PURE__ */ jsx("div", {
841
+ className: cn$1("h-full transition-all", uploadProgress.failed > 0 ? "bg-yellow-06" : "bg-azure-04"),
842
+ style: { width: `${(uploadProgress.completed + uploadProgress.failed) / uploadProgress.total * 100}%` }
843
+ })
844
+ })
845
+ ]
846
+ }), pendingFile ? /* @__PURE__ */ jsxs("div", {
847
+ className: "space-y-4",
848
+ children: [
849
+ /* @__PURE__ */ jsxs("div", {
850
+ className: "flex items-center gap-3",
851
+ children: [/* @__PURE__ */ jsx("div", {
852
+ className: "w-16 h-16 bg-grey-09 rounded overflow-hidden flex-shrink-0",
853
+ children: /* @__PURE__ */ jsx("img", {
854
+ src: URL.createObjectURL(pendingFile),
855
+ alt: "Preview",
856
+ className: "w-full h-full object-contain"
857
+ })
858
+ }), /* @__PURE__ */ jsxs("div", {
859
+ className: "flex-1 min-w-0",
860
+ children: [/* @__PURE__ */ jsx("p", {
861
+ className: "text-sm font-medium text-grey-01 truncate",
862
+ children: pendingFile.name
863
+ }), /* @__PURE__ */ jsxs("p", {
864
+ className: "text-xs text-grey-04",
865
+ children: [(pendingFile.size / 1024).toFixed(1), " KB"]
866
+ })]
867
+ })]
868
+ }),
869
+ /* @__PURE__ */ jsxs("div", { children: [
870
+ /* @__PURE__ */ jsx("label", {
871
+ htmlFor: "custom-name",
872
+ className: "block text-xs text-grey-04 uppercase tracking-wide mb-1",
873
+ children: "Asset Name (optional)"
874
+ }),
875
+ /* @__PURE__ */ jsx("input", {
876
+ id: "custom-name",
877
+ type: "text",
878
+ value: customName,
879
+ onChange: (e) => setCustomName(e.target.value),
880
+ placeholder: pendingFile.name,
881
+ className: "w-full px-3 py-2 border border-grey-09 rounded text-sm focus:outline-none focus:ring-2 focus:ring-azure-04 focus:border-azure-04"
882
+ }),
883
+ /* @__PURE__ */ jsx("p", {
884
+ className: "mt-1 text-xs text-grey-07",
885
+ children: "Leave blank to use original filename"
886
+ })
887
+ ] }),
888
+ /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("label", {
889
+ htmlFor: "alt-text",
890
+ className: "block text-xs text-grey-04 uppercase tracking-wide mb-1",
891
+ children: "Alt Text"
892
+ }), /* @__PURE__ */ jsx("input", {
893
+ id: "alt-text",
894
+ type: "text",
895
+ value: altText,
896
+ onChange: (e) => setAltText(e.target.value),
897
+ placeholder: "Describe the image for accessibility",
898
+ className: "w-full px-3 py-2 border border-grey-09 rounded text-sm focus:outline-none focus:ring-2 focus:ring-azure-04 focus:border-azure-04"
899
+ })] })
900
+ ]
901
+ }) : /* @__PURE__ */ jsxs("div", {
902
+ onDragOver: handleDragOver,
903
+ onDragLeave: handleDragLeave,
904
+ onDrop: handleDrop,
905
+ className: cn$1("border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors bg-grey-11", isDragOver ? "border-azure-04 bg-azure-11" : "border-grey-09 hover:border-grey-07"),
906
+ onClick: () => fileInputRef.current?.click(),
907
+ onKeyDown: (e) => {
908
+ if (e.key === "Enter" || e.key === " ") {
909
+ e.preventDefault();
910
+ fileInputRef.current?.click();
911
+ }
912
+ },
913
+ role: "button",
914
+ tabIndex: 0,
915
+ children: [
916
+ /* @__PURE__ */ jsx(Upload, { className: "mx-auto h-10 w-10 text-grey-04" }),
917
+ /* @__PURE__ */ jsx("p", {
918
+ className: "mt-2 text-sm text-grey-04",
919
+ children: "Drag and drop images here, or click to browse"
920
+ }),
921
+ /* @__PURE__ */ jsx("p", {
922
+ className: "mt-1 text-xs text-grey-07",
923
+ children: "JPEG, PNG, GIF, WebP, SVG, AVIF - Multiple files supported"
924
+ }),
925
+ /* @__PURE__ */ jsx("input", {
926
+ ref: fileInputRef,
927
+ type: "file",
928
+ accept: ACCEPTED_TYPES,
929
+ multiple: true,
930
+ onChange: (e) => handleFiles(e.target.files),
931
+ className: "hidden"
932
+ })
933
+ ]
934
+ })] }),
935
+ activeTab === "url" && /* @__PURE__ */ jsxs("div", {
936
+ className: "space-y-4",
937
+ children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("label", {
938
+ htmlFor: "import-url",
939
+ className: "block text-xs text-grey-04 uppercase tracking-wide mb-1",
940
+ children: "Image URL"
941
+ }), /* @__PURE__ */ jsx("input", {
942
+ id: "import-url",
943
+ type: "url",
944
+ value: importUrl,
945
+ onChange: (e) => setImportUrl(e.target.value),
946
+ placeholder: "https://example.com/image.jpg",
947
+ className: "w-full px-3 py-2 border border-grey-09 rounded text-sm focus:outline-none focus:ring-2 focus:ring-azure-04 focus:border-azure-04"
948
+ })] }), /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("label", {
949
+ htmlFor: "url-alt-text",
950
+ className: "block text-xs text-grey-04 uppercase tracking-wide mb-1",
951
+ children: "Alt Text"
952
+ }), /* @__PURE__ */ jsx("input", {
953
+ id: "url-alt-text",
954
+ type: "text",
955
+ value: altText,
956
+ onChange: (e) => setAltText(e.target.value),
957
+ placeholder: "Describe the image for accessibility",
958
+ className: "w-full px-3 py-2 border border-grey-09 rounded text-sm focus:outline-none focus:ring-2 focus:ring-azure-04 focus:border-azure-04"
959
+ })] })]
960
+ }),
961
+ error && /* @__PURE__ */ jsx("p", {
962
+ className: "mt-4 text-sm text-red-04",
963
+ children: error instanceof Error ? error.message : "Upload failed"
964
+ })
965
+ ]
966
+ }),
967
+ /* @__PURE__ */ jsxs("div", {
968
+ className: "flex items-center justify-end gap-3 px-6 py-4 border-t border-grey-09 bg-grey-11 rounded-b-lg",
969
+ children: [/* @__PURE__ */ jsx("button", {
970
+ type: "button",
971
+ onClick: pendingFile ? handleCancel : onClose,
972
+ disabled: isUploading,
973
+ className: "px-4 py-2 bg-white border border-grey-09 text-grey-04 text-sm rounded hover:bg-grey-11 disabled:opacity-50 transition-colors",
974
+ children: pendingFile ? "Clear" : "Cancel"
975
+ }), activeTab === "file" ? /* @__PURE__ */ jsxs("button", {
976
+ type: "button",
977
+ onClick: handleUpload,
978
+ disabled: isUploading || !pendingFile,
979
+ className: "flex items-center gap-2 px-4 py-2 bg-azure-04 text-white text-sm rounded hover:bg-azure-03 disabled:opacity-50 transition-colors",
980
+ children: [/* @__PURE__ */ jsx(Upload, { className: "w-4 h-4" }), uploadMutation.isPending ? "Uploading..." : "Upload"]
981
+ }) : /* @__PURE__ */ jsxs("button", {
982
+ type: "button",
983
+ onClick: handleImportUrl,
984
+ disabled: isUploading || !importUrl.trim(),
985
+ className: "flex items-center gap-2 px-4 py-2 bg-azure-04 text-white text-sm rounded hover:bg-azure-03 disabled:opacity-50 transition-colors",
986
+ children: [/* @__PURE__ */ jsx(Upload, { className: "w-4 h-4" }), importMutation.isPending ? "Importing..." : "Import"]
987
+ })]
988
+ })
989
+ ]
990
+ })
991
+ });
992
+ }
993
+
994
+ //#endregion
995
+ //#region src/components/media/ImagePicker.tsx
996
+ /**
997
+ * Generic image picker modal with folder tree, media grid, and upload.
998
+ * Renders a 3-panel modal: folder tree sidebar, image grid, and header with Upload button.
999
+ * Callers are responsible for path construction from the selected AssetEntry.
1000
+ */
1001
+ function ImagePicker({ isOpen, onSelect, onClose }) {
1002
+ const [currentFolder, setCurrentFolder] = useState("/");
1003
+ const [showUpload, setShowUpload] = useState(false);
1004
+ useEffect(() => {
1005
+ if (!isOpen) return;
1006
+ const handleKeyDown = (e) => {
1007
+ if (e.key === "Escape") onClose();
1008
+ };
1009
+ document.addEventListener("keydown", handleKeyDown);
1010
+ return () => document.removeEventListener("keydown", handleKeyDown);
1011
+ }, [isOpen, onClose]);
1012
+ if (!isOpen) return null;
1013
+ const handleAssetSelect = (asset) => {
1014
+ onSelect(asset);
1015
+ };
1016
+ const handleBackdropClick = (e) => {
1017
+ if (e.target === e.currentTarget) onClose();
1018
+ };
1019
+ return /* @__PURE__ */ jsxs("div", {
1020
+ className: "fixed inset-0 z-50 flex items-center justify-center bg-black/50",
1021
+ onClick: handleBackdropClick,
1022
+ children: [/* @__PURE__ */ jsxs("div", {
1023
+ className: "bg-white rounded-lg shadow-xl w-full max-w-5xl max-h-[85vh] mx-4 flex flex-col overflow-hidden",
1024
+ children: [/* @__PURE__ */ jsxs("div", {
1025
+ className: "flex items-center justify-between px-6 py-4 border-b border-grey-09 flex-shrink-0",
1026
+ children: [/* @__PURE__ */ jsx("h2", {
1027
+ className: "text-lg font-semibold text-grey-01",
1028
+ children: "Select Image"
1029
+ }), /* @__PURE__ */ jsxs("div", {
1030
+ className: "flex items-center gap-2",
1031
+ children: [/* @__PURE__ */ jsxs("button", {
1032
+ type: "button",
1033
+ onClick: () => setShowUpload(true),
1034
+ className: "flex items-center gap-2 px-3 py-1.5 text-sm bg-azure-04 text-white rounded hover:bg-azure-03 transition-colors",
1035
+ children: [/* @__PURE__ */ jsx(Upload, { className: "w-4 h-4" }), "Upload"]
1036
+ }), /* @__PURE__ */ jsx("button", {
1037
+ type: "button",
1038
+ onClick: onClose,
1039
+ className: "p-1.5 text-grey-04 hover:text-grey-01 transition-colors rounded hover:bg-grey-11",
1040
+ "aria-label": "Close",
1041
+ children: /* @__PURE__ */ jsx(X, { className: "w-5 h-5" })
1042
+ })]
1043
+ })]
1044
+ }), /* @__PURE__ */ jsxs("div", {
1045
+ className: "flex flex-1 min-h-0",
1046
+ children: [/* @__PURE__ */ jsx(FolderTreeSidebar, {
1047
+ currentFolder,
1048
+ onFolderSelect: setCurrentFolder
1049
+ }), /* @__PURE__ */ jsx("div", {
1050
+ className: "flex-1 p-4 overflow-y-auto",
1051
+ children: /* @__PURE__ */ jsx(MediaLibrary, {
1052
+ folder: currentFolder,
1053
+ onFolderChange: setCurrentFolder,
1054
+ mode: "picker",
1055
+ showToolbar: true,
1056
+ onSelect: handleAssetSelect
1057
+ })
1058
+ })]
1059
+ })]
1060
+ }), /* @__PURE__ */ jsx(UploadModal, {
1061
+ isOpen: showUpload,
1062
+ folder: currentFolder,
1063
+ onClose: () => setShowUpload(false),
1064
+ onUploadComplete: () => {
1065
+ setShowUpload(false);
1066
+ }
1067
+ })]
1068
+ });
1069
+ }
1070
+
1071
+ //#endregion
1072
+ //#region src/components/editor/ImagePickerDialog.tsx
1073
+ /**
1074
+ * MDX-specific thin wrapper around ImagePicker.
1075
+ * Bridges MDXEditor gurx signals to the generic ImagePicker component.
1076
+ */
1077
+ function ImagePickerDialog() {
1078
+ const state = useCellValue(imageDialogState$);
1079
+ const insertImage = usePublisher(insertImage$);
1080
+ const closeDialog = usePublisher(closeImageDialog$);
1081
+ const handleSelect = (asset) => {
1082
+ insertImage({ src: `/assets${asset.folder && asset.folder !== "/" ? asset.folder : ""}/${asset.filename}` });
1083
+ closeDialog();
1084
+ };
1085
+ return /* @__PURE__ */ jsx(ImagePicker, {
1086
+ isOpen: state.type !== "inactive",
1087
+ onSelect: handleSelect,
1088
+ onClose: () => closeDialog()
1089
+ });
1090
+ }
1091
+
1092
+ //#endregion
1093
+ //#region src/components/editor/CMSMDXEditor.tsx
1094
+ /**
1095
+ * Error Boundary for catching React errors in MDXEditor.
1096
+ * Prevents editor crashes from breaking the entire CMS.
1097
+ */
1098
+ var MDXEditorErrorBoundary = class extends React.Component {
1099
+ constructor(props) {
1100
+ super(props);
1101
+ this.state = { hasError: false };
1102
+ }
1103
+ static getDerivedStateFromError(error) {
1104
+ return {
1105
+ hasError: true,
1106
+ error
1107
+ };
1108
+ }
1109
+ componentDidCatch(error, errorInfo) {
1110
+ console.error("[CMSMDXEditor] Error boundary caught:", error, errorInfo);
1111
+ }
1112
+ render() {
1113
+ if (this.state.hasError) return /* @__PURE__ */ jsxs("div", {
1114
+ className: "p-4 bg-red-50 border border-red-200 rounded text-red-600",
1115
+ children: [
1116
+ /* @__PURE__ */ jsx("p", {
1117
+ className: "font-semibold mb-2",
1118
+ children: "MDXEditor Error"
1119
+ }),
1120
+ /* @__PURE__ */ jsx("p", {
1121
+ className: "text-sm mb-2",
1122
+ children: this.state.error?.message || "Unknown error occurred"
1123
+ }),
1124
+ /* @__PURE__ */ jsxs("details", {
1125
+ className: "text-xs",
1126
+ children: [/* @__PURE__ */ jsx("summary", {
1127
+ className: "cursor-pointer font-medium",
1128
+ children: "Stack Trace"
1129
+ }), /* @__PURE__ */ jsx("pre", {
1130
+ className: "mt-2 p-2 bg-red-100 rounded overflow-auto whitespace-pre-wrap",
1131
+ children: this.state.error?.stack
1132
+ })]
1133
+ })
1134
+ ]
1135
+ });
1136
+ return this.props.children;
1137
+ }
1138
+ };
1139
+ /**
1140
+ * CMS-integrated MDX Editor with Media Library image picker.
1141
+ * This component wraps MDXEditor with ImagePickerDialog and keyboard shortcuts.
1142
+ */
1143
+ const CMSMDXEditor = React.forwardRef(({ value, onChange, onSave, readOnly = false }, ref) => {
1144
+ useEffect(() => {
1145
+ const handleKeyDown = (e) => {
1146
+ if ((e.ctrlKey || e.metaKey) && e.key === "s") {
1147
+ e.preventDefault();
1148
+ if (onSave) onSave(value);
1149
+ }
1150
+ if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === "i") {
1151
+ e.preventDefault();
1152
+ document.querySelector("[aria-label=\"Insert image\"]")?.click();
1153
+ }
1154
+ };
1155
+ document.addEventListener("keydown", handleKeyDown);
1156
+ return () => document.removeEventListener("keydown", handleKeyDown);
1157
+ }, [value, onSave]);
1158
+ return /* @__PURE__ */ jsx(MDXEditor, {
1159
+ ref,
1160
+ markdown: value,
1161
+ onChange,
1162
+ readOnly,
1163
+ contentEditableClassName: "prose max-w-none",
1164
+ plugins: [
1165
+ headingsPlugin(),
1166
+ listsPlugin(),
1167
+ quotePlugin(),
1168
+ linkPlugin(),
1169
+ linkDialogPlugin(),
1170
+ tablePlugin(),
1171
+ thematicBreakPlugin(),
1172
+ frontmatterPlugin(),
1173
+ codeBlockPlugin({ defaultCodeBlockLanguage: "ts" }),
1174
+ codeMirrorPlugin({ codeBlockLanguages: {
1175
+ text: "Plain Text",
1176
+ js: "JavaScript",
1177
+ jsx: "JavaScript (React)",
1178
+ ts: "TypeScript",
1179
+ tsx: "TypeScript (React)",
1180
+ css: "CSS",
1181
+ html: "HTML",
1182
+ json: "JSON",
1183
+ md: "Markdown",
1184
+ mdx: "MDX",
1185
+ bash: "Bash",
1186
+ python: "Python"
1187
+ } }),
1188
+ diffSourcePlugin({ viewMode: "rich-text" }),
1189
+ markdownShortcutPlugin(),
1190
+ jsxPlugin(),
1191
+ imagePlugin({
1192
+ ImageDialog: ImagePickerDialog,
1193
+ disableImageSettingsButton: true
1194
+ }),
1195
+ toolbarPlugin({ toolbarContents: () => /* @__PURE__ */ jsxs(DiffSourceToggleWrapper, { children: [
1196
+ /* @__PURE__ */ jsx(UndoRedo, {}),
1197
+ /* @__PURE__ */ jsx(Separator, {}),
1198
+ /* @__PURE__ */ jsx(BoldItalicUnderlineToggles, {}),
1199
+ /* @__PURE__ */ jsx(Separator, {}),
1200
+ /* @__PURE__ */ jsx(ListsToggle, {}),
1201
+ /* @__PURE__ */ jsx(Separator, {}),
1202
+ /* @__PURE__ */ jsx(BlockTypeSelect, {}),
1203
+ /* @__PURE__ */ jsx(Separator, {}),
1204
+ /* @__PURE__ */ jsx(CreateLink, {}),
1205
+ /* @__PURE__ */ jsx(InsertImage, {}),
1206
+ /* @__PURE__ */ jsx(InsertTable, {}),
1207
+ /* @__PURE__ */ jsx(InsertThematicBreak, {}),
1208
+ /* @__PURE__ */ jsx(Separator, {}),
1209
+ /* @__PURE__ */ jsx(InsertCodeBlock, {})
1210
+ ] }) })
1211
+ ]
1212
+ });
1213
+ });
1214
+ CMSMDXEditor.displayName = "CMSMDXEditor";
1215
+ /**
1216
+ * DeferredCMSMDXEditor - A wrapper component that defers CMSMDXEditor initialization
1217
+ * to avoid React 19 render-phase state updates.
1218
+ *
1219
+ * See the original DeferredMDXEditor in @conloca/mdx for detailed documentation.
1220
+ */
1221
+ const DeferredCMSMDXEditor = ({ value, onChange, onSave, readOnly }) => {
1222
+ const editorRef = React.useRef(null);
1223
+ const [isReady, setIsReady] = useState(false);
1224
+ useEffect(() => {
1225
+ const timer = setTimeout(() => {
1226
+ setIsReady(true);
1227
+ }, 10);
1228
+ return () => clearTimeout(timer);
1229
+ }, []);
1230
+ if (!isReady) return /* @__PURE__ */ jsx("div", {
1231
+ className: "flex items-center justify-center h-full text-gray-500",
1232
+ "data-testid": "deferred-editor-loading",
1233
+ children: "Initializing editor..."
1234
+ });
1235
+ return /* @__PURE__ */ jsx("div", {
1236
+ "data-testid": "deferred-editor-ready",
1237
+ children: /* @__PURE__ */ jsx(CMSMDXEditor, {
1238
+ ref: editorRef,
1239
+ value,
1240
+ onChange,
1241
+ onSave,
1242
+ readOnly
1243
+ })
1244
+ });
1245
+ };
1246
+ const Dialog = ({ open, onOpenChange, children }) => {
1247
+ if (!open) return null;
1248
+ return /* @__PURE__ */ jsxs("div", {
1249
+ className: "fixed inset-0 z-50 flex items-center justify-center",
1250
+ children: [/* @__PURE__ */ jsx("div", {
1251
+ className: "fixed inset-0 bg-black/50",
1252
+ onClick: () => onOpenChange(false)
1253
+ }), /* @__PURE__ */ jsx("div", {
1254
+ className: "relative z-50 bg-white rounded-lg shadow-lg max-w-[90vw] max-h-[90vh] overflow-hidden",
1255
+ children
1256
+ })]
1257
+ });
1258
+ };
1259
+ const DialogContent = ({ children, className = "" }) => {
1260
+ return /* @__PURE__ */ jsx("div", {
1261
+ className: `p-6 ${className}`,
1262
+ children
1263
+ });
1264
+ };
1265
+ const DialogHeader = ({ children }) => {
1266
+ return /* @__PURE__ */ jsx("div", {
1267
+ className: "mb-4",
1268
+ children
1269
+ });
1270
+ };
1271
+ const DialogTitle = ({ children }) => {
1272
+ return /* @__PURE__ */ jsx("h2", {
1273
+ className: "text-xl font-semibold",
1274
+ children
1275
+ });
1276
+ };
1277
+ /**
1278
+ * Modal wrapper for CMSMDXEditor with integrated Media Library image picker.
1279
+ * Use this instead of MDXEditorModal from @conloca/mdx when you need the image picker.
1280
+ */
1281
+ const CMSMDXEditorModal = ({ isOpen, onClose, filePath, initialContent, onSave, headerExtra, onBeforeClose }) => {
1282
+ const [content, setContent] = useState(initialContent);
1283
+ const [isEditorReady, setIsEditorReady] = useState(false);
1284
+ const [isSaving, setIsSaving] = useState(false);
1285
+ useEffect(() => {
1286
+ setContent(initialContent);
1287
+ }, [initialContent]);
1288
+ const handleClose = () => {
1289
+ if (onBeforeClose && !onBeforeClose()) return;
1290
+ onClose();
1291
+ };
1292
+ useEffect(() => {
1293
+ if (isOpen) {
1294
+ const timer = setTimeout(() => {
1295
+ setIsEditorReady(true);
1296
+ }, 0);
1297
+ return () => clearTimeout(timer);
1298
+ }
1299
+ setIsEditorReady(false);
1300
+ }, [isOpen]);
1301
+ const handleSave = async () => {
1302
+ setIsSaving(true);
1303
+ try {
1304
+ await onSave(content);
1305
+ handleClose();
1306
+ } catch (error) {
1307
+ console.error("Save failed:", error);
1308
+ } finally {
1309
+ setIsSaving(false);
1310
+ }
1311
+ };
1312
+ if (!isOpen) return null;
1313
+ return /* @__PURE__ */ jsx(Dialog, {
1314
+ open: isOpen,
1315
+ onOpenChange: handleClose,
1316
+ children: /* @__PURE__ */ jsxs(DialogContent, {
1317
+ className: "w-[90vw] h-[90vh] flex flex-col",
1318
+ "data-testid": "mdx-editor-modal",
1319
+ children: [
1320
+ /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsxs("div", {
1321
+ className: "flex items-center justify-between gap-4",
1322
+ children: [
1323
+ /* @__PURE__ */ jsx(DialogTitle, { children: filePath ? `Edit: ${filePath}` : "New MDX File" }),
1324
+ headerExtra && /* @__PURE__ */ jsx("div", {
1325
+ className: "flex items-center gap-2",
1326
+ children: headerExtra
1327
+ }),
1328
+ /* @__PURE__ */ jsx("button", {
1329
+ onClick: handleClose,
1330
+ className: "p-2 hover:bg-gray-100 rounded",
1331
+ "aria-label": "Close",
1332
+ children: "✕"
1333
+ })
1334
+ ]
1335
+ }) }),
1336
+ /* @__PURE__ */ jsx("div", {
1337
+ className: "flex-1 overflow-hidden",
1338
+ children: isEditorReady ? /* @__PURE__ */ jsx(MDXEditorErrorBoundary, { children: /* @__PURE__ */ jsx(DeferredCMSMDXEditor, {
1339
+ value: content,
1340
+ onChange: setContent,
1341
+ onSave: handleSave
1342
+ }) }) : /* @__PURE__ */ jsx("div", {
1343
+ className: "flex items-center justify-center h-full",
1344
+ children: /* @__PURE__ */ jsx("div", {
1345
+ className: "text-gray-500",
1346
+ "data-testid": "modal-editor-loading",
1347
+ children: "Loading editor..."
1348
+ })
1349
+ })
1350
+ }),
1351
+ /* @__PURE__ */ jsxs("div", {
1352
+ className: "flex justify-end gap-2 mt-4",
1353
+ children: [/* @__PURE__ */ jsx("button", {
1354
+ onClick: handleClose,
1355
+ className: "px-4 py-2 border border-gray-300 rounded hover:bg-gray-50",
1356
+ disabled: isSaving,
1357
+ children: "Cancel"
1358
+ }), /* @__PURE__ */ jsx("button", {
1359
+ onClick: handleSave,
1360
+ className: "px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",
1361
+ disabled: isSaving,
1362
+ children: isSaving ? "Saving..." : "Save"
1363
+ })]
1364
+ })
1365
+ ]
1366
+ })
1367
+ });
1368
+ };
1369
+
1370
+ //#endregion
1371
+ //#region src/components/puck/MDXContent.tsx
1372
+ /**
1373
+ * Error Boundary for catching React errors in MDXContent rendering.
1374
+ */
1375
+ var MDXContentErrorBoundary = class extends React.Component {
1376
+ constructor(props) {
1377
+ super(props);
1378
+ this.state = { hasError: false };
1379
+ }
1380
+ static getDerivedStateFromError(error) {
1381
+ return {
1382
+ hasError: true,
1383
+ error
1384
+ };
1385
+ }
1386
+ componentDidCatch(error, errorInfo) {
1387
+ console.error("[MDXContent] Error boundary caught:", error, errorInfo);
1388
+ }
1389
+ render() {
1390
+ if (this.state.hasError) return /* @__PURE__ */ jsxs("div", {
1391
+ className: "p-4 bg-red-50 border border-red-200 rounded text-red-600",
1392
+ children: [
1393
+ /* @__PURE__ */ jsx("p", {
1394
+ className: "font-semibold mb-2",
1395
+ children: "MDXContent Rendering Error"
1396
+ }),
1397
+ /* @__PURE__ */ jsx("p", {
1398
+ className: "text-sm mb-2",
1399
+ children: this.state.error?.message || "Unknown error occurred"
1400
+ }),
1401
+ /* @__PURE__ */ jsxs("p", {
1402
+ className: "text-xs text-red-500 mb-2",
1403
+ children: ["Block ID: ", this.props.contentId]
1404
+ }),
1405
+ /* @__PURE__ */ jsxs("details", {
1406
+ className: "text-xs",
1407
+ children: [/* @__PURE__ */ jsx("summary", {
1408
+ className: "cursor-pointer font-medium",
1409
+ children: "Stack Trace"
1410
+ }), /* @__PURE__ */ jsx("pre", {
1411
+ className: "mt-2 p-2 bg-red-100 rounded overflow-auto whitespace-pre-wrap",
1412
+ children: this.state.error?.stack
1413
+ })]
1414
+ })
1415
+ ]
1416
+ });
1417
+ return this.props.children;
1418
+ }
1419
+ };
1420
+ /**
1421
+ * Component for rendering MDX content blocks in the CMS editor.
1422
+ *
1423
+ * Receives a LocalizedEntry and renders its MDX content using the useMDXEvaluation hook.
1424
+ * Displays appropriate loading, error, and empty states.
1425
+ *
1426
+ * @param props - Component props
1427
+ * @param props.entry - LocalizedEntry containing the content and ETag
1428
+ */
1429
+ function MDXContentInner({ entry }) {
1430
+ const actualMdxContent = useMemo(() => {
1431
+ if (!entry?.localized?.content) return null;
1432
+ return entry.localized.content.mdx || null;
1433
+ }, [entry]);
1434
+ const { Component, error: compileError, isLoading: isCompiling, retry } = useMDXEvaluation({
1435
+ mdxContent: actualMdxContent,
1436
+ cacheKey: entry.localized.etag
1437
+ });
1438
+ if (isCompiling) return /* @__PURE__ */ jsxs("div", {
1439
+ className: "flex items-center justify-center p-8 text-grey-04",
1440
+ children: [/* @__PURE__ */ jsx("div", { className: "animate-spin rounded-full h-6 w-6 border-b-2 border-azure-04 mr-3" }), "Loading content..."]
1441
+ });
1442
+ if (compileError) return /* @__PURE__ */ jsxs("div", {
1443
+ className: "p-4 bg-red-50 border border-red-200 rounded text-red-600",
1444
+ children: [
1445
+ /* @__PURE__ */ jsx("p", {
1446
+ className: "font-semibold mb-2",
1447
+ children: "Cannot Render Block Content"
1448
+ }),
1449
+ /* @__PURE__ */ jsx("p", {
1450
+ className: "text-sm mb-2",
1451
+ children: compileError.message
1452
+ }),
1453
+ /* @__PURE__ */ jsx("p", {
1454
+ className: "text-xs text-red-500 mb-3",
1455
+ children: "The block content contains invalid MDX syntax. Please edit the block to fix any syntax errors."
1456
+ }),
1457
+ /* @__PURE__ */ jsx("button", {
1458
+ onClick: retry,
1459
+ className: "px-3 py-1 text-sm bg-red-600 text-white rounded hover:bg-red-700 transition-colors",
1460
+ children: "Retry"
1461
+ })
1462
+ ]
1463
+ });
1464
+ if (!actualMdxContent) return /* @__PURE__ */ jsxs("div", {
1465
+ className: "p-4 bg-yellow-50 border border-yellow-200 rounded text-yellow-700",
1466
+ children: [/* @__PURE__ */ jsx("p", {
1467
+ className: "font-semibold mb-1",
1468
+ children: "Empty Block Content"
1469
+ }), /* @__PURE__ */ jsxs("p", {
1470
+ className: "text-sm",
1471
+ children: [
1472
+ "This block (",
1473
+ entry.id,
1474
+ ") doesn't have any content yet. Click to edit and add some MDX content."
1475
+ ]
1476
+ })]
1477
+ });
1478
+ if (!Component) return /* @__PURE__ */ jsxs("div", {
1479
+ className: "flex items-center justify-center p-8 text-grey-04",
1480
+ children: [/* @__PURE__ */ jsx("div", { className: "animate-spin rounded-full h-6 w-6 border-b-2 border-azure-04 mr-3" }), "Loading MDX..."]
1481
+ });
1482
+ return /* @__PURE__ */ jsx("div", {
1483
+ className: "mdx-content prose prose-sm max-w-none",
1484
+ children: /* @__PURE__ */ jsx(Component, {})
1485
+ });
1486
+ }
1487
+ /**
1488
+ * MDXContent component wrapped with error boundary.
1489
+ */
1490
+ function MDXContent(props) {
1491
+ return /* @__PURE__ */ jsx(MDXContentErrorBoundary, {
1492
+ contentId: props.entry.id,
1493
+ children: /* @__PURE__ */ jsx(MDXContentInner, { ...props })
1494
+ });
1495
+ }
1496
+
1497
+ //#endregion
1498
+ export { useDialogState as _, MediaLibrary as a, cn$1 as c, useMoveAssets as d, useUpdateAssetMetadata as f, useErrorModal as g, getUIConfig as h, UploadModal as i, useAssetUsage as l, configureUI as m, CMSMDXEditorModal as n, MediaToolbar as o, useSiteBaseUrl as p, ImagePicker as r, FolderTreeSidebar as s, MDXContent as t, useFolderTree$1 as u, useClickOutside as v, useDeleteAsset as y };
1499
+ //# sourceMappingURL=puck-C-2dQ-Od.mjs.map