@kidecms/core 0.14.3 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  "use client";
2
2
 
3
3
  import { useState, useCallback, useRef, useMemo, useEffect } from "react";
4
+ import type { CSSProperties } from "react";
4
5
  import {
5
6
  ChevronLeft,
6
7
  ChevronRight,
@@ -10,6 +11,7 @@ import {
10
11
  Images,
11
12
  ImagePlus,
12
13
  Inbox,
14
+ Loader2,
13
15
  MoreHorizontal,
14
16
  Pencil,
15
17
  Search,
@@ -50,6 +52,8 @@ type AssetItem = {
50
52
  mimeType: string;
51
53
  url: string;
52
54
  alt: string | null;
55
+ focalX: number | null;
56
+ focalY: number | null;
53
57
  _createdAt: string;
54
58
  };
55
59
 
@@ -78,6 +82,13 @@ type Props = {
78
82
  pageSize: number;
79
83
  };
80
84
 
85
+ // object-cover crops around the CSS center by default — steer it to the asset's
86
+ // focal point instead, when one is set.
87
+ function focalPointStyle(asset: Pick<AssetItem, "focalX" | "focalY">): CSSProperties | undefined {
88
+ if (asset.focalX == null || asset.focalY == null) return undefined;
89
+ return { objectPosition: `${asset.focalX}% ${asset.focalY}%` };
90
+ }
91
+
81
92
  // Build a "/admin/assets" URL for a sidebar scope ("all" | "unfiled" | folderId).
82
93
  // "all" is the bare route; "unfiled" and folder ids ride on the `folder` param.
83
94
  function assetsUrl(opts: { scope?: string; q?: string; page?: number }) {
@@ -114,7 +125,12 @@ function DraggableAssetCard({
114
125
  <div className="relative">
115
126
  {asset.mimeType.startsWith("image/") ? (
116
127
  <div className="bg-muted/30 aspect-square w-full overflow-hidden">
117
- <img src={thumbnail(asset.url)} alt={asset.alt ?? asset.filename} className="size-full object-cover" />
128
+ <img
129
+ src={thumbnail(asset.url)}
130
+ alt={asset.alt ?? asset.filename}
131
+ className="size-full object-cover"
132
+ style={focalPointStyle(asset)}
133
+ />
118
134
  </div>
119
135
  ) : (
120
136
  <div className="bg-muted/30 flex aspect-square items-center justify-center">
@@ -134,7 +150,9 @@ function DraggableAssetCard({
134
150
  <label
135
151
  className={cn(
136
152
  "border-foreground/40 hover:border-foreground/80 bg-background/80 absolute top-2.5 right-2.5 z-10 flex size-5 cursor-default items-center justify-center rounded border backdrop-blur-sm transition-[opacity,border-color]",
137
- selected ? "border-foreground! opacity-100" : "opacity-0 group-hover:opacity-100",
153
+ selected
154
+ ? "border-foreground! opacity-100"
155
+ : "opacity-0 group-hover:opacity-100 has-[:focus-visible]:opacity-100",
138
156
  )}
139
157
  onClick={(e) => e.stopPropagation()}
140
158
  >
@@ -162,7 +180,7 @@ function DraggableAssetCard({
162
180
  {/* Drag handle */}
163
181
  <div
164
182
  ref={setActivatorNodeRef}
165
- className="bg-background/80 border-foreground/40 hover:border-foreground/80 text-muted-foreground absolute top-2.5 left-2.5 z-10 flex size-5 cursor-grab items-center justify-center rounded border opacity-0 backdrop-blur-sm transition-opacity group-hover:opacity-100 active:cursor-grabbing"
183
+ className="bg-background/80 border-foreground/40 hover:border-foreground/80 text-muted-foreground absolute top-2.5 left-2.5 z-10 flex size-5 cursor-grab items-center justify-center rounded border opacity-0 backdrop-blur-sm transition-opacity group-hover:opacity-100 focus-visible:opacity-100 active:cursor-grabbing"
166
184
  {...attributes}
167
185
  {...listeners}
168
186
  >
@@ -255,7 +273,12 @@ function AssetDragOverlay({ asset }: { asset: AssetItem }) {
255
273
  <div className="relative">
256
274
  {asset.mimeType.startsWith("image/") ? (
257
275
  <div className="bg-muted/30 aspect-square w-full overflow-hidden">
258
- <img src={thumbnail(asset.url)} alt={asset.alt ?? asset.filename} className="size-full object-cover" />
276
+ <img
277
+ src={thumbnail(asset.url)}
278
+ alt={asset.alt ?? asset.filename}
279
+ className="size-full object-cover"
280
+ style={focalPointStyle(asset)}
281
+ />
259
282
  </div>
260
283
  ) : (
261
284
  <div className="bg-muted/30 flex aspect-square items-center justify-center">
@@ -320,7 +343,13 @@ export default function AssetsGrid({
320
343
  const [menuOpen, setMenuOpen] = useState(false);
321
344
  const [menuPos, setMenuPos] = useState({ top: 0, left: 0 });
322
345
 
323
- const uploadFormRef = useRef<HTMLFormElement>(null);
346
+ const [uploading, setUploading] = useState(false);
347
+ const [uploadCount, setUploadCount] = useState(0);
348
+ const [uploadProgress, setUploadProgress] = useState(0);
349
+ const [uploadError, setUploadError] = useState<string | null>(null);
350
+ const [uploadNotice, setUploadNotice] = useState<string | null>(null);
351
+ const [isDraggingFile, setIsDraggingFile] = useState(false);
352
+ const dragDepthRef = useRef(0);
324
353
 
325
354
  const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
326
355
 
@@ -398,6 +427,95 @@ export default function AssetsGrid({
398
427
  [pageSize, scopeFolderParam],
399
428
  );
400
429
 
430
+ // Upload via XHR (not fetch) so real byte-level progress is available for
431
+ // xhr.upload.onprogress — the point of this handler for bulk uploads. The
432
+ // server validates every file before storing any (see upload.ts), so this
433
+ // stays a single request for the whole batch rather than one per file.
434
+ const handleFilesSelected = useCallback(
435
+ (files: FileList) => {
436
+ if (files.length === 0) return;
437
+ setUploadError(null);
438
+ setUploadNotice(null);
439
+ setUploading(true);
440
+ setUploadCount(files.length);
441
+ setUploadProgress(0);
442
+
443
+ const formData = new FormData();
444
+ for (const file of Array.from(files)) formData.append("file", file);
445
+ if (currentFolderId) formData.append("folder", currentFolderId);
446
+
447
+ const xhr = new XMLHttpRequest();
448
+ xhr.open("POST", "/api/cms/assets/upload");
449
+ xhr.upload.onprogress = (e) => {
450
+ if (e.lengthComputable) setUploadProgress(Math.round((e.loaded / e.total) * 100));
451
+ };
452
+ xhr.onload = () => {
453
+ if (xhr.status >= 200 && xhr.status < 300) {
454
+ let uploaded: unknown = null;
455
+ try {
456
+ uploaded = JSON.parse(xhr.responseText);
457
+ } catch {
458
+ /* fall through to list refresh */
459
+ }
460
+ // Single upload → its detail view (matches the old form-flow redirect).
461
+ if (uploaded && !Array.isArray(uploaded)) {
462
+ window.location.assign(
463
+ `/admin/assets/${(uploaded as { _id: string })._id}?_toast=success&_msg=Asset+uploaded`,
464
+ );
465
+ return; // keep the busy state until navigation
466
+ }
467
+ setUploading(false);
468
+ setUploadNotice(`${Array.isArray(uploaded) ? uploaded.length : files.length} assets uploaded`);
469
+ setTimeout(() => setUploadNotice(null), 4000);
470
+ fetchPage(1, query);
471
+ } else {
472
+ setUploading(false);
473
+ try {
474
+ setUploadError(JSON.parse(xhr.responseText).error ?? "Upload failed.");
475
+ } catch {
476
+ setUploadError("Upload failed.");
477
+ }
478
+ }
479
+ };
480
+ xhr.onerror = () => {
481
+ setUploading(false);
482
+ setUploadError("Upload failed. Check your connection and try again.");
483
+ };
484
+ xhr.send(formData);
485
+ },
486
+ [currentFolderId, fetchPage, query],
487
+ );
488
+
489
+ // OS-level file drag onto the page. Guarded on the "Files" drag type so this never
490
+ // fires for dnd-kit's own pointer-based asset-card dragging (no DataTransfer involved
491
+ // there) or for dragging text/selections. A depth counter avoids overlay flicker as
492
+ // the pointer crosses child element boundaries while dragging over the page.
493
+ const handleDragEnter = useCallback((e: React.DragEvent) => {
494
+ if (!e.dataTransfer.types.includes("Files")) return;
495
+ e.preventDefault();
496
+ dragDepthRef.current += 1;
497
+ setIsDraggingFile(true);
498
+ }, []);
499
+ const handleDragOver = useCallback((e: React.DragEvent) => {
500
+ if (!e.dataTransfer.types.includes("Files")) return;
501
+ e.preventDefault();
502
+ }, []);
503
+ const handleDragLeave = useCallback((e: React.DragEvent) => {
504
+ if (!e.dataTransfer.types.includes("Files")) return;
505
+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
506
+ if (dragDepthRef.current === 0) setIsDraggingFile(false);
507
+ }, []);
508
+ const handleDrop = useCallback(
509
+ (e: React.DragEvent) => {
510
+ if (!e.dataTransfer.types.includes("Files")) return;
511
+ e.preventDefault();
512
+ dragDepthRef.current = 0;
513
+ setIsDraggingFile(false);
514
+ if (e.dataTransfer.files.length > 0) handleFilesSelected(e.dataTransfer.files);
515
+ },
516
+ [handleFilesSelected],
517
+ );
518
+
401
519
  // Debounce the filter box: re-query from page 1 on every keystroke. Skip the
402
520
  // initial mount — the SSR render already reflects the URL's `search`.
403
521
  const didMount = useRef(false);
@@ -533,6 +651,14 @@ export default function AssetsGrid({
533
651
  location.reload();
534
652
  }
535
653
 
654
+ const emptyStateMessage = query.trim()
655
+ ? `No assets match “${query.trim()}”.`
656
+ : scope === "unfiled"
657
+ ? "No unfiled assets."
658
+ : scope === "all"
659
+ ? "No assets uploaded yet."
660
+ : "This folder is empty.";
661
+
536
662
  return (
537
663
  <DndContext
538
664
  sensors={sensors}
@@ -542,7 +668,19 @@ export default function AssetsGrid({
542
668
  onDragEnd={handleDragEnd}
543
669
  onDragCancel={handleDragCancel}
544
670
  >
545
- <section className="px-4 py-6 lg:py-8 lg:pr-8 lg:pl-12">
671
+ <section
672
+ className="relative px-4 py-6 lg:py-8 lg:pr-8 lg:pl-12"
673
+ onDragEnter={handleDragEnter}
674
+ onDragOver={handleDragOver}
675
+ onDragLeave={handleDragLeave}
676
+ onDrop={handleDrop}
677
+ >
678
+ {isDraggingFile && (
679
+ <div className="border-primary bg-background/90 pointer-events-none absolute inset-0 z-50 m-2 flex flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed backdrop-blur-sm">
680
+ <Upload className="text-primary size-10" />
681
+ <p className="text-foreground text-sm font-medium">Drop to upload</p>
682
+ </div>
683
+ )}
546
684
  <h1 className="mb-6 text-2xl font-semibold tracking-tight">Assets</h1>
547
685
 
548
686
  <div className="grid gap-8 lg:grid-cols-[230px_minmax(0,1fr)] lg:gap-0">
@@ -615,31 +753,56 @@ export default function AssetsGrid({
615
753
  className="pl-9 text-sm"
616
754
  />
617
755
  </div>
618
- <label className={cn(buttonVariants(), "shrink-0 cursor-pointer")}>
619
- <Upload className="size-4" />
620
- Upload
621
- <form
622
- ref={uploadFormRef}
623
- method="post"
624
- action="/api/cms/assets/upload"
625
- encType="multipart/form-data"
756
+ <label
757
+ className={cn(
758
+ buttonVariants(),
759
+ "shrink-0",
760
+ uploading ? "pointer-events-none opacity-70" : "cursor-pointer",
761
+ )}
762
+ >
763
+ {uploading ? (
764
+ <>
765
+ <Loader2 className="size-4 animate-spin" />
766
+ {uploadProgress < 100
767
+ ? `Uploading ${uploadCount > 1 ? `${uploadCount} files` : "file"}… ${uploadProgress}%`
768
+ : "Processing…"}
769
+ </>
770
+ ) : (
771
+ <>
772
+ <Upload className="size-4" />
773
+ Upload
774
+ </>
775
+ )}
776
+ <input
777
+ type="file"
778
+ name="file"
779
+ accept="image/*,video/*,audio/*,.pdf,.doc,.docx"
780
+ multiple
781
+ disabled={uploading}
626
782
  className="hidden"
627
- >
628
- <input type="hidden" name="redirectTo" value={assetsUrl({ scope })} />
629
- {currentFolderId && <input type="hidden" name="folder" value={currentFolderId} />}
630
- <input
631
- type="file"
632
- name="file"
633
- accept="image/*,video/*,audio/*,.pdf,.doc,.docx"
634
- multiple
635
- required
636
- onChange={(e) => {
637
- if (e.target.value) uploadFormRef.current?.submit();
638
- }}
639
- />
640
- </form>
783
+ onChange={(e) => {
784
+ if (e.target.files?.length) handleFilesSelected(e.target.files);
785
+ e.target.value = "";
786
+ }}
787
+ />
641
788
  </label>
642
789
  </div>
790
+ {uploading && (
791
+ <div
792
+ role="progressbar"
793
+ aria-valuenow={uploadProgress}
794
+ aria-valuemin={0}
795
+ aria-valuemax={100}
796
+ className="bg-muted h-1 w-full overflow-hidden rounded-full"
797
+ >
798
+ <div
799
+ className="bg-primary h-full rounded-full transition-[width]"
800
+ style={{ width: `${uploadProgress}%` }}
801
+ />
802
+ </div>
803
+ )}
804
+ {uploadError && <p className="text-destructive text-sm">{uploadError}</p>}
805
+ {uploadNotice && <p className="text-muted-foreground text-sm">{uploadNotice}</p>}
643
806
 
644
807
  {/* Selection toolbar */}
645
808
  {selectedIds.size > 0 && (
@@ -687,22 +850,10 @@ export default function AssetsGrid({
687
850
  <CardContent className="text-muted-foreground py-12 text-center text-sm">Searching…</CardContent>
688
851
  </Card>
689
852
  ) : (
690
- <Card>
691
- <CardContent className="py-12">
692
- <div className="text-center">
693
- <ImagePlus className="text-muted-foreground/30 mx-auto size-12" />
694
- <p className="text-muted-foreground mt-3 text-sm">
695
- {query.trim()
696
- ? `No assets match “${query.trim()}”.`
697
- : scope === "unfiled"
698
- ? "No unfiled assets."
699
- : scope === "all"
700
- ? "No assets uploaded yet."
701
- : "This folder is empty."}
702
- </p>
703
- </div>
704
- </CardContent>
705
- </Card>
853
+ <div className="bg-muted/20 flex h-40 flex-col items-center justify-center gap-3 rounded-lg border border-dashed">
854
+ <ImagePlus className="text-muted-foreground/30 size-12" />
855
+ <p className="text-muted-foreground text-sm">{emptyStateMessage}</p>
856
+ </div>
706
857
  )}
707
858
 
708
859
  {/* Pagination (client-side — keeps the active filter without a reload) */}
@@ -339,7 +339,7 @@ const ToolbarButton = ({
339
339
  title={title}
340
340
  className={cn(
341
341
  "disabled:hover:text-muted-foreground inline-flex size-8 items-center justify-center rounded-md transition-colors outline-none disabled:opacity-50 disabled:hover:bg-transparent",
342
- active ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
342
+ active ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-muted-strong hover:text-foreground",
343
343
  )}
344
344
  >
345
345
  {children}
@@ -17,6 +17,7 @@ import {
17
17
  ArrowDown,
18
18
  ArrowUp,
19
19
  ArrowUpDown,
20
+ ArrowUpRight,
20
21
  ChevronDown,
21
22
  ChevronLeft,
22
23
  ChevronRight,
@@ -65,6 +66,8 @@ type DataTableRow = {
65
66
  locales: string[];
66
67
  searchText: string;
67
68
  values: Record<string, string>;
69
+ /** Live URL for the "__page" column (e.g. Singles), rendered as an external link. */
70
+ pageHref?: string;
68
71
  };
69
72
 
70
73
  type ServerPaginationConfig = {
@@ -81,6 +84,8 @@ type DocumentsDataTableProps = {
81
84
  collectionSlug: string;
82
85
  draftsEnabled?: boolean;
83
86
  duplicateEnabled?: boolean;
87
+ /** Show the Locales column. Defaults to true for callers (e.g. Recent) that mix collections. */
88
+ showLocalesColumn?: boolean;
84
89
  defaultLocale?: string;
85
90
  labelField?: string;
86
91
  newHref?: string;
@@ -113,6 +118,16 @@ const getVisualStatus = (d: Record<string, unknown>): string => {
113
118
  return status;
114
119
  };
115
120
 
121
+ // Rebuilds row values after a client-side re-fetch (sort/search/page change). The
122
+ // "__page"/"__usage" values are pre-computed server-side (see the collection GET route)
123
+ // since they aren't stored fields — this just reads them back.
124
+ const formatRowValue = (columnKey: string, entry: Record<string, unknown>): string => {
125
+ if (columnKey === "_status") return getVisualStatus(entry);
126
+ if (columnKey === "__usage") return `${Number(entry.__usage ?? 0)} places`;
127
+ if (columnKey === "_updatedAt" || columnKey === "_createdAt") return formatDateClient(entry[columnKey]);
128
+ return String(entry[columnKey] ?? "—");
129
+ };
130
+
116
131
  function DataTableColumnHeader({ column, title }: { column: Column<DataTableRow, unknown>; title: string }) {
117
132
  if (!column.getCanSort()) {
118
133
  return <span>{title}</span>;
@@ -138,6 +153,7 @@ export default function DocumentsDataTable({
138
153
  collectionSlug,
139
154
  draftsEnabled = false,
140
155
  duplicateEnabled = true,
156
+ showLocalesColumn = true,
141
157
  defaultLocale,
142
158
  labelField = "title",
143
159
  newHref,
@@ -235,18 +251,8 @@ export default function DocumentsDataTable({
235
251
  : []),
236
252
  ],
237
253
  searchText: String(entry[labelField] ?? entry.slug ?? entry._id ?? ""),
238
- values: Object.fromEntries(
239
- columns.map((column) => [
240
- column.key,
241
- column.key === "_status"
242
- ? getVisualStatus(entry)
243
- : column.key === "__usage"
244
- ? `${Number(entry.__usage ?? 0)} places`
245
- : column.key === "_updatedAt" || column.key === "_createdAt"
246
- ? formatDateClient(entry[column.key])
247
- : String(entry[column.key] ?? "\u2014"),
248
- ]),
249
- ),
254
+ pageHref: entry._pageHref as string | undefined,
255
+ values: Object.fromEntries(columns.map((column) => [column.key, formatRowValue(column.key, entry)])),
250
256
  })),
251
257
  );
252
258
  setServerTotalDocs(result.totalDocs);
@@ -500,6 +506,23 @@ export default function DocumentsDataTable({
500
506
  />
501
507
  );
502
508
  }
509
+ if (column.key === "__page") {
510
+ return row.original.pageHref ? (
511
+ <a
512
+ href={row.original.pageHref}
513
+ target="_blank"
514
+ rel="noreferrer"
515
+ title={value}
516
+ onClick={(e) => e.stopPropagation()}
517
+ className="text-muted-foreground hover:text-foreground inline-flex max-w-64 min-w-0 items-center gap-1 underline-offset-2 hover:underline"
518
+ >
519
+ <span className="truncate">{value}</span>
520
+ <ArrowUpRight className="size-3.5 shrink-0" />
521
+ </a>
522
+ ) : (
523
+ <div className="text-muted-foreground max-w-64 truncate">{value}</div>
524
+ );
525
+ }
503
526
  const isPrimary = column.key === primaryColumnKey;
504
527
  return (
505
528
  <>
@@ -517,25 +540,35 @@ export default function DocumentsDataTable({
517
540
  );
518
541
  },
519
542
  })),
520
- {
521
- accessorFn: (row) => row.locales.join(", "),
522
- id: "locales",
523
- header: ({ column }) => <DataTableColumnHeader column={column} title="Locales" />,
524
- cell: ({ row }) => (
525
- <div className="flex flex-wrap gap-1.5">
526
- {row.original.locales.map((locale) => (
527
- <a key={locale} href={`${row.original.editHref}?locale=${locale}`} onClick={(e) => e.stopPropagation()}>
528
- <Badge
529
- variant="outline"
530
- className="text-muted-foreground hover:border-foreground/50 hover:text-foreground uppercase transition-colors"
531
- >
532
- {locale}
533
- </Badge>
534
- </a>
535
- ))}
536
- </div>
537
- ),
538
- },
543
+ ...(showLocalesColumn
544
+ ? [
545
+ {
546
+ accessorFn: (row: DataTableRow) => row.locales.join(", "),
547
+ id: "locales",
548
+ header: ({ column }: { column: Column<DataTableRow, unknown> }) => (
549
+ <DataTableColumnHeader column={column} title="Locales" />
550
+ ),
551
+ cell: ({ row }: { row: { original: DataTableRow } }) => (
552
+ <div className="flex flex-wrap gap-1.5">
553
+ {row.original.locales.map((locale) => (
554
+ <a
555
+ key={locale}
556
+ href={`${row.original.editHref}?locale=${locale}`}
557
+ onClick={(e) => e.stopPropagation()}
558
+ >
559
+ <Badge
560
+ variant="outline"
561
+ className="text-muted-foreground hover:border-foreground/50 hover:text-foreground uppercase transition-colors"
562
+ >
563
+ {locale}
564
+ </Badge>
565
+ </a>
566
+ ))}
567
+ </div>
568
+ ),
569
+ } as ColumnDef<DataTableRow>,
570
+ ]
571
+ : []),
539
572
  {
540
573
  id: "actions",
541
574
  enableSorting: false,
@@ -605,7 +638,7 @@ export default function DocumentsDataTable({
605
638
  ),
606
639
  },
607
640
  ],
608
- [columns, draftsEnabled, duplicateEnabled, isPending, primaryColumnKey, isServerMode, runAction],
641
+ [columns, draftsEnabled, duplicateEnabled, showLocalesColumn, isPending, primaryColumnKey, isServerMode, runAction],
609
642
  );
610
643
 
611
644
  const table = useReactTable({
@@ -77,15 +77,8 @@ const {
77
77
  const label = field.label ?? humanize(name);
78
78
  const placeholder = field.admin?.placeholder ?? "";
79
79
  const serializedValue = serializeFieldValue(field, value);
80
- const rows =
81
- field.admin?.rows ??
82
- (field.type === "richText" || field.type === "content"
83
- ? field.type === "content"
84
- ? 14
85
- : 10
86
- : field.type === "json" || field.type === "blocks"
87
- ? 12
88
- : 5);
80
+ const DEFAULT_ROWS: Record<string, number> = { content: 14, richText: 10, json: 12, blocks: 12 };
81
+ const rows = field.admin?.rows ?? DEFAULT_ROWS[field.type] ?? 5;
89
82
  const inputMode = field.type === "number" ? "decimal" : undefined;
90
83
  const controlClass = cn("w-full shadow-none", readOnly && "cursor-not-allowed bg-muted text-muted-foreground");
91
84
  const isTreeEditor =
@@ -162,7 +162,7 @@ export default function ImageBrowseDialog({ open, onOpenChange, onSelect }: Prop
162
162
  </div>
163
163
  ) : (
164
164
  browse.folders.length === 0 && (
165
- <div className="text-muted-foreground flex h-48 items-center justify-center text-sm">
165
+ <div className="bg-muted/20 text-muted-foreground flex h-48 items-center justify-center rounded-lg border border-dashed text-sm">
166
166
  {browse.folderId ? "This folder is empty." : "No images uploaded yet."}
167
167
  </div>
168
168
  )
@@ -108,7 +108,7 @@ export default function ImagePicker({ name, value: initialValue, onChange: onCha
108
108
  setAssetId(null);
109
109
  onChangeProp?.("");
110
110
  }}
111
- className="border-foreground/25 hover:border-foreground bg-background/80 absolute top-2 right-2 flex size-5 items-center justify-center rounded border opacity-0 backdrop-blur-sm transition-[opacity,border-color] group-hover:opacity-100"
111
+ className="border-foreground/25 hover:border-foreground bg-background/80 absolute top-2 right-2 flex size-5 items-center justify-center rounded border opacity-0 backdrop-blur-sm transition-[opacity,border-color] group-hover:opacity-100 focus-visible:opacity-100"
112
112
  >
113
113
  <X className="size-3" />
114
114
  </button>
@@ -41,8 +41,8 @@ export default function InternalLinkPicker({
41
41
  variant="input"
42
42
  role="combobox"
43
43
  aria-expanded={open}
44
- size="lg"
45
- className="w-full justify-between text-sm font-normal"
44
+ size="sm"
45
+ className="bg-background w-full justify-between text-sm font-normal"
46
46
  >
47
47
  <span className={cn("truncate", !selectedLabel && "text-muted-foreground")}>
48
48
  {selectedLabel || "Search documents..."}
@@ -182,7 +182,9 @@ const ToolbarButton = ({
182
182
  title={title}
183
183
  className={cn(
184
184
  "disabled:hover:text-muted-foreground inline-flex size-8 items-center justify-center rounded-md transition-colors outline-none disabled:opacity-50 disabled:hover:bg-transparent",
185
- active ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
185
+ active
186
+ ? "bg-muted-strong text-accent-foreground"
187
+ : "text-muted-foreground hover:bg-muted-strong hover:text-foreground",
186
188
  )}
187
189
  >
188
190
  {children}
@@ -434,7 +434,7 @@ export default function TreeItemsEditor({ name, value, variant, label, linkOptio
434
434
  value={editing.label}
435
435
  onChange={(e) => updateEditing({ label: e.target.value })}
436
436
  placeholder="Label"
437
- className="h-7 min-w-0 flex-3 text-sm"
437
+ className="bg-background h-7 min-w-0 flex-3 text-sm"
438
438
  autoFocus
439
439
  onKeyDown={editKeyHandler}
440
440
  />
@@ -449,7 +449,7 @@ export default function TreeItemsEditor({ name, value, variant, label, linkOptio
449
449
  updateEditing({ linkType: newType, ...(newType === "internal" ? { href: "" } : {}) });
450
450
  }}
451
451
  >
452
- <SelectTrigger className="h-7! min-w-0 flex-2 text-sm">
452
+ <SelectTrigger className="bg-background h-7! min-w-0 flex-2 text-sm">
453
453
  <SelectValue placeholder="Link type" />
454
454
  </SelectTrigger>
455
455
  <SelectContent>
@@ -464,7 +464,7 @@ export default function TreeItemsEditor({ name, value, variant, label, linkOptio
464
464
  value={editing.href}
465
465
  onChange={(e) => updateEditing({ href: e.target.value })}
466
466
  placeholder="https://..."
467
- className="h-7 min-w-0 flex-3 text-sm"
467
+ className="bg-background h-7 min-w-0 flex-3 text-sm"
468
468
  onKeyDown={editKeyHandler}
469
469
  />
470
470
  ) : (
@@ -488,7 +488,7 @@ export default function TreeItemsEditor({ name, value, variant, label, linkOptio
488
488
  updateEditing({ name, ...(editing.autoSlug ? { slug: slugify(name) } : {}) });
489
489
  }}
490
490
  placeholder="Name"
491
- className="h-7 flex-1 text-sm"
491
+ className="bg-background h-7 flex-1 text-sm"
492
492
  autoFocus
493
493
  onKeyDown={editKeyHandler}
494
494
  />
@@ -496,7 +496,7 @@ export default function TreeItemsEditor({ name, value, variant, label, linkOptio
496
496
  value={editing.slug}
497
497
  onChange={(e) => updateEditing({ slug: e.target.value, autoSlug: false })}
498
498
  placeholder="slug"
499
- className="h-7 w-36 text-sm"
499
+ className="bg-background h-7 w-36 text-sm"
500
500
  onKeyDown={editKeyHandler}
501
501
  />
502
502
  </>
@@ -757,13 +757,19 @@ export default function TreeItemsEditor({ name, value, variant, label, linkOptio
757
757
  onDragEnd={handleDragEnd}
758
758
  onDragCancel={handleDragCancel}
759
759
  >
760
- <div className="bg-muted-strong/50 rounded-lg border">
760
+ <div
761
+ className={
762
+ items.length > 0
763
+ ? "bg-muted-strong/50 rounded-lg border"
764
+ : "bg-muted/20 flex h-20 items-center justify-center rounded-lg border border-dashed"
765
+ }
766
+ >
761
767
  {items.length > 0 ? (
762
768
  <SortableContext items={items.map((item) => item.id)} strategy={verticalListSortingStrategy}>
763
769
  {items.map((item) => renderItem(item, 0))}
764
770
  </SortableContext>
765
771
  ) : (
766
- <div className="text-muted-foreground py-8 text-center text-sm">{emptyLabel}</div>
772
+ <p className="text-muted-foreground text-sm">{emptyLabel}</p>
767
773
  )}
768
774
  </div>
769
775
  <DragOverlay dropAnimation={null}>
@@ -332,11 +332,11 @@ const navGroups = [...new Set(navItems.map((item) => item.group))]
332
332
  </main>
333
333
  ) : (
334
334
  <div
335
- class="min-h-screen lg:grid"
335
+ class="min-h-screen min-[1400px]:grid"
336
336
  style="grid-template-columns: 17rem 1fr; transition: grid-template-columns 150ms ease;"
337
337
  >
338
338
  {/* ── Desktop sidebar ──────────────────────────────────────────── */}
339
- <aside class="bg-sidebar/40 sticky top-0 mt-1 hidden h-screen overflow-hidden border-r backdrop-blur transition-transform duration-150 ease-in-out lg:flex lg:flex-col">
339
+ <aside class="bg-sidebar/40 sticky top-0 mt-1 hidden h-screen overflow-hidden border-r backdrop-blur transition-transform duration-150 ease-in-out min-[1400px]:flex min-[1400px]:flex-col">
340
340
  <div class="px-3 pt-4 pb-1">
341
341
  <button
342
342
  type="button"
@@ -422,7 +422,7 @@ const navGroups = [...new Set(navItems.map((item) => item.group))]
422
422
 
423
423
  <div class="min-w-0">
424
424
  {/* ── Mobile header ────────────────────────────────────────── */}
425
- <header class="bg-background/95 supports-backdrop-filter:bg-background/75 flex items-center gap-3 border-b px-4 py-3 backdrop-blur lg:hidden">
425
+ <header class="bg-background/95 supports-backdrop-filter:bg-background/75 flex items-center gap-3 border-b px-4 py-3 backdrop-blur min-[1400px]:hidden">
426
426
  <MobileSidebar client:load>
427
427
  <div class="px-3 pt-4 pb-1">
428
428
  <button
@@ -47,6 +47,7 @@ type CollectionLike = {
47
47
  labels: { singular: string; plural: string };
48
48
  singleton?: boolean;
49
49
  drafts?: boolean;
50
+ auth?: boolean;
50
51
  preview?: boolean | string;
51
52
  pathPrefix?: string;
52
53
  fields: Record<string, any>;
@@ -214,8 +215,8 @@ const publishBlocked =
214
215
  variant === "editorial" && "bg-background sticky top-0 z-30 backdrop-blur-md",
215
216
  ]}
216
217
  >
217
- <div class="flex items-center justify-between gap-3">
218
- <div class="min-w-0">
218
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
219
+ <div class="min-w-0 flex-1">
219
220
  <div class="flex items-center gap-2.5">
220
221
  <h1 class="truncate text-lg font-semibold tracking-tight md:text-xl">
221
222
  {mode === "new" && <LiveHeading client:load initial={`New ${collection.labels.singular}`} />}
@@ -247,7 +248,7 @@ const publishBlocked =
247
248
 
248
249
  {
249
250
  formTab !== "submissions" && (
250
- <div class="flex flex-shrink-0 flex-wrap items-center justify-end gap-2">
251
+ <div class="flex flex-wrap items-center gap-2 sm:flex-shrink-0 sm:justify-end">
251
252
  {hasPreview && previewUrl && !translationMode && (
252
253
  <>
253
254
  <a href={previewUrl} target="_blank" class={buttonVariants({ variant: "outline" })}>
@@ -340,7 +341,7 @@ const publishBlocked =
340
341
  showUnpublish={collection.drafts && doc?._status === "published"}
341
342
  showDiscardDraft={Boolean(collection.drafts && doc?._status === "published" && doc?._published)}
342
343
  showDelete={!isSingleton}
343
- showDuplicate={!isSingleton}
344
+ showDuplicate={!isSingleton && !collection.auth}
344
345
  showSchedule={!!collection.drafts}
345
346
  showCancelSchedule={collection.drafts && doc?._status === "scheduled"}
346
347
  currentPublishAt={doc?._publishAt ? String(doc._publishAt) : undefined}
@@ -357,7 +358,7 @@ const publishBlocked =
357
358
  </div>
358
359
 
359
360
  {/* Body — everything below the sticky bar, inset from the page edges */}
360
- <div class="space-y-6 px-4 pb-8 lg:pr-8 lg:pb-12 lg:pl-20">
361
+ <div class="space-y-6 px-4 pb-8 lg:px-8 lg:pb-12 2xl:px-20">
361
362
  {
362
363
  /* Collaboration review strip. Margins live on this wrapper, which only
363
364
  renders when collaboration is enabled, so non-collab edit views are
@@ -424,7 +425,9 @@ const publishBlocked =
424
425
  action={getFormAction(collection.slug, mode === "edit" ? documentId : undefined)}
425
426
  class:list={[
426
427
  "grid items-start gap-y-10",
427
- hasSidebarColumn ? "2xl:grid-cols-[minmax(0,1fr)_minmax(320px,400px)] 2xl:gap-x-20" : "max-w-3xl",
428
+ hasSidebarColumn
429
+ ? "gap-x-8 lg:grid-cols-[minmax(0,1fr)_minmax(320px,400px)] 2xl:gap-x-20"
430
+ : "max-w-3xl",
428
431
  ]}
429
432
  >
430
433
  <input type="hidden" name="_action" value={mode === "new" ? "create" : "update"} />
@@ -532,7 +535,7 @@ const publishBlocked =
532
535
  </div>
533
536
 
534
537
  {hasSidebarColumn && (
535
- <div class="text-sm 2xl:border-l 2xl:pl-8 [&_button]:text-sm [&_input]:text-sm [&_select]:text-sm [&_textarea]:text-sm">
538
+ <div class="text-sm lg:border-l lg:pl-8 [&_button]:text-sm [&_input]:text-sm [&_select]:text-sm [&_textarea]:text-sm">
536
539
  <div class="space-y-6">
537
540
  {effectiveSidebarFieldSets.map((set) => {
538
541
  const fields = (
@@ -10,8 +10,10 @@ import { REVIEW_STATE_META } from "../lib/collaboration";
10
10
  import {
11
11
  formatDate,
12
12
  formatFieldValue,
13
+ formatPagePath,
13
14
  getLabelField,
14
15
  getListColumns,
16
+ getTranslatableFieldNames,
15
17
  humanize,
16
18
  resolveCollaboration,
17
19
  } from "../../core";
@@ -22,6 +24,9 @@ type CollectionLike = {
22
24
  slug: string;
23
25
  labels: { singular: string; plural: string };
24
26
  drafts?: boolean;
27
+ auth?: boolean;
28
+ preview?: boolean | string;
29
+ pathPrefix?: string;
25
30
  fields: Record<string, any>;
26
31
  views?: Record<string, any>;
27
32
  };
@@ -32,6 +37,9 @@ const runtimeContext = user ? { user } : {};
32
37
  const cmsRuntime = cms as Record<string, any>;
33
38
  const defaultLocale = config.locales?.default ?? "en";
34
39
  const locales = config.locales?.supported ?? [];
40
+ // The Locales column only means something when there's more than one locale
41
+ // and this collection actually has translatable fields to show per-locale.
42
+ const showLocalesColumn = locales.length > 1 && getTranslatableFieldNames(collection).length > 0;
35
43
 
36
44
  const viewConfig = collection.views ?? {};
37
45
  const defaultSort = viewConfig.list?.defaultSort ?? { field: "_updatedAt", direction: "desc" };
@@ -117,40 +125,60 @@ const sharedSectionUsageCounts =
117
125
  runtimeContext,
118
126
  )
119
127
  : {};
120
- const tableRows = docs.map((entry: Record<string, unknown>) => ({
121
- id: String(entry._id),
122
- editHref: `/admin/${collection.slug}/${entry._id}`,
123
- status: getVisualStatus(entry),
124
- locales: [
125
- defaultLocale,
126
- ...(Array.isArray(entry._availableLocales)
127
- ? entry._availableLocales.map((l) => String(l)).filter((l) => l !== defaultLocale)
128
- : []),
129
- ],
130
- searchText: String(entry[getLabelField(collection)] ?? entry.slug ?? entry._id ?? ""),
131
- values: Object.fromEntries(
132
- displayColumns.map((column) => [
133
- column,
134
- column === "__review"
135
- ? REVIEW_STATE_META[
136
- (collabStates[String(entry._id)]?.reviewState ?? "in_progress") as keyof typeof REVIEW_STATE_META
137
- ].label
138
- : column === "__editor"
139
- ? collabStates[String(entry._id)]?.editor
140
- ? (collabUserNames[collabStates[String(entry._id)]!.editor!] ?? "—")
141
- : "Unassigned"
142
- : column === "_status"
143
- ? getVisualStatus(entry)
144
- : column === "__usage"
145
- ? `${sharedSectionUsageCounts[String(entry._id)] ?? 0} places`
146
- : column === "_updatedAt" || column === "_createdAt"
147
- ? formatDate(entry[column])
148
- : column.startsWith("_")
149
- ? String(entry[column] ?? "—")
150
- : formatFieldValue(collection.fields[column], entry[column], relationLabels),
151
- ]),
152
- ),
153
- }));
128
+ const hasPageColumn = displayColumns.includes("__page");
129
+
130
+ // Mirrors EditView's own hasPreview/previewUrl logic, so the listed URL matches
131
+ // what the document's own "Preview" button links to.
132
+ const getPagePath = (entry: Record<string, unknown>): string | null => {
133
+ const hasPreview = hasPageColumn && !!(collection.preview || (collection.pathPrefix && entry?.slug));
134
+ if (!hasPreview) return null;
135
+ return typeof collection.preview === "string"
136
+ ? collection.preview
137
+ : cms.meta.getRouteForDocument(collection.slug, entry);
138
+ };
139
+
140
+ const COLUMN_LABELS: Record<string, string> = {
141
+ __usage: "Used in",
142
+ __review: "Review",
143
+ __editor: "Editor",
144
+ __page: "URL",
145
+ };
146
+ const getColumnLabel = (column: string) => COLUMN_LABELS[column] ?? humanize(column);
147
+
148
+ const formatColumnValue = (column: string, entry: Record<string, unknown>, pagePath: string | null): string => {
149
+ if (column === "__review") {
150
+ const reviewState = collabStates[String(entry._id)]?.reviewState ?? "in_progress";
151
+ return REVIEW_STATE_META[reviewState as keyof typeof REVIEW_STATE_META].label;
152
+ }
153
+ if (column === "__editor") {
154
+ const editorId = collabStates[String(entry._id)]?.editor;
155
+ return editorId ? (collabUserNames[editorId] ?? "—") : "Unassigned";
156
+ }
157
+ if (column === "_status") return getVisualStatus(entry);
158
+ if (column === "__usage") return `${sharedSectionUsageCounts[String(entry._id)] ?? 0} places`;
159
+ if (column === "__page") return formatPagePath(pagePath);
160
+ if (column === "_updatedAt" || column === "_createdAt") return formatDate(entry[column]);
161
+ if (column.startsWith("_")) return String(entry[column] ?? "—");
162
+ return formatFieldValue(collection.fields[column], entry[column], relationLabels);
163
+ };
164
+
165
+ const tableRows = docs.map((entry: Record<string, unknown>) => {
166
+ const pagePath = getPagePath(entry);
167
+ return {
168
+ id: String(entry._id),
169
+ editHref: `/admin/${collection.slug}/${entry._id}`,
170
+ status: getVisualStatus(entry),
171
+ locales: [
172
+ defaultLocale,
173
+ ...(Array.isArray(entry._availableLocales)
174
+ ? entry._availableLocales.map((l) => String(l)).filter((l) => l !== defaultLocale)
175
+ : []),
176
+ ],
177
+ searchText: String(entry[getLabelField(collection)] ?? entry.slug ?? entry._id ?? ""),
178
+ pageHref: pagePath ? `${pagePath}?preview=true` : undefined,
179
+ values: Object.fromEntries(displayColumns.map((column) => [column, formatColumnValue(column, entry, pagePath)])),
180
+ };
181
+ });
154
182
  ---
155
183
 
156
184
  <section class="space-y-6 px-4 py-6 lg:py-8 lg:pr-8 lg:pl-12">
@@ -173,20 +201,15 @@ const tableRows = docs.map((entry: Record<string, unknown>) => ({
173
201
  client:load
174
202
  collectionSlug={collection.slug}
175
203
  draftsEnabled={collection.drafts}
204
+ duplicateEnabled={!collection.auth}
205
+ showLocalesColumn={showLocalesColumn}
176
206
  defaultLocale={locales.length > 1 ? defaultLocale : undefined}
177
207
  labelField={getLabelField(collection)}
178
208
  newHref={`/admin/${collection.slug}/new`}
179
209
  title={collection.labels.plural}
180
210
  columns={displayColumns.map((column) => ({
181
211
  key: column,
182
- label:
183
- column === "__usage"
184
- ? "Used in"
185
- : column === "__review"
186
- ? "Review"
187
- : column === "__editor"
188
- ? "Editor"
189
- : humanize(column),
212
+ label: getColumnLabel(column),
190
213
  sortable: !column.startsWith("__"),
191
214
  }))}
192
215
  data={tableRows}
@@ -2,18 +2,23 @@
2
2
  import DocumentsDataTable from "../components/DocumentsDataTable";
3
3
  import config from "virtual:kide/config";
4
4
  import { cms } from "virtual:kide/api";
5
- import { formatDate, getLabelField } from "../../core";
5
+ import { formatDate, getLabelField, getTranslatableFieldNames } from "../../core";
6
6
  import { canRead, getVisualStatus } from "../lib/access";
7
7
 
8
8
  const user = Astro.locals.user;
9
9
  const runtimeContext = user ? { user } : {};
10
10
  const cmsRuntime = cms as Record<string, any>;
11
11
  const defaultLocale = config.locales?.default ?? "en";
12
+ const locales = config.locales?.supported ?? [];
12
13
 
13
14
  const pinnedSlugs = new Set(["taxonomies", "menus", "authors", "users"]);
14
15
  const contentCollections = config.collections.filter(
15
16
  (c) => !c.auth && !pinnedSlugs.has(c.slug) && canRead(config, user, c.slug),
16
17
  );
18
+ // Same rule as ListView: a Locales column is only meaningful with more than one
19
+ // locale and at least one of the mixed-in collections having translatable fields.
20
+ const showLocalesColumn =
21
+ locales.length > 1 && contentCollections.some((cc) => getTranslatableFieldNames(cc).length > 0);
17
22
 
18
23
  const allEntries: Array<{ doc: Record<string, unknown>; collection: (typeof contentCollections)[0] }> = [];
19
24
  for (const cc of contentCollections) {
@@ -72,5 +77,6 @@ const recentRows = allEntries.slice(0, 50).map(({ doc, collection: cc }) => {
72
77
  ]}
73
78
  data={recentRows}
74
79
  searchPlaceholder="Filter recent entries..."
80
+ showLocalesColumn={showLocalesColumn}
75
81
  />
76
82
  </section>
@@ -2,20 +2,34 @@
2
2
  import DocumentsDataTable from "../components/DocumentsDataTable";
3
3
  import config from "virtual:kide/config";
4
4
  import { cms } from "virtual:kide/api";
5
- import { formatDate } from "../../core";
5
+ import { formatDate, formatPagePath, getTranslatableFieldNames } from "../../core";
6
6
  import { canRead } from "../lib/access";
7
7
 
8
8
  const user = Astro.locals.user;
9
9
  const runtimeContext = user ? { user } : {};
10
10
  const cmsRuntime = cms as Record<string, any>;
11
11
  const defaultLocale = config.locales?.default ?? "en";
12
+ const locales = config.locales?.supported ?? [];
12
13
 
13
14
  const singletonCollections = config.collections.filter((c) => c.singleton && canRead(config, user, c.slug));
15
+ // Same rule as ListView: a Locales column is only meaningful with more than one
16
+ // locale and at least one singleton having translatable fields.
17
+ const showLocalesColumn =
18
+ locales.length > 1 && singletonCollections.some((c) => getTranslatableFieldNames(c).length > 0);
19
+ // Mirrors ListView's own getPagePath, so the listed URL matches what the
20
+ // singleton's own "Preview" button links to.
21
+ const getPagePath = (sc: (typeof singletonCollections)[number], doc: Record<string, unknown> | null): string | null => {
22
+ if (!sc.preview) return null;
23
+ if (typeof sc.preview === "string") return sc.preview;
24
+ return doc ? cms.meta.getRouteForDocument(sc.slug, doc) : null;
25
+ };
26
+
14
27
  const singletonsData = await Promise.all(
15
28
  singletonCollections.map(async (sc) => {
16
29
  const api = cmsRuntime[sc.slug];
17
30
  const singleDocs = await api.find({ status: "any", limit: 1, locale: defaultLocale }, runtimeContext);
18
31
  const singleDoc = singleDocs[0] ?? null;
32
+ const pagePath = getPagePath(sc, singleDoc);
19
33
  return {
20
34
  id: singleDoc ? String(singleDoc._id) : "",
21
35
  collectionSlug: sc.slug,
@@ -31,6 +45,8 @@ const singletonsData = await Promise.all(
31
45
  : [],
32
46
  updatedAt: singleDoc ? formatDate(singleDoc._updatedAt) : "—",
33
47
  editHref: `/admin/${sc.slug}`,
48
+ page: pagePath,
49
+ pageHref: pagePath ? `${pagePath}?preview=true` : null,
34
50
  };
35
51
  }),
36
52
  );
@@ -48,9 +64,9 @@ const singletonsData = await Promise.all(
48
64
  title="Singles"
49
65
  columns={[
50
66
  { key: "name", label: "Name" },
51
- { key: "slug", label: "API slug" },
67
+ { key: "__page", label: "URL" },
52
68
  ...(singletonCollections.some((c) => c.drafts) ? [{ key: "_status", label: "Status" }] : []),
53
- { key: "updatedAt", label: "Last updated" },
69
+ { key: "updatedAt", label: "Updated At" },
54
70
  ]}
55
71
  data={singletonsData.map((s) => ({
56
72
  id: s.id,
@@ -58,8 +74,10 @@ const singletonsData = await Promise.all(
58
74
  editHref: s.editHref,
59
75
  locales: s.locales,
60
76
  searchText: `${s.label} ${s.collectionSlug}`,
61
- values: { name: s.label, slug: s.collectionSlug, _status: s.status, updatedAt: s.updatedAt },
77
+ values: { name: s.label, __page: formatPagePath(s.page), _status: s.status, updatedAt: s.updatedAt },
78
+ pageHref: s.pageHref ?? undefined,
62
79
  }))}
63
80
  searchPlaceholder="Filter singles..."
81
+ showLocalesColumn={showLocalesColumn}
64
82
  />
65
83
  </section>
package/core/admin.ts CHANGED
@@ -103,6 +103,9 @@ export const resolveAdminRoute = (path: string | undefined): AdminRoute => {
103
103
  };
104
104
  };
105
105
 
106
+ /** Display text for a document's public URL in list tables — the bare root path reads as "Homepage" instead of "/". */
107
+ export const formatPagePath = (path: string | null | undefined) => (path === "/" ? "Homepage" : (path ?? "—"));
108
+
106
109
  export const humanize = (value: string) =>
107
110
  value
108
111
  .replace(/^_+/, "")
@@ -150,7 +153,12 @@ export const getListColumns = (collection: CollectionConfig, viewConfig?: { colu
150
153
  return collection.drafts ? viewConfig.columns : viewConfig.columns.filter((column) => column !== "_status");
151
154
  }
152
155
  const firstField = "title" in collection.fields ? "title" : Object.keys(collection.fields)[0];
153
- return collection.drafts ? [firstField, "_status", "_updatedAt"] : [firstField, "_updatedAt"];
156
+ const columns = [firstField];
157
+ if (collection.preview || collection.pathPrefix) columns.push("__page");
158
+ if (collection.drafts) columns.push("_status");
159
+ if (collection.timestamps !== false) columns.push("_createdAt");
160
+ columns.push("_updatedAt");
161
+ return columns;
154
162
  };
155
163
 
156
164
  /**
package/core/index.ts CHANGED
@@ -179,6 +179,7 @@ export {
179
179
  resolveAdminRoute,
180
180
  humanize,
181
181
  formatFieldValue,
182
+ formatPagePath,
182
183
  getListColumns,
183
184
  getFieldGroups,
184
185
  getFieldSets,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.14.3",
3
+ "version": "0.15.0",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",
@@ -65,6 +65,8 @@ const assetData = folderAssets.map((a) => ({
65
65
  mimeType: a.mimeType,
66
66
  url: a.url,
67
67
  alt: a.alt,
68
+ focalX: a.focalX,
69
+ focalY: a.focalY,
68
70
  _createdAt: a._createdAt,
69
71
  }));
70
72
  ---
@@ -32,16 +32,14 @@ if (token) {
32
32
  }
33
33
  }
34
34
 
35
- const errorMessage =
36
- error === "missing"
37
- ? "Name and password are required."
38
- : error === "password"
39
- ? "Passwords do not match."
40
- : error === "short"
41
- ? `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`
42
- : error === "expired" || error === "invalid"
43
- ? "This invite link has expired or already been used."
44
- : null;
35
+ const ERROR_MESSAGES: Record<string, string> = {
36
+ missing: "Name and password are required.",
37
+ password: "Passwords do not match.",
38
+ short: `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`,
39
+ expired: "This invite link has expired or already been used.",
40
+ invalid: "This invite link has expired or already been used.",
41
+ };
42
+ const errorMessage = error ? (ERROR_MESSAGES[error] ?? null) : null;
45
43
  ---
46
44
 
47
45
  <!doctype html>
@@ -10,19 +10,14 @@ import config from "virtual:kide/config";
10
10
 
11
11
  export const prerender = false;
12
12
 
13
+ const ERROR_MESSAGES: Record<string, string> = {
14
+ invalid: "Invalid email or password.",
15
+ missing: "Email and password are required.",
16
+ disabled: "Password login is disabled.",
17
+ "rate-limited": "Too many attempts. Try again in a few minutes.",
18
+ };
13
19
  const error = Astro.url.searchParams.get("error");
14
- const errorMessage =
15
- error === "invalid"
16
- ? "Invalid email or password."
17
- : error === "missing"
18
- ? "Email and password are required."
19
- : error === "disabled"
20
- ? "Password login is disabled."
21
- : error === "rate-limited"
22
- ? "Too many attempts. Try again in a few minutes."
23
- : error
24
- ? "Sign-in failed. Try again."
25
- : null;
20
+ const errorMessage = error ? (ERROR_MESSAGES[error] ?? "Sign-in failed. Try again.") : null;
26
21
  const auth = resolveAdminAuth(config);
27
22
  ---
28
23
 
@@ -15,16 +15,13 @@ if (!auth.password.forgotPassword) return Astro.redirect("/admin/login");
15
15
 
16
16
  const token = Astro.url.searchParams.get("token") ?? "";
17
17
  const error = Astro.url.searchParams.get("error");
18
- const errorMessage =
19
- error === "missing"
20
- ? "Password is required."
21
- : error === "password"
22
- ? "Passwords do not match."
23
- : error === "short"
24
- ? `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`
25
- : error === "invalid"
26
- ? "This reset link is invalid or expired."
27
- : null;
18
+ const ERROR_MESSAGES: Record<string, string> = {
19
+ missing: "Password is required.",
20
+ password: "Passwords do not match.",
21
+ short: `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`,
22
+ invalid: "This reset link is invalid or expired.",
23
+ };
24
+ const errorMessage = error ? (ERROR_MESSAGES[error] ?? null) : null;
28
25
  ---
29
26
 
30
27
  <!doctype html>
@@ -21,15 +21,13 @@ if (tables.users) {
21
21
  }
22
22
  }
23
23
 
24
+ const ERROR_MESSAGES: Record<string, string> = {
25
+ missing: "All fields are required.",
26
+ password: "Passwords do not match.",
27
+ short: `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`,
28
+ };
24
29
  const error = Astro.url.searchParams.get("error");
25
- const errorMessage =
26
- error === "missing"
27
- ? "All fields are required."
28
- : error === "password"
29
- ? "Passwords do not match."
30
- : error === "short"
31
- ? `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`
32
- : null;
30
+ const errorMessage = error ? (ERROR_MESSAGES[error] ?? null) : null;
33
31
  ---
34
32
 
35
33
  <!doctype html>
@@ -3,7 +3,7 @@ import type { APIRoute } from "astro";
3
3
  import config from "virtual:kide/config";
4
4
  import { cms } from "virtual:kide/api";
5
5
  import { collaboration } from "virtual:kide/runtime";
6
- import { isApprover, resolveCollaboration } from "../../../core";
6
+ import { formatPagePath, isApprover, resolveCollaboration } from "../../../core";
7
7
  import { loadSharedSectionUsageCounts } from "../../../admin/lib/edit-data";
8
8
 
9
9
  export const prerender = false;
@@ -124,13 +124,13 @@ const handleHtmlMutation = async (
124
124
  ctx,
125
125
  );
126
126
  }
127
+ const CREATE_MESSAGES: Record<string, string> = {
128
+ publish: `${name} created and published`,
129
+ schedule: `${name} scheduled`,
130
+ };
127
131
  const msg = blocked
128
132
  ? `${name} saved as draft — needs review approval before publishing`
129
- : intent === "publish"
130
- ? `${name} created and published`
131
- : intent === "schedule"
132
- ? `${name} scheduled`
133
- : `${name} created`;
133
+ : (CREATE_MESSAGES[intent] ?? `${name} created`);
134
134
  return redirect(`/admin/${collectionSlug}/${created._id}`, { status: blocked ? "error" : "success", msg });
135
135
  }
136
136
 
@@ -158,19 +158,15 @@ const handleHtmlMutation = async (
158
158
  const actor = locals.user ? { id: locals.user.id, email: locals.user.email, role: locals.user.role } : null;
159
159
  await collaboration.submitForReview(collectionSlug, documentId, actor);
160
160
  }
161
+ const UPDATE_MESSAGES: Record<string, string> = {
162
+ publish: `${name} published`,
163
+ unpublish: `${name} unpublished`,
164
+ schedule: `${name} scheduled`,
165
+ "submit-review": "Saved and submitted for review",
166
+ };
161
167
  const msg = blocked
162
168
  ? `Saved — needs review approval before publishing`
163
- : intent === "publish"
164
- ? `${name} published`
165
- : intent === "unpublish"
166
- ? `${name} unpublished`
167
- : intent === "schedule"
168
- ? `${name} scheduled`
169
- : intent === "submit-review"
170
- ? `Saved and submitted for review`
171
- : collection.drafts
172
- ? `${name} saved as draft`
173
- : `${name} saved`;
169
+ : (UPDATE_MESSAGES[intent] ?? (collection.drafts ? `${name} saved as draft` : `${name} saved`));
174
170
  return redirect(redirectTo, { status: blocked ? "error" : "success", msg });
175
171
  }
176
172
 
@@ -287,6 +283,23 @@ export const GET: APIRoute = async ({ params, url, locals }) => {
287
283
  }
288
284
  }
289
285
 
286
+ // The list table's "URL" column is computed, not stored — resolve it here too so
287
+ // client-side re-fetches (sort/search/page changes) keep showing it. Mirrors
288
+ // ListView.astro's own getPagePath, since both run server-side against the same collection config.
289
+ const collection = getCollection(collectionSlug);
290
+ if (collection.preview || collection.pathPrefix) {
291
+ for (const entry of docs as Array<Record<string, unknown>>) {
292
+ const hasPreview = !!(collection.preview || (collection.pathPrefix && entry.slug));
293
+ const pagePath = hasPreview
294
+ ? typeof collection.preview === "string"
295
+ ? collection.preview
296
+ : cmsRuntime.meta.getRouteForDocument(collectionSlug, entry)
297
+ : null;
298
+ if (pagePath) entry._pageHref = `${pagePath}?preview=true`;
299
+ entry.__page = formatPagePath(pagePath);
300
+ }
301
+ }
302
+
290
303
  const page = Math.floor(offset / limit) + 1;
291
304
  const totalPages = Math.ceil(totalDocs / limit);
292
305
 
@@ -330,11 +343,16 @@ export const POST: APIRoute = async ({ params, request, locals, cache }) => {
330
343
  }
331
344
 
332
345
  if (pathAction === "duplicate" && documentId) {
346
+ const collection = getCollection(collectionSlug);
347
+ if (collection.auth) {
348
+ // Duplicating a user would copy its password hash onto a new account —
349
+ // never useful, and not something field-stripping alone can make safe.
350
+ return Response.json({ error: "Auth collections can't be duplicated." }, { status: 400 });
351
+ }
333
352
  const original = await collectionApi.findById(documentId, { status: "any" }, ctx);
334
353
  if (!original) {
335
354
  return Response.json({ error: "Not found." }, { status: 404 });
336
355
  }
337
- const collection = getCollection(collectionSlug);
338
356
 
339
357
  // Strip system fields and unique values that would conflict
340
358
  const stripFields = (source: Record<string, any>) => {
@@ -131,11 +131,15 @@ export const POST: APIRoute = async ({ request, locals }) => {
131
131
  );
132
132
  }
133
133
 
134
+ // Dev only: let Vite's dev server catch up on the new files before the client
135
+ // reloads, or the just-uploaded asset renders broken until a manual refresh.
136
+ if (import.meta.env.DEV) {
137
+ await new Promise((r) => setTimeout(r, 1000));
138
+ }
139
+
134
140
  const redirectTo = formData.get("redirectTo");
135
141
 
136
142
  if (redirectTo) {
137
- // Delay so Vite's dev server picks up the new files before the redirect
138
- await new Promise((r) => setTimeout(r, 1000));
139
143
  const location =
140
144
  uploaded.length === 1
141
145
  ? `/admin/assets/${uploaded[0]._id}?_toast=success&_msg=Asset+uploaded`