@kidecms/core 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/admin/components/BlockEditor.tsx +3 -12
- package/admin/components/CommandPalette.tsx +19 -72
- package/admin/components/ContentEditor.tsx +4 -10
- package/admin/components/DocumentCombobox.tsx +171 -0
- package/admin/components/FieldControl.astro +16 -32
- package/admin/components/InternalLinkPicker.tsx +30 -62
- package/admin/components/LinkField.tsx +6 -5
- package/admin/components/RelationField.tsx +32 -58
- package/admin/components/RepeaterInput.tsx +3 -6
- package/admin/components/SharedSectionBlockField.tsx +2 -6
- package/admin/components/TreeItemsEditor.tsx +4 -4
- package/admin/components/TreeSelect.tsx +33 -19
- package/admin/components/block-fields.tsx +21 -50
- package/admin/components/content-block-spec.ts +5 -6
- package/admin/lib/edit-data.ts +84 -129
- package/admin/lib/use-document-search.ts +107 -0
- package/admin/views/EditView.astro +18 -27
- package/admin/views/ListView.astro +3 -1
- package/admin/views/RecentView.astro +32 -9
- package/core/generator.ts +7 -1
- package/package.json +1 -1
- package/routes/api/admin/search.ts +102 -45
package/admin/lib/edit-data.ts
CHANGED
|
@@ -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
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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
|
-
/**
|
|
71
|
-
|
|
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<
|
|
79
|
-
const
|
|
80
|
-
|
|
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
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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
|
|
111
|
+
return labelsByField;
|
|
127
112
|
}
|
|
128
113
|
|
|
129
|
-
|
|
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
|
-
)
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
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
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
):
|
|
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
|
-
|
|
35
|
+
loadLinkableCollections,
|
|
36
36
|
loadParentFormTitle,
|
|
37
|
-
|
|
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
|
|
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
|
|
109
|
-
|
|
110
|
-
|
|
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).
|
|
@@ -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
|
-
|
|
497
|
-
|
|
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
|
-
|
|
571
|
-
|
|
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
|
-
|
|
685
|
-
|
|
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
|
-
|
|
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
|
};
|
|
@@ -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
|
-
|
|
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
|
|
26
|
-
|
|
27
|
-
|
|
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
|
-
|
|
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.
|
|
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);
|
package/core/generator.ts
CHANGED
|
@@ -84,11 +84,17 @@ const generateMainTable = (collection: CollectionConfig): string => {
|
|
|
84
84
|
// cron tick, filtering on _status plus the due timestamp. Without these it is a
|
|
85
85
|
// full table scan per collection, per tick.
|
|
86
86
|
const indexes: string[] = [];
|
|
87
|
+
const idxPrefix = snakeCase(collection.slug);
|
|
87
88
|
if (collection.drafts) {
|
|
88
|
-
const idxPrefix = snakeCase(collection.slug);
|
|
89
89
|
indexes.push(` publishIdx: index("${idxPrefix}_publish_idx").on(table._status, table._publishAt),`);
|
|
90
90
|
indexes.push(` unpublishIdx: index("${idxPrefix}_unpublish_idx").on(table._status, table._unpublishAt),`);
|
|
91
91
|
}
|
|
92
|
+
// The admin lists, the Recent view and most editorial listings sort by
|
|
93
|
+
// _updatedAt; without an index each of them is a full scan plus a temp
|
|
94
|
+
// sort per collection, per request — noticeable from a few thousand rows.
|
|
95
|
+
if (collection.timestamps !== false) {
|
|
96
|
+
indexes.push(` updatedIdx: index("${idxPrefix}_updated_idx").on(table._updatedAt),`);
|
|
97
|
+
}
|
|
92
98
|
|
|
93
99
|
const body = `{\n${columns.join("\n")}\n}`;
|
|
94
100
|
if (indexes.length === 0) return `export const ${varName} = sqliteTable("${tableName}", ${body});`;
|