@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,7 +2,6 @@ import {
2
2
  SHARED_SECTIONS_COLLECTION,
3
3
  extractSharedSectionRefsFromDocument,
4
4
  getLabelField,
5
- getSharedBlockTypes,
6
5
  type SharedSectionOption,
7
6
  } from "../../core";
8
7
  import { canRead } from "./access";
@@ -43,114 +42,95 @@ export type RelationMeta = {
43
42
  labelField?: string;
44
43
  };
45
44
 
46
- export type RelationOptions = {
47
- relationOptionsByField: Record<string, Array<{ value: string; label: string }>>;
48
- relationMetaByField: Record<string, RelationMeta>;
49
- };
50
-
51
- export const loadRelationOptionList = async (
52
- collectionSlug: string,
53
- config: any,
54
- cmsRuntime: CmsRuntime,
55
- defaultLocale: string,
56
- runtimeContext: RuntimeContext,
57
- ) => {
58
- const relatedDocs = await cmsRuntime[collectionSlug].find(
59
- { status: "any", limit: 100, sort: { field: "_updatedAt", direction: "desc" }, locale: defaultLocale },
60
- runtimeContext,
61
- );
62
- const relatedCollection = config.collections.find((c: any) => c.slug === collectionSlug);
63
- const labelField = relatedCollection ? getLabelField(relatedCollection) : "title";
64
- return relatedDocs.map((item: Record<string, unknown>) => ({
65
- value: String(item._id),
66
- label: String(item[labelField] ?? item.slug ?? item._id),
67
- }));
68
- };
45
+ /** Relation metadata for the edit form. Option lists are no longer preloaded:
46
+ * the combobox searches the target collection on the server and resolves
47
+ * labels for already-selected ids itself (see RelationField). */
48
+ export function loadRelationMeta(collection: CollectionLike, config: any, user: User): Record<string, RelationMeta> {
49
+ const relationMetaByField: Record<string, RelationMeta> = {};
50
+ for (const [fieldName, field] of Object.entries(collection.fields) as [string, any][]) {
51
+ if (field.type !== "relation" || !canRead(config, user, field.collection)) continue;
52
+ const relatedCollection = config.collections.find((c: any) => c.slug === field.collection);
53
+ if (!relatedCollection) continue;
54
+ relationMetaByField[fieldName] = {
55
+ collectionSlug: field.collection,
56
+ collectionLabel: relatedCollection.labels.singular,
57
+ hasMany: field.hasMany ?? false,
58
+ labelField: getLabelField(relatedCollection),
59
+ };
60
+ }
61
+ return relationMetaByField;
62
+ }
69
63
 
70
- /** Fetch relation option lists for top-level relation fields and any relations nested inside blocks. */
71
- export async function loadRelationOptions(
64
+ /** Labels for the ids a document's relation fields currently point at, so the
65
+ * edit form renders selections named without a client round trip. Only the
66
+ * selected ids are fetched — never a catalogue. */
67
+ export async function loadRelationLabels(
72
68
  collection: CollectionLike,
69
+ doc: Record<string, unknown> | null,
73
70
  config: any,
74
71
  user: User,
75
72
  cmsRuntime: CmsRuntime,
76
73
  defaultLocale: string,
77
74
  runtimeContext: RuntimeContext,
78
- ): Promise<RelationOptions> {
79
- const relationOptionsByField: Record<string, Array<{ value: string; label: string }>> = {};
80
- const relationMetaByField: Record<string, RelationMeta> = {};
75
+ ): Promise<Record<string, Array<{ value: string; label: string }>>> {
76
+ const labelsByField: Record<string, Array<{ value: string; label: string }>> = {};
77
+ if (!doc) return labelsByField;
81
78
 
82
79
  for (const [fieldName, field] of Object.entries(collection.fields) as [string, any][]) {
83
- if (field.type === "relation" && canRead(config, user, field.collection)) {
84
- const relatedCollection = config.collections.find((c: any) => c.slug === field.collection);
85
- relationOptionsByField[fieldName] = await loadRelationOptionList(
86
- field.collection,
87
- config,
88
- cmsRuntime,
89
- defaultLocale,
90
- runtimeContext,
91
- );
92
- if (relatedCollection) {
93
- relationMetaByField[fieldName] = {
94
- collectionSlug: field.collection,
95
- collectionLabel: relatedCollection.labels.singular,
96
- hasMany: field.hasMany ?? false,
97
- labelField: getLabelField(relatedCollection),
98
- };
99
- }
100
- }
101
- // Relations nested inside block types — both standalone `blocks` fields and inline
102
- // blocks in a `content` field use the same `block:<field>:<type>:<subField>` key scheme.
103
- // The parent field name keeps two block-bearing fields that share a block-type name
104
- // (but target different collections) from colliding.
105
- const blockTypes = field.type === "blocks" ? field.types : field.type === "content" ? field.blocks : null;
106
- if (blockTypes) {
107
- for (const [typeName, typeFields] of Object.entries(blockTypes)) {
108
- for (const [subFieldName, subField] of Object.entries(typeFields as Record<string, any>) as [string, any][]) {
109
- if (subField.type === "relation" && canRead(config, user, subField.collection)) {
110
- const key = `block:${fieldName}:${typeName}:${subFieldName}`;
111
- if (!relationOptionsByField[key]) {
112
- relationOptionsByField[key] = await loadRelationOptionList(
113
- subField.collection,
114
- config,
115
- cmsRuntime,
116
- defaultLocale,
117
- runtimeContext,
118
- );
119
- }
120
- }
121
- }
80
+ if (field.type !== "relation" || !canRead(config, user, field.collection)) continue;
81
+ const relatedCollection = config.collections.find((c: any) => c.slug === field.collection);
82
+ const api = cmsRuntime[field.collection];
83
+ if (!relatedCollection || !api) continue;
84
+
85
+ let raw = doc[fieldName];
86
+ if (field.hasMany && typeof raw === "string") {
87
+ try {
88
+ raw = JSON.parse(raw);
89
+ } catch {
90
+ raw = [];
122
91
  }
123
92
  }
93
+ const ids = field.hasMany ? (Array.isArray(raw) ? raw.map(String) : []) : raw ? [String(raw)] : [];
94
+ if (ids.length === 0) continue;
95
+
96
+ const labelField = getLabelField(relatedCollection);
97
+ const relatedDocs = await Promise.all(
98
+ ids.map((id) =>
99
+ api
100
+ .find({ where: { _id: id }, status: "any", limit: 1, locale: defaultLocale }, runtimeContext)
101
+ .then((docs: Array<Record<string, unknown>>) => docs[0])
102
+ .catch(() => undefined),
103
+ ),
104
+ );
105
+ labelsByField[fieldName] = ids.flatMap((id, i) => {
106
+ const related = relatedDocs[i];
107
+ return related ? [{ value: id, label: String(related[labelField] ?? related.slug ?? id) }] : [];
108
+ });
124
109
  }
125
110
 
126
- return { relationOptionsByField, relationMetaByField };
111
+ return labelsByField;
127
112
  }
128
113
 
129
- export async function loadSharedBlockRelationOptions(
114
+ /** Label lookup for list columns that show a relation. Capped; fine for the
115
+ * small reference collections such columns usually point at. */
116
+ export const loadRelationOptionList = async (
117
+ collectionSlug: string,
130
118
  config: any,
131
- user: User,
132
119
  cmsRuntime: CmsRuntime,
133
120
  defaultLocale: string,
134
121
  runtimeContext: RuntimeContext,
135
- ): Promise<Record<string, Array<{ value: string; label: string }>>> {
136
- const relationOptions: Record<string, Array<{ value: string; label: string }>> = {};
137
- const sharedBlockTypes = getSharedBlockTypes(config);
138
-
139
- for (const [typeName, typeFields] of Object.entries(sharedBlockTypes)) {
140
- for (const [fieldName, field] of Object.entries(typeFields) as [string, any][]) {
141
- if (field.type !== "relation" || !canRead(config, user, field.collection)) continue;
142
- relationOptions[`shared:${typeName}:${fieldName}`] = await loadRelationOptionList(
143
- field.collection,
144
- config,
145
- cmsRuntime,
146
- defaultLocale,
147
- runtimeContext,
148
- );
149
- }
150
- }
151
-
152
- return relationOptions;
153
- }
122
+ ) => {
123
+ const relatedDocs = await cmsRuntime[collectionSlug].find(
124
+ { status: "any", limit: 100, sort: { field: "_updatedAt", direction: "desc" }, locale: defaultLocale },
125
+ runtimeContext,
126
+ );
127
+ const relatedCollection = config.collections.find((c: any) => c.slug === collectionSlug);
128
+ const labelField = relatedCollection ? getLabelField(relatedCollection) : "title";
129
+ return relatedDocs.map((item: Record<string, unknown>) => ({
130
+ value: String(item._id),
131
+ label: String(item[labelField] ?? item.slug ?? item._id),
132
+ }));
133
+ };
154
134
 
155
135
  export async function loadSharedSectionOptions(
156
136
  config: any,
@@ -262,45 +242,20 @@ export async function loadSharedSectionUsageCounts(
262
242
  return counts;
263
243
  }
264
244
 
265
- export type MenuLinkGroup = {
266
- collection: string;
267
- label: string;
268
- items: Array<{ id: string; label: string; href: string }>;
269
- };
270
-
271
- /** For menu editing: list linkable published documents across content collections. */
272
- export async function loadMenuLinkOptions(
273
- config: any,
274
- user: User,
275
- cmsRuntime: CmsRuntime,
276
- defaultLocale: string,
277
- runtimeContext: RuntimeContext,
278
- ): Promise<MenuLinkGroup[]> {
279
- const linkableCollections = config.collections.filter(
280
- (c: any) =>
281
- !c.singleton &&
282
- !["users", "menus", "taxonomies", "authors"].includes(c.slug) &&
283
- c.fields.slug &&
284
- canRead(config, user, c.slug),
285
- );
286
- const menuLinkOptions: MenuLinkGroup[] = [];
287
- for (const lc of linkableCollections) {
288
- const lcApi = cmsRuntime[lc.slug];
289
- const lcDocs = await lcApi.find(
290
- { status: "published", limit: 200, sort: { field: "_updatedAt", direction: "desc" }, locale: defaultLocale },
291
- runtimeContext,
292
- );
293
- menuLinkOptions.push({
294
- collection: lc.slug,
295
- label: lc.labels.plural,
296
- items: lcDocs.map((d: Record<string, unknown>) => ({
297
- id: String(d._id),
298
- label: String(d[getLabelField(lc)] ?? d.slug ?? d._id),
299
- href: cmsRuntime.meta.getRouteForDocument(lc.slug, d),
300
- })),
301
- });
302
- }
303
- return menuLinkOptions;
245
+ export type LinkableCollection = { collection: string; label: string };
246
+
247
+ /** Collections whose documents an internal link may point at. The picker
248
+ * searches them on the server; nothing is preloaded. */
249
+ export function loadLinkableCollections(config: any, user: User): LinkableCollection[] {
250
+ return config.collections
251
+ .filter(
252
+ (c: any) =>
253
+ !c.singleton &&
254
+ !["users", "menus", "taxonomies", "authors"].includes(c.slug) &&
255
+ c.fields.slug &&
256
+ canRead(config, user, c.slug),
257
+ )
258
+ .map((c: any) => ({ collection: c.slug, label: c.labels.plural }));
304
259
  }
305
260
 
306
261
  export type ReverseRef = {
@@ -0,0 +1,107 @@
1
+ import * as React from "react";
2
+
3
+ /**
4
+ * Debounced document lookup against /api/cms/admin/search, shared by the
5
+ * command palette, relation comboboxes and internal-link pickers so they all
6
+ * behave the same: nothing is preloaded, two characters start a search, and a
7
+ * picker opened without a query shows the most recently updated documents.
8
+ */
9
+ export type DocumentHit = {
10
+ collection: string;
11
+ collectionLabel: string;
12
+ docId: string;
13
+ title: string;
14
+ editUrl: string;
15
+ href: string | null;
16
+ status: string | null;
17
+ };
18
+
19
+ export const MIN_QUERY_LENGTH = 2;
20
+ export const DEBOUNCE_MS = 200;
21
+
22
+ type Params = { q?: string; collections?: string[]; ids?: string[]; limit?: number };
23
+
24
+ const searchUrl = ({ q, collections, ids, limit }: Params) => {
25
+ const params = new URLSearchParams();
26
+ if (q) params.set("q", q);
27
+ if (collections?.length) params.set("collection", collections.join(","));
28
+ if (ids?.length) params.set("ids", ids.join(","));
29
+ if (limit) params.set("limit", String(limit));
30
+ return `/api/cms/admin/search?${params.toString()}`;
31
+ };
32
+
33
+ export async function fetchDocuments(params: Params, signal?: AbortSignal): Promise<DocumentHit[]> {
34
+ const res = await fetch(searchUrl(params), { signal, credentials: "same-origin" });
35
+ if (!res.ok) return [];
36
+ const data = (await res.json()) as { results?: DocumentHit[] };
37
+ return Array.isArray(data.results) ? data.results : [];
38
+ }
39
+
40
+ type Options = {
41
+ /** Target collections. Omit for the palette (every collection). */
42
+ collections?: string[];
43
+ limit?: number;
44
+ /** Fetch the most recent documents when the query is empty (pickers). Off for the palette. */
45
+ recentWhenEmpty?: boolean;
46
+ /** Only fetch while true, e.g. while the popover is open. */
47
+ enabled?: boolean;
48
+ };
49
+
50
+ export function useDocumentSearch({ collections, limit, recentWhenEmpty = false, enabled = true }: Options = {}) {
51
+ const [query, setQueryState] = React.useState("");
52
+ // Last completed fetch, tagged with the request it answers — `loading` is
53
+ // derived from the tag mismatch so it's true from the first keystroke.
54
+ const [fetched, setFetched] = React.useState<{ key: string; hits: DocumentHit[] } | null>(null);
55
+
56
+ const trimmed = query.trim();
57
+ const tooShort = trimmed.length > 0 && trimmed.length < MIN_QUERY_LENGTH;
58
+ const shouldFetch = enabled && (trimmed.length >= MIN_QUERY_LENGTH || (recentWhenEmpty && trimmed.length === 0));
59
+ const fetchKey = JSON.stringify([trimmed, collections ?? [], limit ?? null]);
60
+
61
+ // Clearing happens in the event handler, never synchronously inside the
62
+ // effect, so a keystroke that drops below the minimum drops stale results.
63
+ const setQuery = React.useCallback(
64
+ (next: string) => {
65
+ setQueryState(next);
66
+ const t = next.trim();
67
+ if (t.length < MIN_QUERY_LENGTH && !(recentWhenEmpty && t.length === 0)) setFetched(null);
68
+ },
69
+ [recentWhenEmpty],
70
+ );
71
+
72
+ React.useEffect(() => {
73
+ if (!shouldFetch) return;
74
+ const controller = new AbortController();
75
+ const timer = setTimeout(
76
+ async () => {
77
+ try {
78
+ const hits = await fetchDocuments({ q: trimmed, collections, limit }, controller.signal);
79
+ setFetched({ key: fetchKey, hits });
80
+ } catch (err) {
81
+ if ((err as { name?: string })?.name !== "AbortError") setFetched({ key: fetchKey, hits: [] });
82
+ }
83
+ },
84
+ trimmed ? DEBOUNCE_MS : 0,
85
+ );
86
+ return () => {
87
+ controller.abort();
88
+ clearTimeout(timer);
89
+ };
90
+ // `fetchKey` encodes trimmed + collections identity + limit.
91
+ // eslint-disable-next-line react-hooks/exhaustive-deps
92
+ }, [fetchKey, shouldFetch]);
93
+
94
+ const reset = React.useCallback(() => {
95
+ setQueryState("");
96
+ setFetched(null);
97
+ }, []);
98
+
99
+ return {
100
+ query,
101
+ setQuery,
102
+ results: fetched?.hits ?? [],
103
+ loading: shouldFetch && fetched?.key !== fetchKey,
104
+ tooShort,
105
+ reset,
106
+ };
107
+ }
@@ -32,11 +32,11 @@ import {
32
32
  } from "../lib/access";
33
33
  import {
34
34
  loadDocument,
35
- loadMenuLinkOptions,
35
+ loadLinkableCollections,
36
36
  loadParentFormTitle,
37
- loadRelationOptions,
37
+ loadRelationLabels,
38
+ loadRelationMeta,
38
39
  loadReverseRefs,
39
- loadSharedBlockRelationOptions,
40
40
  loadSharedSectionOptions,
41
41
  } from "../lib/edit-data";
42
42
  import EditScripts from "./edit/EditScripts.astro";
@@ -96,8 +96,12 @@ if (mode === "edit" && documentId) {
96
96
  }
97
97
  }
98
98
 
99
- const { relationOptionsByField, relationMetaByField } = await loadRelationOptions(
99
+ const relationMetaByField = loadRelationMeta(collection, config, user);
100
+ // Seed labels for the ids this document already points at, so relation fields
101
+ // render named selections immediately instead of resolving them client-side.
102
+ const relationLabelsByField = await loadRelationLabels(
100
103
  collection,
104
+ doc,
101
105
  config,
102
106
  user,
103
107
  cmsRuntime,
@@ -105,13 +109,10 @@ const { relationOptionsByField, relationMetaByField } = await loadRelationOption
105
109
  runtimeContext,
106
110
  );
107
111
  const sharedBlockTypes = getSharedBlockTypes(config);
108
- const [sharedBlockRelationOptions, sharedSectionOptions] = await Promise.all([
109
- loadSharedBlockRelationOptions(config, user, cmsRuntime, defaultLocale, runtimeContext),
110
- loadSharedSectionOptions(config, user, cmsRuntime, defaultLocale, runtimeContext),
111
- ]);
112
- // Loaded for every collection: menu trees and any link field (standalone or
113
- // inside blocks) offer the same internal-document picker.
114
- const menuLinkOptions = await loadMenuLinkOptions(config, user, cmsRuntime, defaultLocale, runtimeContext);
112
+ const sharedSectionOptions = await loadSharedSectionOptions(config, user, cmsRuntime, defaultLocale, runtimeContext);
113
+ // Menu trees and any link field (standalone or inside blocks) share the same
114
+ // internal-document picker; it searches these collections on the server.
115
+ const linkableCollections = loadLinkableCollections(config, user);
115
116
  const reverseRefs =
116
117
  mode === "edit" && documentId
117
118
  ? await loadReverseRefs(collection, documentId, config, user, cmsRuntime, defaultLocale, runtimeContext)
@@ -180,10 +181,6 @@ const previewUrl = hasPreview
180
181
 
181
182
  const getCurrentValue = (fieldName: string) => (doc ? doc[fieldName] : undefined);
182
183
  const getSharedValue = (fieldName: string) => (baseDoc ? baseDoc[fieldName] : undefined);
183
- const blockRelationOptions: Record<string, Array<{ value: string; label: string }>> = {};
184
- for (const [key, opts] of Object.entries(relationOptionsByField)) {
185
- if (key.startsWith("block:")) blockRelationOptions[key] = opts;
186
- }
187
184
 
188
185
  // Editorial collaboration UI — shown only for collections in the collaboration
189
186
  // list, and only on normal document edits (not submissions or the translation form).
@@ -384,7 +381,7 @@ const publishBlocked =
384
381
  }
385
382
  {
386
383
  showCollab && collabData && documentId && (
387
- <div class="-mt-6 mb-8 lg:-ml-12">
384
+ <div class="-mt-6 mb-8 2xl:-mx-8">
388
385
  <CollaborationReviewBar
389
386
  client:load
390
387
  collection={collection.slug}
@@ -491,12 +488,10 @@ const publishBlocked =
491
488
  field={collection.fields[fieldName]}
492
489
  value={getCurrentValue(fieldName)}
493
490
  readOnly={isFieldReadOnly(fieldName)}
494
- relationOptions={relationOptionsByField[fieldName] ?? []}
495
491
  relationMeta={relationMetaByField[fieldName]}
496
- menuLinkOptions={menuLinkOptions}
497
- blockRelationOptions={blockRelationOptions}
492
+ relationOptions={relationLabelsByField[fieldName] ?? []}
493
+ linkableCollections={linkableCollections}
498
494
  sharedBlockTypes={sharedBlockTypes}
499
- sharedBlockRelationOptions={sharedBlockRelationOptions}
500
495
  sharedSectionOptions={sharedSectionOptions}
501
496
  />
502
497
  );
@@ -565,12 +560,10 @@ const publishBlocked =
565
560
  field={collection.fields[fieldName]}
566
561
  value={getCurrentValue(fieldName)}
567
562
  readOnly={isFieldReadOnly(fieldName)}
568
- relationOptions={relationOptionsByField[fieldName] ?? []}
569
563
  relationMeta={relationMetaByField[fieldName]}
570
- menuLinkOptions={menuLinkOptions}
571
- blockRelationOptions={blockRelationOptions}
564
+ relationOptions={relationLabelsByField[fieldName] ?? []}
565
+ linkableCollections={linkableCollections}
572
566
  sharedBlockTypes={sharedBlockTypes}
573
- sharedBlockRelationOptions={sharedBlockRelationOptions}
574
567
  sharedSectionOptions={sharedSectionOptions}
575
568
  />
576
569
  {aiEnabled && fieldName === "seoDescription" && !isFieldReadOnly(fieldName) && (
@@ -679,12 +672,10 @@ const publishBlocked =
679
672
  field={fieldDef}
680
673
  value={getCurrentValue(fieldName)}
681
674
  readOnly={isFieldReadOnly(fieldName)}
682
- relationOptions={relationOptionsByField[fieldName] ?? []}
683
675
  relationMeta={relationMetaByField[fieldName]}
684
- menuLinkOptions={menuLinkOptions}
685
- blockRelationOptions={blockRelationOptions}
676
+ relationOptions={relationLabelsByField[fieldName] ?? []}
677
+ linkableCollections={linkableCollections}
686
678
  sharedBlockTypes={sharedBlockTypes}
687
- sharedBlockRelationOptions={sharedBlockRelationOptions}
688
679
  sharedSectionOptions={sharedSectionOptions}
689
680
  />
690
681
  {aiEnabled &&
@@ -158,7 +158,9 @@ const formatColumnValue = (column: string, entry: Record<string, unknown>, pageP
158
158
  if (column === "_status") return getVisualStatus(entry);
159
159
  if (column === "__usage") return `${sharedSectionUsageCounts[String(entry._id)] ?? 0} places`;
160
160
  if (column === "__page") return formatPagePath(pagePath);
161
- if (column === "_updatedAt" || column === "_createdAt") return formatDate(entry[column]);
161
+ // Timestamps and any `date` field render with the admin date settings, not as raw ISO strings.
162
+ if (column === "_updatedAt" || column === "_createdAt" || collection.fields[column]?.type === "date")
163
+ return formatDate(entry[column]);
162
164
  if (column.startsWith("_")) return String(entry[column] ?? "—");
163
165
  return formatFieldValue(collection.fields[column], entry[column], relationLabels);
164
166
  };
@@ -0,0 +1,100 @@
1
+ ---
2
+ import DocumentsDataTable from "../components/DocumentsDataTable";
3
+ import config from "virtual:kide/config";
4
+ import { cms } from "virtual:kide/api";
5
+ import { collaboration } from "virtual:kide/runtime";
6
+ import { formatDate, getLabelField, isApprover, resolveCollaboration } from "../../core";
7
+ import { canRead, getVisualStatus } from "../lib/access";
8
+ import { REVIEW_STATE_META, eligibleCollabSlugs, loadNeedsYou } from "../lib/collaboration";
9
+
10
+ const user = Astro.locals.user;
11
+ const runtimeContext = user ? { user } : {};
12
+ const cmsRuntime = cms as Record<string, any>;
13
+ const defaultLocale = config.locales?.default ?? "en";
14
+
15
+ const eligible = eligibleCollabSlugs(config, user, resolveCollaboration, canRead);
16
+ const approver = isApprover(config, user?.role);
17
+
18
+ const items = user
19
+ ? await loadNeedsYou({ collaboration, userId: String(user.id), isApprover: approver, eligibleSlugs: eligible })
20
+ : [];
21
+
22
+ // Hydrate each queued document. A row whose document is gone is skipped rather
23
+ // than rendered as a broken link.
24
+ type Hydrated = { item: (typeof items)[number]; doc: Record<string, unknown>; collection: any };
25
+ const hydrated: Hydrated[] = [];
26
+ for (const item of items) {
27
+ const collection = config.collections.find((c: any) => c.slug === item.collectionSlug);
28
+ const api = cmsRuntime[item.collectionSlug];
29
+ if (!collection || !api) continue;
30
+ const doc = await api
31
+ .findById(item.documentId, { status: "any", locale: defaultLocale }, runtimeContext)
32
+ .catch(() => null);
33
+ if (!doc) continue;
34
+ hydrated.push({ item, doc, collection });
35
+ }
36
+
37
+ hydrated.sort((a, b) => String(b.doc._updatedAt ?? "").localeCompare(String(a.doc._updatedAt ?? "")));
38
+
39
+ const rows = hydrated.map(({ item, doc, collection }) => {
40
+ const displayTitle = collection.singleton
41
+ ? collection.labels.singular
42
+ : String(doc[getLabelField(collection)] ?? doc.slug ?? collection.labels.singular);
43
+
44
+ return {
45
+ id: `${item.collectionSlug}:${item.documentId}`,
46
+ editHref: `/admin/${item.collectionSlug}/${item.documentId}`,
47
+ status: collection.drafts ? getVisualStatus(doc) : "",
48
+ singleton: collection.singleton,
49
+ locales: [defaultLocale],
50
+ searchText: displayTitle,
51
+ values: {
52
+ title: displayTitle,
53
+ collection: collection.labels.singular,
54
+ _review: REVIEW_STATE_META[item.reviewState].label,
55
+ _reason: item.reason === "assigned" ? "Assigned to you" : "Waiting for your review",
56
+ _updatedAt: formatDate(doc._updatedAt),
57
+ },
58
+ };
59
+ });
60
+ ---
61
+
62
+ <section class="space-y-6 px-4 py-6 lg:py-8 lg:pr-8 lg:pl-12">
63
+ <div class="flex items-start justify-between gap-4">
64
+ <div>
65
+ <h1 class="text-2xl font-semibold tracking-tight">Needs you</h1>
66
+ <p class="text-muted-foreground mt-1 text-sm">
67
+ {
68
+ approver
69
+ ? "Documents assigned to you, and anything submitted for review."
70
+ : "Documents assigned to you that still need work."
71
+ }
72
+ </p>
73
+ </div>
74
+ </div>
75
+ {
76
+ rows.length === 0 ? (
77
+ <div class="text-muted-foreground rounded-lg border border-dashed px-6 py-12 text-center text-sm">
78
+ Nothing needs you right now.
79
+ </div>
80
+ ) : (
81
+ <DocumentsDataTable
82
+ client:load
83
+ collectionSlug="needs-you"
84
+ draftsEnabled={true}
85
+ duplicateEnabled={false}
86
+ showLocalesColumn={false}
87
+ title="Needs you"
88
+ columns={[
89
+ { key: "title", label: "Title" },
90
+ { key: "collection", label: "Collection" },
91
+ { key: "_reason", label: "Why" },
92
+ { key: "_review", label: "Review" },
93
+ { key: "_updatedAt", label: "Updated" },
94
+ ]}
95
+ data={rows}
96
+ searchPlaceholder="Filter…"
97
+ />
98
+ )
99
+ }
100
+ </section>
@@ -1,8 +1,9 @@
1
1
  ---
2
+ import { desc } from "drizzle-orm";
2
3
  import DocumentsDataTable from "../components/DocumentsDataTable";
3
4
  import config from "virtual:kide/config";
4
5
  import { cms } from "virtual:kide/api";
5
- import { formatDate, getLabelField, getTranslatableFieldNames } from "../../core";
6
+ import { formatDate, getDb, getLabelField, getSchema, getTranslatableFieldNames } from "../../core";
6
7
  import { canRead, getVisualStatus } from "../lib/access";
7
8
 
8
9
  const user = Astro.locals.user;
@@ -10,28 +11,50 @@ const runtimeContext = user ? { user } : {};
10
11
  const cmsRuntime = cms as Record<string, any>;
11
12
  const defaultLocale = config.locales?.default ?? "en";
12
13
  const locales = config.locales?.supported ?? [];
14
+ const RECENT_LIMIT = 50;
13
15
 
16
+ // Bulk/system collections hidden from the sidebar (redirects, logs, …) are not
17
+ // "recent work" either — and they tend to be the biggest tables.
14
18
  const pinnedSlugs = new Set(["taxonomies", "menus", "authors", "users"]);
15
19
  const contentCollections = config.collections.filter(
16
- (c) => !c.auth && !pinnedSlugs.has(c.slug) && canRead(config, user, c.slug),
20
+ (c) => !c.auth && !pinnedSlugs.has(c.slug) && c.admin?.sidebar !== false && canRead(config, user, c.slug),
17
21
  );
18
22
  // Same rule as ListView: a Locales column is only meaningful with more than one
19
23
  // locale and at least one of the mixed-in collections having translatable fields.
20
24
  const showLocalesColumn =
21
25
  locales.length > 1 && contentCollections.some((cc) => getTranslatableFieldNames(cc).length > 0);
22
26
 
23
- const allEntries: Array<{ doc: Record<string, unknown>; collection: (typeof contentCollections)[0] }> = [];
27
+ // Two passes so the page cost stays flat as content grows:
28
+ // 1. one tiny (_id, _updatedAt) query per collection — index-backed, no JSON
29
+ // 2. load only the 50 winning documents through the API (access rules,
30
+ // translations, published snapshot) instead of 50 × N full documents.
31
+ const db = await getDb();
32
+ const schema = getSchema();
33
+ const candidates: Array<{ id: string; updatedAt: string; collection: (typeof contentCollections)[0] }> = [];
24
34
  for (const cc of contentCollections) {
25
- const api = cmsRuntime[cc.slug];
26
- const docs = await api.find(
27
- { status: "any", locale: defaultLocale, sort: { field: "_updatedAt", direction: "desc" }, limit: 50 },
35
+ const table = (schema.cmsTables as Record<string, { main: any }>)[cc.slug]?.main;
36
+ if (!table?._updatedAt) continue;
37
+ const rows = (await db
38
+ .select({ id: table._id, updatedAt: table._updatedAt })
39
+ .from(table)
40
+ .orderBy(desc(table._updatedAt))
41
+ .limit(RECENT_LIMIT)) as Array<{ id: string; updatedAt: string }>;
42
+ for (const row of rows)
43
+ candidates.push({ id: String(row.id), updatedAt: String(row.updatedAt ?? ""), collection: cc });
44
+ }
45
+ candidates.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
46
+
47
+ const allEntries: Array<{ doc: Record<string, unknown>; collection: (typeof contentCollections)[0] }> = [];
48
+ for (const candidate of candidates.slice(0, RECENT_LIMIT)) {
49
+ // find() (not findById) so per-document read rules apply exactly as in ListView.
50
+ const [doc] = await cmsRuntime[candidate.collection.slug].find(
51
+ { where: { _id: candidate.id }, status: "any", locale: defaultLocale, limit: 1 },
28
52
  runtimeContext,
29
53
  );
30
- for (const doc of docs) allEntries.push({ doc, collection: cc });
54
+ if (doc) allEntries.push({ doc, collection: candidate.collection });
31
55
  }
32
- allEntries.sort((a, b) => String(b.doc._updatedAt ?? "").localeCompare(String(a.doc._updatedAt ?? "")));
33
56
 
34
- const recentRows = allEntries.slice(0, 50).map(({ doc, collection: cc }) => {
57
+ const recentRows = allEntries.map(({ doc, collection: cc }) => {
35
58
  const displayTitle = cc.singleton
36
59
  ? cc.labels.singular
37
60
  : String(doc[getLabelField(cc)] ?? doc.slug ?? cc.labels.singular);