@kidecms/core 0.19.1 → 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.
Files changed (39) hide show
  1. package/admin/components/AssetsGrid.tsx +1 -1
  2. package/admin/components/BlockEditor.tsx +3 -12
  3. package/admin/components/CollaborationReviewBar.tsx +245 -61
  4. package/admin/components/CommandPalette.tsx +19 -72
  5. package/admin/components/ContentEditor.tsx +4 -10
  6. package/admin/components/DocumentCombobox.tsx +171 -0
  7. package/admin/components/FieldControl.astro +16 -32
  8. package/admin/components/InternalLinkPicker.tsx +30 -62
  9. package/admin/components/LinkField.tsx +6 -5
  10. package/admin/components/RelationField.tsx +32 -58
  11. package/admin/components/RepeaterInput.tsx +3 -6
  12. package/admin/components/SharedSectionBlockField.tsx +2 -6
  13. package/admin/components/TreeItemsEditor.tsx +4 -4
  14. package/admin/components/TreeSelect.tsx +33 -19
  15. package/admin/components/block-fields.tsx +21 -50
  16. package/admin/components/content-block-spec.ts +5 -6
  17. package/admin/layouts/AdminLayout.astro +41 -2
  18. package/admin/lib/collaboration.ts +91 -0
  19. package/admin/lib/edit-data.ts +84 -129
  20. package/admin/lib/use-document-search.ts +107 -0
  21. package/admin/views/EditView.astro +19 -28
  22. package/admin/views/ListView.astro +3 -1
  23. package/admin/views/NeedsYouView.astro +100 -0
  24. package/admin/views/RecentView.astro +32 -9
  25. package/admin/views/edit/EditScripts.astro +90 -15
  26. package/core/admin.ts +2 -0
  27. package/core/api.ts +31 -2
  28. package/core/collaboration.ts +73 -0
  29. package/core/generator.ts +25 -2
  30. package/core/index.ts +8 -2
  31. package/middleware/auth.ts +7 -1
  32. package/package.json +1 -1
  33. package/routes/admin/[...path].astro +19 -6
  34. package/routes/admin/setup.astro +3 -2
  35. package/routes/api/[collection]/[...path].ts +12 -5
  36. package/routes/api/admin/search.ts +102 -45
  37. package/routes/api/auth/setup.ts +7 -5
  38. package/routes/api/collaboration/index.ts +15 -0
  39. package/admin/components/Untitled +0 -1
@@ -803,7 +803,7 @@ export default function AssetsGrid({
803
803
 
804
804
  {/* ── Main: search, grid, pagination ── */}
805
805
  <div className="min-w-0 space-y-4 lg:border-l lg:pl-8">
806
- <div className="bg-background sticky top-0 z-20 -mx-0.5 flex items-center justify-between gap-3 border-b px-0.5 py-3">
806
+ <div className="bg-background sticky top-0 z-20 -mx-0.5 flex items-center justify-between gap-3 px-0.5 py-3">
807
807
  <div className="relative w-full sm:max-w-xs">
808
808
  <Search className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2" />
809
809
  <Input
@@ -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
  />
@@ -1,11 +1,26 @@
1
1
  "use client";
2
2
 
3
3
  import { useRef, useState } from "react";
4
- import { Check, ChevronDown, Clock, GitCommitVertical, MessageSquare, MessageSquarePlus } from "lucide-react";
4
+ import {
5
+ Check,
6
+ ChevronDown,
7
+ Clock,
8
+ EllipsisVertical,
9
+ GitCommitVertical,
10
+ MessageSquare,
11
+ MessageSquarePlus,
12
+ UserRound,
13
+ } from "lucide-react";
5
14
 
6
15
  import { cn } from "../lib/utils";
7
16
  import { buttonVariants } from "./ui/button";
8
- import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "./ui/dropdown-menu";
17
+ import {
18
+ DropdownMenu,
19
+ DropdownMenuContent,
20
+ DropdownMenuItem,
21
+ DropdownMenuSeparator,
22
+ DropdownMenuTrigger,
23
+ } from "./ui/dropdown-menu";
9
24
  import { Sheet, SheetContent, SheetTitle } from "./ui/sheet";
10
25
  import { REVIEW_STATE_META, type CollabActivity, type CollabComment, type CollabUser } from "../lib/collaboration";
11
26
  import type { ReviewState } from "../../core";
@@ -23,6 +38,19 @@ type Props = {
23
38
  canApprove: boolean;
24
39
  };
25
40
 
41
+ function EmptyAvatar({ size = "size-6" }: { size?: string }) {
42
+ return (
43
+ <span
44
+ className={cn(
45
+ size,
46
+ "border-muted-foreground/80 text-muted-foreground inline-flex shrink-0 items-center justify-center rounded-full border border-dashed",
47
+ )}
48
+ >
49
+ <UserRound className="size-3" />
50
+ </span>
51
+ );
52
+ }
53
+
26
54
  function Avatar({ initials, color, size = "size-6" }: { initials: string; color: string; size?: string }) {
27
55
  return (
28
56
  <span
@@ -48,6 +76,13 @@ export default function CollaborationReviewBar(props: Props) {
48
76
  const [draft, setDraft] = useState("");
49
77
  const [busy, setBusy] = useState(false);
50
78
 
79
+ // Self-assign stays a one-click action at the top — with a long roster, hunting
80
+ // for your own name is the slow path. It is only offered when it would change
81
+ // something, and you are then dropped from the roster below so the same person
82
+ // never appears twice.
83
+ const showAssignToMe = !!currentUser && editor?.id !== currentUser.id;
84
+ const rosterUsers = showAssignToMe ? assignableUsers.filter((u) => u.id !== currentUser!.id) : assignableUsers;
85
+
51
86
  const post = async (payload: Record<string, unknown>) => {
52
87
  setBusy(true);
53
88
  try {
@@ -89,7 +124,15 @@ export default function CollaborationReviewBar(props: Props) {
89
124
  }
90
125
  };
91
126
 
92
- const commentInputRef = useRef<HTMLInputElement>(null);
127
+ const commentInputRef = useRef<HTMLTextAreaElement>(null);
128
+
129
+ // Grow with the text instead of scrolling a one-line box: a comment you cannot
130
+ // read back while writing it is the main thing wrong with a single-line field.
131
+ const autoGrow = (el: HTMLTextAreaElement | null) => {
132
+ if (!el) return;
133
+ el.style.height = "auto";
134
+ el.style.height = `${Math.min(el.scrollHeight, 160)}px`;
135
+ };
93
136
  const openComments = (focus = false) => {
94
137
  setTab("comments");
95
138
  setOpen(true);
@@ -110,9 +153,11 @@ export default function CollaborationReviewBar(props: Props) {
110
153
  field: null,
111
154
  body,
112
155
  resolved: false,
156
+ edited: false,
113
157
  },
114
158
  ]);
115
159
  setDraft("");
160
+ if (commentInputRef.current) commentInputRef.current.style.height = "auto";
116
161
  } catch (err) {
117
162
  window.alert(err instanceof Error ? err.message : "Could not add comment.");
118
163
  }
@@ -129,6 +174,51 @@ export default function CollaborationReviewBar(props: Props) {
129
174
  }
130
175
  };
131
176
 
177
+ // Mirrors the server rule in authorizeComment(): the author, or an approver
178
+ // tidying a thread. The API re-checks — this only decides what to render.
179
+ const [editingId, setEditingId] = useState<string | null>(null);
180
+ const [editDraft, setEditDraft] = useState("");
181
+
182
+ // Author-only, matching the server. Approvers can remove a comment but not
183
+ // rewrite one that carries someone else's name.
184
+ const canEditComment = (comment: CollabComment) => !!currentUser && comment.author.id === currentUser.id;
185
+
186
+ const startEdit = (comment: CollabComment) => {
187
+ setEditingId(comment.id);
188
+ setEditDraft(comment.body);
189
+ };
190
+
191
+ const saveEdit = async (comment: CollabComment) => {
192
+ const body = editDraft.trim();
193
+ if (!body || body === comment.body) {
194
+ setEditingId(null);
195
+ return;
196
+ }
197
+ const snapshot = comments;
198
+ setComments((prev) => prev.map((c) => (c.id === comment.id ? { ...c, body, edited: true } : c)));
199
+ setEditingId(null);
200
+ try {
201
+ await post({ action: "updateComment", commentId: comment.id, body });
202
+ } catch (err) {
203
+ setComments(snapshot);
204
+ window.alert(err instanceof Error ? err.message : "Could not save comment.");
205
+ }
206
+ };
207
+
208
+ const canDeleteComment = (comment: CollabComment) =>
209
+ !!currentUser && (comment.author.id === currentUser.id || canApprove);
210
+
211
+ const deleteComment = async (comment: CollabComment) => {
212
+ const snapshot = comments;
213
+ setComments((prev) => prev.filter((c) => c.id !== comment.id));
214
+ try {
215
+ await post({ action: "deleteComment", commentId: comment.id });
216
+ } catch (err) {
217
+ setComments(snapshot);
218
+ window.alert(err instanceof Error ? err.message : "Could not delete comment.");
219
+ }
220
+ };
221
+
132
222
  const meta = REVIEW_STATE_META[reviewState];
133
223
  const canEdit = reviewState === "in_progress" || reviewState === "changes_requested";
134
224
 
@@ -236,27 +326,31 @@ export default function CollaborationReviewBar(props: Props) {
236
326
  className="hover:bg-foreground/5 flex items-center gap-1.5 rounded-md px-1.5 py-1 outline-none disabled:opacity-60"
237
327
  >
238
328
  <span className="text-muted-foreground text-xs">Assignee</span>
239
- {editor && <Avatar initials={editor.initials} color={editor.color} />}
240
- <span className={cn("text-sm", editor ? "font-medium" : "text-muted-foreground")}>
241
- {editor?.name ?? "none"}
329
+ {editor ? <Avatar initials={editor.initials} color={editor.color} /> : <EmptyAvatar />}
330
+ <span className={cn("text-sm", editor && "font-medium")}>
331
+ {editor ? (editor.id === currentUser?.id ? "You" : editor.name) : "No assignee"}
242
332
  </span>
243
333
  <ChevronDown className="text-muted-foreground size-3.5" />
244
334
  </DropdownMenuTrigger>
245
335
  <DropdownMenuContent align="end" className="min-w-48">
246
- {currentUser && editor?.id !== currentUser.id && (
247
- <DropdownMenuItem onClick={() => changeEditor(currentUser.id)}>
248
- <Avatar initials={currentUser.initials} color={currentUser.color} size="size-5" />
249
- <span className="flex-1">Assign to me</span>
250
- </DropdownMenuItem>
336
+ {showAssignToMe && currentUser && (
337
+ <>
338
+ <DropdownMenuItem onClick={() => changeEditor(currentUser.id)}>
339
+ <Avatar initials={currentUser.initials} color={currentUser.color} size="size-5" />
340
+ <span className="flex-1 font-medium">Assign to me</span>
341
+ </DropdownMenuItem>
342
+ <DropdownMenuSeparator />
343
+ </>
251
344
  )}
252
345
  <DropdownMenuItem onClick={() => changeEditor("")}>
253
- <span className="text-muted-foreground flex-1">Unassigned</span>
346
+ <EmptyAvatar size="size-5" />
347
+ <span className="flex-1">No assignee</span>
254
348
  {!editor && <Check className="text-muted-foreground size-3.5" />}
255
349
  </DropdownMenuItem>
256
- {assignableUsers.map((u) => (
350
+ {rosterUsers.map((u) => (
257
351
  <DropdownMenuItem key={u.id} onClick={() => changeEditor(u.id)}>
258
352
  <Avatar initials={u.initials} color={u.color} size="size-5" />
259
- <span className="flex-1">{u.name}</span>
353
+ <span className="flex-1">{u.id === currentUser?.id ? `${u.name} (you)` : u.name}</span>
260
354
  {editor?.id === u.id && <Check className="text-muted-foreground size-3.5" />}
261
355
  </DropdownMenuItem>
262
356
  ))}
@@ -314,10 +408,12 @@ export default function CollaborationReviewBar(props: Props) {
314
408
  <li className="text-muted-foreground px-4 py-8 text-center text-sm">No comments yet.</li>
315
409
  )}
316
410
  {comments.map((c) => (
317
- <li key={c.id} className="flex gap-3 px-4 py-3">
318
- <Avatar initials={c.author.initials} color={c.author.color} size="size-7" />
319
- <div className="min-w-0 flex-1">
320
- <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
411
+ <li key={c.id} className="px-4 py-4">
412
+ {/* Same border+padding as the body below, so the avatar's left edge
413
+ lines up with the comment text in both read and edit states. */}
414
+ <div className="flex min-w-0 items-center gap-3 border border-transparent px-2">
415
+ <Avatar initials={c.author.initials} color={c.author.color} size="size-7" />
416
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1">
321
417
  <span className="text-sm font-medium">{c.author.name}</span>
322
418
  <span className="text-muted-foreground text-xs">{c.time}</span>
323
419
  {c.field && (
@@ -325,58 +421,146 @@ export default function CollaborationReviewBar(props: Props) {
325
421
  on {c.field}
326
422
  </span>
327
423
  )}
328
- <button
329
- type="button"
330
- disabled={busy}
331
- onClick={() => toggleResolve(c)}
332
- className="text-muted-foreground hover:text-foreground ml-auto text-[10px] font-medium"
333
- >
334
- {c.resolved ? "Reopen" : "Resolve"}
335
- </button>
424
+ <DropdownMenu>
425
+ <DropdownMenuTrigger
426
+ disabled={busy}
427
+ aria-label="Comment actions"
428
+ className="text-muted-foreground hover:bg-foreground/5 hover:text-foreground ml-auto rounded-md p-1 outline-none disabled:opacity-60"
429
+ >
430
+ <EllipsisVertical className="size-3.5" />
431
+ </DropdownMenuTrigger>
432
+ <DropdownMenuContent align="end" className="min-w-32">
433
+ {canEditComment(c) && (
434
+ <DropdownMenuItem onClick={() => startEdit(c)}>Edit</DropdownMenuItem>
435
+ )}
436
+ <DropdownMenuItem onClick={() => toggleResolve(c)}>
437
+ {c.resolved ? "Reopen" : "Resolve"}
438
+ </DropdownMenuItem>
439
+ {canDeleteComment(c) && (
440
+ <DropdownMenuItem variant="destructive" onClick={() => deleteComment(c)}>
441
+ Delete
442
+ </DropdownMenuItem>
443
+ )}
444
+ </DropdownMenuContent>
445
+ </DropdownMenu>
336
446
  </div>
337
- <p className={cn("mt-1 text-sm", c.resolved && "text-muted-foreground line-through")}>{c.body}</p>
338
447
  </div>
448
+ {editingId === c.id ? (
449
+ <form
450
+ className="mt-2 grid gap-2"
451
+ onSubmit={(e) => {
452
+ e.preventDefault();
453
+ void saveEdit(c);
454
+ }}
455
+ >
456
+ <textarea
457
+ autoFocus
458
+ rows={1}
459
+ ref={autoGrow}
460
+ value={editDraft}
461
+ onChange={(e) => {
462
+ setEditDraft(e.target.value);
463
+ autoGrow(e.target);
464
+ }}
465
+ onKeyDown={(e) => {
466
+ if (e.key === "Escape") setEditingId(null);
467
+ if (e.key === "Enter" && !e.shiftKey) {
468
+ e.preventDefault();
469
+ void saveEdit(c);
470
+ }
471
+ }}
472
+ className="border-input bg-background w-full resize-none rounded-md border px-2 py-1 text-sm outline-none"
473
+ />
474
+ <div className="flex justify-end gap-2">
475
+ <button
476
+ type="button"
477
+ onClick={() => setEditingId(null)}
478
+ className={cn(buttonVariants({ variant: "outline", size: "sm" }))}
479
+ >
480
+ Cancel
481
+ </button>
482
+ <button type="submit" disabled={busy} className={cn(buttonVariants({ size: "sm" }))}>
483
+ Save
484
+ </button>
485
+ </div>
486
+ </form>
487
+ ) : (
488
+ <p
489
+ className={cn(
490
+ "mt-2 rounded-md border border-transparent px-2 py-1 text-sm whitespace-pre-wrap",
491
+ c.resolved && "text-muted-foreground line-through",
492
+ )}
493
+ >
494
+ {c.body}
495
+ {c.edited && <span className="text-muted-foreground ml-1.5 text-[10px]">(edited)</span>}
496
+ </p>
497
+ )}
339
498
  </li>
340
499
  ))}
341
500
  </ul>
342
- <div className="bg-background sticky bottom-0 flex items-center gap-2 border-t px-4 py-3">
343
- <MessageSquarePlus className="text-muted-foreground size-4 shrink-0" />
344
- <input
345
- ref={commentInputRef}
346
- type="text"
347
- value={draft}
348
- disabled={busy || !currentUser}
349
- onChange={(e) => setDraft(e.target.value)}
350
- onKeyDown={(e) => {
351
- if (e.key === "Enter") submitComment();
352
- }}
353
- placeholder={currentUser ? "Write a comment…" : "Sign in to comment"}
354
- className="border-input bg-background w-full rounded-md border px-3 py-1.5 text-sm outline-none"
355
- />
501
+ <div className="bg-background sticky bottom-0 flex items-start gap-2 border-t px-4 py-3">
502
+ <MessageSquarePlus className="text-muted-foreground mt-2 size-4 shrink-0" />
503
+ <div className="min-w-0 flex-1">
504
+ <textarea
505
+ ref={commentInputRef}
506
+ rows={1}
507
+ value={draft}
508
+ disabled={busy || !currentUser}
509
+ onChange={(e) => {
510
+ setDraft(e.target.value);
511
+ autoGrow(e.target);
512
+ }}
513
+ onKeyDown={(e) => {
514
+ // Enter sends; Shift+Enter starts a new line.
515
+ if (e.key === "Enter" && !e.shiftKey) {
516
+ e.preventDefault();
517
+ submitComment();
518
+ }
519
+ }}
520
+ placeholder={currentUser ? "Write a comment…" : "Sign in to comment"}
521
+ className="border-input bg-background w-full resize-none rounded-md border px-3 py-1.5 text-sm outline-none"
522
+ />
523
+ {draft.trim() && (
524
+ // Only the non-obvious half needs teaching — they already found Enter.
525
+ <p className="text-muted-foreground mt-1.5 flex items-center gap-1.5 text-xs">
526
+ <kbd className="text-foreground/45 inline-flex items-center gap-1 rounded border px-1.5 py-0.5 font-sans text-[11px] leading-none font-medium">
527
+ Shift + Enter
528
+ </kbd>
529
+ for a new line
530
+ </p>
531
+ )}
532
+ </div>
356
533
  </div>
357
534
  </div>
358
535
  )}
359
536
 
360
- {tab === "activity" && (
361
- <ul className="flex-1 space-y-4 overflow-y-auto px-4 py-4">
362
- {activity.length === 0 && <li className="text-muted-foreground text-center text-sm">No activity yet.</li>}
363
- {activity.map((a, i) => (
364
- <li key={i} className="flex gap-3">
365
- <div className="flex flex-col items-center">
366
- <Avatar initials={a.actor.initials} color={a.actor.color} />
367
- {i < activity.length - 1 && <GitCommitVertical className="text-border mt-1 size-4" />}
368
- </div>
369
- <div className="min-w-0 flex-1 pt-0.5">
370
- <p className="text-sm">
371
- <span className="font-medium">{a.actor.name}</span>{" "}
372
- <span className="text-muted-foreground">{a.text}</span>
373
- </p>
374
- <span className="text-muted-foreground text-xs">{a.time}</span>
375
- </div>
376
- </li>
377
- ))}
378
- </ul>
379
- )}
537
+ {tab === "activity" &&
538
+ (activity.length === 0 ? (
539
+ // Centre it: a lone line pinned to the top of a full-height sheet reads
540
+ // as a layout bug rather than an empty state.
541
+ <div className="text-muted-foreground flex flex-1 flex-col items-center justify-center gap-2 px-4 text-sm">
542
+ <Clock className="size-5 opacity-40" />
543
+ <p>No activity yet.</p>
544
+ </div>
545
+ ) : (
546
+ <ul className="flex-1 space-y-4 overflow-y-auto px-4 py-4">
547
+ {activity.map((a, i) => (
548
+ <li key={i} className="flex gap-3">
549
+ <div className="flex flex-col items-center">
550
+ <Avatar initials={a.actor.initials} color={a.actor.color} />
551
+ {i < activity.length - 1 && <GitCommitVertical className="text-border mt-1 size-4" />}
552
+ </div>
553
+ <div className="min-w-0 flex-1 pt-0.5">
554
+ <p className="text-sm">
555
+ <span className="font-medium">{a.actor.name}</span>{" "}
556
+ <span className="text-muted-foreground">{a.text}</span>
557
+ </p>
558
+ <span className="text-muted-foreground text-xs">{a.time}</span>
559
+ </div>
560
+ </li>
561
+ ))}
562
+ </ul>
563
+ ))}
380
564
  </SheetContent>
381
565
  </Sheet>
382
566
  </>
@@ -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),