@kidecms/core 0.18.0 → 0.19.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,10 +1,10 @@
1
1
  "use client";
2
2
 
3
3
  import { useState, useCallback, useRef, useMemo, useEffect } from "react";
4
- import type { CSSProperties } from "react";
5
4
  import {
6
5
  ChevronLeft,
7
6
  ChevronRight,
7
+ CircleCheck,
8
8
  Folder,
9
9
  FolderPlus,
10
10
  GripVertical,
@@ -30,7 +30,7 @@ import {
30
30
  type DragStartEvent,
31
31
  type DragEndEvent,
32
32
  } from "@dnd-kit/core";
33
- import { cn, thumbnail } from "../lib/utils";
33
+ import { cn, focalPointStyle, thumbnail } from "../lib/utils";
34
34
  import { Badge } from "./ui/badge";
35
35
  import { Button, buttonVariants } from "./ui/button";
36
36
  import { Card, CardContent } from "./ui/card";
@@ -82,13 +82,6 @@ type Props = {
82
82
  pageSize: number;
83
83
  };
84
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
-
92
85
  // Build a "/admin/assets" URL for a sidebar scope ("all" | "unfiled" | folderId).
93
86
  // "all" is the bare route; "unfiled" and folder ids ride on the `folder` param.
94
87
  function assetsUrl(opts: { scope?: string; q?: string; page?: number }) {
@@ -332,6 +325,9 @@ export default function AssetsGrid({
332
325
  const [renameOpen, setRenameOpen] = useState(false);
333
326
  const [deleteOpen, setDeleteOpen] = useState(false);
334
327
  const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
328
+ const [bulkUsage, setBulkUsage] = useState<{ tone: "warn" | "muted"; message: string } | null>(null);
329
+ // Guards against a slow lookup from a previous dialog landing on a new selection.
330
+ const bulkUsageRequest = useRef(0);
335
331
  const [createName, setCreateName] = useState("");
336
332
  const [renameName, setRenameName] = useState("");
337
333
  const [activeFolderId, setActiveFolderId] = useState<string | null>(null);
@@ -588,6 +584,69 @@ export default function AssetsGrid({
588
584
  function resetDialogState() {
589
585
  setLoading(false);
590
586
  setError(null);
587
+ setBulkUsage(null);
588
+ bulkUsageRequest.current += 1;
589
+ }
590
+
591
+ /**
592
+ * Reports where the selected assets are used. Always sets a message — silence
593
+ * would make "none are used" indistinguishable from "the check failed", which
594
+ * is how a broken usage lookup goes unnoticed for a long time. The message is
595
+ * the whole dialog body, not an aside: what happens to the content is the point
596
+ * of the decision, so it must not read as a footnote to a generic warning.
597
+ */
598
+ async function loadBulkUsage(ids: string[]) {
599
+ const token = ++bulkUsageRequest.current;
600
+ const one = ids.length === 1;
601
+ const subject = one ? "This asset" : `These ${ids.length} assets`;
602
+ const settle = (tone: "warn" | "muted", message: string) => {
603
+ if (token === bulkUsageRequest.current) setBulkUsage({ tone, message });
604
+ };
605
+
606
+ settle("muted", `Checking where ${one ? "this asset is" : "these assets are"} used…`);
607
+ try {
608
+ const res = await fetch(`/api/cms/asset-usage?ids=${ids.map(encodeURIComponent).join(",")}`);
609
+ if (!res.ok) {
610
+ settle(
611
+ "muted",
612
+ `Couldn't check where ${one ? "this asset is" : "these assets are"} used. Deleting cannot be undone.`,
613
+ );
614
+ return;
615
+ }
616
+ const { counts, incomplete } = (await res.json()) as {
617
+ counts: Record<string, number>;
618
+ incomplete?: string[];
619
+ };
620
+ const used = ids.filter((id) => (counts[id] ?? 0) > 0);
621
+
622
+ if (used.length > 0) {
623
+ const places = used.reduce((sum, id) => sum + (counts[id] ?? 0), 0);
624
+ const where = places === 1 ? "1 place" : `${places} places`;
625
+ const subjectUsed = one
626
+ ? "This asset is"
627
+ : `${used.length} of these ${ids.length} assets ${used.length === 1 ? "is" : "are"}`;
628
+ settle(
629
+ "warn",
630
+ `${subjectUsed} used in ${where} — deleting will leave ${places === 1 ? "that place" : "those places"} without an image. This cannot be undone.`,
631
+ );
632
+ return;
633
+ }
634
+
635
+ if (incomplete?.length) {
636
+ settle(
637
+ "warn",
638
+ `Couldn't search ${incomplete.join(", ")}, so ${one ? "this asset" : "these assets"} may still be in use. Deleting cannot be undone.`,
639
+ );
640
+ return;
641
+ }
642
+
643
+ settle("muted", `${subject} ${one ? "isn't" : "aren't"} used by any document. Deleting cannot be undone.`);
644
+ } catch {
645
+ settle(
646
+ "muted",
647
+ `Couldn't check where ${one ? "this asset is" : "these assets are"} used. Deleting cannot be undone.`,
648
+ );
649
+ }
591
650
  }
592
651
 
593
652
  async function handleCreateFolder() {
@@ -641,7 +700,8 @@ export default function AssetsGrid({
641
700
  setLoading(true);
642
701
  setError(null);
643
702
  const ids = Array.from(selectedIds);
644
- const results = await Promise.all(ids.map((id) => fetch(`/api/cms/assets/${id}`, { method: "DELETE" })));
703
+ // force=1: the dialog already showed the usage warning and the editor accepted it.
704
+ const results = await Promise.all(ids.map((id) => fetch(`/api/cms/assets/${id}?force=1`, { method: "DELETE" })));
645
705
  const failed = results.filter((r) => !r.ok).length;
646
706
  if (failed > 0 && failed === ids.length) {
647
707
  setLoading(false);
@@ -802,7 +862,20 @@ export default function AssetsGrid({
802
862
  </div>
803
863
  )}
804
864
  {uploadError && <p className="text-destructive text-sm">{uploadError}</p>}
805
- {uploadNotice && <p className="text-muted-foreground text-sm">{uploadNotice}</p>}
865
+
866
+ {/* Same look and timing as the server-rendered Toast.astro */}
867
+ {uploadNotice && (
868
+ <div className="fixed top-4 left-1/2 z-[60] w-full max-w-sm -translate-x-1/2">
869
+ <div
870
+ role="status"
871
+ className="bg-card flex items-center gap-2 rounded-lg border border-green-500/30 px-5 py-3 text-sm shadow-lg"
872
+ style={{ animation: "toast-in 0.25s ease-out, toast-out 0.3s ease-in 2.7s forwards" }}
873
+ >
874
+ <CircleCheck className="size-4 shrink-0 text-green-600 dark:text-green-400" />
875
+ <span className="text-green-700 dark:text-green-400">{uploadNotice}</span>
876
+ </div>
877
+ </div>
878
+ )}
806
879
 
807
880
  {/* Selection toolbar */}
808
881
  {selectedIds.size > 0 && (
@@ -815,6 +888,7 @@ export default function AssetsGrid({
815
888
  onClick={() => {
816
889
  resetDialogState();
817
890
  setBulkDeleteOpen(true);
891
+ void loadBulkUsage(Array.from(selectedIds));
818
892
  }}
819
893
  >
820
894
  <Trash2 className="size-3.5" />
@@ -1027,10 +1101,10 @@ export default function AssetsGrid({
1027
1101
  <Dialog open={bulkDeleteOpen} onOpenChange={setBulkDeleteOpen}>
1028
1102
  <DialogContent>
1029
1103
  <DialogHeader>
1030
- <DialogTitle>Delete assets</DialogTitle>
1031
- <DialogDescription>
1032
- Are you sure you want to delete {selectedIds.size} asset{selectedIds.size > 1 ? "s" : ""}? This action
1033
- cannot be undone.
1104
+ <DialogTitle>Delete {selectedIds.size === 1 ? "asset" : `${selectedIds.size} assets`}</DialogTitle>
1105
+ <DialogDescription className={cn(bulkUsage?.tone === "warn" && "text-foreground font-medium")}>
1106
+ {bulkUsage?.message ??
1107
+ `Deleting ${selectedIds.size === 1 ? "this asset" : "these assets"} cannot be undone.`}
1034
1108
  </DialogDescription>
1035
1109
  </DialogHeader>
1036
1110
  {error && <p className="text-destructive text-sm">{error}</p>}
@@ -2,6 +2,7 @@
2
2
 
3
3
  import { useState } from "react";
4
4
  import { CalendarClock, CheckIcon, EllipsisVertical } from "lucide-react";
5
+ import { cn } from "../lib/utils";
5
6
  import {
6
7
  AlertDialog,
7
8
  AlertDialogClose,
@@ -52,6 +53,12 @@ type Props = {
52
53
  versions?: Version[];
53
54
  restoreEndpoint?: string;
54
55
  redirectTo?: string;
56
+ /** Overrides the reference lookup — assets report usage from a different endpoint. */
57
+ referencesEndpoint?: string;
58
+ /** Noun used in the delete dialog ("document", "asset", …). */
59
+ entityLabel?: string;
60
+ /** Adds `_force=1` to the delete submit, telling the API the warning was shown and accepted. */
61
+ forceOnConfirm?: boolean;
55
62
  };
56
63
 
57
64
  export default function DocumentActions({
@@ -69,10 +76,13 @@ export default function DocumentActions({
69
76
  versions = [],
70
77
  restoreEndpoint,
71
78
  redirectTo,
79
+ referencesEndpoint,
80
+ entityLabel = "document",
81
+ forceOnConfirm,
72
82
  }: Props) {
73
83
  const [scheduleOpen, setScheduleOpen] = useState(false);
74
84
  const [deleteOpen, setDeleteOpen] = useState(false);
75
- const [refWarning, setRefWarning] = useState<string | null>(null);
85
+ const [refWarning, setRefWarning] = useState<{ tone: "warn" | "muted"; message: string } | null>(null);
76
86
  const [publishAt, setPublishAt] = useState(currentPublishAt ? toLocalDatetime(currentPublishAt) : "");
77
87
  const [unpublishAt, setUnpublishAt] = useState(currentUnpublishAt ? toLocalDatetime(currentUnpublishAt) : "");
78
88
 
@@ -102,11 +112,21 @@ export default function DocumentActions({
102
112
  }
103
113
  };
104
114
 
105
- const submitAction = (action: string) => {
115
+ const submitAction = (action: string, force?: boolean) => {
106
116
  const form = document.getElementById(formId) as HTMLFormElement | null;
107
117
  if (!form) return;
108
118
  const input = form.querySelector<HTMLInputElement>('input[name="_action"]');
109
119
  if (input) input.value = action;
120
+ if (force) {
121
+ let forceInput = form.querySelector<HTMLInputElement>('input[name="_force"]');
122
+ if (!forceInput) {
123
+ forceInput = document.createElement("input");
124
+ forceInput.type = "hidden";
125
+ forceInput.name = "_force";
126
+ form.appendChild(forceInput);
127
+ }
128
+ forceInput.value = "1";
129
+ }
110
130
  form.submit();
111
131
  };
112
132
 
@@ -228,23 +248,45 @@ export default function DocumentActions({
228
248
  variant="destructive"
229
249
  onClick={async () => {
230
250
  setRefWarning(null);
231
- if (collectionSlug && documentId) {
232
- try {
233
- const res = await fetch(`/api/cms/references/${collectionSlug}/${documentId}`);
234
- if (res.ok) {
235
- const { refs, total } = await res.json();
236
- if (total > 0) {
237
- const parts = refs.map(
238
- (r: { collection: string; count: number }) => `${r.count} ${r.collection.toLowerCase()}`,
239
- );
240
- setRefWarning(
241
- `This document is referenced by ${parts.join(", ")}. Deleting it will leave broken references.`,
242
- );
243
- }
244
- }
245
- } catch {}
246
- }
251
+ const endpoint =
252
+ referencesEndpoint ??
253
+ (collectionSlug && documentId ? `/api/cms/references/${collectionSlug}/${documentId}` : null);
247
254
  setDeleteOpen(true);
255
+ if (!endpoint) return;
256
+
257
+ // Always report the outcome. Staying silent on a failed lookup makes
258
+ // "nothing references this" and "the check never ran" identical, which
259
+ // is exactly how a broken reference check goes unnoticed.
260
+ try {
261
+ const res = await fetch(endpoint);
262
+ if (!res.ok) {
263
+ setRefWarning({ tone: "muted", message: `Couldn't check what references this ${entityLabel}.` });
264
+ return;
265
+ }
266
+ const payload = await res.json();
267
+ const parts = summarizeRefs(payload);
268
+ if (parts.length > 0) {
269
+ setRefWarning({
270
+ tone: "warn",
271
+ message: `This ${entityLabel} is referenced by ${parts.join(", ")} — deleting it will leave those references broken. This cannot be undone.`,
272
+ });
273
+ } else if (Array.isArray(payload.incomplete) && payload.incomplete.length > 0) {
274
+ setRefWarning({
275
+ tone: "warn",
276
+ message: `Couldn't search ${payload.incomplete.join(", ")}, so this ${entityLabel} may still be referenced. Deleting it cannot be undone.`,
277
+ });
278
+ } else {
279
+ setRefWarning({
280
+ tone: "muted",
281
+ message: `Nothing references this ${entityLabel}. Deleting it cannot be undone.`,
282
+ });
283
+ }
284
+ } catch {
285
+ setRefWarning({
286
+ tone: "muted",
287
+ message: `Couldn't check what references this ${entityLabel}. Deleting it cannot be undone.`,
288
+ });
289
+ }
248
290
  }}
249
291
  >
250
292
  Delete
@@ -302,19 +344,16 @@ export default function DocumentActions({
302
344
  <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
303
345
  <AlertDialogContent>
304
346
  <AlertDialogHeader>
305
- <AlertDialogTitle>Delete document</AlertDialogTitle>
306
- <AlertDialogDescription>
307
- {refWarning && (
308
- <span className="mb-2 block font-medium text-amber-600 dark:text-amber-400">{refWarning}</span>
309
- )}
310
- This action cannot be undone. This will permanently delete this document.
347
+ <AlertDialogTitle>Delete {entityLabel}</AlertDialogTitle>
348
+ <AlertDialogDescription className={cn(refWarning?.tone === "warn" && "text-foreground font-medium")}>
349
+ {refWarning?.message ?? `Deleting this ${entityLabel} cannot be undone.`}
311
350
  </AlertDialogDescription>
312
351
  </AlertDialogHeader>
313
352
  <AlertDialogFooter>
314
353
  <AlertDialogClose>
315
354
  <Button variant="outline">Cancel</Button>
316
355
  </AlertDialogClose>
317
- <Button variant="destructive" onClick={() => submitAction("delete")}>
356
+ <Button variant="destructive" onClick={() => submitAction("delete", forceOnConfirm)}>
318
357
  Delete
319
358
  </Button>
320
359
  </AlertDialogFooter>
@@ -331,3 +370,24 @@ function toLocalDatetime(iso: string): string {
331
370
  const local = new Date(date.getTime() - offset * 60000);
332
371
  return local.toISOString().slice(0, 16);
333
372
  }
373
+
374
+ /**
375
+ * Both reference endpoints answer "where is this used" in their own shape:
376
+ * `/api/cms/references/*` returns pre-counted `refs`, the asset endpoint returns
377
+ * the matching documents grouped by collection.
378
+ */
379
+ function summarizeRefs(payload: {
380
+ refs?: Array<{ collection: string; count: number }>;
381
+ usage?: Array<{ collectionLabel: string; docs: unknown[] }>;
382
+ incomplete?: string[];
383
+ }): string[] {
384
+ if (Array.isArray(payload.usage)) {
385
+ return payload.usage
386
+ .filter((entry) => entry.docs.length > 0)
387
+ .map((entry) => `${entry.docs.length} ${entry.collectionLabel.toLowerCase()}`);
388
+ }
389
+ if (Array.isArray(payload.refs)) {
390
+ return payload.refs.filter((ref) => ref.count > 0).map((ref) => `${ref.count} ${ref.collection.toLowerCase()}`);
391
+ }
392
+ return [];
393
+ }
@@ -798,7 +798,13 @@ export default function DocumentsDataTable({
798
798
  {headerGroup.headers
799
799
  .filter((header) => header.column.id !== "search")
800
800
  .map((header) => (
801
- <TableHead key={header.id} className={header.column.id === "select" ? "w-10" : undefined}>
801
+ <TableHead
802
+ key={header.id}
803
+ className={cn(
804
+ header.column.id === "select" && "w-10",
805
+ header.column.id === primaryColumnKey && "max-sm:min-w-48",
806
+ )}
807
+ >
802
808
  {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
803
809
  </TableHead>
804
810
  ))}
@@ -821,6 +827,7 @@ export default function DocumentsDataTable({
821
827
  // including a wrapped multi-line title, for a consistent row.
822
828
  "align-middle break-words whitespace-normal",
823
829
  cell.column.id === "select" && "w-10",
830
+ cell.column.id === primaryColumnKey && "max-sm:min-w-48",
824
831
  )}
825
832
  >
826
833
  {flexRender(cell.column.columnDef.cell, cell.getContext())}
@@ -1,13 +1,15 @@
1
1
  import { useState, useCallback, useEffect } from "react";
2
2
  import { ChevronRight, Folder, Loader2, X } from "lucide-react";
3
3
  import { Dialog, DialogClose, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";
4
- import { thumbnail } from "../lib/utils";
4
+ import { focalPointStyle, thumbnail } from "../lib/utils";
5
5
 
6
6
  type AssetRecord = {
7
7
  _id: string;
8
8
  filename: string;
9
9
  mimeType: string;
10
10
  url: string;
11
+ focalX?: number | null;
12
+ focalY?: number | null;
11
13
  _createdAt: string;
12
14
  };
13
15
 
@@ -156,7 +158,12 @@ export default function ImageBrowseDialog({ open, onOpenChange, onSelect }: Prop
156
158
  }}
157
159
  className="hover:border-foreground relative aspect-square overflow-hidden rounded-lg border transition-colors"
158
160
  >
159
- <img src={thumbnail(asset.url)} alt={asset.filename} className="size-full object-cover" />
161
+ <img
162
+ src={thumbnail(asset.url)}
163
+ alt={asset.filename}
164
+ className="size-full object-cover"
165
+ style={focalPointStyle(asset)}
166
+ />
160
167
  </button>
161
168
  ))}
162
169
  </div>
@@ -1,6 +1,6 @@
1
1
  import { useState, useRef, useCallback, useEffect } from "react";
2
2
  import { ImagePlus, Loader2, Upload, X } from "lucide-react";
3
- import { cn, thumbnail } from "../lib/utils";
3
+ import { cn, focalPointStyle, thumbnail } from "../lib/utils";
4
4
  import { Button } from "./ui/button";
5
5
  import ImageBrowseDialog from "./ImageBrowseDialog";
6
6
 
@@ -14,6 +14,7 @@ type Props = {
14
14
  export default function ImagePicker({ name, value: initialValue, onChange: onChangeProp }: Props) {
15
15
  const [value, setValue] = useState(initialValue ?? "");
16
16
  const [assetId, setAssetId] = useState<string | null>(null);
17
+ const [focal, setFocal] = useState<{ focalX: number | null; focalY: number | null } | null>(null);
17
18
  const [localPreview, setLocalPreview] = useState<string | null>(null);
18
19
  const [uploading, setUploading] = useState(false);
19
20
  const [open, setOpen] = useState(false);
@@ -26,7 +27,10 @@ export default function ImagePicker({ name, value: initialValue, onChange: onCha
26
27
  fetch(`/api/cms/assets?url=${encodeURIComponent(value)}`)
27
28
  .then((res) => (res.ok ? res.json() : null))
28
29
  .then((asset) => {
29
- if (asset?._id) setAssetId(asset._id);
30
+ if (asset?._id) {
31
+ setAssetId(asset._id);
32
+ setFocal({ focalX: asset.focalX ?? null, focalY: asset.focalY ?? null });
33
+ }
30
34
  })
31
35
  .catch(() => {});
32
36
  }, []); // eslint-disable-line react-hooks/exhaustive-deps
@@ -53,6 +57,7 @@ export default function ImagePicker({ name, value: initialValue, onChange: onCha
53
57
  const asset = await res.json();
54
58
  setValue(asset.url);
55
59
  setAssetId(asset._id);
60
+ setFocal({ focalX: asset.focalX ?? null, focalY: asset.focalY ?? null });
56
61
  onChangeProp?.(asset.url);
57
62
  } catch (e) {
58
63
  console.error("Upload failed:", e);
@@ -91,7 +96,12 @@ export default function ImagePicker({ name, value: initialValue, onChange: onCha
91
96
  assetId && "hover:border-foreground/50 cursor-pointer",
92
97
  )}
93
98
  >
94
- <img src={imgSrc} alt="" className="size-full object-cover" />
99
+ <img
100
+ src={imgSrc}
101
+ alt=""
102
+ className="size-full object-cover"
103
+ style={localPreview ? undefined : focal ? focalPointStyle(focal) : undefined}
104
+ />
95
105
  </a>
96
106
  ) : (
97
107
  <div className="bg-field flex size-40 items-center justify-center rounded-lg border">
@@ -141,6 +151,7 @@ export default function ImagePicker({ name, value: initialValue, onChange: onCha
141
151
  setLocalPreview(null);
142
152
  setValue(asset.url);
143
153
  setAssetId(asset._id);
154
+ setFocal({ focalX: asset.focalX ?? null, focalY: asset.focalY ?? null });
144
155
  onChangeProp?.(asset.url);
145
156
  }}
146
157
  />
@@ -17,10 +17,14 @@ export default function InternalLinkPicker({
17
17
  editHref,
18
18
  linkOptions,
19
19
  onSelect,
20
+ className,
21
+ triggerClassName,
20
22
  }: {
21
23
  editHref: string;
22
24
  linkOptions: LinkOptionGroup[];
23
25
  onSelect: (item: { id: string; label: string; href: string }) => void;
26
+ className?: string;
27
+ triggerClassName?: string;
24
28
  }) {
25
29
  const [open, setOpen] = React.useState(false);
26
30
 
@@ -34,14 +38,14 @@ export default function InternalLinkPicker({
34
38
  }, [editHref, linkOptions]);
35
39
 
36
40
  return (
37
- <div className="min-w-0 flex-1">
41
+ <div className={cn("min-w-0 flex-1", className)}>
38
42
  <Popover open={open} onOpenChange={setOpen}>
39
43
  <PopoverTrigger asChild>
40
44
  <Button
41
45
  variant="input"
42
46
  role="combobox"
43
47
  aria-expanded={open}
44
- className="h-9 w-full min-w-0 justify-between rounded-lg px-3 text-sm font-normal"
48
+ className={cn("h-9 w-full min-w-0 justify-between rounded-lg px-3 text-sm font-normal", triggerClassName)}
45
49
  >
46
50
  <span className={cn("truncate", !selectedLabel && "text-muted-foreground")}>
47
51
  {selectedLabel || "Search documents..."}
@@ -471,6 +471,8 @@ export default function TreeItemsEditor({ name, value, variant, label, linkOptio
471
471
  <InternalLinkPicker
472
472
  editHref={editing.href}
473
473
  linkOptions={linkOptions}
474
+ className="flex-3"
475
+ triggerClassName="bg-background h-7 rounded-md"
474
476
  onSelect={(item) => {
475
477
  updateEditing({ href: item.href, ...(!editing.label ? { label: item.label } : {}) });
476
478
  }}
@@ -0,0 +1 @@
1
+ deleting
@@ -17,3 +17,15 @@ export function thumbnail(src: string, width: number = 480): string {
17
17
  const w = clampWidth(width);
18
18
  return `/api/cms/img${src}?w=${w}`;
19
19
  }
20
+
21
+ /**
22
+ * `object-position` style for an `object-cover` thumbnail, so the visible crop
23
+ * follows the asset's focal point instead of centering, when one is set.
24
+ */
25
+ export function focalPointStyle(asset: {
26
+ focalX?: number | null;
27
+ focalY?: number | null;
28
+ }): { objectPosition: string } | undefined {
29
+ if (asset.focalX == null || asset.focalY == null) return undefined;
30
+ return { objectPosition: `${asset.focalX}% ${asset.focalY}%` };
31
+ }
@@ -2,9 +2,14 @@
2
2
  import AdminCard from "../../components/AdminCard.astro";
3
3
  import type { ReverseRef } from "../../lib/edit-data";
4
4
 
5
- const { reverseRefs, variant = "editorial" } = Astro.props as {
5
+ const {
6
+ reverseRefs,
7
+ variant = "editorial",
8
+ title = "Referenced by",
9
+ } = Astro.props as {
6
10
  reverseRefs: ReverseRef[];
7
11
  variant?: "editorial" | "record";
12
+ title?: string;
8
13
  };
9
14
 
10
15
  const allDocs = reverseRefs.flatMap((ref) =>
@@ -57,10 +62,10 @@ const hidden = allDocs.slice(30);
57
62
  );
58
63
 
59
64
  return variant === "record" ? (
60
- <AdminCard title="Referenced by">{list}</AdminCard>
65
+ <AdminCard title={title}>{list}</AdminCard>
61
66
  ) : (
62
67
  <div class="grid gap-2">
63
- <span class="text-foreground/80 text-sm leading-none font-medium">Referenced by</span>
68
+ <span class="text-foreground/80 text-sm leading-none font-medium">{title}</span>
64
69
  {list}
65
70
  </div>
66
71
  );
package/core/api.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { and, asc, desc, eq, inArray, like, lte, ne, or, sql } from "drizzle-orm";
2
2
  import { nanoid } from "nanoid";
3
3
 
4
+ import { setUsageConfig } from "./asset-usage";
4
5
  import { recordAudit, type AuditActor } from "./audit";
5
6
  import { hashPassword, MIN_PASSWORD_LENGTH } from "./auth";
6
7
  import type { CMSConfig, CollectionConfig, FieldConfig, RichTextDocument } from "./define";
@@ -407,6 +408,10 @@ export const createCms = (config: CMSConfig) => {
407
408
  }
408
409
  const collectionMap = getCollectionMap(config);
409
410
 
411
+ // Lets assets.delete() check whether a file is still referenced without every
412
+ // caller having to thread the config in.
413
+ setUsageConfig(config);
414
+
410
415
  // Webhook `name` routes deliveries — must be unique and non-empty.
411
416
  const webhookNames = (config.admin?.webhooks ?? []).map((webhook) => webhook.name.trim());
412
417
  if (webhookNames.some((name) => name === "")) {