@kidecms/core 0.29.3 → 0.30.1

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.
@@ -46,21 +46,29 @@ type SharedSectionOption = {
46
46
 
47
47
  type Props = {
48
48
  name: string;
49
- value?: string;
49
+ /** Serialized JSON from the form, or the array itself when nested inside another block. */
50
+ value?: string | unknown[];
51
+ /** The field's label — names the items in the empty state ("No fields added yet"). */
52
+ label?: string;
50
53
  types: BlockTypesMeta;
51
54
  linkOptions?: LinkableCollection[];
52
55
  sharedSections?: SharedSectionOption[];
53
56
  sharedEnabled?: boolean;
57
+ /**
58
+ * Controlled mode, for a `blocks` sub-field inside another block: the parent owns
59
+ * the value, form serialization and live preview, so no hidden input or broadcast.
60
+ */
61
+ onChange?: (blocks: unknown[]) => void;
54
62
  };
55
63
 
56
64
  const SHARED_BLOCK_TYPE = "__shared";
57
65
 
58
66
  const isSharedBlock = (block: Block) => block.type === SHARED_BLOCK_TYPE && typeof block.ref === "string";
59
67
 
60
- function parseBlocks(value: string | undefined, types: BlockTypesMeta): Block[] {
68
+ function parseBlocks(value: string | unknown[] | undefined, types: BlockTypesMeta): Block[] {
61
69
  if (!value) return [];
62
70
  try {
63
- const parsed = JSON.parse(value);
71
+ const parsed = typeof value === "string" ? JSON.parse(value) : value;
64
72
  if (!Array.isArray(parsed)) return [];
65
73
  return parsed.map((item: Record<string, unknown>) => ({
66
74
  ...item,
@@ -72,8 +80,10 @@ function parseBlocks(value: string | undefined, types: BlockTypesMeta): Block[]
72
80
  }
73
81
  }
74
82
 
83
+ const stripKeys = (blocks: Block[]) => blocks.map(({ _key, ...rest }) => rest);
84
+
75
85
  function serializeBlocks(blocks: Block[]): string {
76
- return JSON.stringify(blocks.map(({ _key, ...rest }) => rest));
86
+ return JSON.stringify(stripKeys(blocks));
77
87
  }
78
88
 
79
89
  // -----------------------------------------------
@@ -221,7 +231,7 @@ function SortableBlock({
221
231
 
222
232
  {/* Content */}
223
233
  {isExpanded && (
224
- <div ref={contentRef} className="space-y-4 border-t px-4 py-4">
234
+ <div ref={contentRef} className="space-y-6 border-t px-4 py-5">
225
235
  {shared ? (
226
236
  <div className="space-y-3">
227
237
  <div>
@@ -286,11 +296,14 @@ function SortableBlock({
286
296
  export default function BlockEditor({
287
297
  name,
288
298
  value,
299
+ label,
289
300
  types,
290
301
  linkOptions = [],
291
302
  sharedSections = [],
292
303
  sharedEnabled = true,
304
+ onChange,
293
305
  }: Props) {
306
+ const controlled = Boolean(onChange);
294
307
  const [blocks, setBlocks] = useState<Block[]>(() => parseBlocks(value, types));
295
308
  const [expandedKeys, setExpandedKeys] = useState<Set<string>>(() => new Set());
296
309
  const [newBlockKey, setNewBlockKey] = useState<string | null>(null);
@@ -320,6 +333,7 @@ export default function BlockEditor({
320
333
  // Live preview: broadcast block data for server-side rendering. Also replay the
321
334
  // current value when a preview tab opened after edits announces itself.
322
335
  useEffect(() => {
336
+ if (controlled) return;
323
337
  if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
324
338
  const channel = previewChannelRef.current;
325
339
  if (!channel) return;
@@ -328,17 +342,18 @@ export default function BlockEditor({
328
342
  channel.onmessage = (e: MessageEvent) => {
329
343
  if (e.data?.type === "preview-ready") broadcast();
330
344
  };
331
- }, [blocks, name]);
345
+ }, [blocks, name, controlled]);
332
346
 
333
347
  const updateBlocks = useCallback(
334
348
  (updater: (prev: Block[]) => Block[]) => {
335
349
  setBlocks((prev) => {
336
350
  const next = updater(prev);
337
- setTimeout(dispatchChange, 0);
351
+ // Deferred: never update a parent from inside this state updater.
352
+ setTimeout(() => (onChange ? onChange(stripKeys(next)) : dispatchChange()), 0);
338
353
  return next;
339
354
  });
340
355
  },
341
- [dispatchChange],
356
+ [dispatchChange, onChange],
342
357
  );
343
358
 
344
359
  const handleDragStart = useCallback(() => {
@@ -495,48 +510,52 @@ export default function BlockEditor({
495
510
  const serialized = serializeBlocks(blocks);
496
511
 
497
512
  return (
498
- <div className="space-y-3">
499
- <input type="hidden" ref={hiddenRef} name={name} value={serialized} />
513
+ // Nested lists sit tighter: they're one group inside a block, not a page-level field.
514
+ <div className={controlled ? "space-y-2" : "space-y-3"}>
515
+ {!controlled && <input type="hidden" ref={hiddenRef} name={name} value={serialized} />}
500
516
 
501
- {blocks.length === 0 && (
517
+ {blocks.length === 0 && !controlled && (
502
518
  <div className="bg-field-subtle flex h-20 items-center justify-center rounded-lg border border-dashed">
503
- <p className="text-muted-foreground text-sm">No blocks added yet</p>
519
+ <p className="text-muted-foreground text-sm">No {label ? label.toLowerCase() : "blocks"} added yet</p>
504
520
  </div>
505
521
  )}
506
522
 
507
- <DndContext
508
- sensors={sensors}
509
- collisionDetection={closestCenter}
510
- onDragStart={handleDragStart}
511
- onDragEnd={handleDragEnd}
512
- >
513
- <SortableContext items={blocks.map((b) => b._key)} strategy={verticalListSortingStrategy}>
514
- <div className="space-y-3">
515
- {blocks.map((block) => {
516
- const fieldsMeta = isSharedBlock(block) ? {} : (types[block.type] ?? {});
517
- const sharedSection = isSharedBlock(block) ? sharedSectionsById.get(String(block.ref)) : undefined;
518
- return (
519
- <SortableBlock
520
- key={block._key}
521
- block={block}
522
- fieldsMeta={fieldsMeta}
523
- isExpanded={expandedKeys.has(block._key)}
524
- autoFocus={newBlockKey === block._key}
525
- onAutoFocused={() => setNewBlockKey(null)}
526
- onToggle={() => toggleExpanded(block._key)}
527
- onRemove={() => removeBlock(block._key)}
528
- onDetach={() => detachSharedBlock(block._key)}
529
- onSaveShared={() => saveAsShared(block._key)}
530
- sharedEnabled={sharedEnabled}
531
- onUpdateField={(fn, v) => updateField(block._key, fn, v)}
532
- linkOptions={linkOptions}
533
- sharedSection={sharedSection}
534
- />
535
- );
536
- })}
537
- </div>
538
- </SortableContext>
539
- </DndContext>
523
+ {/* An empty nested list renders nothing, so no stray gap sits above the add buttons. */}
524
+ {(blocks.length > 0 || !controlled) && (
525
+ <DndContext
526
+ sensors={sensors}
527
+ collisionDetection={closestCenter}
528
+ onDragStart={handleDragStart}
529
+ onDragEnd={handleDragEnd}
530
+ >
531
+ <SortableContext items={blocks.map((b) => b._key)} strategy={verticalListSortingStrategy}>
532
+ <div className={controlled ? "space-y-2" : "space-y-3"}>
533
+ {blocks.map((block) => {
534
+ const fieldsMeta = isSharedBlock(block) ? {} : (types[block.type] ?? {});
535
+ const sharedSection = isSharedBlock(block) ? sharedSectionsById.get(String(block.ref)) : undefined;
536
+ return (
537
+ <SortableBlock
538
+ key={block._key}
539
+ block={block}
540
+ fieldsMeta={fieldsMeta}
541
+ isExpanded={expandedKeys.has(block._key)}
542
+ autoFocus={newBlockKey === block._key}
543
+ onAutoFocused={() => setNewBlockKey(null)}
544
+ onToggle={() => toggleExpanded(block._key)}
545
+ onRemove={() => removeBlock(block._key)}
546
+ onDetach={() => detachSharedBlock(block._key)}
547
+ onSaveShared={() => saveAsShared(block._key)}
548
+ sharedEnabled={sharedEnabled}
549
+ onUpdateField={(fn, v) => updateField(block._key, fn, v)}
550
+ linkOptions={linkOptions}
551
+ sharedSection={sharedSection}
552
+ />
553
+ );
554
+ })}
555
+ </div>
556
+ </SortableContext>
557
+ </DndContext>
558
+ )}
540
559
 
541
560
  {/* Add block buttons */}
542
561
  <div className="flex flex-wrap gap-2">
@@ -5,16 +5,20 @@ type Props = {
5
5
  name: string;
6
6
  checked?: boolean;
7
7
  disabled?: boolean;
8
+ /** Shown beside the box — a checkbox names itself instead of taking a label above it. */
9
+ label?: string;
10
+ required?: boolean;
8
11
  };
9
12
 
10
- export default function CheckboxField({ name, checked: initial = false, disabled }: Props) {
13
+ export default function CheckboxField({ name, checked: initial = false, disabled, label, required }: Props) {
11
14
  const [checked, setChecked] = useState(initial);
12
15
  const hiddenRef = useRef<HTMLInputElement>(null);
13
16
 
14
17
  return (
15
- <label className="group inline-flex cursor-pointer items-center gap-3 text-sm">
18
+ <label className="group inline-flex w-fit cursor-pointer items-center gap-3 text-sm has-disabled:cursor-not-allowed">
16
19
  <input type="hidden" name={name} value={checked ? "true" : "false"} ref={hiddenRef} />
17
20
  <Checkbox
21
+ id={name}
18
22
  className="group-hover:border-primary/60 disabled:group-hover:border-input"
19
23
  checked={checked}
20
24
  onCheckedChange={(v) => {
@@ -25,7 +29,12 @@ export default function CheckboxField({ name, checked: initial = false, disabled
25
29
  }}
26
30
  disabled={disabled}
27
31
  />
28
- <span className="text-muted-foreground select-none">{checked ? "true" : "false"}</span>
32
+ {label && (
33
+ <span className="text-foreground/80 leading-none font-medium select-none">
34
+ {label}
35
+ {required ? " *" : ""}
36
+ </span>
37
+ )}
29
38
  </label>
30
39
  );
31
40
  }
@@ -260,7 +260,7 @@ function BlockNodeView(props: NodeViewProps) {
260
260
  </div>
261
261
 
262
262
  {expanded && (
263
- <div className="space-y-4 border-t px-4 py-4" contentEditable={false}>
263
+ <div className="space-y-6 border-t px-4 py-5" contentEditable={false}>
264
264
  {isShared ? (
265
265
  <div className="space-y-3">
266
266
  <div>
@@ -59,6 +59,13 @@ type Props = {
59
59
  entityLabel?: string;
60
60
  /** Adds `_force=1` to the delete submit, telling the API the warning was shown and accepted. */
61
61
  forceOnConfirm?: boolean;
62
+ /**
63
+ * Offers "Change language…" — only passed while the document exists in one language
64
+ * (with a translation, the API refuses to move the original to that locale).
65
+ */
66
+ languages?: Array<{ value: string; label: string }>;
67
+ /** The language the document is currently written in. */
68
+ contentLanguage?: string;
62
69
  };
63
70
 
64
71
  export default function DocumentActions({
@@ -79,8 +86,12 @@ export default function DocumentActions({
79
86
  referencesEndpoint,
80
87
  entityLabel = "document",
81
88
  forceOnConfirm,
89
+ languages,
90
+ contentLanguage,
82
91
  }: Props) {
83
92
  const [scheduleOpen, setScheduleOpen] = useState(false);
93
+ const [languageOpen, setLanguageOpen] = useState(false);
94
+ const [language, setLanguage] = useState(contentLanguage ?? "");
84
95
  const [deleteOpen, setDeleteOpen] = useState(false);
85
96
  const [refWarning, setRefWarning] = useState<{ tone: "warn" | "muted"; message: string } | null>(null);
86
97
  const [publishAt, setPublishAt] = useState(currentPublishAt ? toLocalDatetime(currentPublishAt) : "");
@@ -94,6 +105,7 @@ export default function DocumentActions({
94
105
  showDelete ||
95
106
  showSchedule ||
96
107
  showCancelSchedule ||
108
+ Boolean(languages?.length) ||
97
109
  versions.length > 0;
98
110
  if (!hasActions) return null;
99
111
 
@@ -170,6 +182,21 @@ export default function DocumentActions({
170
182
  form.submit();
171
183
  };
172
184
 
185
+ // Saves the document with its new original language (and any pending edits).
186
+ const submitLanguage = () => {
187
+ const form = document.getElementById(formId) as HTMLFormElement | null;
188
+ if (!form || !language || language === contentLanguage) return;
189
+ let input = form.querySelector<HTMLInputElement>('input[name="_sourceLocale"]');
190
+ if (!input) {
191
+ input = document.createElement("input");
192
+ input.type = "hidden";
193
+ input.name = "_sourceLocale";
194
+ form.appendChild(input);
195
+ }
196
+ input.value = language;
197
+ form.submit();
198
+ };
199
+
173
200
  const restoreVersion = (version: number) => {
174
201
  if (!restoreEndpoint) return;
175
202
  const form = document.createElement("form");
@@ -206,6 +233,9 @@ export default function DocumentActions({
206
233
  <DropdownMenuContent align="end" className="w-48">
207
234
  {canDuplicate && <DropdownMenuItem onClick={duplicate}>Duplicate</DropdownMenuItem>}
208
235
  {showSchedule && <DropdownMenuItem onClick={() => setScheduleOpen(true)}>Schedule publish</DropdownMenuItem>}
236
+ {languages && languages.length > 1 && (
237
+ <DropdownMenuItem onClick={() => setLanguageOpen(true)}>Change language…</DropdownMenuItem>
238
+ )}
209
239
  {showCancelSchedule && (
210
240
  <DropdownMenuItem onClick={() => submitAction("unpublish")}>Cancel schedule</DropdownMenuItem>
211
241
  )}
@@ -341,6 +371,45 @@ export default function DocumentActions({
341
371
  </DialogContent>
342
372
  </Dialog>
343
373
 
374
+ {languages && languages.length > 1 && (
375
+ <Dialog open={languageOpen} onOpenChange={setLanguageOpen}>
376
+ <DialogContent>
377
+ <DialogHeader>
378
+ <DialogTitle>Change language</DialogTitle>
379
+ <DialogDescription>
380
+ Marks the language this document is written in. The content is not translated — use this when it was
381
+ saved under the wrong language.
382
+ </DialogDescription>
383
+ </DialogHeader>
384
+ <div className="grid gap-2 py-2">
385
+ <label htmlFor="document-language" className="text-sm font-medium">
386
+ Language
387
+ </label>
388
+ <select
389
+ id="document-language"
390
+ value={language}
391
+ onChange={(e) => setLanguage(e.target.value)}
392
+ className="border-input bg-background flex h-9 w-full rounded-md border px-3 py-1 text-sm shadow-sm"
393
+ >
394
+ {languages.map((option) => (
395
+ <option key={option.value} value={option.value}>
396
+ {option.label}
397
+ </option>
398
+ ))}
399
+ </select>
400
+ </div>
401
+ <DialogFooter>
402
+ <DialogClose>
403
+ <Button variant="outline">Cancel</Button>
404
+ </DialogClose>
405
+ <Button onClick={submitLanguage} disabled={!language || language === contentLanguage}>
406
+ Change language
407
+ </Button>
408
+ </DialogFooter>
409
+ </DialogContent>
410
+ </Dialog>
411
+ )}
412
+
344
413
  <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
345
414
  <AlertDialogContent>
346
415
  <AlertDialogHeader>
@@ -21,6 +21,7 @@ import {
21
21
  ChevronDown,
22
22
  ChevronLeft,
23
23
  ChevronRight,
24
+ Check,
24
25
  Loader2,
25
26
  MoreHorizontal,
26
27
  Search,
@@ -96,6 +97,8 @@ type DocumentsDataTableProps = {
96
97
  serverPagination?: ServerPaginationConfig;
97
98
  /** Bulk status change: if provided, renders "Mark as <status>" entries in the selection menu. */
98
99
  statusOptions?: string[];
100
+ /** Language filter in the toolbar (multilingual collections only); each option is a server-side link. */
101
+ languageFilter?: { active: string; options: Array<{ value: string; label: string; href: string }> };
99
102
  };
100
103
 
101
104
  const formatDateClient = (value: unknown): string => {
@@ -163,6 +166,7 @@ export default function DocumentsDataTable({
163
166
  data,
164
167
  serverPagination,
165
168
  statusOptions,
169
+ languageFilter,
166
170
  }: DocumentsDataTableProps) {
167
171
  const isServerMode = !!serverPagination;
168
172
 
@@ -552,7 +556,7 @@ export default function DocumentsDataTable({
552
556
  {row.original.locales.map((locale) => (
553
557
  <a
554
558
  key={locale}
555
- href={`${row.original.editHref}?locale=${locale}`}
559
+ href={`${row.original.editHref.split("?")[0]}?locale=${locale}`}
556
560
  onClick={(e) => e.stopPropagation()}
557
561
  >
558
562
  <Badge
@@ -710,6 +714,29 @@ export default function DocumentsDataTable({
710
714
  </div>
711
715
 
712
716
  <div className="flex flex-wrap items-center gap-2">
717
+ {languageFilter && (
718
+ <DropdownMenu>
719
+ <DropdownMenuTrigger asChild>
720
+ <Button variant="outline" size="sm">
721
+ {languageFilter.active
722
+ ? (languageFilter.options.find((option) => option.value === languageFilter.active)?.label ??
723
+ "All languages")
724
+ : "All languages"}
725
+ <ChevronDown className="size-4" />
726
+ </Button>
727
+ </DropdownMenuTrigger>
728
+ <DropdownMenuContent align="end" className="w-44">
729
+ {languageFilter.options.map((option) => (
730
+ <DropdownMenuItem key={option.value} onClick={() => window.location.assign(option.href)}>
731
+ <Check
732
+ className={cn("size-4", option.value === languageFilter.active ? "opacity-100" : "opacity-0")}
733
+ />
734
+ {option.label}
735
+ </DropdownMenuItem>
736
+ ))}
737
+ </DropdownMenuContent>
738
+ </DropdownMenu>
739
+ )}
713
740
  {selectedRows.length > 0 && (
714
741
  <DropdownMenu>
715
742
  <DropdownMenuTrigger asChild>
@@ -117,6 +117,16 @@ const toSubFieldMeta = (subField: FieldConfig): SubFieldMeta => ({
117
117
  "itemFields" in subField && subField.itemFields
118
118
  ? Object.fromEntries(Object.entries(subField.itemFields).map(([name, f]) => [name, toSubFieldMeta(f)]))
119
119
  : undefined,
120
+ // A `blocks` sub-field inside a block renders its own nested block editor.
121
+ types:
122
+ subField.type === "blocks"
123
+ ? Object.fromEntries(
124
+ Object.entries(subField.types).map(([typeName, typeFields]) => [
125
+ typeName,
126
+ Object.fromEntries(Object.entries(typeFields).map(([name, f]) => [name, toSubFieldMeta(f)])),
127
+ ]),
128
+ )
129
+ : undefined,
120
130
  });
121
131
 
122
132
  const toBlockTypesMeta = (source: Record<string, Record<string, FieldConfig>> | null | undefined) =>
@@ -147,15 +157,23 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
147
157
  : {}}
148
158
  >
149
159
  {
150
- !isTreeEditor && (
160
+ !isTreeEditor && field.type !== "boolean" && (
151
161
  <Label htmlFor={name}>
152
162
  {label}
153
163
  {field.required ? " *" : ""}
154
164
  </Label>
155
165
  )
156
166
  }
157
- {field.description && <p class="text-muted-foreground -mt-1 text-xs leading-5">{field.description}</p>}
158
- {field.admin?.help && <p class="text-muted-foreground -mt-1 -mb-0.5 text-xs leading-5">{field.admin.help}</p>}
167
+ {
168
+ field.type !== "boolean" && field.description && (
169
+ <p class="text-muted-foreground -mt-1 text-xs leading-5">{field.description}</p>
170
+ )
171
+ }
172
+ {
173
+ field.type !== "boolean" && field.admin?.help && (
174
+ <p class="text-muted-foreground -mt-1 -mb-0.5 text-xs leading-5">{field.admin.help}</p>
175
+ )
176
+ }
159
177
 
160
178
  {
161
179
  CustomComponent && (
@@ -255,7 +273,19 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
255
273
  )}
256
274
 
257
275
  {field.type === "boolean" && (
258
- <CheckboxField client:load name={name} checked={Boolean(value)} disabled={readOnly} />
276
+ <div class="grid gap-1.5">
277
+ <CheckboxField
278
+ client:load
279
+ name={name}
280
+ checked={Boolean(value)}
281
+ disabled={readOnly}
282
+ label={label}
283
+ required={field.required}
284
+ />
285
+ {/* Indented to the label text: box (1rem) + gap (0.75rem). */}
286
+ {field.description && <p class="text-muted-foreground pl-7 text-xs leading-5">{field.description}</p>}
287
+ {field.admin?.help && <p class="text-muted-foreground pl-7 text-xs leading-5">{field.admin.help}</p>}
288
+ </div>
259
289
  )}
260
290
 
261
291
  {field.type === "select" && field.admin?.component !== "radio" && (
@@ -414,6 +444,7 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
414
444
  client:load
415
445
  name={name}
416
446
  value={serializedValue}
447
+ label={label}
417
448
  types={blockTypesMeta}
418
449
  linkOptions={linkableCollections}
419
450
  sharedSections={"shared" in field && field.shared === false ? [] : sharedSectionOptions}
@@ -71,7 +71,7 @@ export default function SharedSectionBlockField({ name, value, types }: Props) {
71
71
  />
72
72
 
73
73
  {selectedType && Object.keys(fieldsMeta).length > 0 && (
74
- <div className="space-y-4 rounded-lg border px-4 py-4">
74
+ <div className="space-y-6 rounded-lg border px-4 py-5">
75
75
  {Object.entries(fieldsMeta).map(([fieldName, meta]) => (
76
76
  <SubField
77
77
  key={fieldName}
@@ -43,8 +43,13 @@ export default function UnsavedGuard({
43
43
  const saveBtn = doc.querySelector<HTMLButtonElement>(`button[type="submit"][form="${formId}"][value="save"]`);
44
44
  const publishBtn = doc.querySelector<HTMLButtonElement>(`button[type="submit"][form="${formId}"][value="publish"]`);
45
45
 
46
- const initialData = new FormData(form);
47
- const initialSnapshot = serializeFormData(initialData);
46
+ // After an in-place save (EditScripts swaps this guard in without a reload), the
47
+ // clean baseline is exactly what was submitted — edits typed while the save was in
48
+ // flight stay dirty instead of being silently treated as saved.
49
+ const win = window as Window & { __kideSubmittedForm?: FormData };
50
+ const submitted = win.__kideSubmittedForm;
51
+ delete win.__kideSubmittedForm;
52
+ const initialSnapshot = serializeFormData(submitted ?? new FormData(form));
48
53
 
49
54
  const updateButtons = (dirty: boolean) => {
50
55
  if (isNew) return;
@@ -61,6 +66,8 @@ export default function UnsavedGuard({
61
66
  dirtyRef.current = currentSnapshot !== initialSnapshot;
62
67
  updateButtons(dirtyRef.current);
63
68
  };
69
+ // Edits made while an in-place save was in flight are already unsaved.
70
+ if (submitted) checkDirty();
64
71
 
65
72
  // Mark as clean when form is submitted
66
73
  const handleSubmit = () => {
@@ -27,6 +27,9 @@ import LinkField from "./LinkField";
27
27
  import type { LinkableCollection } from "./InternalLinkPicker";
28
28
  import DocumentCombobox, { useRelationLabels } from "./DocumentCombobox";
29
29
  import YoutubeField from "./YoutubeField";
30
+ // Circular with BlockEditor (which renders SubField); both sides only use the
31
+ // other at render time, so the cycle is safe.
32
+ import BlockEditor from "./BlockEditor";
30
33
 
31
34
  // -----------------------------------------------
32
35
  // Shared types — describe a block sub-field. Used by both the standalone
@@ -49,6 +52,8 @@ export type SubFieldMeta = {
49
52
  condition?: { field: string; value: string | string[] | boolean };
50
53
  /** Typed repeater row schema (json + admin.component "repeater"). */
51
54
  itemFields?: Record<string, SubFieldMeta>;
55
+ /** Block types of a nested `blocks` sub-field. */
56
+ types?: Record<string, Record<string, SubFieldMeta>>;
52
57
  };
53
58
 
54
59
  /** Same semantics as the edit form's conditional-visibility script (EditScripts). */
@@ -76,28 +81,8 @@ export function humanize(value: string) {
76
81
  .replace(/^\w/, (char) => char.toUpperCase());
77
82
  }
78
83
 
79
- /** Build a blank value object for a freshly inserted block of the given type. */
80
- export function blankBlockFields(fieldsMeta: Record<string, SubFieldMeta>): Record<string, unknown> {
81
- const out: Record<string, unknown> = {};
82
- for (const [fieldName, meta] of Object.entries(fieldsMeta)) {
83
- if (meta.defaultValue !== undefined) out[fieldName] = meta.defaultValue;
84
- else if (meta.type === "boolean") out[fieldName] = false;
85
- else if (meta.type === "array") out[fieldName] = [];
86
- else out[fieldName] = "";
87
- }
88
- return out;
89
- }
90
-
91
- /** First text-ish field value, truncated — used for collapsed block previews. */
92
- export function getPreviewText(values: Record<string, unknown>, fieldsMeta: Record<string, SubFieldMeta>): string {
93
- for (const [key, meta] of Object.entries(fieldsMeta)) {
94
- if (meta.type === "text" && values[key]) {
95
- const text = String(values[key]);
96
- return text.length > 60 ? text.slice(0, 60) + "..." : text;
97
- }
98
- }
99
- return "";
100
- }
84
+ // Pure value helpers live in a React-free module so they can be unit-tested.
85
+ export { blankBlockFields, getPreviewText } from "./block-values";
101
86
 
102
87
  // -----------------------------------------------
103
88
  // Sub-field label + control wrapper
@@ -126,6 +111,16 @@ export function SubField({
126
111
 
127
112
  if (meta.condition && !matchesCondition(meta.condition.value, siblings?.[meta.condition.field])) return null;
128
113
 
114
+ // A checkbox carries its own label beside the box; help sits below, under the label text.
115
+ if (meta.type === "boolean") {
116
+ return (
117
+ <div className="grid gap-1.5">
118
+ <SubFieldControl fieldId={fieldId} meta={meta} value={value} onChange={onChange} label={label} />
119
+ {meta.admin?.help && <p className="text-muted-foreground pl-7 text-xs leading-5">{meta.admin.help}</p>}
120
+ </div>
121
+ );
122
+ }
123
+
129
124
  return (
130
125
  <div className="grid gap-2">
131
126
  <Label htmlFor={fieldId}>
@@ -283,12 +278,15 @@ export function SubFieldControl({
283
278
  value,
284
279
  onChange,
285
280
  linkOptions = [],
281
+ label,
286
282
  }: {
287
283
  fieldId: string;
288
284
  meta: SubFieldMeta;
289
285
  value: unknown;
290
286
  onChange: (value: unknown) => void;
291
287
  linkOptions?: LinkableCollection[];
288
+ /** Checkbox text (booleans render their label beside the box). */
289
+ label?: string;
292
290
  }) {
293
291
  const strValue = value == null ? "" : String(value);
294
292
 
@@ -337,14 +335,19 @@ export function SubFieldControl({
337
335
 
338
336
  case "boolean":
339
337
  return (
340
- <label className="group inline-flex cursor-pointer items-center gap-3 text-sm">
338
+ <label className="group inline-flex w-fit cursor-pointer items-center gap-3 text-sm">
341
339
  <Checkbox
342
340
  id={fieldId}
343
341
  className="group-hover:border-primary/60"
344
342
  checked={Boolean(value)}
345
343
  onCheckedChange={(checked) => onChange(Boolean(checked))}
346
344
  />
347
- <span className="text-muted-foreground select-none">{value ? "true" : "false"}</span>
345
+ {label && (
346
+ <span className="text-foreground/80 leading-none font-medium select-none">
347
+ {label}
348
+ {meta.required ? " *" : ""}
349
+ </span>
350
+ )}
348
351
  </label>
349
352
  );
350
353
 
@@ -391,6 +394,20 @@ export function SubFieldControl({
391
394
  case "array":
392
395
  return <ArrayControl fieldId={fieldId} meta={meta} value={value} onChange={onChange} />;
393
396
 
397
+ case "blocks":
398
+ // A nested block list: typed "+ Type" buttons, each item shows only its own fields.
399
+ return (
400
+ <BlockEditor
401
+ name={fieldId}
402
+ value={Array.isArray(value) ? value : []}
403
+ label={meta.label}
404
+ types={meta.types ?? {}}
405
+ linkOptions={linkOptions}
406
+ sharedEnabled={false}
407
+ onChange={onChange}
408
+ />
409
+ );
410
+
394
411
  case "json":
395
412
  if (meta.admin?.component === "repeater") {
396
413
  return (
@@ -533,7 +550,7 @@ function SortableRepeaterItem({
533
550
  </div>
534
551
 
535
552
  {isExpanded && (
536
- <div ref={contentRef} className="space-y-3 border-t px-4 py-3">
553
+ <div ref={contentRef} className="space-y-5 border-t px-4 py-4">
537
554
  {itemFields
538
555
  ? fieldKeys.map((key) => (
539
556
  <SubField