@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
@@ -2,14 +2,13 @@
2
2
 
3
3
  import { useMemo, useState } from "react";
4
4
 
5
- import { SubField, blankBlockFields, humanize, type BlockTypesMeta, type RelationOption } from "./block-fields";
5
+ import { SubField, blankBlockFields, humanize, type BlockTypesMeta } from "./block-fields";
6
6
  import SelectField from "./SelectField";
7
7
 
8
8
  type Props = {
9
9
  name: string;
10
10
  value?: string;
11
11
  types: BlockTypesMeta;
12
- blockRelationOptions?: Record<string, RelationOption[]>;
13
12
  };
14
13
 
15
14
  type SharedBlock = {
@@ -35,7 +34,7 @@ function parseInitialBlock(value: string | undefined, types: BlockTypesMeta): Sh
35
34
  }
36
35
  }
37
36
 
38
- export default function SharedSectionBlockField({ name, value, types, blockRelationOptions = {} }: Props) {
37
+ export default function SharedSectionBlockField({ name, value, types }: Props) {
39
38
  const [block, setBlock] = useState<SharedBlock>(() => parseInitialBlock(value, types));
40
39
  const typeNames = Object.keys(types);
41
40
  const selectedType = block.type;
@@ -50,8 +49,6 @@ export default function SharedSectionBlockField({ name, value, types, blockRelat
50
49
  setBlock((prev) => ({ ...prev, [fieldName]: fieldValue }));
51
50
  };
52
51
 
53
- const relationOptionsFor = (fieldName: string) => blockRelationOptions[`shared:${selectedType}:${fieldName}`] ?? [];
54
-
55
52
  if (typeNames.length === 0) {
56
53
  return (
57
54
  <div className="bg-field-subtle text-muted-foreground rounded-lg border border-dashed px-4 py-3 text-sm">
@@ -83,7 +80,6 @@ export default function SharedSectionBlockField({ name, value, types, blockRelat
83
80
  meta={meta}
84
81
  value={block[fieldName]}
85
82
  onChange={(v) => updateField(fieldName, v)}
86
- relationOptions={meta.type === "relation" ? relationOptionsFor(fieldName) : []}
87
83
  />
88
84
  ))}
89
85
  </div>
@@ -30,7 +30,7 @@ import { Input } from "./ui/input";
30
30
  import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
31
31
  import { Collapsible, CollapsibleTrigger, CollapsibleContent } from "./ui/collapsible";
32
32
  import { cn } from "../lib/utils";
33
- import InternalLinkPicker, { type LinkOptionGroup } from "./InternalLinkPicker";
33
+ import InternalLinkPicker, { type LinkableCollection } from "./InternalLinkPicker";
34
34
  import {
35
35
  type TreeItem,
36
36
  generateId,
@@ -67,7 +67,7 @@ type Props = {
67
67
  value?: string;
68
68
  variant: "menu" | "taxonomy";
69
69
  label?: string;
70
- linkOptions?: LinkOptionGroup[];
70
+ linkOptions?: LinkableCollection[];
71
71
  };
72
72
 
73
73
  function blankEdit(id: string): EditState {
@@ -298,7 +298,7 @@ export default function TreeItemsEditor({ name, value, variant, label, linkOptio
298
298
 
299
299
  const startEdit = (item: TreeItem) => {
300
300
  if (variant === "menu") {
301
- const isInternal = linkOptions.some((group) => group.items.some((li) => li.href === String(item.href ?? "")));
301
+ const isInternal = String(item.href ?? "").startsWith("/");
302
302
  setEditing({
303
303
  ...blankEdit(item.id),
304
304
  label: String(item.label ?? ""),
@@ -470,7 +470,7 @@ export default function TreeItemsEditor({ name, value, variant, label, linkOptio
470
470
  ) : (
471
471
  <InternalLinkPicker
472
472
  editHref={editing.href}
473
- linkOptions={linkOptions}
473
+ collections={linkOptions}
474
474
  className="flex-3"
475
475
  triggerClassName="bg-background h-7 rounded-md"
476
476
  onSelect={(item) => {
@@ -78,6 +78,7 @@ export default function TreeSelect({
78
78
  }: Props) {
79
79
  const [value, setValue] = useState(initialValue ?? "");
80
80
  const [open, setOpen] = useState(false);
81
+ const [query, setQuery] = useState("");
81
82
  const hiddenRef = useRef<HTMLInputElement>(null);
82
83
  const isInitial = useRef(true);
83
84
 
@@ -91,10 +92,21 @@ export default function TreeSelect({
91
92
 
92
93
  const selected = items.find((i) => i.value === value);
93
94
 
95
+ // Filtering is ours, not cmdk's: cmdk reorders the DOM while filtering (and
96
+ // doesn't restore it when the query clears), which would bump the pinned
97
+ // "None" row around — and "None" is a clear-action, not a match for any query.
98
+ const q = query.trim().toLowerCase();
99
+ const filtered = q ? items.filter((item) => item.path.join(" / ").toLowerCase().includes(q)) : items;
100
+
101
+ const handleOpenChange = (next: boolean) => {
102
+ setOpen(next);
103
+ if (!next) setQuery("");
104
+ };
105
+
94
106
  return (
95
107
  <div className="space-y-2">
96
108
  <input ref={hiddenRef} type="hidden" name={name} value={value} />
97
- <Popover open={open} onOpenChange={setOpen}>
109
+ <Popover open={open} onOpenChange={handleOpenChange}>
98
110
  <PopoverTrigger asChild>
99
111
  <Button
100
112
  variant="input"
@@ -122,31 +134,33 @@ export default function TreeSelect({
122
134
  </Button>
123
135
  </PopoverTrigger>
124
136
  <PopoverContent className="w-(--radix-popover-trigger-width) p-0" align="start">
125
- <Command>
126
- <CommandInput placeholder={searchPlaceholder} />
137
+ <Command shouldFilter={false}>
138
+ <CommandInput value={query} onValueChange={setQuery} placeholder={searchPlaceholder} />
127
139
  <CommandList>
128
- <CommandEmpty>{emptyMessage}</CommandEmpty>
129
- <CommandItem
130
- value="__none__"
131
- onSelect={() => {
132
- setValue("");
133
- onChangeProp?.("");
134
- setOpen(false);
135
- }}
136
- >
137
- <div className="flex items-center">
138
- <Check className={cn("mr-2 ml-1 size-4 shrink-0", !value ? "opacity-100" : "opacity-0")} />
139
- <span className="text-muted-foreground">None</span>
140
- </div>
141
- </CommandItem>
142
- {items.map((item) => (
140
+ {filtered.length === 0 && <CommandEmpty>{emptyMessage}</CommandEmpty>}
141
+ {!q && (
142
+ <CommandItem
143
+ value="__none__"
144
+ onSelect={() => {
145
+ setValue("");
146
+ onChangeProp?.("");
147
+ handleOpenChange(false);
148
+ }}
149
+ >
150
+ <div className="flex items-center">
151
+ <Check className={cn("mr-2 ml-1 size-4 shrink-0", !value ? "opacity-100" : "opacity-0")} />
152
+ <span className="text-muted-foreground">None</span>
153
+ </div>
154
+ </CommandItem>
155
+ )}
156
+ {filtered.map((item) => (
143
157
  <CommandItem
144
158
  key={item.value}
145
159
  value={item.path.join(" / ")}
146
160
  onSelect={() => {
147
161
  setValue(item.value === value ? "" : item.value);
148
162
  onChangeProp?.(item.value === value ? "" : item.value);
149
- setOpen(false);
163
+ handleOpenChange(false);
150
164
  }}
151
165
  >
152
166
  <div className="flex items-center" style={{ paddingLeft: `${item.depth * 1.25}rem` }}>
@@ -24,7 +24,8 @@ import ImagePicker from "./ImagePicker";
24
24
  import SelectField from "./SelectField";
25
25
  import ColorField from "./ColorField";
26
26
  import LinkField from "./LinkField";
27
- import type { LinkOptionGroup } from "./InternalLinkPicker";
27
+ import type { LinkableCollection } from "./InternalLinkPicker";
28
+ import DocumentCombobox, { useRelationLabels } from "./DocumentCombobox";
28
29
  import YoutubeField from "./YoutubeField";
29
30
 
30
31
  // -----------------------------------------------
@@ -51,8 +52,6 @@ export type SubFieldMeta = {
51
52
 
52
53
  export type BlockTypesMeta = Record<string, Record<string, SubFieldMeta>>;
53
54
 
54
- export type RelationOption = { value: string; label: string };
55
-
56
55
  export function generateKey() {
57
56
  return "blk_" + Math.random().toString(36).slice(2, 9);
58
57
  }
@@ -100,7 +99,6 @@ export function SubField({
100
99
  meta,
101
100
  value,
102
101
  onChange,
103
- relationOptions = [],
104
102
  linkOptions = [],
105
103
  }: {
106
104
  blockKey: string;
@@ -108,8 +106,7 @@ export function SubField({
108
106
  meta: SubFieldMeta;
109
107
  value: unknown;
110
108
  onChange: (value: unknown) => void;
111
- relationOptions?: RelationOption[];
112
- linkOptions?: LinkOptionGroup[];
109
+ linkOptions?: LinkableCollection[];
113
110
  }) {
114
111
  const label = meta.label ?? humanize(fieldName);
115
112
  const fieldId = `${blockKey}_${fieldName}`;
@@ -121,14 +118,7 @@ export function SubField({
121
118
  {meta.required ? " *" : ""}
122
119
  </Label>
123
120
  {meta.admin?.help && <p className="text-muted-foreground text-xs leading-5">{meta.admin.help}</p>}
124
- <SubFieldControl
125
- fieldId={fieldId}
126
- meta={meta}
127
- value={value}
128
- onChange={onChange}
129
- relationOptions={relationOptions}
130
- linkOptions={linkOptions}
131
- />
121
+ <SubFieldControl fieldId={fieldId} meta={meta} value={value} onChange={onChange} linkOptions={linkOptions} />
132
122
  </div>
133
123
  );
134
124
  }
@@ -181,16 +171,15 @@ function RelationControl({
181
171
  meta,
182
172
  value,
183
173
  onChange,
184
- relationOptions,
185
174
  }: {
186
175
  fieldId: string;
187
176
  meta: SubFieldMeta;
188
177
  value: unknown;
189
178
  onChange: (value: unknown) => void;
190
- relationOptions: RelationOption[];
191
179
  }) {
192
180
  const selected = parseSelected(meta, value);
193
- const getLabel = (id: string) => relationOptions?.find((o) => o.value === id)?.label ?? id;
181
+ const collectionSlug = meta.collection ?? "";
182
+ const { getLabel, remember } = useRelationLabels(collectionSlug, selected);
194
183
  const toggle = (id: string) => {
195
184
  if (meta.hasMany) {
196
185
  const next = selected.includes(id) ? selected.filter((v) => v !== id) : [...selected, id];
@@ -208,7 +197,7 @@ function RelationControl({
208
197
  key={id}
209
198
  className="bg-card text-secondary-foreground inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-sm"
210
199
  >
211
- {getLabel(id)}
200
+ {getLabel(id) ?? "…"}
212
201
  <button
213
202
  type="button"
214
203
  onClick={() => toggle(id)}
@@ -220,18 +209,17 @@ function RelationControl({
220
209
  ))}
221
210
  </div>
222
211
  )}
223
- <SelectField
224
- name={fieldId}
225
- value={meta.hasMany ? "" : (selected[0] ?? "")}
226
- placeholder={`Select ${meta.label?.toLowerCase() ?? "item"}...`}
227
- items={(relationOptions ?? []).map((o) => ({ value: o.value, label: o.label }))}
228
- onChange={(v) => {
229
- if (meta.hasMany && v) {
230
- if (!selected.includes(v)) onChange([...selected, v]);
231
- } else {
232
- onChange(v);
233
- }
212
+ <DocumentCombobox
213
+ collections={[collectionSlug]}
214
+ placeholder={`Search ${meta.label?.toLowerCase() ?? "documents"}...`}
215
+ display={meta.hasMany ? "" : selected[0] ? (getLabel(selected[0]) ?? "…") : ""}
216
+ isSelected={(hit) => selected.includes(hit.docId)}
217
+ onPick={(hit) => {
218
+ remember([hit]);
219
+ toggle(hit.docId);
234
220
  }}
221
+ closeOnPick={!meta.hasMany}
222
+ triggerId={fieldId}
235
223
  />
236
224
  </div>
237
225
  );
@@ -278,15 +266,13 @@ export function SubFieldControl({
278
266
  meta,
279
267
  value,
280
268
  onChange,
281
- relationOptions = [],
282
269
  linkOptions = [],
283
270
  }: {
284
271
  fieldId: string;
285
272
  meta: SubFieldMeta;
286
273
  value: unknown;
287
274
  onChange: (value: unknown) => void;
288
- relationOptions?: RelationOption[];
289
- linkOptions?: LinkOptionGroup[];
275
+ linkOptions?: LinkableCollection[];
290
276
  }) {
291
277
  const strValue = value == null ? "" : String(value);
292
278
 
@@ -384,15 +370,7 @@ export function SubFieldControl({
384
370
  );
385
371
 
386
372
  case "relation":
387
- return (
388
- <RelationControl
389
- fieldId={fieldId}
390
- meta={meta}
391
- value={value}
392
- onChange={onChange}
393
- relationOptions={relationOptions}
394
- />
395
- );
373
+ return <RelationControl fieldId={fieldId} meta={meta} value={value} onChange={onChange} />;
396
374
 
397
375
  case "array":
398
376
  return <ArrayControl fieldId={fieldId} meta={meta} value={value} onChange={onChange} />;
@@ -403,7 +381,6 @@ export function SubFieldControl({
403
381
  <RepeaterField
404
382
  blockKey={fieldId}
405
383
  itemFields={meta.itemFields}
406
- relationOptions={relationOptions}
407
384
  linkOptions={linkOptions}
408
385
  value={value}
409
386
  onChange={onChange}
@@ -440,7 +417,6 @@ function SortableRepeaterItem({
440
417
  item,
441
418
  fieldKeys,
442
419
  itemFields,
443
- relationOptions,
444
420
  linkOptions,
445
421
  index,
446
422
  isExpanded,
@@ -454,8 +430,7 @@ function SortableRepeaterItem({
454
430
  item: Record<string, unknown>;
455
431
  fieldKeys: string[];
456
432
  itemFields?: Record<string, SubFieldMeta>;
457
- relationOptions?: RelationOption[];
458
- linkOptions?: LinkOptionGroup[];
433
+ linkOptions?: LinkableCollection[];
459
434
  index: number;
460
435
  isExpanded: boolean;
461
436
  autoFocus?: boolean;
@@ -552,7 +527,6 @@ function SortableRepeaterItem({
552
527
  meta={itemFields[key]}
553
528
  value={item[key]}
554
529
  onChange={(v) => onUpdate(key, v)}
555
- relationOptions={relationOptions}
556
530
  linkOptions={linkOptions}
557
531
  />
558
532
  ))
@@ -593,15 +567,13 @@ function parseArray(value: unknown): unknown[] {
593
567
  export function RepeaterField({
594
568
  blockKey,
595
569
  itemFields,
596
- relationOptions,
597
570
  linkOptions,
598
571
  value,
599
572
  onChange,
600
573
  }: {
601
574
  blockKey: string;
602
575
  itemFields?: Record<string, SubFieldMeta>;
603
- relationOptions?: RelationOption[];
604
- linkOptions?: LinkOptionGroup[];
576
+ linkOptions?: LinkableCollection[];
605
577
  value: unknown;
606
578
  onChange: (value: unknown) => void;
607
579
  }) {
@@ -707,7 +679,6 @@ export function RepeaterField({
707
679
  item={item}
708
680
  fieldKeys={fieldKeys}
709
681
  itemFields={itemFields}
710
- relationOptions={relationOptions}
711
682
  linkOptions={linkOptions}
712
683
  index={index}
713
684
  isExpanded={expandedKeys.has(String(item._key))}
@@ -1,7 +1,7 @@
1
1
  import { mergeAttributes, isNodeSelection, type Editor } from "@tiptap/core";
2
2
  import { NodeSelection, TextSelection } from "@tiptap/pm/state";
3
- import type { BlockTypesMeta, RelationOption } from "./block-fields";
4
- import type { LinkOptionGroup } from "./InternalLinkPicker";
3
+ import type { BlockTypesMeta } from "./block-fields";
4
+ import type { LinkableCollection } from "./InternalLinkPicker";
5
5
 
6
6
  /**
7
7
  * Schema/serialization spec for the inline `content` block node — kept free of React
@@ -23,9 +23,8 @@ export const SHARED_BLOCK_TYPE = "__shared";
23
23
 
24
24
  export type BlockNodeOptions = {
25
25
  types: BlockTypesMeta;
26
- blockRelationOptions: Record<string, RelationOption[]>;
27
- linkOptions?: LinkOptionGroup[];
28
- /** Name of the `content` field this editor belongs to — namespaces relation-option keys. */
26
+ linkOptions?: LinkableCollection[];
27
+ /** Name of the `content` field this editor belongs to — namespaces sub-field DOM ids. */
29
28
  fieldName: string;
30
29
  };
31
30
 
@@ -37,7 +36,7 @@ export const blockNodeSpec = {
37
36
  selectable: true,
38
37
 
39
38
  addOptions(): BlockNodeOptions {
40
- return { types: {}, blockRelationOptions: {}, fieldName: "" };
39
+ return { types: {}, fieldName: "" };
41
40
  },
42
41
 
43
42
  addAttributes() {
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  import "virtual:kide/admin-css";
3
3
  import { cms } from "virtual:kide/api";
4
+ import config from "virtual:kide/config";
4
5
 
5
6
  import {
6
7
  ChevronDown,
@@ -79,6 +80,10 @@ import MobileSidebar from "../components/MobileSidebar";
79
80
  import SidebarUserMenu from "../components/SidebarUserMenu";
80
81
  import Toast from "../components/Toast.astro";
81
82
  import { cn } from "../lib/utils";
83
+ import { eligibleCollabSlugs, loadNeedsYou } from "../lib/collaboration";
84
+ import { canRead } from "../lib/access";
85
+ import { isApprover, resolveCollaboration } from "../../core";
86
+ import { collaboration } from "virtual:kide/runtime";
82
87
 
83
88
  const {
84
89
  title = "Admin",
@@ -131,6 +136,25 @@ const pinnedIcons: Record<string, any> = {
131
136
  users: Users,
132
137
  };
133
138
 
139
+ // "Needs you" queue — the nav entry only exists when collaboration is switched on
140
+ // for at least one readable collection, and its badge is the whole notification
141
+ // story for now: without a count nobody visits a queue they have to remember.
142
+ const needsYouSlugs = eligibleCollabSlugs(config, user, resolveCollaboration, canRead);
143
+ let needsYouCount = 0;
144
+ if (needsYouSlugs.size > 0 && user) {
145
+ try {
146
+ const queue = await loadNeedsYou({
147
+ collaboration,
148
+ userId: String(user.id),
149
+ isApprover: isApprover(config, user.role),
150
+ eligibleSlugs: needsYouSlugs,
151
+ });
152
+ needsYouCount = queue.length;
153
+ } catch {
154
+ // Table may not exist yet on first run — a missing badge beats a broken layout.
155
+ }
156
+ }
157
+
134
158
  // Unread submissions badge — shown next to "Forms" in the sidebar.
135
159
  let unreadSubmissions = 0;
136
160
  try {
@@ -187,10 +211,25 @@ type NavItem = {
187
211
  weight: number;
188
212
  group: string;
189
213
  badge?: number;
214
+ /** Word after the count. "new" suits an inbox of arrivals; a work queue is not new. */
215
+ badgeLabel?: string;
190
216
  };
191
217
  const navItems: NavItem[] = [];
192
218
 
193
219
  // Built-in nav items with default weights (spaced by 10 for easy interleaving)
220
+ if (needsYouSlugs.size > 0) {
221
+ navItems.push({
222
+ href: "/admin/needs-you",
223
+ label: "Needs you",
224
+ Icon: Inbox,
225
+ active: activeCollection === "needs-you",
226
+ badge: needsYouCount > 0 ? needsYouCount : undefined,
227
+ badgeLabel: "open",
228
+ weight: -10,
229
+ group: "Content",
230
+ });
231
+ }
232
+
194
233
  navItems.push({
195
234
  href: "/admin/recent",
196
235
  label: "Recent",
@@ -390,7 +429,7 @@ const navGroups = [...new Set(navItems.map((item) => item.group))]
390
429
  <span class="flex-1">{item.label}</span>
391
430
  {item.badge ? (
392
431
  <span class="text-muted-foreground/80 text-xs tabular-nums">
393
- {item.badge > 99 ? "99+" : item.badge} new
432
+ {item.badge > 99 ? "99+" : item.badge} {item.badgeLabel ?? "new"}
394
433
  </span>
395
434
  ) : null}
396
435
  </a>
@@ -470,7 +509,7 @@ const navGroups = [...new Set(navItems.map((item) => item.group))]
470
509
  <span class="flex-1">{item.label}</span>
471
510
  {item.badge ? (
472
511
  <span class="text-muted-foreground/80 text-xs tabular-nums">
473
- {item.badge > 99 ? "99+" : item.badge} new
512
+ {item.badge > 99 ? "99+" : item.badge} {item.badgeLabel ?? "new"}
474
513
  </span>
475
514
  ) : null}
476
515
  </a>
@@ -10,6 +10,7 @@ export type CollabComment = {
10
10
  field: string | null;
11
11
  body: string;
12
12
  resolved: boolean;
13
+ edited: boolean;
13
14
  };
14
15
  export type CollabActivity = { actor: CollabUser; text: string; time: string };
15
16
 
@@ -157,6 +158,7 @@ export async function loadCollaborationData(opts: {
157
158
  field: c.field ?? null,
158
159
  body: String(c.body),
159
160
  resolved: Boolean(c.resolved),
161
+ edited: !!c.editedAt,
160
162
  }))
161
163
  // listComments is newest-first; show comments oldest-first like a thread.
162
164
  .reverse();
@@ -176,3 +178,92 @@ export async function loadCollaborationData(opts: {
176
178
  currentUser: currentUser ? toUser(currentUser.id, currentUser.email) : null,
177
179
  };
178
180
  }
181
+
182
+ // --- "Needs you" queue ---------------------------------------------------
183
+
184
+ export type NeedsYouItem = {
185
+ collectionSlug: string;
186
+ documentId: string;
187
+ reviewState: ReviewState;
188
+ /** Why it is in the queue: the user holds it, or it is waiting on their approval. */
189
+ reason: "assigned" | "awaiting_review";
190
+ };
191
+
192
+ type NeedsYouOpts = {
193
+ collaboration: {
194
+ assignedTo: (
195
+ userId: string,
196
+ ) => Promise<Array<{ collection: string; documentId: string; reviewState: ReviewState }>>;
197
+ inReviewStates: (
198
+ states: readonly ReviewState[],
199
+ ) => Promise<Array<{ collection: string; documentId: string; reviewState: ReviewState; editor: string | null }>>;
200
+ };
201
+ userId: string;
202
+ isApprover: boolean;
203
+ /** Slugs the user may read AND that have collaboration switched on. */
204
+ eligibleSlugs: Set<string>;
205
+ };
206
+
207
+ /**
208
+ * The documents genuinely waiting on this person: their own unfinished
209
+ * assignments, plus — for approvers — anything submitted for review by anyone.
210
+ * "Assigned to me" alone is the wrong question for an approver, who never holds
211
+ * the documents they are being asked to look at.
212
+ */
213
+ export async function loadNeedsYou(opts: NeedsYouOpts): Promise<NeedsYouItem[]> {
214
+ const { collaboration, userId, isApprover, eligibleSlugs } = opts;
215
+ if (eligibleSlugs.size === 0 || !userId) return [];
216
+
217
+ const open: ReadonlyArray<ReviewState> = ["in_progress", "ready_for_review", "changes_requested"];
218
+ const byKey = new Map<string, NeedsYouItem>();
219
+
220
+ const [mine, awaiting] = await Promise.all([
221
+ collaboration.assignedTo(userId).catch(() => []),
222
+ isApprover ? collaboration.inReviewStates(["ready_for_review"]).catch(() => []) : Promise.resolve([]),
223
+ ]);
224
+
225
+ for (const row of mine) {
226
+ if (!eligibleSlugs.has(row.collection) || !open.includes(row.reviewState)) continue;
227
+ byKey.set(`${row.collection}:${row.documentId}`, {
228
+ collectionSlug: row.collection,
229
+ documentId: row.documentId,
230
+ reviewState: row.reviewState,
231
+ reason: "assigned",
232
+ });
233
+ }
234
+
235
+ for (const row of awaiting) {
236
+ if (!eligibleSlugs.has(row.collection)) continue;
237
+ const key = `${row.collection}:${row.documentId}`;
238
+ // Something you hold *and* must approve stays listed once, as your own work.
239
+ if (byKey.has(key)) continue;
240
+ byKey.set(key, {
241
+ collectionSlug: row.collection,
242
+ documentId: row.documentId,
243
+ reviewState: row.reviewState,
244
+ reason: "awaiting_review",
245
+ });
246
+ }
247
+
248
+ return [...byKey.values()];
249
+ }
250
+
251
+ /**
252
+ * Collections the user may read that also have collaboration switched on. Shared
253
+ * by the nav badge and the view so a count can never disagree with its own list.
254
+ */
255
+ export function eligibleCollabSlugs(
256
+ config: any,
257
+ user: { role?: string } | null | undefined,
258
+ resolveCollaboration: (config: any, slug: string) => { enabled: boolean },
259
+ canRead: (config: any, user: any, slug: string) => boolean,
260
+ ): Set<string> {
261
+ const slugs = new Set<string>();
262
+ for (const collection of config.collections ?? []) {
263
+ if (collection.auth) continue;
264
+ if (!resolveCollaboration(config, collection.slug).enabled) continue;
265
+ if (!canRead(config, user, collection.slug)) continue;
266
+ slugs.add(collection.slug);
267
+ }
268
+ return slugs;
269
+ }