@kidecms/core 0.1.11 → 0.14.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 (180) hide show
  1. package/LICENSE +21 -0
  2. package/admin/components/AssetsGrid.tsx +366 -173
  3. package/admin/components/BlockEditor.tsx +260 -679
  4. package/admin/components/CheckboxField.tsx +2 -2
  5. package/admin/components/CollaborationReviewBar.tsx +384 -0
  6. package/admin/components/ColorField.tsx +87 -0
  7. package/admin/components/CommandPalette.tsx +169 -0
  8. package/admin/components/ContentEditor.tsx +687 -0
  9. package/admin/components/DocumentActions.tsx +4 -2
  10. package/admin/components/DocumentsDataTable.tsx +91 -10
  11. package/admin/components/FieldControl.astro +151 -26
  12. package/admin/components/FocalPointSelector.tsx +27 -1
  13. package/admin/components/InternalLinkPicker.tsx +4 -3
  14. package/admin/components/LinkField.tsx +126 -0
  15. package/admin/components/RelationField.tsx +105 -26
  16. package/admin/components/RepeaterInput.tsx +46 -0
  17. package/admin/components/RichTextEditor.tsx +44 -9
  18. package/admin/components/SharedSectionBlockField.tsx +93 -0
  19. package/admin/components/SidebarUserMenu.tsx +1 -1
  20. package/admin/components/Toast.astro +1 -1
  21. package/admin/components/TreeItemsEditor.tsx +20 -19
  22. package/admin/components/TreeSelect.tsx +2 -2
  23. package/admin/components/YoutubeField.tsx +48 -0
  24. package/admin/components/block-fields.tsx +777 -0
  25. package/admin/components/content-block-spec.ts +114 -0
  26. package/admin/components/slash-command.tsx +242 -0
  27. package/admin/components/tree-utils.ts +14 -2
  28. package/admin/components/ui/badge.tsx +2 -3
  29. package/admin/components/ui/button.tsx +5 -4
  30. package/admin/components/ui/checkbox.tsx +1 -1
  31. package/admin/components/ui/input.tsx +1 -1
  32. package/admin/components/ui/select.tsx +1 -1
  33. package/admin/components/ui/table.tsx +1 -1
  34. package/admin/components/ui/textarea.tsx +1 -1
  35. package/admin/layouts/AdminLayout.astro +323 -123
  36. package/admin/lib/access.ts +54 -0
  37. package/admin/lib/collaboration.ts +178 -0
  38. package/admin/lib/edit-data.ts +448 -0
  39. package/admin/views/AccessDeniedView.astro +8 -0
  40. package/admin/views/EditView.astro +706 -0
  41. package/admin/views/ListView.astro +202 -0
  42. package/admin/views/RecentView.astro +76 -0
  43. package/admin/views/SinglesView.astro +65 -0
  44. package/admin/views/edit/EditScripts.astro +145 -0
  45. package/admin/views/edit/ReverseReferencesList.astro +68 -0
  46. package/core/admin.ts +193 -0
  47. package/core/ai.ts +87 -0
  48. package/core/api.ts +1392 -0
  49. package/core/assets.ts +336 -0
  50. package/core/audit.ts +86 -0
  51. package/core/auth-config.ts +44 -0
  52. package/core/auth.ts +303 -0
  53. package/core/collaboration.ts +276 -0
  54. package/core/content.ts +27 -0
  55. package/core/create-admin.ts +28 -0
  56. package/core/define.ts +623 -0
  57. package/core/field-model.ts +172 -0
  58. package/core/generator.ts +519 -0
  59. package/core/http.ts +42 -0
  60. package/core/image.ts +219 -0
  61. package/core/index.ts +211 -0
  62. package/core/locks.ts +52 -0
  63. package/core/log.ts +37 -0
  64. package/core/migrate.ts +278 -0
  65. package/core/rate-limit.ts +110 -0
  66. package/core/request-scope.ts +33 -0
  67. package/core/richtext.ts +1 -0
  68. package/core/runtime.ts +63 -0
  69. package/core/schema.ts +32 -0
  70. package/core/search.ts +489 -0
  71. package/core/seed.ts +101 -0
  72. package/core/shared-sections.ts +96 -0
  73. package/core/tasks.ts +176 -0
  74. package/core/values.ts +433 -0
  75. package/core/webhooks.ts +85 -0
  76. package/core/youtube.ts +39 -0
  77. package/internals/cli.mjs +34 -0
  78. package/internals/context.ts +67 -0
  79. package/internals/create-admin.ts +40 -0
  80. package/internals/describe.ts +25 -0
  81. package/internals/eject.ts +144 -0
  82. package/internals/generator.ts +11 -0
  83. package/internals/integration.ts +481 -0
  84. package/internals/mcp.ts +397 -0
  85. package/internals/project.ts +31 -0
  86. package/internals/push.ts +160 -0
  87. package/internals/reindex.ts +11 -0
  88. package/internals/restore.ts +257 -0
  89. package/internals/seed.ts +15 -0
  90. package/internals/upgrade.ts +785 -0
  91. package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
  92. package/middleware/auth.ts +130 -17
  93. package/middleware/push.ts +121 -0
  94. package/package.json +55 -67
  95. package/platform/cloudflare/cf-env.ts +60 -0
  96. package/platform/cloudflare/database.ts +28 -0
  97. package/platform/cloudflare/globals.d.ts +5 -0
  98. package/platform/cloudflare/storage.ts +33 -0
  99. package/platform/cloudflare/uploads-route.ts +37 -0
  100. package/platform/node/database.ts +39 -0
  101. package/platform/node/storage.ts +52 -0
  102. package/routes/admin/[...path].astro +71 -0
  103. package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
  104. package/routes/admin/assets/index.astro +90 -0
  105. package/routes/{pages/admin/login.astro → admin/forgot-password.astro} +21 -19
  106. package/routes/{pages/admin → admin}/invite.astro +13 -6
  107. package/routes/admin/login.astro +103 -0
  108. package/routes/admin/reset-password.astro +73 -0
  109. package/routes/{pages/admin → admin}/setup.astro +32 -8
  110. package/routes/api/{cms/[collection] → [collection]}/[...path].ts +67 -15
  111. package/routes/api/admin/search.ts +89 -0
  112. package/routes/api/{cms/assets → assets}/[id].ts +24 -14
  113. package/routes/api/{cms/assets → assets}/index.ts +4 -2
  114. package/routes/api/assets/upload.ts +147 -0
  115. package/routes/api/auth/forgot-password.ts +77 -0
  116. package/routes/api/{cms/auth → auth}/invite.ts +41 -9
  117. package/routes/api/auth/login.ts +167 -0
  118. package/routes/api/{cms/auth → auth}/logout.ts +11 -2
  119. package/routes/api/auth/reset-password.ts +85 -0
  120. package/routes/api/auth/setup.ts +110 -0
  121. package/routes/api/auth/sso/[provider]/start.ts +34 -0
  122. package/routes/api/collaboration/index.ts +106 -0
  123. package/routes/api/cron/_authorize.ts +25 -0
  124. package/routes/api/{cms/cron → cron}/publish.ts +3 -9
  125. package/routes/api/cron/tasks.ts +34 -0
  126. package/routes/api/forms/submit/[slug].ts +143 -0
  127. package/routes/api/img/[...path].ts +65 -0
  128. package/routes/api/{cms/preview → preview}/render.ts +8 -3
  129. package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
  130. package/routes/api/webhooks/[provider].ts +54 -0
  131. package/README.md +0 -28
  132. package/dist/admin.d.ts +0 -33
  133. package/dist/admin.js +0 -92
  134. package/dist/ai.d.ts +0 -15
  135. package/dist/ai.js +0 -70
  136. package/dist/api.d.ts +0 -14
  137. package/dist/api.js +0 -833
  138. package/dist/assets.d.ts +0 -51
  139. package/dist/assets.js +0 -163
  140. package/dist/auth.d.ts +0 -30
  141. package/dist/auth.js +0 -132
  142. package/dist/content.d.ts +0 -3
  143. package/dist/content.js +0 -29
  144. package/dist/create-admin.d.ts +0 -5
  145. package/dist/create-admin.js +0 -23
  146. package/dist/define.d.ts +0 -254
  147. package/dist/define.js +0 -36
  148. package/dist/generator.d.ts +0 -9
  149. package/dist/generator.js +0 -370
  150. package/dist/image.d.ts +0 -9
  151. package/dist/image.js +0 -69
  152. package/dist/index.d.ts +0 -28
  153. package/dist/index.js +0 -16
  154. package/dist/integration.d.ts +0 -14
  155. package/dist/integration.js +0 -327
  156. package/dist/locks.d.ts +0 -7
  157. package/dist/locks.js +0 -37
  158. package/dist/richtext.d.ts +0 -1
  159. package/dist/richtext.js +0 -1
  160. package/dist/runtime.d.ts +0 -24
  161. package/dist/runtime.js +0 -26
  162. package/dist/schema.d.ts +0 -17
  163. package/dist/schema.js +0 -13
  164. package/dist/seed.d.ts +0 -2
  165. package/dist/seed.js +0 -84
  166. package/dist/values.d.ts +0 -8
  167. package/dist/values.js +0 -102
  168. package/dist/webhooks.d.ts +0 -2
  169. package/dist/webhooks.js +0 -73
  170. package/routes/api/cms/assets/upload.ts +0 -112
  171. package/routes/api/cms/auth/login.ts +0 -124
  172. package/routes/api/cms/auth/setup.ts +0 -77
  173. package/routes/api/cms/img/[...path].ts +0 -24
  174. package/routes/pages/admin/[...path].astro +0 -1107
  175. package/routes/pages/admin/assets/index.astro +0 -63
  176. /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
  177. /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
  178. /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
  179. /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
  180. /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
@@ -0,0 +1,777 @@
1
+ "use client";
2
+
3
+ import { useState, useCallback, useEffect, useMemo, useRef } from "react";
4
+ import { GripVertical, ChevronRight, Plus, Trash2 } from "lucide-react";
5
+ import { cn } from "../lib/utils";
6
+ import {
7
+ DndContext,
8
+ closestCenter,
9
+ KeyboardSensor,
10
+ PointerSensor,
11
+ useSensor,
12
+ useSensors,
13
+ type DragEndEvent,
14
+ } from "@dnd-kit/core";
15
+ import { SortableContext, useSortable, verticalListSortingStrategy, arrayMove } from "@dnd-kit/sortable";
16
+ import { CSS } from "@dnd-kit/utilities";
17
+ import { Button } from "./ui/button";
18
+ import { Checkbox } from "./ui/checkbox";
19
+ import { Input } from "./ui/input";
20
+ import { Label } from "./ui/label";
21
+ import { Textarea } from "./ui/textarea";
22
+ import RichTextEditor from "./RichTextEditor";
23
+ import ImagePicker from "./ImagePicker";
24
+ import SelectField from "./SelectField";
25
+ import ColorField from "./ColorField";
26
+ import LinkField from "./LinkField";
27
+ import type { LinkOptionGroup } from "./InternalLinkPicker";
28
+ import YoutubeField from "./YoutubeField";
29
+
30
+ // -----------------------------------------------
31
+ // Shared types — describe a block sub-field. Used by both the standalone
32
+ // `blocks` editor (BlockEditor) and the inline `content` editor (ContentEditor).
33
+ // -----------------------------------------------
34
+
35
+ export type SubFieldMeta = {
36
+ type: string;
37
+ label?: string;
38
+ required?: boolean;
39
+ options?: string[];
40
+ from?: string;
41
+ admin?: { placeholder?: string; rows?: number; help?: string; component?: string };
42
+ defaultValue?: unknown;
43
+ /** Predefined palette for `admin.component === "color"` sub-fields. */
44
+ colors?: { label: string; value: string }[];
45
+ of?: { type: string };
46
+ collection?: string;
47
+ hasMany?: boolean;
48
+ /** Typed repeater row schema (json + admin.component "repeater"). */
49
+ itemFields?: Record<string, SubFieldMeta>;
50
+ };
51
+
52
+ export type BlockTypesMeta = Record<string, Record<string, SubFieldMeta>>;
53
+
54
+ export type RelationOption = { value: string; label: string };
55
+
56
+ export function generateKey() {
57
+ return "blk_" + Math.random().toString(36).slice(2, 9);
58
+ }
59
+
60
+ export function humanize(value: string) {
61
+ return value
62
+ .replace(/^_+/, "")
63
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
64
+ .replace(/[-_]/g, " ")
65
+ .replace(/\s+/g, " ")
66
+ .trim()
67
+ .replace(/^\w/, (char) => char.toUpperCase());
68
+ }
69
+
70
+ /** Build a blank value object for a freshly inserted block of the given type. */
71
+ export function blankBlockFields(fieldsMeta: Record<string, SubFieldMeta>): Record<string, unknown> {
72
+ const out: Record<string, unknown> = {};
73
+ for (const [fieldName, meta] of Object.entries(fieldsMeta)) {
74
+ if (meta.defaultValue !== undefined) out[fieldName] = meta.defaultValue;
75
+ else if (meta.type === "boolean") out[fieldName] = false;
76
+ else if (meta.type === "array") out[fieldName] = [];
77
+ else out[fieldName] = "";
78
+ }
79
+ return out;
80
+ }
81
+
82
+ /** First text-ish field value, truncated — used for collapsed block previews. */
83
+ export function getPreviewText(values: Record<string, unknown>, fieldsMeta: Record<string, SubFieldMeta>): string {
84
+ for (const [key, meta] of Object.entries(fieldsMeta)) {
85
+ if (meta.type === "text" && values[key]) {
86
+ const text = String(values[key]);
87
+ return text.length > 60 ? text.slice(0, 60) + "..." : text;
88
+ }
89
+ }
90
+ return "";
91
+ }
92
+
93
+ // -----------------------------------------------
94
+ // Sub-field label + control wrapper
95
+ // -----------------------------------------------
96
+
97
+ export function SubField({
98
+ blockKey,
99
+ fieldName,
100
+ meta,
101
+ value,
102
+ onChange,
103
+ relationOptions = [],
104
+ linkOptions = [],
105
+ }: {
106
+ blockKey: string;
107
+ fieldName: string;
108
+ meta: SubFieldMeta;
109
+ value: unknown;
110
+ onChange: (value: unknown) => void;
111
+ relationOptions?: RelationOption[];
112
+ linkOptions?: LinkOptionGroup[];
113
+ }) {
114
+ const label = meta.label ?? humanize(fieldName);
115
+ const fieldId = `${blockKey}_${fieldName}`;
116
+
117
+ return (
118
+ <div className="grid gap-2">
119
+ <Label htmlFor={fieldId}>
120
+ {label}
121
+ {meta.required ? " *" : ""}
122
+ </Label>
123
+ {meta.admin?.help && <p className="text-muted-foreground text-xs leading-5">{meta.admin.help}</p>}
124
+ <SubFieldControl
125
+ fieldId={fieldId}
126
+ meta={meta}
127
+ value={value}
128
+ onChange={onChange}
129
+ relationOptions={relationOptions}
130
+ linkOptions={linkOptions}
131
+ />
132
+ </div>
133
+ );
134
+ }
135
+
136
+ function JsonTextarea({
137
+ fieldId,
138
+ rows,
139
+ value,
140
+ fallback,
141
+ onChange,
142
+ }: {
143
+ fieldId: string;
144
+ rows: number;
145
+ value: unknown;
146
+ fallback: unknown;
147
+ onChange: (value: unknown) => void;
148
+ }) {
149
+ const strValue = value == null ? "" : String(value);
150
+ return (
151
+ <Textarea
152
+ id={fieldId}
153
+ rows={rows}
154
+ value={typeof value === "string" ? strValue : JSON.stringify(value ?? fallback, null, 2)}
155
+ onChange={(e) => {
156
+ try {
157
+ onChange(JSON.parse(e.target.value));
158
+ } catch {
159
+ onChange(e.target.value);
160
+ }
161
+ }}
162
+ />
163
+ );
164
+ }
165
+
166
+ function parseSelected(meta: SubFieldMeta, value: unknown): string[] {
167
+ if (!meta.hasMany) return value ? [String(value)] : [];
168
+ if (Array.isArray(value)) return value as string[];
169
+ if (typeof value === "string" && value) {
170
+ try {
171
+ return JSON.parse(value) as string[];
172
+ } catch {
173
+ return [];
174
+ }
175
+ }
176
+ return [];
177
+ }
178
+
179
+ function RelationControl({
180
+ fieldId,
181
+ meta,
182
+ value,
183
+ onChange,
184
+ relationOptions,
185
+ }: {
186
+ fieldId: string;
187
+ meta: SubFieldMeta;
188
+ value: unknown;
189
+ onChange: (value: unknown) => void;
190
+ relationOptions: RelationOption[];
191
+ }) {
192
+ const selected = parseSelected(meta, value);
193
+ const getLabel = (id: string) => relationOptions?.find((o) => o.value === id)?.label ?? id;
194
+ const toggle = (id: string) => {
195
+ if (meta.hasMany) {
196
+ const next = selected.includes(id) ? selected.filter((v) => v !== id) : [...selected, id];
197
+ onChange(next);
198
+ } else {
199
+ onChange(selected[0] === id ? "" : id);
200
+ }
201
+ };
202
+ return (
203
+ <div className="space-y-2">
204
+ {meta.hasMany && selected.length > 0 && (
205
+ <div className="flex flex-wrap gap-1.5">
206
+ {selected.map((id) => (
207
+ <span
208
+ key={id}
209
+ className="bg-card text-secondary-foreground inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-sm"
210
+ >
211
+ {getLabel(id)}
212
+ <button
213
+ type="button"
214
+ onClick={() => toggle(id)}
215
+ className="text-muted-foreground hover:text-foreground -mr-0.5 rounded p-0.5"
216
+ >
217
+ <Trash2 className="size-3" />
218
+ </button>
219
+ </span>
220
+ ))}
221
+ </div>
222
+ )}
223
+ <SelectField
224
+ name={fieldId}
225
+ value={meta.hasMany ? "" : (selected[0] ?? "")}
226
+ placeholder={`Select ${meta.label?.toLowerCase() ?? "item"}...`}
227
+ items={(relationOptions ?? []).map((o) => ({ value: o.value, label: o.label }))}
228
+ onChange={(v) => {
229
+ if (meta.hasMany && v) {
230
+ if (!selected.includes(v)) onChange([...selected, v]);
231
+ } else {
232
+ onChange(v);
233
+ }
234
+ }}
235
+ />
236
+ </div>
237
+ );
238
+ }
239
+
240
+ function ArrayControl({
241
+ fieldId,
242
+ meta,
243
+ value,
244
+ onChange,
245
+ }: {
246
+ fieldId: string;
247
+ meta: SubFieldMeta;
248
+ value: unknown;
249
+ onChange: (value: unknown) => void;
250
+ }) {
251
+ if (meta.of?.type === "image") {
252
+ return <ArrayImageField fieldId={fieldId} value={value} onChange={onChange} />;
253
+ }
254
+ if (meta.of?.type === "text") {
255
+ const items = Array.isArray(value) ? value : [];
256
+ return (
257
+ <Input
258
+ id={fieldId}
259
+ value={items.join(", ")}
260
+ placeholder={meta.admin?.placeholder ?? "item1, item2, item3"}
261
+ onChange={(e) => {
262
+ const parts = e.target.value
263
+ .split(",")
264
+ .map((s: string) => s.trim())
265
+ .filter(Boolean);
266
+ onChange(parts);
267
+ }}
268
+ />
269
+ );
270
+ }
271
+ return (
272
+ <JsonTextarea fieldId={fieldId} rows={meta.admin?.rows ?? 5} value={value} fallback={[]} onChange={onChange} />
273
+ );
274
+ }
275
+
276
+ export function SubFieldControl({
277
+ fieldId,
278
+ meta,
279
+ value,
280
+ onChange,
281
+ relationOptions = [],
282
+ linkOptions = [],
283
+ }: {
284
+ fieldId: string;
285
+ meta: SubFieldMeta;
286
+ value: unknown;
287
+ onChange: (value: unknown) => void;
288
+ relationOptions?: RelationOption[];
289
+ linkOptions?: LinkOptionGroup[];
290
+ }) {
291
+ const strValue = value == null ? "" : String(value);
292
+
293
+ // Colour fields render a palette dropdown regardless of their (text) storage type.
294
+ if (meta.admin?.component === "color") {
295
+ return (
296
+ <ColorField value={strValue} placeholder={meta.admin?.placeholder} colors={meta.colors} onChange={onChange} />
297
+ );
298
+ }
299
+
300
+ // Link fields render a structured URL + label + new-tab control.
301
+ if (meta.admin?.component === "link") {
302
+ return <LinkField value={value as never} onChange={onChange} linkOptions={linkOptions} />;
303
+ }
304
+
305
+ // YouTube fields render a URL input with a thumbnail preview.
306
+ if (meta.admin?.component === "youtube") {
307
+ return <YoutubeField value={strValue} placeholder={meta.admin?.placeholder} onChange={(v) => onChange(v)} />;
308
+ }
309
+
310
+ switch (meta.type) {
311
+ case "text":
312
+ case "email":
313
+ case "date":
314
+ return (
315
+ <Input
316
+ id={fieldId}
317
+ type={meta.type === "email" ? "email" : meta.type === "date" ? "date" : "text"}
318
+ value={strValue}
319
+ placeholder={meta.admin?.placeholder ?? ""}
320
+ required={meta.required}
321
+ onChange={(e) => onChange(e.target.value)}
322
+ />
323
+ );
324
+
325
+ case "number":
326
+ return (
327
+ <Input
328
+ id={fieldId}
329
+ type="number"
330
+ value={strValue}
331
+ required={meta.required}
332
+ onChange={(e) => onChange(e.target.value === "" ? "" : Number(e.target.value))}
333
+ />
334
+ );
335
+
336
+ case "boolean":
337
+ return (
338
+ <label className="group inline-flex cursor-pointer items-center gap-3 text-sm">
339
+ <Checkbox
340
+ id={fieldId}
341
+ className="group-hover:border-primary/60"
342
+ checked={Boolean(value)}
343
+ onCheckedChange={(checked) => onChange(Boolean(checked))}
344
+ />
345
+ <span className="text-muted-foreground select-none">{value ? "true" : "false"}</span>
346
+ </label>
347
+ );
348
+
349
+ case "select":
350
+ return (
351
+ <SelectField
352
+ name={fieldId}
353
+ value={strValue}
354
+ placeholder="Select an option"
355
+ items={(meta.options ?? []).map((o) => ({ value: o, label: o }))}
356
+ onChange={(v) => onChange(v)}
357
+ />
358
+ );
359
+
360
+ case "richText":
361
+ return (
362
+ <RichTextEditor
363
+ name={fieldId}
364
+ initialValue={typeof value === "string" ? strValue : JSON.stringify(value ?? "")}
365
+ rows={meta.admin?.rows ?? 8}
366
+ onChange={(v) => {
367
+ try {
368
+ onChange(JSON.parse(v));
369
+ } catch {
370
+ onChange(v);
371
+ }
372
+ }}
373
+ />
374
+ );
375
+
376
+ case "image":
377
+ return (
378
+ <ImagePicker
379
+ name={fieldId}
380
+ value={strValue}
381
+ placeholder={meta.admin?.placeholder}
382
+ onChange={(v) => onChange(v)}
383
+ />
384
+ );
385
+
386
+ case "relation":
387
+ return (
388
+ <RelationControl
389
+ fieldId={fieldId}
390
+ meta={meta}
391
+ value={value}
392
+ onChange={onChange}
393
+ relationOptions={relationOptions}
394
+ />
395
+ );
396
+
397
+ case "array":
398
+ return <ArrayControl fieldId={fieldId} meta={meta} value={value} onChange={onChange} />;
399
+
400
+ case "json":
401
+ if (meta.admin?.component === "repeater") {
402
+ return (
403
+ <RepeaterField
404
+ blockKey={fieldId}
405
+ itemFields={meta.itemFields}
406
+ relationOptions={relationOptions}
407
+ linkOptions={linkOptions}
408
+ value={value}
409
+ onChange={onChange}
410
+ />
411
+ );
412
+ }
413
+ return (
414
+ <JsonTextarea fieldId={fieldId} rows={meta.admin?.rows ?? 5} value={value} fallback={{}} onChange={onChange} />
415
+ );
416
+
417
+ default:
418
+ return (
419
+ <JsonTextarea fieldId={fieldId} rows={meta.admin?.rows ?? 5} value={value} fallback="" onChange={onChange} />
420
+ );
421
+ }
422
+ }
423
+
424
+ // -----------------------------------------------
425
+ // Repeater (json + admin.component === "repeater")
426
+ // -----------------------------------------------
427
+
428
+ function getRepeaterPreview(item: Record<string, unknown>, fieldKeys: string[]): string {
429
+ for (const key of fieldKeys) {
430
+ const v = item[key];
431
+ if (v == null || v === "" || typeof v === "object") continue;
432
+ const text = String(v);
433
+ if (text) return text.length > 60 ? text.slice(0, 60) + "..." : text;
434
+ }
435
+ return "";
436
+ }
437
+
438
+ function SortableRepeaterItem({
439
+ blockKey,
440
+ item,
441
+ fieldKeys,
442
+ itemFields,
443
+ relationOptions,
444
+ linkOptions,
445
+ index,
446
+ isExpanded,
447
+ autoFocus,
448
+ onAutoFocused,
449
+ onToggle,
450
+ onRemove,
451
+ onUpdate,
452
+ }: {
453
+ blockKey: string;
454
+ item: Record<string, unknown>;
455
+ fieldKeys: string[];
456
+ itemFields?: Record<string, SubFieldMeta>;
457
+ relationOptions?: RelationOption[];
458
+ linkOptions?: LinkOptionGroup[];
459
+ index: number;
460
+ isExpanded: boolean;
461
+ autoFocus?: boolean;
462
+ onAutoFocused?: () => void;
463
+ onToggle: () => void;
464
+ onRemove: () => void;
465
+ onUpdate: (key: string, val: unknown) => void;
466
+ }) {
467
+ const contentRef = useRef<HTMLDivElement>(null);
468
+ const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({
469
+ id: String(item._key),
470
+ });
471
+
472
+ useEffect(() => {
473
+ if (autoFocus && isExpanded && contentRef.current) {
474
+ const input = contentRef.current.querySelector<HTMLElement>("input, textarea");
475
+ if (input) {
476
+ input.focus();
477
+ onAutoFocused?.();
478
+ }
479
+ }
480
+ }, [autoFocus, isExpanded, onAutoFocused]);
481
+
482
+ const style = {
483
+ transform: CSS.Transform.toString(transform),
484
+ transition,
485
+ };
486
+
487
+ const preview = getRepeaterPreview(item, fieldKeys);
488
+
489
+ return (
490
+ <div
491
+ ref={setNodeRef}
492
+ style={style}
493
+ className={cn("bg-card overflow-hidden rounded-lg border", isDragging && "z-10 opacity-90 shadow-lg")}
494
+ >
495
+ <div
496
+ className="group/row bg-muted-strong/50 hover:bg-muted-strong/70 flex items-center gap-2 px-3 py-2 transition-colors select-none"
497
+ onClick={onToggle}
498
+ >
499
+ <button
500
+ type="button"
501
+ ref={setActivatorNodeRef}
502
+ className="text-muted-foreground/50 hover:text-muted-foreground -ml-1 cursor-grab touch-none rounded p-1 transition-colors active:cursor-grabbing"
503
+ {...attributes}
504
+ {...listeners}
505
+ onClick={(e) => e.stopPropagation()}
506
+ >
507
+ <GripVertical className="size-4" />
508
+ </button>
509
+
510
+ <ChevronRight
511
+ className={cn(
512
+ "text-muted-foreground group-hover/row:text-foreground/70 size-4 shrink-0 transition-[color,transform]",
513
+ isExpanded && "rotate-90",
514
+ )}
515
+ />
516
+
517
+ <span className="text-muted-foreground group-hover/row:text-foreground/70 text-xs font-medium transition-colors">
518
+ #{index + 1}
519
+ </span>
520
+
521
+ {!isExpanded && preview && (
522
+ <span className="text-foreground/70 group-hover/row:text-foreground/85 min-w-0 truncate text-sm transition-colors">
523
+ {preview}
524
+ </span>
525
+ )}
526
+
527
+ <div className="ml-auto">
528
+ <Button
529
+ type="button"
530
+ variant="ghost"
531
+ size="icon-xs"
532
+ title="Remove item"
533
+ className="text-muted-foreground hover:text-destructive"
534
+ onClick={(e) => {
535
+ e.stopPropagation();
536
+ onRemove();
537
+ }}
538
+ >
539
+ <Trash2 className="size-3.5" />
540
+ </Button>
541
+ </div>
542
+ </div>
543
+
544
+ {isExpanded && (
545
+ <div ref={contentRef} className="space-y-3 border-t px-4 py-3">
546
+ {itemFields
547
+ ? fieldKeys.map((key) => (
548
+ <SubField
549
+ key={key}
550
+ blockKey={`${blockKey}_${index}`}
551
+ fieldName={key}
552
+ meta={itemFields[key]}
553
+ value={item[key]}
554
+ onChange={(v) => onUpdate(key, v)}
555
+ relationOptions={relationOptions}
556
+ linkOptions={linkOptions}
557
+ />
558
+ ))
559
+ : fieldKeys.map((key) => (
560
+ <div key={key} className="grid gap-1">
561
+ <Label className="text-xs">{humanize(key)}</Label>
562
+ {key.includes("description") ||
563
+ key.includes("body") ||
564
+ key.includes("content") ||
565
+ key.includes("answer") ? (
566
+ <Textarea
567
+ rows={3}
568
+ value={String(item[key] ?? "")}
569
+ onChange={(e) => onUpdate(key, e.target.value)}
570
+ />
571
+ ) : (
572
+ <Input value={String(item[key] ?? "")} onChange={(e) => onUpdate(key, e.target.value)} />
573
+ )}
574
+ </div>
575
+ ))}
576
+ </div>
577
+ )}
578
+ </div>
579
+ );
580
+ }
581
+
582
+ function parseArray(value: unknown): unknown[] {
583
+ if (Array.isArray(value)) return value;
584
+ if (typeof value === "string") {
585
+ try {
586
+ const p = JSON.parse(value);
587
+ if (Array.isArray(p)) return p;
588
+ } catch {}
589
+ }
590
+ return [];
591
+ }
592
+
593
+ export function RepeaterField({
594
+ blockKey,
595
+ itemFields,
596
+ relationOptions,
597
+ linkOptions,
598
+ value,
599
+ onChange,
600
+ }: {
601
+ blockKey: string;
602
+ itemFields?: Record<string, SubFieldMeta>;
603
+ relationOptions?: RelationOption[];
604
+ linkOptions?: LinkOptionGroup[];
605
+ value: unknown;
606
+ onChange: (value: unknown) => void;
607
+ }) {
608
+ const [newItemKey, setNewItemKey] = useState<string | null>(null);
609
+ const [expandedKeys, setExpandedKeys] = useState<Set<string>>(() => new Set());
610
+ const savedExpandedRef = useRef<Set<string> | null>(null);
611
+ const [items, setItems] = useState<Array<Record<string, unknown>>>(() => {
612
+ const raw = parseArray(value);
613
+ return raw.map((item: unknown) => {
614
+ const obj = (item ?? {}) as Record<string, unknown>;
615
+ return obj._key ? obj : { ...obj, _key: generateKey() };
616
+ });
617
+ });
618
+
619
+ useEffect(() => {
620
+ onChange(items);
621
+ }, [items]); // eslint-disable-line react-hooks/exhaustive-deps
622
+
623
+ // Typed rows use the declared itemFields; legacy rows auto-detect string keys.
624
+ const fieldKeys = itemFields
625
+ ? Object.keys(itemFields)
626
+ : items.length > 0
627
+ ? Object.keys(items[0]).filter((k) => k !== "_key")
628
+ : ["title", "description"];
629
+
630
+ const sensors = useSensors(
631
+ useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
632
+ useSensor(KeyboardSensor),
633
+ );
634
+
635
+ const addItem = () => {
636
+ const key = generateKey();
637
+ const blank: Record<string, unknown> = { _key: key };
638
+ for (const k of fieldKeys) {
639
+ const fieldMeta = itemFields?.[k];
640
+ if (fieldMeta?.defaultValue !== undefined) blank[k] = fieldMeta.defaultValue;
641
+ else if (fieldMeta?.type === "boolean") blank[k] = false;
642
+ else if (fieldMeta?.type === "array") blank[k] = [];
643
+ else blank[k] = "";
644
+ }
645
+ setNewItemKey(key);
646
+ setItems((prev) => [...prev, blank]);
647
+ setExpandedKeys((prev) => new Set(prev).add(key));
648
+ };
649
+
650
+ const removeItem = (index: number) => {
651
+ setItems((prev) => prev.filter((_, i) => i !== index));
652
+ };
653
+
654
+ const updateItem = (index: number, key: string, val: unknown) => {
655
+ setItems((prev) => prev.map((item, i) => (i === index ? { ...item, [key]: val } : item)));
656
+ };
657
+
658
+ const toggleExpanded = (key: string) => {
659
+ setExpandedKeys((prev) => {
660
+ const next = new Set(prev);
661
+ if (next.has(key)) next.delete(key);
662
+ else next.add(key);
663
+ return next;
664
+ });
665
+ };
666
+
667
+ const handleDragStart = () => {
668
+ savedExpandedRef.current = new Set(expandedKeys);
669
+ setExpandedKeys(new Set());
670
+ };
671
+
672
+ const handleDragEnd = (event: DragEndEvent) => {
673
+ if (savedExpandedRef.current) {
674
+ setExpandedKeys(savedExpandedRef.current);
675
+ savedExpandedRef.current = null;
676
+ }
677
+ const { active, over } = event;
678
+ if (!over || active.id === over.id) return;
679
+ setItems((prev) => {
680
+ const oldIndex = prev.findIndex((item) => item._key === active.id);
681
+ const newIndex = prev.findIndex((item) => item._key === over.id);
682
+ if (oldIndex === -1 || newIndex === -1) return prev;
683
+ return arrayMove(prev, oldIndex, newIndex);
684
+ });
685
+ };
686
+
687
+ return (
688
+ <div className="space-y-3">
689
+ <DndContext
690
+ sensors={sensors}
691
+ collisionDetection={closestCenter}
692
+ onDragStart={handleDragStart}
693
+ onDragEnd={handleDragEnd}
694
+ >
695
+ <SortableContext items={items.map((item) => String(item._key))} strategy={verticalListSortingStrategy}>
696
+ {items.map((item, index) => (
697
+ <SortableRepeaterItem
698
+ key={String(item._key ?? index)}
699
+ blockKey={blockKey}
700
+ item={item}
701
+ fieldKeys={fieldKeys}
702
+ itemFields={itemFields}
703
+ relationOptions={relationOptions}
704
+ linkOptions={linkOptions}
705
+ index={index}
706
+ isExpanded={expandedKeys.has(String(item._key))}
707
+ autoFocus={newItemKey === item._key}
708
+ onAutoFocused={() => setNewItemKey(null)}
709
+ onToggle={() => toggleExpanded(String(item._key))}
710
+ onRemove={() => removeItem(index)}
711
+ onUpdate={(key, val) => updateItem(index, key, val)}
712
+ />
713
+ ))}
714
+ </SortableContext>
715
+ </DndContext>
716
+ <Button type="button" variant="outline" size="sm" className="text-foreground/70" onClick={addItem}>
717
+ <Plus className="size-3.5" />
718
+ Add item
719
+ </Button>
720
+ </div>
721
+ );
722
+ }
723
+
724
+ function ArrayImageField({
725
+ fieldId,
726
+ value,
727
+ onChange,
728
+ }: {
729
+ fieldId: string;
730
+ value: unknown;
731
+ onChange: (value: unknown) => void;
732
+ }) {
733
+ const items: string[] = useMemo(() => (Array.isArray(value) ? value.map(String) : []), [value]);
734
+
735
+ const addImage = useCallback(() => {
736
+ onChange([...items, ""]);
737
+ }, [items, onChange]);
738
+
739
+ const removeImage = useCallback(
740
+ (index: number) => {
741
+ onChange(items.filter((_, i) => i !== index));
742
+ },
743
+ [items, onChange],
744
+ );
745
+
746
+ const updateImage = useCallback(
747
+ (index: number, v: string) => {
748
+ const next = [...items];
749
+ next[index] = v;
750
+ onChange(next);
751
+ },
752
+ [items, onChange],
753
+ );
754
+
755
+ return (
756
+ <div className="space-y-3">
757
+ {items.map((img, i) => (
758
+ <div key={`${fieldId}_img_${i}`} className="relative">
759
+ <ImagePicker name={`${fieldId}_img_${i}`} value={img} onChange={(v) => updateImage(i, v)} />
760
+ <Button
761
+ type="button"
762
+ variant="ghost"
763
+ size="icon"
764
+ className="text-muted-foreground hover:text-destructive absolute top-0 right-0 size-7"
765
+ onClick={() => removeImage(i)}
766
+ >
767
+ <Trash2 className="size-3.5" />
768
+ </Button>
769
+ </div>
770
+ ))}
771
+ <Button type="button" variant="outline" size="sm" onClick={addImage}>
772
+ <Plus className="mr-1 size-3.5" />
773
+ Add Image
774
+ </Button>
775
+ </div>
776
+ );
777
+ }