@kidecms/core 0.24.0 → 0.25.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.
@@ -41,13 +41,17 @@ export default function ColorField({ name, value: initial, placeholder, colors =
41
41
  onChange?.(v);
42
42
  };
43
43
 
44
- const selected = colors.find((c) => c.value.toLowerCase() === value.trim().toLowerCase());
44
+ // A stored value outside the palette (imported content, a palette edit) must stay
45
+ // visible and re-selectable rather than collapsing into the empty placeholder.
46
+ const known = colors.find((c) => c.value.toLowerCase() === value.trim().toLowerCase());
47
+ const options = value && !known ? [{ label: "Custom", value }, ...colors] : colors;
48
+ const selected = known ?? options.find((c) => c.value === value);
45
49
 
46
50
  return (
47
51
  <div className="relative">
48
52
  {name && <input type="hidden" name={name} value={value} ref={hiddenRef} />}
49
53
 
50
- <Select items={colors} value={value} onValueChange={(v) => set((v as string) ?? "")}>
54
+ <Select items={options} value={value} onValueChange={(v) => set((v as string) ?? "")}>
51
55
  <SelectTrigger className={cn("w-full", value && "pr-14")}>
52
56
  {selected ? (
53
57
  <span className="flex flex-1 items-center gap-2">
@@ -61,7 +65,7 @@ export default function ColorField({ name, value: initial, placeholder, colors =
61
65
  </SelectTrigger>
62
66
  <SelectContent>
63
67
  <SelectGroup>
64
- {colors.map((c) => (
68
+ {options.map((c) => (
65
69
  <SelectItem key={c.value} value={c.value}>
66
70
  <Swatch color={c.value} />
67
71
  <span className="flex-1">{c.label}</span>
@@ -357,7 +357,7 @@ const ToolbarButton = ({
357
357
  title={title}
358
358
  className={cn(
359
359
  "disabled:hover:text-muted-foreground inline-flex size-8 items-center justify-center rounded-md transition-colors outline-none disabled:opacity-50 disabled:hover:bg-transparent",
360
- active ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-muted-strong hover:text-foreground",
360
+ active ? "bg-foreground/10 text-foreground" : "text-muted-foreground hover:bg-muted-strong hover:text-foreground",
361
361
  )}
362
362
  >
363
363
  {children}
@@ -183,7 +183,7 @@ const ToolbarButton = ({
183
183
  className={cn(
184
184
  "disabled:hover:text-muted-foreground inline-flex size-8 items-center justify-center rounded-md transition-colors outline-none disabled:opacity-50 disabled:hover:bg-transparent",
185
185
  active
186
- ? "bg-muted-strong text-accent-foreground"
186
+ ? "bg-foreground/10 text-foreground"
187
187
  : "text-muted-foreground hover:bg-muted-strong hover:text-foreground",
188
188
  )}
189
189
  >
@@ -35,7 +35,8 @@ export const FIELD_MODEL: Record<string, FieldModelEntry> = {
35
35
  select: { storage: "text", control: "dropdown", valueShape: "string (one of `options`)" },
36
36
  color: {
37
37
  storage: "text",
38
- control: "colour swatch picker (brand palette + custom + hex)",
38
+ control:
39
+ "colour swatch picker — palette from admin.colors (or per-field colors); no free hex entry, off-palette values show as 'Custom'",
39
40
  valueShape: "hex string e.g. '#00BB5F' (empty string = inherit default)",
40
41
  },
41
42
  richText: {
package/core/migrate.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * (internals/describe.ts) and `createCmsContext` (internals/context.ts).
7
7
  */
8
8
  import type { CMSConfig, CollectionConfig, FieldConfig } from "./define";
9
+ import { getTranslatableFieldNames } from "./define";
9
10
  import { describeModel, FIELD_MODEL, CONTENT_AST_SCHEMA } from "./field-model";
10
11
 
11
12
  export type ValidationIssue = { field: string; message: string };
@@ -58,12 +59,70 @@ const validateField = (
58
59
  case "content":
59
60
  validateContent(name, field, value, errors, warnings);
60
61
  break;
62
+ case "json":
63
+ if (field.itemFields && Array.isArray(value)) validateRows(name, field.itemFields, value, warnings);
64
+ break;
65
+ case "blocks":
66
+ if (!Array.isArray(value)) errors.push({ field: name, message: "blocks expects an array" });
67
+ else validateBlockList(name, field.types, value, warnings);
68
+ break;
61
69
  case "date":
62
70
  if (Number.isNaN(Date.parse(String(value)))) warnings.push({ field: name, message: "date is not parseable" });
63
71
  break;
64
72
  }
65
73
  };
66
74
 
75
+ /**
76
+ * Nested shapes (inline/standalone block fields, repeater rows) are stored as
77
+ * the importer wrote them — the API does not re-validate them on save. Check
78
+ * them anyway so a wrong key surfaces in the report instead of as raw JSON in
79
+ * the editor, but as warnings: the top-level document still counts as valid.
80
+ */
81
+ const validateShape = (
82
+ prefix: string,
83
+ declared: Record<string, FieldConfig>,
84
+ value: Record<string, unknown>,
85
+ warnings: ValidationIssue[],
86
+ ) => {
87
+ const nested: ValidationIssue[] = [];
88
+ for (const [key, sub] of Object.entries(declared)) validateField(`${prefix}.${key}`, sub, value[key], nested, nested);
89
+ for (const key of Object.keys(value)) {
90
+ if (!(key in declared)) nested.push({ field: `${prefix}.${key}`, message: "not a declared field" });
91
+ }
92
+ warnings.push(...nested);
93
+ };
94
+
95
+ const validateRows = (
96
+ name: string,
97
+ itemFields: Record<string, FieldConfig>,
98
+ rows: unknown[],
99
+ warnings: ValidationIssue[],
100
+ ) => {
101
+ rows.forEach((row, i) => {
102
+ if (!row || typeof row !== "object" || Array.isArray(row)) {
103
+ warnings.push({ field: `${name}[${i}]`, message: "repeater row expects an object" });
104
+ return;
105
+ }
106
+ validateShape(`${name}[${i}]`, itemFields, row as Record<string, unknown>, warnings);
107
+ });
108
+ };
109
+
110
+ const validateBlockList = (
111
+ name: string,
112
+ types: Record<string, Record<string, FieldConfig>>,
113
+ blocks: unknown[],
114
+ warnings: ValidationIssue[],
115
+ ) => {
116
+ blocks.forEach((block, i) => {
117
+ const { type, ...fields } = (block ?? {}) as { type?: string } & Record<string, unknown>;
118
+ if (!type || !(type in types)) {
119
+ warnings.push({ field: `${name}[${i}]`, message: `block type '${type}' is not declared in this field's types` });
120
+ return;
121
+ }
122
+ validateShape(`${name}[${i}]<${type}>`, types[type], fields, warnings);
123
+ });
124
+ };
125
+
67
126
  const validateContent = (
68
127
  name: string,
69
128
  field: Extract<FieldConfig, { type: "content" }>,
@@ -75,15 +134,20 @@ const validateContent = (
75
134
  errors.push({ field: name, message: "content expects { type:'root', children:[…] }" });
76
135
  return;
77
136
  }
78
- const declared = new Set(Object.keys(field.blocks ?? {}));
79
- for (const node of (value as { children?: Array<{ type?: string; blockType?: string }> }).children ?? []) {
80
- if (node?.type === "block" && node.blockType && !declared.has(node.blockType)) {
137
+ const declared = field.blocks ?? {};
138
+ const children = (value as { children?: Array<{ type?: string; blockType?: string; fields?: unknown }> }).children;
139
+ (children ?? []).forEach((node, i) => {
140
+ if (node?.type !== "block" || !node.blockType) return;
141
+ if (!(node.blockType in declared)) {
81
142
  warnings.push({
82
143
  field: name,
83
144
  message: `inline block '${node.blockType}' is not declared in this field's blocks`,
84
145
  });
146
+ return;
85
147
  }
86
- }
148
+ const fields = node.fields && typeof node.fields === "object" ? (node.fields as Record<string, unknown>) : {};
149
+ validateShape(`${name}[${i}]<${node.blockType}>`, declared[node.blockType], fields, warnings);
150
+ });
87
151
  };
88
152
 
89
153
  /** Validate a document's fields against its collection schema. */
@@ -100,6 +164,61 @@ export const validateDocument = (collection: CollectionConfig, data: Record<stri
100
164
  return { ok: errors.length === 0, errors, warnings };
101
165
  };
102
166
 
167
+ /**
168
+ * Validate an import item's per-locale overlays. Translation tables only exist
169
+ * for fields marked `translatable: true`, and `upsertTranslation` silently drops
170
+ * everything else — so catch both here, before the base document is written.
171
+ */
172
+ export const validateTranslations = (
173
+ config: CMSConfig,
174
+ collection: CollectionConfig,
175
+ translations: Record<string, Record<string, unknown>> | undefined,
176
+ ): ValidationResult => {
177
+ const errors: ValidationIssue[] = [];
178
+ const warnings: ValidationIssue[] = [];
179
+ const locales = Object.keys(translations ?? {});
180
+ if (locales.length === 0) return { ok: true, errors, warnings };
181
+
182
+ const translatable = new Set(getTranslatableFieldNames(collection));
183
+ if (!config.locales || translatable.size === 0) {
184
+ errors.push({
185
+ field: "translations",
186
+ message: !config.locales
187
+ ? "no locales configured (set `locales` in cms.config.ts)"
188
+ : `collection has no translatable fields (mark them \`translatable: true\`, then cms:generate + cms:push)`,
189
+ });
190
+ return { ok: false, errors, warnings };
191
+ }
192
+
193
+ for (const locale of locales) {
194
+ const prefix = `translations.${locale}`;
195
+ if (locale === config.locales.default) {
196
+ errors.push({ field: prefix, message: `'${locale}' is the default locale — put it in \`data\`` });
197
+ continue;
198
+ }
199
+ if (!config.locales.supported.includes(locale)) {
200
+ errors.push({ field: prefix, message: `'${locale}' is not in locales.supported` });
201
+ continue;
202
+ }
203
+ const overlay = translations![locale] ?? {};
204
+ const keys = Object.keys(overlay).filter((k) => !k.startsWith("_"));
205
+ const kept = keys.filter((k) => translatable.has(k));
206
+ for (const key of keys) {
207
+ if (!translatable.has(key))
208
+ warnings.push({ field: `${prefix}.${key}`, message: "not a translatable field (will be dropped)" });
209
+ }
210
+ if (keys.length && kept.length === 0) {
211
+ errors.push({
212
+ field: prefix,
213
+ message: "none of these fields are translatable — the whole translation would be dropped",
214
+ });
215
+ continue;
216
+ }
217
+ for (const key of kept) validateField(`${prefix}.${key}`, collection.fields[key], overlay[key], errors, warnings);
218
+ }
219
+ return { ok: errors.length === 0, errors, warnings };
220
+ };
221
+
103
222
  // ---------------------------------------------------------------------------
104
223
  // Batch loader (import IR → CMS) with dry-run + validation report.
105
224
  // ---------------------------------------------------------------------------
@@ -173,10 +292,13 @@ export const importDocuments = async (
173
292
  report.failed++;
174
293
  continue;
175
294
  }
176
- const result = validateDocument(collection, item.data);
177
- if (result.warnings.length) report.warnings.push({ collection: item.collection, id, warnings: result.warnings });
178
- if (!result.ok) {
179
- report.invalid.push({ collection: item.collection, id, errors: result.errors });
295
+ const doc = validateDocument(collection, item.data);
296
+ const i18n = validateTranslations(config, collection, item.translations);
297
+ const warnings = [...doc.warnings, ...i18n.warnings];
298
+ const errors = [...doc.errors, ...i18n.errors];
299
+ if (warnings.length) report.warnings.push({ collection: item.collection, id, warnings });
300
+ if (errors.length) {
301
+ report.invalid.push({ collection: item.collection, id, errors });
180
302
  report.failed++;
181
303
  continue;
182
304
  }
@@ -235,6 +357,10 @@ export const renderModelMarkdown = (config: CMSConfig): string => {
235
357
  out.push("");
236
358
  out.push(`**Locales:** default \`${model.locales.default}\`, supported \`${model.locales.supported.join(", ")}\``);
237
359
  out.push("");
360
+ out.push("> The **i18n** column is `yes` only for fields declared `translatable: true`. Only those");
361
+ out.push("> fields accept per-locale values (`translations` in an import item, `upsertTranslation`);");
362
+ out.push("> everything else is base-locale only. A collection with no `yes` has no translation table.");
363
+ out.push("");
238
364
 
239
365
  out.push("## Field types");
240
366
  out.push("");
@@ -252,8 +378,9 @@ export const renderModelMarkdown = (config: CMSConfig): string => {
252
378
  out.push(`root: ${CONTENT_AST_SCHEMA.root}`);
253
379
  for (const [k, v] of Object.entries(CONTENT_AST_SCHEMA.nodes)) out.push(` ${k}: ${v}`);
254
380
  out.push("```");
255
- out.push("> A `content` field stores any `{type:'root'}` doc as-is — inline block `fields` are not");
256
- out.push("> validated. Build prose with `htmlToRichText(html)`; declare `blocks` for the editor.");
381
+ out.push("> A `content` field stores any `{type:'root'}` doc as-is — the API does not check inline");
382
+ out.push("> block `fields` on save, but `load({ dryRun: true })` reports mismatches as warnings.");
383
+ out.push("> Build prose with `htmlToRichText(html)`; declare `blocks` for the editor.");
257
384
  out.push("");
258
385
 
259
386
  for (const collection of model.collections) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",