@kidecms/core 0.20.0 → 0.21.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.
@@ -25,10 +25,9 @@ import {
25
25
  getPreviewText,
26
26
  humanize,
27
27
  type BlockTypesMeta,
28
- type RelationOption,
29
28
  type SubFieldMeta,
30
29
  } from "./block-fields";
31
- import type { LinkOptionGroup } from "./InternalLinkPicker";
30
+ import type { LinkableCollection } from "./InternalLinkPicker";
32
31
 
33
32
  type Block = {
34
33
  _key: string;
@@ -47,8 +46,7 @@ type Props = {
47
46
  name: string;
48
47
  value?: string;
49
48
  types: BlockTypesMeta;
50
- blockRelationOptions?: Record<string, RelationOption[]>;
51
- linkOptions?: LinkOptionGroup[];
49
+ linkOptions?: LinkableCollection[];
52
50
  sharedSections?: SharedSectionOption[];
53
51
  sharedEnabled?: boolean;
54
52
  };
@@ -92,7 +90,6 @@ function SortableBlock({
92
90
  onSaveShared,
93
91
  sharedEnabled,
94
92
  onUpdateField,
95
- getRelationOptions,
96
93
  linkOptions = [],
97
94
  sharedSection,
98
95
  }: {
@@ -107,8 +104,7 @@ function SortableBlock({
107
104
  onSaveShared: () => void;
108
105
  sharedEnabled: boolean;
109
106
  onUpdateField: (fieldName: string, value: unknown) => void;
110
- getRelationOptions: (blockType: string, fieldName: string) => RelationOption[];
111
- linkOptions?: LinkOptionGroup[];
107
+ linkOptions?: LinkableCollection[];
112
108
  sharedSection?: SharedSectionOption;
113
109
  }) {
114
110
  const contentRef = useRef<HTMLDivElement>(null);
@@ -252,7 +248,6 @@ function SortableBlock({
252
248
  meta={meta}
253
249
  value={block[fieldName]}
254
250
  onChange={(v) => onUpdateField(fieldName, v)}
255
- relationOptions={meta.type === "relation" ? getRelationOptions(block.type, fieldName) : []}
256
251
  linkOptions={linkOptions}
257
252
  />
258
253
  ))
@@ -271,7 +266,6 @@ export default function BlockEditor({
271
266
  name,
272
267
  value,
273
268
  types,
274
- blockRelationOptions = {},
275
269
  linkOptions = [],
276
270
  sharedSections = [],
277
271
  sharedEnabled = true,
@@ -513,9 +507,6 @@ export default function BlockEditor({
513
507
  onSaveShared={() => saveAsShared(block._key)}
514
508
  sharedEnabled={sharedEnabled}
515
509
  onUpdateField={(fn, v) => updateField(block._key, fn, v)}
516
- getRelationOptions={(blockType, fieldName) =>
517
- blockRelationOptions[`block:${name}:${blockType}:${fieldName}`] ?? []
518
- }
519
510
  linkOptions={linkOptions}
520
511
  sharedSection={sharedSection}
521
512
  />
@@ -5,29 +5,20 @@ import * as React from "react";
5
5
  import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "./ui/command";
6
6
  import { Dialog, DialogContent, DialogDescription, DialogTitle } from "./ui/dialog";
7
7
 
8
- type Result = {
9
- collection: string;
10
- collectionLabel: string;
11
- docId: string;
12
- title: string;
13
- editUrl: string;
14
- status: string | null;
15
- };
8
+ import { MIN_QUERY_LENGTH, useDocumentSearch, type DocumentHit } from "../lib/use-document-search";
16
9
 
17
- const MIN_QUERY_LENGTH = 2;
18
- const DEBOUNCE_MS = 150;
10
+ type Result = DocumentHit;
19
11
 
20
12
  export default function CommandPalette() {
21
13
  const [open, setOpen] = React.useState(false);
22
- const [query, setQuery] = React.useState("");
23
- const [results, setResults] = React.useState<Result[]>([]);
24
- const [loading, setLoading] = React.useState(false);
25
- // Controlled cmdk selection so we can force "highlight first item" every time the result
26
- // set changes — cmdk would otherwise hold onto the previous highlight even when that item
27
- // is no longer in the list (especially with shouldFilter={false}).
28
- const [selected, setSelected] = React.useState("");
14
+ const { query, setQuery, results, loading, reset } = useDocumentSearch({ enabled: open });
15
+ // Controlled cmdk selection so the first hit is highlighted whenever the result
16
+ // set changes — cmdk would otherwise hold onto a highlight that is no longer in
17
+ // the list (especially with shouldFilter={false}).
18
+ const [chosen, setChosen] = React.useState("");
29
19
 
30
20
  const itemValue = (r: Result) => `${r.collection}:${r.docId}`;
21
+ const selected = results.some((r) => itemValue(r) === chosen) ? chosen : results[0] ? itemValue(results[0]) : "";
31
22
 
32
23
  React.useEffect(() => {
33
24
  const keyHandler = (e: KeyboardEvent) => {
@@ -45,60 +36,16 @@ export default function CommandPalette() {
45
36
  };
46
37
  }, []);
47
38
 
48
- const handleOpenChange = React.useCallback((next: boolean) => {
49
- setOpen(next);
50
- if (!next) {
51
- setQuery("");
52
- setResults([]);
53
- setLoading(false);
54
- setSelected("");
55
- }
56
- }, []);
57
-
58
- const handleQueryChange = React.useCallback((next: string) => {
59
- setQuery(next);
60
- if (next.trim().length < MIN_QUERY_LENGTH) {
61
- setResults([]);
62
- setLoading(false);
63
- setSelected("");
64
- } else {
65
- setLoading(true);
66
- }
67
- }, []);
68
-
69
- React.useEffect(() => {
70
- const trimmed = query.trim();
71
- if (trimmed.length < MIN_QUERY_LENGTH) return;
72
-
73
- const controller = new AbortController();
74
- const timer = setTimeout(async () => {
75
- try {
76
- const res = await fetch(`/api/cms/admin/search?q=${encodeURIComponent(trimmed)}`, {
77
- signal: controller.signal,
78
- credentials: "same-origin",
79
- });
80
- if (!res.ok) {
81
- setResults([]);
82
- setLoading(false);
83
- return;
84
- }
85
- const data = (await res.json()) as { results?: Result[] };
86
- const next = Array.isArray(data.results) ? data.results : [];
87
- setResults(next);
88
- setSelected(next.length > 0 ? itemValue(next[0]) : "");
89
- setLoading(false);
90
- } catch (err) {
91
- if ((err as { name?: string })?.name !== "AbortError") {
92
- setResults([]);
93
- setLoading(false);
94
- }
39
+ const handleOpenChange = React.useCallback(
40
+ (next: boolean) => {
41
+ setOpen(next);
42
+ if (!next) {
43
+ reset();
44
+ setChosen("");
95
45
  }
96
- }, DEBOUNCE_MS);
97
- return () => {
98
- controller.abort();
99
- clearTimeout(timer);
100
- };
101
- }, [query]);
46
+ },
47
+ [reset],
48
+ );
102
49
 
103
50
  const grouped = React.useMemo(() => {
104
51
  // Group by collectionLabel rather than collection slug so that all singletons
@@ -129,8 +76,8 @@ export default function CommandPalette() {
129
76
  <DialogDescription className="sr-only">
130
77
  Search content collections by title and open the edit view.
131
78
  </DialogDescription>
132
- <Command shouldFilter={false} value={selected} onValueChange={setSelected}>
133
- <CommandInput value={query} onValueChange={handleQueryChange} placeholder="Search content…" autoFocus />
79
+ <Command shouldFilter={false} value={selected} onValueChange={setChosen}>
80
+ <CommandInput value={query} onValueChange={setQuery} placeholder="Search content…" autoFocus />
134
81
  <CommandList className="max-h-[60vh]">
135
82
  {showHint && (
136
83
  <div className="text-muted-foreground py-6 text-center text-sm">
@@ -33,8 +33,8 @@ import {
33
33
  type CmsNode,
34
34
  type LinkGroup,
35
35
  } from "./RichTextEditor";
36
- import { SubField, humanize, type BlockTypesMeta, type RelationOption, type SubFieldMeta } from "./block-fields";
37
- import type { LinkOptionGroup } from "./InternalLinkPicker";
36
+ import { SubField, humanize, type BlockTypesMeta, type SubFieldMeta } from "./block-fields";
37
+ import type { LinkableCollection } from "./InternalLinkPicker";
38
38
  import { blockNodeSpec, BLOCK_NODE_NAME, SHARED_BLOCK_TYPE, type BlockNodeOptions } from "./content-block-spec";
39
39
  import { SlashCommand, type SharedSectionOption } from "./slash-command";
40
40
 
@@ -113,9 +113,6 @@ function BlockNodeView(props: NodeViewProps) {
113
113
  updateAttributes({ fields: { ...fields, [fieldName]: value } });
114
114
  };
115
115
 
116
- const getRelationOptions = (fieldName: string): RelationOption[] =>
117
- options.blockRelationOptions[`block:${options.fieldName}:${blockType}:${fieldName}`] ?? [];
118
-
119
116
  const isShared = blockType === SHARED_BLOCK_TYPE;
120
117
  const sharedTitle = String(fields.title ?? "Shared section");
121
118
  const sharedRef = String(fields.ref ?? "");
@@ -286,7 +283,6 @@ function BlockNodeView(props: NodeViewProps) {
286
283
  meta={meta}
287
284
  value={fields[fieldName]}
288
285
  onChange={(v) => updateField(fieldName, v)}
289
- relationOptions={meta.type === "relation" ? getRelationOptions(fieldName) : []}
290
286
  linkOptions={options.linkOptions ?? []}
291
287
  />
292
288
  ))}
@@ -377,8 +373,7 @@ type Props = {
377
373
  initialValue?: string;
378
374
  rows?: number;
379
375
  types: BlockTypesMeta;
380
- blockRelationOptions?: Record<string, RelationOption[]>;
381
- linkOptions?: LinkOptionGroup[];
376
+ linkOptions?: LinkableCollection[];
382
377
  /** Shared sections offered by the `/` menu. */
383
378
  sharedSections?: SharedSectionOption[];
384
379
  /** When true, show a button that expands the editor into a fullscreen overlay. */
@@ -391,7 +386,6 @@ export default function ContentEditor({
391
386
  initialValue,
392
387
  rows = 14,
393
388
  types,
394
- blockRelationOptions = {},
395
389
  linkOptions = [],
396
390
  sharedSections = [],
397
391
  fullscreen = false,
@@ -471,7 +465,7 @@ export default function ContentEditor({
471
465
  showOnlyCurrent: true,
472
466
  placeholder: ({ node }) => (node.type.name === "paragraph" ? "Type / for commands…" : ""),
473
467
  }),
474
- BlockNode.configure({ types, blockRelationOptions, linkOptions, fieldName: name }),
468
+ BlockNode.configure({ types, linkOptions, fieldName: name }),
475
469
  SlashCommand.configure({ types, sharedSections }),
476
470
  ],
477
471
  content: contentToTiptap(parsedInitial),
@@ -0,0 +1,171 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { Check, ChevronsUpDown } from "lucide-react";
5
+ import { Button } from "./ui/button";
6
+ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "./ui/command";
7
+ import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
8
+ import { cn } from "../lib/utils";
9
+ import { MIN_QUERY_LENGTH, fetchDocuments, useDocumentSearch, type DocumentHit } from "../lib/use-document-search";
10
+
11
+ /**
12
+ * The one document-picking combobox: trigger button, popover, server-backed
13
+ * search with recent documents while the query is empty. Every relation-style
14
+ * picker in the admin (top-level relation fields, relation sub-fields inside
15
+ * blocks, internal-link pickers) renders this and differs only in how it
16
+ * stores the pick.
17
+ */
18
+ export default function DocumentCombobox({
19
+ collections,
20
+ groups,
21
+ placeholder,
22
+ display,
23
+ isSelected,
24
+ onPick,
25
+ closeOnPick = false,
26
+ dimUnselected = false,
27
+ limit = 20,
28
+ size,
29
+ triggerId,
30
+ triggerClassName,
31
+ }: {
32
+ /** Collection slugs to search. */
33
+ collections: string[];
34
+ /** When set, results render grouped by collection under these labels. */
35
+ groups?: Array<{ collection: string; label: string }>;
36
+ placeholder: string;
37
+ /** Trigger text; empty renders the placeholder muted. */
38
+ display: string;
39
+ isSelected: (hit: DocumentHit) => boolean;
40
+ onPick: (hit: DocumentHit) => void;
41
+ /** Close the popover after a pick (single-select behavior). */
42
+ closeOnPick?: boolean;
43
+ /** Dim unselected rows, e.g. when a hasMany field is at maxItems. */
44
+ dimUnselected?: boolean;
45
+ limit?: number;
46
+ size?: React.ComponentProps<typeof Button>["size"];
47
+ triggerId?: string;
48
+ triggerClassName?: string;
49
+ }) {
50
+ const [open, setOpen] = React.useState(false);
51
+ const { query, setQuery, results, loading, tooShort, reset } = useDocumentSearch({
52
+ collections,
53
+ limit,
54
+ recentWhenEmpty: true,
55
+ enabled: open,
56
+ });
57
+
58
+ const handleOpenChange = (next: boolean) => {
59
+ setOpen(next);
60
+ if (!next) reset();
61
+ };
62
+
63
+ const pick = (hit: DocumentHit) => {
64
+ onPick(hit);
65
+ if (closeOnPick) handleOpenChange(false);
66
+ };
67
+
68
+ const grouped = React.useMemo(() => {
69
+ if (!groups) return null;
70
+ const byCollection = new Map<string, DocumentHit[]>();
71
+ for (const hit of results) byCollection.set(hit.collection, [...(byCollection.get(hit.collection) ?? []), hit]);
72
+ return groups
73
+ .filter((group) => byCollection.has(group.collection))
74
+ .map((group) => ({ ...group, items: byCollection.get(group.collection)! }));
75
+ }, [groups, results]);
76
+
77
+ const renderHit = (hit: DocumentHit) => (
78
+ <CommandItem
79
+ key={hit.docId}
80
+ value={`${hit.collection}:${hit.docId}`}
81
+ onSelect={() => pick(hit)}
82
+ className={cn(dimUnselected && !isSelected(hit) && "opacity-40")}
83
+ >
84
+ <Check className={cn("size-4", isSelected(hit) ? "opacity-100" : "opacity-0")} />
85
+ <span className="flex-1 truncate">{hit.title}</span>
86
+ {hit.status && hit.status !== "published" && (
87
+ <span className="bg-muted text-muted-foreground rounded px-1.5 py-0.5 text-[10px] tracking-wide uppercase">
88
+ {hit.status}
89
+ </span>
90
+ )}
91
+ </CommandItem>
92
+ );
93
+
94
+ return (
95
+ <Popover open={open} onOpenChange={handleOpenChange}>
96
+ <PopoverTrigger asChild>
97
+ <Button
98
+ id={triggerId}
99
+ variant="input"
100
+ role="combobox"
101
+ aria-expanded={open}
102
+ size={size}
103
+ className={cn("w-full justify-between text-sm font-normal", triggerClassName)}
104
+ >
105
+ <span className={cn("truncate", !display && "text-muted-foreground")}>{display || placeholder}</span>
106
+ <ChevronsUpDown className="ml-2 size-4 shrink-0 opacity-50" />
107
+ </Button>
108
+ </PopoverTrigger>
109
+ <PopoverContent className="w-(--radix-popover-trigger-width) p-0" align="start">
110
+ <Command shouldFilter={false}>
111
+ <CommandInput value={query} onValueChange={setQuery} placeholder={placeholder} />
112
+ <CommandList>
113
+ {tooShort && (
114
+ <div className="text-muted-foreground py-6 text-center text-sm">
115
+ Type at least {MIN_QUERY_LENGTH} characters to search.
116
+ </div>
117
+ )}
118
+ {loading && results.length === 0 && (
119
+ <div className="text-muted-foreground py-6 text-center text-sm">Searching…</div>
120
+ )}
121
+ {!loading && !tooShort && results.length === 0 && <CommandEmpty>No documents found.</CommandEmpty>}
122
+ {grouped
123
+ ? grouped.map((group) => (
124
+ <CommandGroup key={group.collection} heading={group.label}>
125
+ {group.items.map(renderHit)}
126
+ </CommandGroup>
127
+ ))
128
+ : results.map(renderHit)}
129
+ </CommandList>
130
+ </Command>
131
+ </PopoverContent>
132
+ </Popover>
133
+ );
134
+ }
135
+
136
+ /**
137
+ * id → label bookkeeping for relation pickers: seeded from the server-rendered
138
+ * page when possible, resolved through the search API once on mount for
139
+ * anything missing (e.g. values inside blocks), and extended as hits are
140
+ * picked.
141
+ */
142
+ export function useRelationLabels(
143
+ collectionSlug: string,
144
+ initialSelected: string[],
145
+ seed: Array<{ value: string; label: string }> = [],
146
+ ) {
147
+ const [labels, setLabels] = React.useState<Record<string, string>>(() =>
148
+ Object.fromEntries(seed.map((option) => [option.value, option.label])),
149
+ );
150
+
151
+ const remember = React.useCallback((hits: Array<{ docId: string; title: string }>) => {
152
+ if (hits.length === 0) return;
153
+ setLabels((prev) => ({ ...prev, ...Object.fromEntries(hits.map((hit) => [hit.docId, hit.title])) }));
154
+ }, []);
155
+
156
+ // Only the initial selection needs resolving; later picks arrive with their label.
157
+ React.useEffect(() => {
158
+ const missing = initialSelected.filter((id) => !(id in labels));
159
+ if (missing.length === 0 || !collectionSlug) return;
160
+ const controller = new AbortController();
161
+ fetchDocuments({ collections: [collectionSlug], ids: missing }, controller.signal)
162
+ .then(remember)
163
+ .catch(() => {});
164
+ return () => controller.abort();
165
+ // eslint-disable-next-line react-hooks/exhaustive-deps
166
+ }, []);
167
+
168
+ const getLabel = React.useCallback((id: string): string | undefined => labels[id], [labels]);
169
+
170
+ return { getLabel, remember };
171
+ }
@@ -35,11 +35,7 @@ type RelationMeta = {
35
35
  labelField?: string;
36
36
  };
37
37
 
38
- type LinkOptionGroup = {
39
- collection: string;
40
- label: string;
41
- items: Array<{ id: string; label: string; href: string }>;
42
- };
38
+ type LinkableCollection = { collection: string; label: string };
43
39
 
44
40
  type SharedSectionOption = {
45
41
  id: string;
@@ -55,10 +51,8 @@ const {
55
51
  relationOptions = [],
56
52
  relationMeta,
57
53
  readOnly = false,
58
- menuLinkOptions = [],
59
- blockRelationOptions = {},
54
+ linkableCollections = [],
60
55
  sharedBlockTypes = {},
61
- sharedBlockRelationOptions = {},
62
56
  sharedSectionOptions = [],
63
57
  } = Astro.props as {
64
58
  name: string;
@@ -67,10 +61,8 @@ const {
67
61
  relationOptions?: RelationOption[];
68
62
  relationMeta?: RelationMeta;
69
63
  readOnly?: boolean;
70
- menuLinkOptions?: LinkOptionGroup[];
71
- blockRelationOptions?: Record<string, RelationOption[]>;
64
+ linkableCollections?: LinkableCollection[];
72
65
  sharedBlockTypes?: Record<string, Record<string, FieldConfig>>;
73
- sharedBlockRelationOptions?: Record<string, RelationOption[]>;
74
66
  sharedSectionOptions?: SharedSectionOption[];
75
67
  };
76
68
 
@@ -305,14 +297,14 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
305
297
  />
306
298
  )}
307
299
 
300
+ {/* No name attribute — the stored value must never be submitted (or clobbered) from here. */}
308
301
  {field.type === "relation" && (readOnly || !relationMeta) && (
309
- <SelectField
310
- client:load
311
- name={name}
312
- value={String(value ?? "")}
313
- placeholder="Select a document"
314
- disabled={readOnly}
315
- items={relationOptions}
302
+ <Input
303
+ className={controlClass}
304
+ type="text"
305
+ id={name}
306
+ defaultValue={relationOptions.length > 0 ? relationOptions.map((o) => o.label).join(", ") : serializedValue}
307
+ readOnly
316
308
  />
317
309
  )}
318
310
 
@@ -339,8 +331,7 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
339
331
  initialValue={value ? JSON.stringify(value) : ""}
340
332
  rows={rows}
341
333
  types={blockTypesMeta}
342
- blockRelationOptions={blockRelationOptions}
343
- linkOptions={menuLinkOptions}
334
+ linkOptions={linkableCollections}
344
335
  sharedSections={sharedSectionOptions}
345
336
  fullscreen={field.fullscreen !== false}
346
337
  />
@@ -364,7 +355,7 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
364
355
  value={serializedValue}
365
356
  variant="menu"
366
357
  label={label}
367
- linkOptions={menuLinkOptions}
358
+ linkOptions={linkableCollections}
368
359
  />
369
360
  )}
370
361
 
@@ -373,17 +364,11 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
373
364
  )}
374
365
 
375
366
  {field.type === "json" && field.admin?.component === "shared-section-block" && !readOnly && (
376
- <SharedSectionBlockField
377
- client:load
378
- name={name}
379
- value={serializedValue}
380
- types={sharedBlockTypesMeta}
381
- blockRelationOptions={sharedBlockRelationOptions}
382
- />
367
+ <SharedSectionBlockField client:load name={name} value={serializedValue} types={sharedBlockTypesMeta} />
383
368
  )}
384
369
 
385
370
  {field.type === "json" && field.admin?.component === "link" && !readOnly && (
386
- <LinkField client:load name={name} value={serializedValue} linkOptions={menuLinkOptions} />
371
+ <LinkField client:load name={name} value={serializedValue} linkOptions={linkableCollections} />
387
372
  )}
388
373
 
389
374
  {field.type === "json" && field.admin?.component === "repeater" && !readOnly && (
@@ -398,7 +383,7 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
398
383
  )
399
384
  : undefined
400
385
  }
401
- linkOptions={menuLinkOptions}
386
+ linkOptions={linkableCollections}
402
387
  />
403
388
  )}
404
389
 
@@ -424,8 +409,7 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
424
409
  name={name}
425
410
  value={serializedValue}
426
411
  types={blockTypesMeta}
427
- blockRelationOptions={blockRelationOptions}
428
- linkOptions={menuLinkOptions}
412
+ linkOptions={linkableCollections}
429
413
  sharedSections={"shared" in field && field.shared === false ? [] : sharedSectionOptions}
430
414
  sharedEnabled={!("shared" in field && field.shared === false)}
431
415
  />
@@ -1,84 +1,52 @@
1
1
  "use client";
2
2
 
3
3
  import * as React from "react";
4
- import { Check, ChevronsUpDown } from "lucide-react";
5
- import { Button } from "./ui/button";
6
- import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "./ui/command";
7
- import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
8
4
  import { cn } from "../lib/utils";
5
+ import DocumentCombobox from "./DocumentCombobox";
9
6
 
10
- export type LinkOptionGroup = {
11
- collection: string;
12
- label: string;
13
- items: Array<{ id: string; label: string; href: string }>;
14
- };
7
+ /** A collection whose documents can be the target of an internal link. */
8
+ export type LinkableCollection = { collection: string; label: string };
15
9
 
10
+ export type LinkTarget = { id: string; label: string; href: string };
11
+
12
+ /**
13
+ * Picks an internal document by searching the linkable collections on the
14
+ * server. The stored value is the document's public route (plus its title),
15
+ * so selection is matched by href rather than id.
16
+ */
16
17
  export default function InternalLinkPicker({
17
18
  editHref,
18
- linkOptions,
19
+ editTitle,
20
+ collections,
19
21
  onSelect,
20
22
  className,
21
23
  triggerClassName,
22
24
  }: {
23
25
  editHref: string;
24
- linkOptions: LinkOptionGroup[];
25
- onSelect: (item: { id: string; label: string; href: string }) => void;
26
+ /** Title stored with the link — shown instead of the raw path. */
27
+ editTitle?: string;
28
+ collections: LinkableCollection[];
29
+ onSelect: (item: LinkTarget) => void;
26
30
  className?: string;
27
31
  triggerClassName?: string;
28
32
  }) {
29
- const [open, setOpen] = React.useState(false);
30
-
31
- const selectedLabel = React.useMemo(() => {
32
- if (!editHref) return "";
33
- for (const group of linkOptions) {
34
- const found = group.items.find((item) => item.href === editHref);
35
- if (found) return found.label;
36
- }
37
- return editHref;
38
- }, [editHref, linkOptions]);
33
+ const slugs = React.useMemo(() => collections.map((c) => c.collection), [collections]);
39
34
 
40
35
  return (
41
36
  <div className={cn("min-w-0 flex-1", className)}>
42
- <Popover open={open} onOpenChange={setOpen}>
43
- <PopoverTrigger asChild>
44
- <Button
45
- variant="input"
46
- role="combobox"
47
- aria-expanded={open}
48
- className={cn("h-9 w-full min-w-0 justify-between rounded-lg px-3 text-sm font-normal", triggerClassName)}
49
- >
50
- <span className={cn("truncate", !selectedLabel && "text-muted-foreground")}>
51
- {selectedLabel || "Search documents..."}
52
- </span>
53
- <ChevronsUpDown className="ml-2 size-4 shrink-0 opacity-50" />
54
- </Button>
55
- </PopoverTrigger>
56
- <PopoverContent className="w-(--radix-popover-trigger-width) p-0" align="start">
57
- <Command>
58
- <CommandInput placeholder="Search documents..." />
59
- <CommandList>
60
- <CommandEmpty>No documents found.</CommandEmpty>
61
- {linkOptions.map((group) => (
62
- <CommandGroup key={group.collection} heading={group.label}>
63
- {group.items.map((item) => (
64
- <CommandItem
65
- key={item.id}
66
- value={`${item.label} ${item.href}`}
67
- onSelect={() => {
68
- onSelect(item);
69
- setOpen(false);
70
- }}
71
- >
72
- <Check className={cn("size-4", editHref === item.href ? "opacity-100" : "opacity-0")} />
73
- {item.label}
74
- </CommandItem>
75
- ))}
76
- </CommandGroup>
77
- ))}
78
- </CommandList>
79
- </Command>
80
- </PopoverContent>
81
- </Popover>
37
+ <DocumentCombobox
38
+ collections={slugs}
39
+ groups={collections}
40
+ limit={10}
41
+ placeholder="Search documents..."
42
+ display={editTitle || editHref}
43
+ isSelected={(hit) => !!editHref && hit.href === editHref}
44
+ onPick={(hit) => {
45
+ if (hit.href) onSelect({ id: hit.docId, label: hit.title, href: hit.href });
46
+ }}
47
+ closeOnPick
48
+ triggerClassName={cn("h-9 min-w-0 rounded-lg px-3", triggerClassName)}
49
+ />
82
50
  </div>
83
51
  );
84
52
  }
@@ -5,12 +5,12 @@ import { Checkbox } from "./ui/checkbox";
5
5
  import { Input } from "./ui/input";
6
6
  import { Label } from "./ui/label";
7
7
  import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
8
- import InternalLinkPicker, { type LinkOptionGroup } from "./InternalLinkPicker";
8
+ import InternalLinkPicker, { type LinkableCollection } from "./InternalLinkPicker";
9
9
 
10
10
  // A structured link control: URL + label + open-in-new-tab, stored as
11
11
  // { type, url, label, title, newTab }. A leading "/" is treated as an internal
12
- // link. When linkOptions are provided, internal links are chosen with a document
13
- // picker instead of a hand-typed path (which silently breaks on slug edits).
12
+ // link. When linkable collections are provided, internal links are chosen with a
13
+ // document picker instead of a hand-typed path (which silently breaks on slug edits).
14
14
  // `title` is the picked document's title — renderers use it as the link text
15
15
  // when `label` is left empty.
16
16
  type LinkValue = { type?: string; url?: string; label?: string; title?: string; newTab?: boolean };
@@ -19,7 +19,7 @@ type Props = {
19
19
  name?: string;
20
20
  value?: string | LinkValue;
21
21
  onChange?: (value: LinkValue) => void;
22
- linkOptions?: LinkOptionGroup[];
22
+ linkOptions?: LinkableCollection[];
23
23
  };
24
24
 
25
25
  function parse(v: unknown): LinkValue {
@@ -92,7 +92,8 @@ export default function LinkField({ name, value: initial, onChange, linkOptions
92
92
  {linkType === "internal" ? (
93
93
  <InternalLinkPicker
94
94
  editHref={value.url ?? ""}
95
- linkOptions={linkOptions}
95
+ editTitle={value.title}
96
+ collections={linkOptions}
96
97
  onSelect={(item) => set({ url: item.href, title: item.label })}
97
98
  />
98
99
  ) : (