@kidecms/core 0.25.1 → 0.26.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/admin-base.css +5 -0
- package/admin/components/ContentEditor.tsx +36 -11
- package/admin/components/DocumentCombobox.tsx +53 -11
- package/admin/components/DocumentsDataTable.tsx +5 -6
- package/admin/components/EditorImage.tsx +134 -0
- package/admin/components/RelationField.tsx +2 -1
- package/admin/components/RichTextEditor.tsx +23 -13
- package/admin/components/block-fields.tsx +2 -1
- package/admin/components/slash-command.tsx +29 -5
- package/admin/lib/edit-data.ts +12 -8
- package/admin/lib/editor-commands.ts +23 -0
- package/admin/lib/use-document-search.ts +17 -8
- package/admin/views/EditView.astro +63 -24
- package/admin/views/ListView.astro +1 -6
- package/admin/views/RecentView.astro +1 -6
- package/admin/views/SinglesView.astro +3 -6
- package/core/api.ts +67 -4
- package/core/generator.ts +12 -2
- package/core/migrate.ts +24 -5
- package/core/values.ts +3 -1
- package/internals/mcp-worker.ts +5 -5
- package/internals/mcp.ts +3 -1
- package/package.json +1 -1
- package/routes/api/[collection]/[...path].ts +1 -1
- package/routes/api/admin/search.ts +11 -3
package/admin/lib/edit-data.ts
CHANGED
|
@@ -14,6 +14,10 @@ type CollectionLike = { slug: string; fields: Record<string, any> };
|
|
|
14
14
|
type LoadedDocument = {
|
|
15
15
|
doc: Record<string, unknown> | null;
|
|
16
16
|
baseDoc: Record<string, unknown> | null;
|
|
17
|
+
/** Locale the base row is written in — the tab that edits the document itself. */
|
|
18
|
+
baseLocale: string;
|
|
19
|
+
/** The locale actually shown: the request's, else the base locale. */
|
|
20
|
+
locale: string;
|
|
17
21
|
versions: Array<{ version: number; createdAt: string }>;
|
|
18
22
|
};
|
|
19
23
|
|
|
@@ -21,18 +25,18 @@ type LoadedDocument = {
|
|
|
21
25
|
export async function loadDocument(
|
|
22
26
|
collectionApi: any,
|
|
23
27
|
documentId: string,
|
|
24
|
-
requestedLocale: string,
|
|
28
|
+
requestedLocale: string | null,
|
|
25
29
|
defaultLocale: string,
|
|
26
30
|
runtimeContext: RuntimeContext,
|
|
27
31
|
): Promise<LoadedDocument> {
|
|
28
|
-
const
|
|
29
|
-
if (!
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
const base = await collectionApi.findById(documentId, { status: "any" }, runtimeContext);
|
|
33
|
+
if (!base) return { doc: null, baseDoc: null, baseLocale: defaultLocale, locale: defaultLocale, versions: [] };
|
|
34
|
+
const baseLocale = String(base._sourceLocale ?? defaultLocale);
|
|
35
|
+
const locale = requestedLocale ?? baseLocale;
|
|
36
|
+
const doc =
|
|
37
|
+
locale === baseLocale ? base : await collectionApi.findById(documentId, { status: "any", locale }, runtimeContext);
|
|
34
38
|
const versions = await collectionApi.versions(documentId, runtimeContext);
|
|
35
|
-
return { doc, baseDoc, versions };
|
|
39
|
+
return { doc, baseDoc: base, baseLocale, locale, versions };
|
|
36
40
|
}
|
|
37
41
|
|
|
38
42
|
export type RelationMeta = {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Editor } from "@tiptap/core";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Headings are already bold; a bold mark carried over from the paragraph would
|
|
5
|
+
* render heavier than the rest of the line. Toggle the heading, then clear bold
|
|
6
|
+
* across every heading the selection touches (the Bold button is disabled inside
|
|
7
|
+
* headings, so this is the only way a mark could get in).
|
|
8
|
+
*/
|
|
9
|
+
export const toggleHeading = (editor: Editor, level: 2 | 3) =>
|
|
10
|
+
editor
|
|
11
|
+
.chain()
|
|
12
|
+
.focus()
|
|
13
|
+
.toggleHeading({ level })
|
|
14
|
+
.command(({ tr, state }) => {
|
|
15
|
+
const bold = state.schema.marks.bold;
|
|
16
|
+
if (!bold) return true;
|
|
17
|
+
const { from, to } = tr.selection;
|
|
18
|
+
tr.doc.nodesBetween(from, to, (node, pos) => {
|
|
19
|
+
if (node.type.name === "heading") tr.removeMark(pos, pos + node.nodeSize, bold);
|
|
20
|
+
});
|
|
21
|
+
return true;
|
|
22
|
+
})
|
|
23
|
+
.run();
|
|
@@ -30,11 +30,17 @@ const searchUrl = ({ q, collections, ids, limit }: Params) => {
|
|
|
30
30
|
return `/api/cms/admin/search?${params.toString()}`;
|
|
31
31
|
};
|
|
32
32
|
|
|
33
|
-
export
|
|
33
|
+
export type DocumentPage = { hits: DocumentHit[]; hasMore: boolean };
|
|
34
|
+
|
|
35
|
+
export async function fetchDocumentPage(params: Params, signal?: AbortSignal): Promise<DocumentPage> {
|
|
34
36
|
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 : [];
|
|
37
|
+
if (!res.ok) return { hits: [], hasMore: false };
|
|
38
|
+
const data = (await res.json()) as { results?: DocumentHit[]; hasMore?: boolean };
|
|
39
|
+
return { hits: Array.isArray(data.results) ? data.results : [], hasMore: data.hasMore === true };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function fetchDocuments(params: Params, signal?: AbortSignal): Promise<DocumentHit[]> {
|
|
43
|
+
return (await fetchDocumentPage(params, signal)).hits;
|
|
38
44
|
}
|
|
39
45
|
|
|
40
46
|
type Options = {
|
|
@@ -51,7 +57,7 @@ export function useDocumentSearch({ collections, limit, recentWhenEmpty = false,
|
|
|
51
57
|
const [query, setQueryState] = React.useState("");
|
|
52
58
|
// Last completed fetch, tagged with the request it answers — `loading` is
|
|
53
59
|
// derived from the tag mismatch so it's true from the first keystroke.
|
|
54
|
-
const [fetched, setFetched] = React.useState<{ key: string
|
|
60
|
+
const [fetched, setFetched] = React.useState<({ key: string } & DocumentPage) | null>(null);
|
|
55
61
|
|
|
56
62
|
const trimmed = query.trim();
|
|
57
63
|
const tooShort = trimmed.length > 0 && trimmed.length < MIN_QUERY_LENGTH;
|
|
@@ -75,10 +81,11 @@ export function useDocumentSearch({ collections, limit, recentWhenEmpty = false,
|
|
|
75
81
|
const timer = setTimeout(
|
|
76
82
|
async () => {
|
|
77
83
|
try {
|
|
78
|
-
const
|
|
79
|
-
setFetched({ key: fetchKey,
|
|
84
|
+
const page = await fetchDocumentPage({ q: trimmed, collections, limit }, controller.signal);
|
|
85
|
+
setFetched({ key: fetchKey, ...page });
|
|
80
86
|
} catch (err) {
|
|
81
|
-
if ((err as { name?: string })?.name !== "AbortError")
|
|
87
|
+
if ((err as { name?: string })?.name !== "AbortError")
|
|
88
|
+
setFetched({ key: fetchKey, hits: [], hasMore: false });
|
|
82
89
|
}
|
|
83
90
|
},
|
|
84
91
|
trimmed ? DEBOUNCE_MS : 0,
|
|
@@ -100,6 +107,8 @@ export function useDocumentSearch({ collections, limit, recentWhenEmpty = false,
|
|
|
100
107
|
query,
|
|
101
108
|
setQuery,
|
|
102
109
|
results: fetched?.hits ?? [],
|
|
110
|
+
/** The server cut the list at `limit` — more documents match than are shown. */
|
|
111
|
+
hasMore: fetched?.hasMore ?? false,
|
|
103
112
|
loading: shouldFetch && fetched?.key !== fetchKey,
|
|
104
113
|
tooShort,
|
|
105
114
|
reset,
|
|
@@ -9,6 +9,7 @@ import DocumentLock from "../components/DocumentLock";
|
|
|
9
9
|
import LiveHeading from "../components/LiveHeading";
|
|
10
10
|
import UnsavedGuard from "../components/UnsavedGuard";
|
|
11
11
|
import FieldControl from "../components/FieldControl.astro";
|
|
12
|
+
import SelectField from "../components/SelectField";
|
|
12
13
|
import { StatusBadge } from "../components/ui/badge";
|
|
13
14
|
import { buttonVariants } from "../components/ui/button";
|
|
14
15
|
import config from "virtual:kide/config";
|
|
@@ -72,7 +73,7 @@ const runtimeContext = user ? { user } : {};
|
|
|
72
73
|
const cmsRuntime = cms as Record<string, any> & { meta: typeof cms.meta };
|
|
73
74
|
const locales = config.locales?.supported ?? [];
|
|
74
75
|
const defaultLocale = config.locales?.default ?? "en";
|
|
75
|
-
const requestedLocale = Astro.url.searchParams.get("locale")
|
|
76
|
+
const requestedLocale = Astro.url.searchParams.get("locale");
|
|
76
77
|
const aiEnabled = isAiEnabled();
|
|
77
78
|
const collectionApi = cmsRuntime[collection.slug];
|
|
78
79
|
const isSingleton = collection.singleton === true;
|
|
@@ -84,12 +85,18 @@ const isFieldReadOnly = (fieldName: string) => isFieldReadOnlyFn(collection, use
|
|
|
84
85
|
let doc: Record<string, unknown> | null = null;
|
|
85
86
|
let baseDoc: Record<string, unknown> | null = null;
|
|
86
87
|
let versions: Array<{ version: number; createdAt: string }> = [];
|
|
88
|
+
// The locale the base row is written in (`_sourceLocale`); its tab edits the
|
|
89
|
+
// document itself, every other tab edits a translation overlay.
|
|
90
|
+
let baseLocale = defaultLocale;
|
|
91
|
+
let selectedLocale = requestedLocale ?? defaultLocale;
|
|
87
92
|
if (mode === "edit" && documentId) {
|
|
88
93
|
try {
|
|
89
94
|
const loaded = await loadDocument(collectionApi, documentId, requestedLocale, defaultLocale, runtimeContext);
|
|
90
95
|
if (!loaded.doc) return Astro.redirect(`/admin/${collection.slug}`);
|
|
91
96
|
doc = loaded.doc;
|
|
92
97
|
baseDoc = loaded.baseDoc;
|
|
98
|
+
baseLocale = loaded.baseLocale;
|
|
99
|
+
selectedLocale = loaded.locale;
|
|
93
100
|
versions = loaded.versions;
|
|
94
101
|
} catch {
|
|
95
102
|
return Astro.redirect(`/admin/${collection.slug}?_toast=error&_msg=Access+denied`);
|
|
@@ -145,11 +152,15 @@ const formatSubmissionValue = (value: unknown): string => {
|
|
|
145
152
|
};
|
|
146
153
|
|
|
147
154
|
// --- Layout / derived state ---
|
|
148
|
-
const selectedLocale = mode === "new" ? defaultLocale : requestedLocale;
|
|
149
155
|
const translatableFields = Object.entries(collection.fields)
|
|
150
156
|
.filter(([, field]: [string, any]) => field.translatable)
|
|
151
157
|
.map(([fieldName]) => fieldName);
|
|
152
|
-
const
|
|
158
|
+
const hasLocales = locales.length > 1 && translatableFields.length > 0;
|
|
159
|
+
const translationMode = mode === "edit" && hasLocales && selectedLocale !== baseLocale;
|
|
160
|
+
// Locales the document exists in: its content language plus every saved translation.
|
|
161
|
+
const availableLocales = new Set(
|
|
162
|
+
Array.isArray(baseDoc?._availableLocales) ? (baseDoc!._availableLocales as string[]) : [baseLocale],
|
|
163
|
+
);
|
|
153
164
|
const fieldSets = getFieldSets(collection);
|
|
154
165
|
const primaryFieldSets = fieldSets.filter((set: { position?: string }) => set.position !== "sidebar");
|
|
155
166
|
const sidebarFieldSets = fieldSets.filter((set: { position?: string }) => set.position === "sidebar");
|
|
@@ -163,9 +174,11 @@ const hasDocMeta = Boolean(mode === "edit" && doc && collection.drafts);
|
|
|
163
174
|
|
|
164
175
|
// Editable fields that live in the sidebar (slug, category, etc.). The meta
|
|
165
176
|
// group (Referenced by / Info) only draws a top divider when these exist above it.
|
|
166
|
-
const hasSidebarFields =
|
|
167
|
-
|
|
168
|
-
)
|
|
177
|
+
const hasSidebarFields =
|
|
178
|
+
effectiveSidebarFieldSets.some((set) =>
|
|
179
|
+
set.fields.some((fieldName) => collection.fields[fieldName] && !isFieldHidden(fieldName)),
|
|
180
|
+
) ||
|
|
181
|
+
(hasLocales && !translationMode);
|
|
169
182
|
const hasSidebarMeta = reverseRefs.length > 0 || hasDocMeta;
|
|
170
183
|
|
|
171
184
|
// Whether to render the right-hand sidebar column at all (avoids a stray sticky
|
|
@@ -261,22 +274,33 @@ const publishBlocked =
|
|
|
261
274
|
<div class="bg-border mx-1 h-6 w-px" />
|
|
262
275
|
</>
|
|
263
276
|
)}
|
|
264
|
-
{
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
277
|
+
{hasLocales && mode === "edit" && (
|
|
278
|
+
<>
|
|
279
|
+
{locales.map((locale) => (
|
|
280
|
+
<a
|
|
281
|
+
href={`/admin/${collection.slug}/${documentId}?locale=${locale}`}
|
|
282
|
+
title={
|
|
283
|
+
locale === baseLocale
|
|
284
|
+
? "Content language"
|
|
285
|
+
: availableLocales.has(locale)
|
|
286
|
+
? undefined
|
|
287
|
+
: "Not translated yet"
|
|
288
|
+
}
|
|
289
|
+
class:list={[
|
|
290
|
+
buttonVariants({ variant: "outline", size: "sm" }),
|
|
291
|
+
selectedLocale === locale
|
|
292
|
+
? "border-primary/50 bg-background ring-ring/30 font-medium ring-2"
|
|
293
|
+
: availableLocales.has(locale)
|
|
294
|
+
? "text-muted-foreground"
|
|
295
|
+
: "text-muted-foreground/50 border-dashed",
|
|
296
|
+
]}
|
|
297
|
+
>
|
|
298
|
+
{locale.toUpperCase()}
|
|
299
|
+
</a>
|
|
300
|
+
))}
|
|
301
|
+
<div class="bg-border mx-1 h-6 w-px" />
|
|
302
|
+
</>
|
|
303
|
+
)}
|
|
280
304
|
{translationMode ? (
|
|
281
305
|
<button
|
|
282
306
|
class={buttonVariants({ variant: "outline" })}
|
|
@@ -586,6 +610,21 @@ const publishBlocked =
|
|
|
586
610
|
);
|
|
587
611
|
return variant === "record" ? <AdminCard title="Settings">{fields}</AdminCard> : fields;
|
|
588
612
|
})}
|
|
613
|
+
{hasLocales && !translationMode && !isSubmissionView && (
|
|
614
|
+
<div class="grid gap-1.5">
|
|
615
|
+
<label for="_sourceLocale" class="text-foreground/80 text-sm leading-none font-medium">
|
|
616
|
+
Content language
|
|
617
|
+
</label>
|
|
618
|
+
<SelectField
|
|
619
|
+
client:load
|
|
620
|
+
name="_sourceLocale"
|
|
621
|
+
value={baseLocale}
|
|
622
|
+
placeholder="Select a language"
|
|
623
|
+
items={locales.map((locale) => ({ value: locale, label: locale.toUpperCase() }))}
|
|
624
|
+
/>
|
|
625
|
+
<p class="text-muted-foreground text-xs">The language this document is written in.</p>
|
|
626
|
+
</div>
|
|
627
|
+
)}
|
|
589
628
|
{hasSidebarMeta && (
|
|
590
629
|
<div
|
|
591
630
|
class:list={[
|
|
@@ -689,13 +728,13 @@ const publishBlocked =
|
|
|
689
728
|
endpoint="/api/cms/ai/translate"
|
|
690
729
|
payload={{
|
|
691
730
|
text: sourceText,
|
|
692
|
-
sourceLocale:
|
|
731
|
+
sourceLocale: baseLocale,
|
|
693
732
|
targetLocale: selectedLocale,
|
|
694
733
|
fieldName,
|
|
695
734
|
fieldType,
|
|
696
735
|
}}
|
|
697
736
|
targetField={fieldName}
|
|
698
|
-
label={`Translate from ${
|
|
737
|
+
label={`Translate from ${baseLocale.toUpperCase()}`}
|
|
699
738
|
/>
|
|
700
739
|
</div>
|
|
701
740
|
)}
|
|
@@ -171,12 +171,7 @@ const tableRows = docs.map((entry: Record<string, unknown>) => {
|
|
|
171
171
|
id: String(entry._id),
|
|
172
172
|
editHref: `/admin/${collection.slug}/${entry._id}`,
|
|
173
173
|
status: getVisualStatus(entry),
|
|
174
|
-
locales: [
|
|
175
|
-
defaultLocale,
|
|
176
|
-
...(Array.isArray(entry._availableLocales)
|
|
177
|
-
? entry._availableLocales.map((l) => String(l)).filter((l) => l !== defaultLocale)
|
|
178
|
-
: []),
|
|
179
|
-
],
|
|
174
|
+
locales: Array.isArray(entry._availableLocales) ? entry._availableLocales.map((l) => String(l)) : [defaultLocale],
|
|
180
175
|
searchText: String(entry[getLabelField(collection)] ?? entry.slug ?? entry._id ?? ""),
|
|
181
176
|
pageHref: pagePath ? getPageHref(pagePath, !collection.drafts || entry._status === "published") : undefined,
|
|
182
177
|
values: Object.fromEntries(displayColumns.map((column) => [column, formatColumnValue(column, entry, pagePath)])),
|
|
@@ -66,12 +66,7 @@ const recentRows = allEntries.map(({ doc, collection: cc }) => {
|
|
|
66
66
|
editHref: `/admin/${cc.slug}/${doc._id}`,
|
|
67
67
|
status,
|
|
68
68
|
singleton: cc.singleton,
|
|
69
|
-
locales: [
|
|
70
|
-
defaultLocale,
|
|
71
|
-
...(Array.isArray(doc._availableLocales)
|
|
72
|
-
? doc._availableLocales.map((l) => String(l)).filter((l) => l !== defaultLocale)
|
|
73
|
-
: []),
|
|
74
|
-
],
|
|
69
|
+
locales: Array.isArray(doc._availableLocales) ? doc._availableLocales.map((l) => String(l)) : [defaultLocale],
|
|
75
70
|
searchText: displayTitle,
|
|
76
71
|
values: {
|
|
77
72
|
title: displayTitle,
|
|
@@ -36,12 +36,9 @@ const singletonsData = await Promise.all(
|
|
|
36
36
|
label: sc.labels.singular,
|
|
37
37
|
status: singleDoc && sc.drafts ? String(singleDoc._status ?? "draft") : "",
|
|
38
38
|
locales: singleDoc
|
|
39
|
-
?
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
? singleDoc._availableLocales.filter((l: string) => l !== defaultLocale)
|
|
43
|
-
: []),
|
|
44
|
-
]
|
|
39
|
+
? Array.isArray(singleDoc._availableLocales)
|
|
40
|
+
? singleDoc._availableLocales.map((l: string) => String(l))
|
|
41
|
+
: [defaultLocale]
|
|
45
42
|
: [],
|
|
46
43
|
updatedAt: singleDoc ? formatDate(singleDoc._updatedAt) : "—",
|
|
47
44
|
editHref: `/admin/${sc.slug}`,
|
package/core/api.ts
CHANGED
|
@@ -24,6 +24,13 @@ export type FindOptions = {
|
|
|
24
24
|
offset?: number;
|
|
25
25
|
status?: "draft" | "published" | "scheduled" | "any";
|
|
26
26
|
locale?: string;
|
|
27
|
+
/**
|
|
28
|
+
* With `locale`: `"fallback"` (default) returns every document, overlaying the
|
|
29
|
+
* translation when one exists; `"exact"` returns only documents that exist in
|
|
30
|
+
* that locale — their source locale, or a translation row. Use `"exact"` for
|
|
31
|
+
* listings and `"fallback"` for single-document routes.
|
|
32
|
+
*/
|
|
33
|
+
availability?: "fallback" | "exact";
|
|
27
34
|
search?: string;
|
|
28
35
|
};
|
|
29
36
|
|
|
@@ -454,6 +461,23 @@ export const createCms = (config: CMSConfig) => {
|
|
|
454
461
|
const createCollectionApi = (slug: string) => {
|
|
455
462
|
const collection = ensureCollection(config, slug);
|
|
456
463
|
|
|
464
|
+
const supportedLocales = config.locales?.supported ?? [];
|
|
465
|
+
/** Locale the base row is written in; undefined when the project has no locales. */
|
|
466
|
+
const sourceLocaleOf = (doc: Record<string, unknown>): string | undefined =>
|
|
467
|
+
config.locales ? String(doc._sourceLocale ?? config.locales.default) : undefined;
|
|
468
|
+
const resolveSourceLocale = (value: unknown): string => {
|
|
469
|
+
if (value === undefined || value === null || value === "") return config.locales!.default;
|
|
470
|
+
const locale = String(value);
|
|
471
|
+
if (!supportedLocales.includes(locale)) throw new Error(`Locale "${locale}" is not in locales.supported.`);
|
|
472
|
+
return locale;
|
|
473
|
+
};
|
|
474
|
+
/** `availability: "exact"` — the document must exist in the requested locale. */
|
|
475
|
+
const availabilityCondition = (tables: any, options: { locale?: string; availability?: string }) => {
|
|
476
|
+
if (!options.locale || options.availability !== "exact" || !tables.translations || !config.locales) return null;
|
|
477
|
+
const tr = tables.translations;
|
|
478
|
+
return sql`(${tables.main._sourceLocale} = ${options.locale} OR EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale}))`;
|
|
479
|
+
};
|
|
480
|
+
|
|
457
481
|
const overlayLocale = (
|
|
458
482
|
doc: Record<string, unknown>,
|
|
459
483
|
translations: Array<Record<string, unknown>>,
|
|
@@ -461,7 +485,13 @@ export const createCms = (config: CMSConfig) => {
|
|
|
461
485
|
) => {
|
|
462
486
|
const baseDoc = { ...doc };
|
|
463
487
|
const translatableFields = getTranslatableFieldNames(collection);
|
|
464
|
-
const
|
|
488
|
+
const sourceLocale = sourceLocaleOf(doc);
|
|
489
|
+
const availableLocales = [
|
|
490
|
+
...new Set([
|
|
491
|
+
...(sourceLocale ? [sourceLocale] : []),
|
|
492
|
+
...translations.map((translation) => String(translation._languageCode)),
|
|
493
|
+
]),
|
|
494
|
+
];
|
|
465
495
|
|
|
466
496
|
if (locale) {
|
|
467
497
|
const translation = translations.find((entry) => entry._languageCode === locale);
|
|
@@ -563,6 +593,8 @@ export const createCms = (config: CMSConfig) => {
|
|
|
563
593
|
}
|
|
564
594
|
}
|
|
565
595
|
}
|
|
596
|
+
const availability = availabilityCondition(tables, options);
|
|
597
|
+
if (availability) conditions.push(availability);
|
|
566
598
|
|
|
567
599
|
if (options.search?.trim()) {
|
|
568
600
|
const searchTerm = `%${options.search.trim().toLowerCase()}%`;
|
|
@@ -648,13 +680,18 @@ export const createCms = (config: CMSConfig) => {
|
|
|
648
680
|
},
|
|
649
681
|
|
|
650
682
|
async findOne(
|
|
651
|
-
filter: Record<string, unknown> & {
|
|
683
|
+
filter: Record<string, unknown> & {
|
|
684
|
+
locale?: string;
|
|
685
|
+
availability?: FindOptions["availability"];
|
|
686
|
+
status?: FindOptions["status"];
|
|
687
|
+
},
|
|
652
688
|
context: RuntimeContext = {},
|
|
653
689
|
) {
|
|
654
690
|
const docs = await this.find(
|
|
655
691
|
{
|
|
656
|
-
where: pick(filter, Object.keys(collection.fields).concat(["_id", "_status", "slug"])),
|
|
692
|
+
where: pick(filter, Object.keys(collection.fields).concat(["_id", "_status", "slug", "_sourceLocale"])),
|
|
657
693
|
locale: filter.locale,
|
|
694
|
+
availability: filter.availability,
|
|
658
695
|
status: filter.status,
|
|
659
696
|
limit: 1,
|
|
660
697
|
},
|
|
@@ -746,6 +783,7 @@ export const createCms = (config: CMSConfig) => {
|
|
|
746
783
|
docValues._status = status;
|
|
747
784
|
if (status === "published") docValues._publishedAt = createdAt;
|
|
748
785
|
}
|
|
786
|
+
if (tables.translations) docValues._sourceLocale = resolveSourceLocale(data._sourceLocale);
|
|
749
787
|
if (collection.timestamps !== false) {
|
|
750
788
|
docValues._createdAt = createdAt;
|
|
751
789
|
docValues._updatedAt = createdAt;
|
|
@@ -758,7 +796,11 @@ export const createCms = (config: CMSConfig) => {
|
|
|
758
796
|
_id: nanoid(),
|
|
759
797
|
_docId: docId,
|
|
760
798
|
_version: 1,
|
|
761
|
-
_snapshot: JSON.stringify({
|
|
799
|
+
_snapshot: JSON.stringify({
|
|
800
|
+
...transformedInput,
|
|
801
|
+
_status: docValues._status,
|
|
802
|
+
...(tables.translations ? { _sourceLocale: docValues._sourceLocale } : {}),
|
|
803
|
+
}),
|
|
762
804
|
_createdAt: createdAt,
|
|
763
805
|
});
|
|
764
806
|
}
|
|
@@ -844,6 +886,22 @@ export const createCms = (config: CMSConfig) => {
|
|
|
844
886
|
if (collection.timestamps !== false) {
|
|
845
887
|
updateValues._updatedAt = now();
|
|
846
888
|
}
|
|
889
|
+
if (tables.translations && data._sourceLocale !== undefined) {
|
|
890
|
+
const nextSource = resolveSourceLocale(data._sourceLocale);
|
|
891
|
+
if (nextSource !== sourceLocaleOf(existing)) {
|
|
892
|
+
// The base row would then claim a language that a translation row
|
|
893
|
+
// already holds — two texts for one locale. Make the editor pick.
|
|
894
|
+
const clash = await db
|
|
895
|
+
.select({ _id: tables.translations._id })
|
|
896
|
+
.from(tables.translations)
|
|
897
|
+
.where(and(eq(tables.translations._entityId, id), eq(tables.translations._languageCode, nextSource)))
|
|
898
|
+
.limit(1);
|
|
899
|
+
if (clash.length > 0) {
|
|
900
|
+
throw new Error(`Delete the "${nextSource}" translation before making it the content language.`);
|
|
901
|
+
}
|
|
902
|
+
updateValues._sourceLocale = nextSource;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
847
905
|
|
|
848
906
|
// Guarded live via WHERE, not the stale `existing.role` — a role promoted after this
|
|
849
907
|
// row was read but before this statement runs must still be protected.
|
|
@@ -1183,6 +1241,8 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1183
1241
|
}
|
|
1184
1242
|
}
|
|
1185
1243
|
}
|
|
1244
|
+
const availability = availabilityCondition(tables, filter);
|
|
1245
|
+
if (availability) conditions.push(availability);
|
|
1186
1246
|
if (filter.search?.trim()) {
|
|
1187
1247
|
const searchTerm = `%${filter.search.trim().toLowerCase()}%`;
|
|
1188
1248
|
const searchableTypes = new Set(["text", "slug", "email", "select"]);
|
|
@@ -1286,6 +1346,9 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1286
1346
|
const existing = deserializeFromDb(collection, existingRows[0] as Record<string, unknown>);
|
|
1287
1347
|
const allowed = await canAccess(collection, "update", context, existing);
|
|
1288
1348
|
if (!allowed) throw new Error(`Access denied for ${collection.slug}.`);
|
|
1349
|
+
if (locale === sourceLocaleOf(existing)) {
|
|
1350
|
+
throw new Error(`"${locale}" is this document's content language — edit the document itself.`);
|
|
1351
|
+
}
|
|
1289
1352
|
|
|
1290
1353
|
const translatableFields = getTranslatableFieldNames(collection);
|
|
1291
1354
|
const translatedValues = prepareIncomingData(collection, data, locale, existing);
|
package/core/generator.ts
CHANGED
|
@@ -62,7 +62,7 @@ const generateColumnDef = (fieldName: string, field: FieldConfig, options: { bar
|
|
|
62
62
|
return ` ${fieldName}: ${col},`;
|
|
63
63
|
};
|
|
64
64
|
|
|
65
|
-
const generateMainTable = (collection: CollectionConfig): string => {
|
|
65
|
+
const generateMainTable = (config: CMSConfig, collection: CollectionConfig): string => {
|
|
66
66
|
const tableName = `cms_${snakeCase(collection.slug)}`;
|
|
67
67
|
const varName = `cms${pascalCase(collection.slug)}`;
|
|
68
68
|
const columns: string[] = [` _id: text("_id").primaryKey(),`];
|
|
@@ -71,6 +71,15 @@ const generateMainTable = (collection: CollectionConfig): string => {
|
|
|
71
71
|
columns.push(generateColumnDef(fieldName, field));
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
// The language the base row is written in. A document exists in this locale
|
|
75
|
+
// plus every locale it has a translation row for; the default keeps existing
|
|
76
|
+
// rows on today's "base row = default locale" behaviour.
|
|
77
|
+
if (config.locales && getTranslatableFieldNames(collection).length > 0) {
|
|
78
|
+
columns.push(
|
|
79
|
+
` _sourceLocale: text("_source_locale").notNull().default(${JSON.stringify(config.locales.default)}),`,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
74
83
|
if (collection.drafts) {
|
|
75
84
|
columns.push(` _status: text("_status").notNull().default("draft"),`);
|
|
76
85
|
columns.push(` _publishedAt: text("_published_at"),`);
|
|
@@ -151,7 +160,7 @@ const generateSchemaFile = (config: CMSConfig): string => {
|
|
|
151
160
|
];
|
|
152
161
|
|
|
153
162
|
for (const collection of config.collections) {
|
|
154
|
-
parts.push(generateMainTable(collection));
|
|
163
|
+
parts.push(generateMainTable(config, collection));
|
|
155
164
|
const translationsTable = generateTranslationsTable(config, collection);
|
|
156
165
|
if (translationsTable) parts.push("", translationsTable);
|
|
157
166
|
const versionsTable = generateVersionsTable(collection);
|
|
@@ -456,6 +465,7 @@ const generateTypesFile = (config: CMSConfig, coreImportPath: string): string =>
|
|
|
456
465
|
_createdAt: string;
|
|
457
466
|
_updatedAt: string;
|
|
458
467
|
_locale?: string | null;
|
|
468
|
+
_sourceLocale?: string;
|
|
459
469
|
_availableLocales?: string[];
|
|
460
470
|
};`);
|
|
461
471
|
parts.push("");
|
package/core/migrate.ts
CHANGED
|
@@ -187,12 +187,24 @@ const validateContent = (
|
|
|
187
187
|
};
|
|
188
188
|
|
|
189
189
|
/** Validate a document's fields against its collection schema. */
|
|
190
|
-
export const validateDocument = (
|
|
190
|
+
export const validateDocument = (
|
|
191
|
+
collection: CollectionConfig,
|
|
192
|
+
data: Record<string, unknown>,
|
|
193
|
+
config?: CMSConfig,
|
|
194
|
+
): ValidationResult => {
|
|
191
195
|
const errors: ValidationIssue[] = [];
|
|
192
196
|
const warnings: ValidationIssue[] = [];
|
|
193
197
|
for (const [name, field] of Object.entries(collection.fields)) {
|
|
194
198
|
validateField(name, field, data[name], errors, warnings);
|
|
195
199
|
}
|
|
200
|
+
if (data._sourceLocale !== undefined && data._sourceLocale !== null && data._sourceLocale !== "") {
|
|
201
|
+
const locale = String(data._sourceLocale);
|
|
202
|
+
if (!config?.locales) errors.push({ field: "_sourceLocale", message: "no locales configured" });
|
|
203
|
+
else if (!config.locales.supported.includes(locale))
|
|
204
|
+
errors.push({ field: "_sourceLocale", message: `'${locale}' is not in locales.supported` });
|
|
205
|
+
else if (getTranslatableFieldNames(collection).length === 0)
|
|
206
|
+
warnings.push({ field: "_sourceLocale", message: "collection has no translatable fields (ignored)" });
|
|
207
|
+
}
|
|
196
208
|
for (const key of Object.keys(data)) {
|
|
197
209
|
if (key.startsWith("_")) continue;
|
|
198
210
|
if (!(key in collection.fields)) warnings.push({ field: key, message: "not a declared field (will be ignored)" });
|
|
@@ -209,6 +221,7 @@ export const validateTranslations = (
|
|
|
209
221
|
config: CMSConfig,
|
|
210
222
|
collection: CollectionConfig,
|
|
211
223
|
translations: Record<string, Record<string, unknown>> | undefined,
|
|
224
|
+
sourceLocale?: unknown,
|
|
212
225
|
): ValidationResult => {
|
|
213
226
|
const errors: ValidationIssue[] = [];
|
|
214
227
|
const warnings: ValidationIssue[] = [];
|
|
@@ -226,10 +239,11 @@ export const validateTranslations = (
|
|
|
226
239
|
return { ok: false, errors, warnings };
|
|
227
240
|
}
|
|
228
241
|
|
|
242
|
+
const base = sourceLocale ? String(sourceLocale) : config.locales.default;
|
|
229
243
|
for (const locale of locales) {
|
|
230
244
|
const prefix = `translations.${locale}`;
|
|
231
|
-
if (locale ===
|
|
232
|
-
errors.push({ field: prefix, message: `'${locale}' is the
|
|
245
|
+
if (locale === base) {
|
|
246
|
+
errors.push({ field: prefix, message: `'${locale}' is the document's content language — put it in \`data\`` });
|
|
233
247
|
continue;
|
|
234
248
|
}
|
|
235
249
|
if (!config.locales.supported.includes(locale)) {
|
|
@@ -328,8 +342,8 @@ export const importDocuments = async (
|
|
|
328
342
|
report.failed++;
|
|
329
343
|
continue;
|
|
330
344
|
}
|
|
331
|
-
const doc = validateDocument(collection, item.data);
|
|
332
|
-
const i18n = validateTranslations(config, collection, item.translations);
|
|
345
|
+
const doc = validateDocument(collection, item.data, config);
|
|
346
|
+
const i18n = validateTranslations(config, collection, item.translations, item.data._sourceLocale);
|
|
333
347
|
const warnings = [...doc.warnings, ...i18n.warnings];
|
|
334
348
|
const errors = [...doc.errors, ...i18n.errors];
|
|
335
349
|
if (warnings.length) report.warnings.push({ collection: item.collection, id, warnings });
|
|
@@ -396,6 +410,11 @@ export const renderModelMarkdown = (config: CMSConfig): string => {
|
|
|
396
410
|
out.push("> The **i18n** column is `yes` only for fields declared `translatable: true`. Only those");
|
|
397
411
|
out.push("> fields accept per-locale values (`translations` in an import item, `upsertTranslation`);");
|
|
398
412
|
out.push("> everything else is base-locale only. A collection with no `yes` has no translation table.");
|
|
413
|
+
out.push(`> Every document has \`_sourceLocale\` — the language its base row is written in (default`);
|
|
414
|
+
out.push(`> \`${model.locales.default}\`). A document exists in its source locale plus every locale it has a`);
|
|
415
|
+
out.push(
|
|
416
|
+
"> translation for; content that only exists in one language is a base doc in that language with no overlay.",
|
|
417
|
+
);
|
|
399
418
|
out.push("");
|
|
400
419
|
|
|
401
420
|
out.push("## Field types");
|
package/core/values.ts
CHANGED
|
@@ -211,7 +211,9 @@ const walkBlocks = (el: HtmlEl, out: RichTextNode[]): void => {
|
|
|
211
211
|
const leaves = inlineChildren(child.children);
|
|
212
212
|
if (meaningful(leaves)) out.push({ type: "paragraph", children: leaves });
|
|
213
213
|
} else if (/^h[1-6]$/.test(tag)) {
|
|
214
|
-
|
|
214
|
+
// Headings render bold already; a <strong> inside one (WordPress does this)
|
|
215
|
+
// would only leave the editor's Bold toggle lit for no visible reason.
|
|
216
|
+
const leaves = inlineChildren(child.children).map(({ bold: _bold, ...leaf }) => leaf);
|
|
215
217
|
if (meaningful(leaves)) out.push({ type: "heading", level: Number(tag[1]), children: leaves });
|
|
216
218
|
} else if (tag === "ul" || tag === "ol") {
|
|
217
219
|
const items = child.children
|
package/internals/mcp-worker.ts
CHANGED
|
@@ -77,19 +77,19 @@ const ops: Record<string, (args: OpArgs) => unknown> = {
|
|
|
77
77
|
|
|
78
78
|
describeCollection: ({ collection }) => collectionModel(collection),
|
|
79
79
|
|
|
80
|
-
listDocuments: async ({ collection, where, search, sort, limit, offset, status, locale }) => {
|
|
80
|
+
listDocuments: async ({ collection, where, search, sort, limit, offset, status, locale, availability }) => {
|
|
81
81
|
const collectionApi = getCollectionApi(collection);
|
|
82
|
-
const options = { where, search, sort, limit, offset, status, locale };
|
|
82
|
+
const options = { where, search, sort, limit, offset, status, locale, availability };
|
|
83
83
|
const [docs, totalDocs] = await Promise.all([
|
|
84
84
|
collectionApi.find(options, runtimeContext()),
|
|
85
|
-
collectionApi.count({ where, search, status, locale }, runtimeContext()),
|
|
85
|
+
collectionApi.count({ where, search, status, locale, availability }, runtimeContext()),
|
|
86
86
|
]);
|
|
87
87
|
return { docs, totalDocs, limit, offset };
|
|
88
88
|
},
|
|
89
89
|
|
|
90
|
-
countDocuments: async ({ collection, where, search, status, locale }) => {
|
|
90
|
+
countDocuments: async ({ collection, where, search, status, locale, availability }) => {
|
|
91
91
|
const collectionApi = getCollectionApi(collection);
|
|
92
|
-
const totalDocs = await collectionApi.count({ where, search, status, locale }, runtimeContext());
|
|
92
|
+
const totalDocs = await collectionApi.count({ where, search, status, locale, availability }, runtimeContext());
|
|
93
93
|
return { totalDocs };
|
|
94
94
|
},
|
|
95
95
|
|
package/internals/mcp.ts
CHANGED
|
@@ -199,7 +199,7 @@ server.registerTool(
|
|
|
199
199
|
{
|
|
200
200
|
title: "List documents",
|
|
201
201
|
description:
|
|
202
|
-
"List documents in a collection with optional filters, search, sort, locale, status, limit, and offset.",
|
|
202
|
+
"List documents in a collection with optional filters, search, sort, locale, status, limit, and offset. With locale, availability 'exact' lists only documents that exist in that locale (their _sourceLocale or a translation); the default 'fallback' lists every document.",
|
|
203
203
|
inputSchema: {
|
|
204
204
|
collection: z.string().min(1),
|
|
205
205
|
where: jsonObjectSchema.optional(),
|
|
@@ -209,6 +209,7 @@ server.registerTool(
|
|
|
209
209
|
offset: z.number().int().min(0).default(0),
|
|
210
210
|
status: statusSchema.optional(),
|
|
211
211
|
locale: z.string().min(1).optional(),
|
|
212
|
+
availability: z.enum(["fallback", "exact"]).optional(),
|
|
212
213
|
},
|
|
213
214
|
},
|
|
214
215
|
async (args) => toResult(await workerCall("listDocuments", args)),
|
|
@@ -225,6 +226,7 @@ server.registerTool(
|
|
|
225
226
|
search: z.string().optional(),
|
|
226
227
|
status: statusSchema.optional(),
|
|
227
228
|
locale: z.string().min(1).optional(),
|
|
229
|
+
availability: z.enum(["fallback", "exact"]).optional(),
|
|
228
230
|
},
|
|
229
231
|
},
|
|
230
232
|
async (args) => toResult(await workerCall("countDocuments", args)),
|