@kidecms/core 0.20.0 → 0.22.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,7 @@ 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) : []}
251
+ siblings={block}
256
252
  linkOptions={linkOptions}
257
253
  />
258
254
  ))
@@ -271,7 +267,6 @@ export default function BlockEditor({
271
267
  name,
272
268
  value,
273
269
  types,
274
- blockRelationOptions = {},
275
270
  linkOptions = [],
276
271
  sharedSections = [],
277
272
  sharedEnabled = true,
@@ -513,9 +508,6 @@ export default function BlockEditor({
513
508
  onSaveShared={() => saveAsShared(block._key)}
514
509
  sharedEnabled={sharedEnabled}
515
510
  onUpdateField={(fn, v) => updateField(block._key, fn, v)}
516
- getRelationOptions={(blockType, fieldName) =>
517
- blockRelationOptions[`block:${name}:${blockType}:${fieldName}`] ?? []
518
- }
519
511
  linkOptions={linkOptions}
520
512
  sharedSection={sharedSection}
521
513
  />
@@ -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,7 @@ 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) : []}
286
+ siblings={fields}
290
287
  linkOptions={options.linkOptions ?? []}
291
288
  />
292
289
  ))}
@@ -377,8 +374,7 @@ type Props = {
377
374
  initialValue?: string;
378
375
  rows?: number;
379
376
  types: BlockTypesMeta;
380
- blockRelationOptions?: Record<string, RelationOption[]>;
381
- linkOptions?: LinkOptionGroup[];
377
+ linkOptions?: LinkableCollection[];
382
378
  /** Shared sections offered by the `/` menu. */
383
379
  sharedSections?: SharedSectionOption[];
384
380
  /** When true, show a button that expands the editor into a fullscreen overlay. */
@@ -391,7 +387,6 @@ export default function ContentEditor({
391
387
  initialValue,
392
388
  rows = 14,
393
389
  types,
394
- blockRelationOptions = {},
395
390
  linkOptions = [],
396
391
  sharedSections = [],
397
392
  fullscreen = false,
@@ -471,7 +466,7 @@ export default function ContentEditor({
471
466
  showOnlyCurrent: true,
472
467
  placeholder: ({ node }) => (node.type.name === "paragraph" ? "Type / for commands…" : ""),
473
468
  }),
474
- BlockNode.configure({ types, blockRelationOptions, linkOptions, fieldName: name }),
469
+ BlockNode.configure({ types, linkOptions, fieldName: name }),
475
470
  SlashCommand.configure({ types, sharedSections }),
476
471
  ],
477
472
  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
 
@@ -116,6 +108,7 @@ const toSubFieldMeta = (subField: FieldConfig): SubFieldMeta => ({
116
108
  of: "of" in subField && subField.of ? { type: subField.of.type } : undefined,
117
109
  collection: "collection" in subField ? subField.collection : undefined,
118
110
  hasMany: "hasMany" in subField ? subField.hasMany : undefined,
111
+ condition: subField.condition,
119
112
  itemFields:
120
113
  "itemFields" in subField && subField.itemFields
121
114
  ? Object.fromEntries(Object.entries(subField.itemFields).map(([name, f]) => [name, toSubFieldMeta(f)]))
@@ -305,14 +298,14 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
305
298
  />
306
299
  )}
307
300
 
301
+ {/* No name attribute — the stored value must never be submitted (or clobbered) from here. */}
308
302
  {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}
303
+ <Input
304
+ className={controlClass}
305
+ type="text"
306
+ id={name}
307
+ defaultValue={relationOptions.length > 0 ? relationOptions.map((o) => o.label).join(", ") : serializedValue}
308
+ readOnly
316
309
  />
317
310
  )}
318
311
 
@@ -339,8 +332,7 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
339
332
  initialValue={value ? JSON.stringify(value) : ""}
340
333
  rows={rows}
341
334
  types={blockTypesMeta}
342
- blockRelationOptions={blockRelationOptions}
343
- linkOptions={menuLinkOptions}
335
+ linkOptions={linkableCollections}
344
336
  sharedSections={sharedSectionOptions}
345
337
  fullscreen={field.fullscreen !== false}
346
338
  />
@@ -364,7 +356,7 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
364
356
  value={serializedValue}
365
357
  variant="menu"
366
358
  label={label}
367
- linkOptions={menuLinkOptions}
359
+ linkOptions={linkableCollections}
368
360
  />
369
361
  )}
370
362
 
@@ -373,17 +365,11 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
373
365
  )}
374
366
 
375
367
  {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
- />
368
+ <SharedSectionBlockField client:load name={name} value={serializedValue} types={sharedBlockTypesMeta} />
383
369
  )}
384
370
 
385
371
  {field.type === "json" && field.admin?.component === "link" && !readOnly && (
386
- <LinkField client:load name={name} value={serializedValue} linkOptions={menuLinkOptions} />
372
+ <LinkField client:load name={name} value={serializedValue} linkOptions={linkableCollections} />
387
373
  )}
388
374
 
389
375
  {field.type === "json" && field.admin?.component === "repeater" && !readOnly && (
@@ -398,7 +384,7 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
398
384
  )
399
385
  : undefined
400
386
  }
401
- linkOptions={menuLinkOptions}
387
+ linkOptions={linkableCollections}
402
388
  />
403
389
  )}
404
390
 
@@ -424,8 +410,7 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
424
410
  name={name}
425
411
  value={serializedValue}
426
412
  types={blockTypesMeta}
427
- blockRelationOptions={blockRelationOptions}
428
- linkOptions={menuLinkOptions}
413
+ linkOptions={linkableCollections}
429
414
  sharedSections={"shared" in field && field.shared === false ? [] : sharedSectionOptions}
430
415
  sharedEnabled={!("shared" in field && field.shared === false)}
431
416
  />
@@ -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; collection: 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, collection: hit.collection, 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
  }