@bygghammar/cms-platform 0.14.0 → 0.15.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bygghammar/cms-platform",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Shared CMS platform: blocks, block types, i18n core, UI primitives and design-token contract used by every Bygghammar/Voyara site.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -95,7 +95,8 @@
95
95
  "./platform/contract": "./src/platform/contract.ts",
96
96
  "./backoffice/media/ReviewImageUpload": "./src/backoffice/media/ReviewImageUpload.tsx",
97
97
  "./migrations/*": "./migrations/*",
98
- "./backoffice/seo/PageSeoPanelView": "./src/backoffice/seo/PageSeoPanelView.tsx"
98
+ "./backoffice/seo/PageSeoPanelView": "./src/backoffice/seo/PageSeoPanelView.tsx",
99
+ "./backoffice/SectionFormView": "./src/backoffice/SectionFormView.tsx"
99
100
  },
100
101
  "dependencies": {
101
102
  "fflate": "^0.8.3"
@@ -0,0 +1,799 @@
1
+ import {
2
+ createContext,
3
+ useContext,
4
+ useState,
5
+ type ComponentType,
6
+ type CSSProperties,
7
+ type ReactNode,
8
+ } from "react";
9
+ import {
10
+ ChevronDown,
11
+ ChevronRight,
12
+ GripVertical,
13
+ Plus,
14
+ Trash2,
15
+ ArrowUp,
16
+ ArrowDown,
17
+ Image as ImageIcon,
18
+ Crosshair,
19
+ } from "lucide-react";
20
+ import {
21
+ DndContext,
22
+ closestCenter,
23
+ PointerSensor,
24
+ KeyboardSensor,
25
+ useSensor,
26
+ useSensors,
27
+ type DragEndEvent,
28
+ } from "@dnd-kit/core";
29
+ import {
30
+ SortableContext,
31
+ arrayMove,
32
+ useSortable,
33
+ sortableKeyboardCoordinates,
34
+ verticalListSortingStrategy,
35
+ } from "@dnd-kit/sortable";
36
+ import { CSS } from "@dnd-kit/utilities";
37
+
38
+ import { MediaPickerDialog } from "./inspectors/fields";
39
+
40
+ /**
41
+ * Generic recursive editor for CMS section values, shared by every site.
42
+ *
43
+ * Shape detection (no per-section schema needed):
44
+ * - Localized<string> → object whose keys are a subset of the host locales
45
+ * and whose values are strings.
46
+ * - LocalizedImage → object with a string `src` and a Localized `alt`.
47
+ * - Array → sortable list of items of the array's element shape.
48
+ * - Plain object → recurse into fields.
49
+ * - string/number/bool → primitive input.
50
+ *
51
+ * Everything site-specific (locale list, image renderer, focus editor, the
52
+ * managed-forms list) is injected by the host.
53
+ * Backoffice copy is English by project rule.
54
+ */
55
+
56
+ type AnyVal = unknown;
57
+
58
+ export type SectionFormImageProps = {
59
+ src: string;
60
+ alt: string;
61
+ className?: string;
62
+ responsive?: boolean;
63
+ };
64
+
65
+ export type SectionFormFocusPickerProps = {
66
+ src: string;
67
+ modal?: boolean;
68
+ title?: string;
69
+ onClose?: () => void;
70
+ };
71
+
72
+ export type SectionFormManagedForm = {
73
+ key: string;
74
+ name: string;
75
+ is_active?: boolean | null;
76
+ };
77
+
78
+ export type SectionFormDeps = {
79
+ /** Locale codes the site edits, in tab order. */
80
+ locales: readonly string[];
81
+ /** Locale shown first and used for list summaries. */
82
+ defaultLocale: string;
83
+ /** Host image component (focal cropping, responsive sources, …). */
84
+ ImageComponent: ComponentType<SectionFormImageProps>;
85
+ /** Host focus-point editor, already wired to its persistence calls. */
86
+ FocusPickerComponent: ComponentType<SectionFormFocusPickerProps>;
87
+ /** Managed forms offered by the `formKey` picker. */
88
+ forms: SectionFormManagedForm[];
89
+ };
90
+
91
+ const DepsContext = createContext<SectionFormDeps | null>(null);
92
+
93
+ function useDeps(): SectionFormDeps {
94
+ const deps = useContext(DepsContext);
95
+ if (!deps) throw new Error("SectionFormView deps are missing");
96
+ return deps;
97
+ }
98
+
99
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
100
+ return typeof v === "object" && v !== null && !Array.isArray(v);
101
+ }
102
+
103
+ function makeIsLocalizedString(locales: readonly string[]) {
104
+ const set = new Set<string>(locales);
105
+ return (v: unknown): v is Record<string, string> => {
106
+ if (!isPlainObject(v)) return false;
107
+ const keys = Object.keys(v);
108
+ if (keys.length === 0) return false;
109
+ return keys.every((k) => set.has(k) && typeof v[k] === "string");
110
+ };
111
+ }
112
+
113
+ function isLocalizedImage(
114
+ v: unknown,
115
+ ): v is { src: string; alt: Record<string, string>; width?: number; height?: number } {
116
+ return isPlainObject(v) && typeof v.src === "string" && isPlainObject(v.alt);
117
+ }
118
+
119
+ function labelize(key: string): string {
120
+ return key
121
+ .replace(/([A-Z])/g, " $1")
122
+ .replace(/[_-]+/g, " ")
123
+ .replace(/\s+/g, " ")
124
+ .trim()
125
+ .replace(/^./, (c) => c.toUpperCase());
126
+ }
127
+
128
+ function useIsLocalizedString() {
129
+ const { locales } = useDeps();
130
+ return makeIsLocalizedString(locales);
131
+ }
132
+
133
+ function blankLike(template: unknown, deps: SectionFormDeps): unknown {
134
+ const isLocalizedString = makeIsLocalizedString(deps.locales);
135
+ if (isLocalizedString(template)) return { [deps.defaultLocale]: "" };
136
+ if (isLocalizedImage(template)) return { src: "", alt: { [deps.defaultLocale]: "" } };
137
+ if (Array.isArray(template)) return [];
138
+ if (isPlainObject(template)) {
139
+ const out: Record<string, unknown> = {};
140
+ for (const [k, v] of Object.entries(template)) out[k] = blankLike(v, deps);
141
+ if (typeof out["id"] === "string") out["id"] = `it_${Math.random().toString(36).slice(2, 8)}`;
142
+ return out;
143
+ }
144
+ if (typeof template === "string") return "";
145
+ if (typeof template === "number") return 0;
146
+ if (typeof template === "boolean") return false;
147
+ return "";
148
+ }
149
+
150
+ export function SectionFormView({
151
+ value,
152
+ onChange,
153
+ deps,
154
+ }: {
155
+ value: AnyVal;
156
+ onChange: (next: AnyVal) => void;
157
+ deps: SectionFormDeps;
158
+ }) {
159
+ return (
160
+ <DepsContext.Provider value={deps}>
161
+ <Node value={value} onChange={onChange} path="" depth={0} />
162
+ </DepsContext.Provider>
163
+ );
164
+ }
165
+
166
+ function Node({
167
+ value,
168
+ onChange,
169
+ path,
170
+ depth,
171
+ fieldLabel,
172
+ }: {
173
+ value: AnyVal;
174
+ onChange: (v: AnyVal) => void;
175
+ path: string;
176
+ depth: number;
177
+ fieldLabel?: string;
178
+ }) {
179
+ const isLocalizedString = useIsLocalizedString();
180
+ if (isLocalizedString(value)) {
181
+ return <LocalizedStringField value={value} onChange={onChange} label={fieldLabel} />;
182
+ }
183
+ if (isLocalizedImage(value)) {
184
+ return <ImageField value={value} onChange={onChange} label={fieldLabel} />;
185
+ }
186
+ if (Array.isArray(value)) {
187
+ return (
188
+ <ArrayField value={value} onChange={onChange} path={path} depth={depth} label={fieldLabel} />
189
+ );
190
+ }
191
+ if (isPlainObject(value)) {
192
+ return (
193
+ <ObjectField value={value} onChange={onChange} path={path} depth={depth} label={fieldLabel} />
194
+ );
195
+ }
196
+ if (path.endsWith("formKey") && (typeof value === "string" || value == null)) {
197
+ return (
198
+ <FormKeyField
199
+ value={(value as string) ?? ""}
200
+ onChange={onChange}
201
+ label={fieldLabel ?? "Form"}
202
+ />
203
+ );
204
+ }
205
+ return (
206
+ <PrimitiveField
207
+ value={value}
208
+ onChange={onChange}
209
+ label={fieldLabel}
210
+ hint={
211
+ path.endsWith("autoplayMs")
212
+ ? "Autoplay speed in milliseconds (e.g. 5000 = 5 seconds). Set to 0 to turn autoplay off."
213
+ : undefined
214
+ }
215
+ />
216
+ );
217
+ }
218
+
219
+ /* -------------------- Managed form picker -------------------- */
220
+
221
+ function FormKeyField({
222
+ value,
223
+ onChange,
224
+ label,
225
+ }: {
226
+ value: string;
227
+ onChange: (v: AnyVal) => void;
228
+ label?: string;
229
+ }) {
230
+ const { forms } = useDeps();
231
+ const known = forms.some((f) => f.key === value);
232
+
233
+ return (
234
+ <Field label={label}>
235
+ <select
236
+ value={value}
237
+ onChange={(e) => onChange(e.target.value)}
238
+ className="w-full border border-ink/20 bg-white px-3 py-2 text-sm"
239
+ >
240
+ <option value="">Select a form…</option>
241
+ {forms.map((f) => (
242
+ <option key={f.key} value={f.key}>
243
+ {f.name} ({f.key}){f.is_active === false ? " — inactive" : ""}
244
+ </option>
245
+ ))}
246
+ {value && !known ? <option value={value}>{value} — missing</option> : null}
247
+ </select>
248
+ <p className="mt-1 text-xs text-ink/50">
249
+ Fields, notifications and submissions are managed in Forms.
250
+ </p>
251
+ </Field>
252
+ );
253
+ }
254
+
255
+ /* -------------------- Localized string -------------------- */
256
+
257
+ function LocalizedStringField({
258
+ value,
259
+ onChange,
260
+ label,
261
+ }: {
262
+ value: Record<string, string>;
263
+ onChange: (v: Record<string, string>) => void;
264
+ label?: string;
265
+ }) {
266
+ const { locales, defaultLocale } = useDeps();
267
+ const [locale, setLocale] = useState<string>(defaultLocale);
268
+ const current = value[locale] ?? "";
269
+ const multiline = current.length > 60 || current.includes("\n");
270
+ return (
271
+ <Field label={label}>
272
+ <div className="border border-ink/15 bg-white">
273
+ <div className="flex items-center gap-1 border-b border-ink/10 px-2 py-1">
274
+ {locales.map((loc) => {
275
+ const filled = typeof value[loc] === "string" && value[loc]!.trim().length > 0;
276
+ return (
277
+ <button
278
+ key={loc}
279
+ type="button"
280
+ onClick={() => setLocale(loc)}
281
+ className={`px-2 py-1 text-[0.65rem] uppercase tracking-[0.18em] ${
282
+ loc === locale ? "bg-ink text-paper" : "text-ink/60 hover:text-ink"
283
+ }`}
284
+ title={filled ? "Has content" : "Empty"}
285
+ >
286
+ {loc}
287
+ {!filled && <span className="ml-1 opacity-50">·</span>}
288
+ </button>
289
+ );
290
+ })}
291
+ </div>
292
+ {multiline ? (
293
+ <textarea
294
+ value={current}
295
+ onChange={(e) => onChange({ ...value, [locale]: e.target.value })}
296
+ className="w-full p-3 text-sm bg-white text-ink outline-none min-h-[100px] resize-y font-sans"
297
+ />
298
+ ) : (
299
+ <input
300
+ type="text"
301
+ value={current}
302
+ onChange={(e) => onChange({ ...value, [locale]: e.target.value })}
303
+ className="w-full p-3 text-sm bg-white text-ink outline-none"
304
+ />
305
+ )}
306
+ </div>
307
+ </Field>
308
+ );
309
+ }
310
+
311
+ /* -------------------- Image -------------------- */
312
+
313
+ function ImageField({
314
+ value,
315
+ onChange,
316
+ label,
317
+ }: {
318
+ value: { src: string; alt: Record<string, string>; width?: number; height?: number };
319
+ onChange: (v: {
320
+ src: string;
321
+ alt: Record<string, string>;
322
+ width?: number;
323
+ height?: number;
324
+ }) => void;
325
+ label?: string;
326
+ }) {
327
+ const { ImageComponent, FocusPickerComponent } = useDeps();
328
+ const [pickerOpen, setPickerOpen] = useState(false);
329
+ const isVideo = /\.(mp4|webm|mov)(\?|$)/i.test(value.src);
330
+ const [focusOpen, setFocusOpen] = useState(false);
331
+ return (
332
+ <Field label={label}>
333
+ <div className="border border-ink/15 bg-white p-3 space-y-3 min-w-0">
334
+ <div className="flex gap-3 items-start min-w-0">
335
+ {value.src ? (
336
+ isVideo ? (
337
+ <video
338
+ src={value.src}
339
+ muted
340
+ className="w-24 h-24 shrink-0 object-cover border border-ink/10 bg-ice/40"
341
+ />
342
+ ) : (
343
+ <ImageComponent
344
+ src={value.src}
345
+ responsive={false}
346
+ alt=""
347
+ className="w-24 h-24 shrink-0 object-cover border border-ink/10 bg-ice/40"
348
+ />
349
+ )
350
+ ) : (
351
+ <div className="w-24 h-24 shrink-0 border border-dashed border-ink/20 grid place-items-center text-[0.6rem] uppercase tracking-[0.2em] text-ink/40">
352
+ no media
353
+ </div>
354
+ )}
355
+ <div className="flex-1 min-w-0 space-y-2">
356
+ <label className="block text-[0.6rem] uppercase tracking-[0.2em] text-ink/55">
357
+ Source URL
358
+ </label>
359
+ <div className="flex flex-wrap gap-2 min-w-0">
360
+ <input
361
+ type="text"
362
+ value={value.src}
363
+ onChange={(e) => onChange({ ...value, src: e.target.value })}
364
+ placeholder="https://…"
365
+ className="w-full min-w-0 border border-ink/15 p-2 text-sm text-ink bg-white outline-none"
366
+ />
367
+ <button
368
+ type="button"
369
+ onClick={() => setPickerOpen(true)}
370
+ className="inline-flex shrink-0 items-center gap-1 border border-ink/20 px-3 py-2 text-[0.7rem] uppercase tracking-widest hover:border-sea"
371
+ >
372
+ <ImageIcon className="size-3.5" /> Library
373
+ </button>
374
+ {value.src && !isVideo ? (
375
+ <button
376
+ type="button"
377
+ onClick={() => setFocusOpen(true)}
378
+ className="inline-flex shrink-0 items-center gap-1 border border-ink/20 px-3 py-2 text-[0.7rem] uppercase tracking-widest hover:border-sea"
379
+ title="Choose which part of the image stays visible when cropped"
380
+ >
381
+ <Crosshair className="size-3.5" /> Focus
382
+ </button>
383
+ ) : null}
384
+ </div>
385
+
386
+ <div className="flex flex-wrap gap-2 min-w-0">
387
+ <div className="flex-1 min-w-[6rem]">
388
+ <label className="block text-[0.6rem] uppercase tracking-[0.2em] text-ink/55">
389
+ Width
390
+ </label>
391
+ <input
392
+ type="number"
393
+ value={value.width ?? ""}
394
+ onChange={(e) =>
395
+ onChange({
396
+ ...value,
397
+ width: e.target.value ? Number(e.target.value) : undefined,
398
+ })
399
+ }
400
+ className="w-full min-w-0 border border-ink/15 p-2 text-sm bg-white text-ink outline-none"
401
+ />
402
+ </div>
403
+ <div className="flex-1 min-w-[6rem]">
404
+ <label className="block text-[0.6rem] uppercase tracking-[0.2em] text-ink/55">
405
+ Height
406
+ </label>
407
+ <input
408
+ type="number"
409
+ value={value.height ?? ""}
410
+ onChange={(e) =>
411
+ onChange({
412
+ ...value,
413
+ height: e.target.value ? Number(e.target.value) : undefined,
414
+ })
415
+ }
416
+ className="w-full min-w-0 border border-ink/15 p-2 text-sm bg-white text-ink outline-none"
417
+ />
418
+ </div>
419
+ </div>
420
+ </div>
421
+ </div>
422
+ <LocalizedStringField
423
+ value={value.alt}
424
+ onChange={(alt) => onChange({ ...value, alt })}
425
+ label="Alt text (per language, required for SEO)"
426
+ />
427
+ </div>
428
+ {pickerOpen && (
429
+ <MediaPickerDialog
430
+ accept="any"
431
+ onPick={(m) => onChange({ ...value, src: m.url })}
432
+ onClose={() => setPickerOpen(false)}
433
+ />
434
+ )}
435
+ {focusOpen && value.src ? (
436
+ <FocusPickerComponent
437
+ src={value.src}
438
+ modal
439
+ title={value.src.split("/").pop()}
440
+ onClose={() => setFocusOpen(false)}
441
+ />
442
+ ) : null}
443
+ </Field>
444
+ );
445
+ }
446
+
447
+ /* -------------------- Array -------------------- */
448
+
449
+ function ArrayField({
450
+ value,
451
+ onChange,
452
+ path,
453
+ depth,
454
+ label,
455
+ }: {
456
+ value: unknown[];
457
+ onChange: (v: unknown[]) => void;
458
+ path: string;
459
+ depth: number;
460
+ label?: string;
461
+ }) {
462
+ const deps = useDeps();
463
+ const [openIdx, setOpenIdx] = useState<number | null>(value.length <= 3 ? 0 : null);
464
+ // Stable per-position ids so dnd-kit can reorder items whose original data has no id.
465
+ const [ids, setIds] = useState<string[]>(() =>
466
+ value.map((_, i) => `row_${i}_${Math.random().toString(36).slice(2, 8)}`),
467
+ );
468
+ if (ids.length !== value.length) {
469
+ // Rebuild when items are added/removed externally (add/remove below always keeps ids in sync).
470
+ setIds(value.map((_, i) => `row_${i}_${Math.random().toString(36).slice(2, 8)}`));
471
+ }
472
+
473
+ const sensors = useSensors(
474
+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
475
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
476
+ );
477
+
478
+ const update = (i: number, next: unknown) => {
479
+ const copy = value.slice();
480
+ copy[i] = next;
481
+ onChange(copy);
482
+ };
483
+ const move = (i: number, dir: -1 | 1) => {
484
+ const j = i + dir;
485
+ if (j < 0 || j >= value.length) return;
486
+ onChange(arrayMove(value.slice(), i, j));
487
+ setIds((prev) => arrayMove(prev, i, j));
488
+ setOpenIdx(j);
489
+ };
490
+ const remove = (i: number) => {
491
+ const copy = value.slice();
492
+ copy.splice(i, 1);
493
+ onChange(copy);
494
+ setIds((prev) => {
495
+ const nx = prev.slice();
496
+ nx.splice(i, 1);
497
+ return nx;
498
+ });
499
+ setOpenIdx(null);
500
+ };
501
+ const add = () => {
502
+ const template = value[0] ?? "";
503
+ const next = value.concat([blankLike(template, deps)]);
504
+ onChange(next);
505
+ setIds((prev) => [...prev, `row_${prev.length}_${Math.random().toString(36).slice(2, 8)}`]);
506
+ setOpenIdx(next.length - 1);
507
+ };
508
+
509
+ const onDragEnd = (e: DragEndEvent) => {
510
+ const { active, over } = e;
511
+ if (!over || active.id === over.id) return;
512
+ const oi = ids.indexOf(String(active.id));
513
+ const ni = ids.indexOf(String(over.id));
514
+ if (oi < 0 || ni < 0) return;
515
+ onChange(arrayMove(value.slice(), oi, ni));
516
+ setIds((prev) => arrayMove(prev, oi, ni));
517
+ if (openIdx === oi) setOpenIdx(ni);
518
+ else if (openIdx === ni) setOpenIdx(oi);
519
+ };
520
+
521
+ return (
522
+ <Field label={label ? `${label} (${value.length})` : undefined}>
523
+ <div className="border border-ink/10 bg-ice/20 min-w-0">
524
+ {value.length === 0 && <div className="p-4 text-xs text-ink/50 italic">Empty list</div>}
525
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
526
+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>
527
+ <ul className="divide-y divide-ink/10">
528
+ {value.map((item, i) => (
529
+ <SortableArrayRow
530
+ key={ids[i]}
531
+ id={ids[i]!}
532
+ index={i}
533
+ lastIndex={value.length - 1}
534
+ open={openIdx === i}
535
+ summary={itemSummary(item, deps)}
536
+ onToggle={() => setOpenIdx(openIdx === i ? null : i)}
537
+ onMoveUp={() => move(i, -1)}
538
+ onMoveDown={() => move(i, 1)}
539
+ onRemove={() => {
540
+ if (confirm("Remove this item?")) remove(i);
541
+ }}
542
+ >
543
+ {openIdx === i && (
544
+ <div className="border-t border-ink/10 p-4 bg-ice/10">
545
+ <Node
546
+ value={item}
547
+ onChange={(next) => update(i, next)}
548
+ path={`${path}[${i}]`}
549
+ depth={depth + 1}
550
+ />
551
+ </div>
552
+ )}
553
+ </SortableArrayRow>
554
+ ))}
555
+ </ul>
556
+ </SortableContext>
557
+ </DndContext>
558
+ <div className="border-t border-ink/10 p-2">
559
+ <button
560
+ type="button"
561
+ onClick={add}
562
+ className="inline-flex items-center gap-2 text-xs uppercase tracking-[0.18em] text-ink/70 hover:text-ink px-2 py-1"
563
+ >
564
+ <Plus className="size-3" /> Add item
565
+ </button>
566
+ </div>
567
+ </div>
568
+ </Field>
569
+ );
570
+ }
571
+
572
+ function SortableArrayRow({
573
+ id,
574
+ index,
575
+ lastIndex,
576
+ open,
577
+ summary,
578
+ onToggle,
579
+ onMoveUp,
580
+ onMoveDown,
581
+ onRemove,
582
+ children,
583
+ }: {
584
+ id: string;
585
+ index: number;
586
+ lastIndex: number;
587
+ open: boolean;
588
+ summary: string;
589
+ onToggle: () => void;
590
+ onMoveUp: () => void;
591
+ onMoveDown: () => void;
592
+ onRemove: () => void;
593
+ children?: ReactNode;
594
+ }) {
595
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
596
+ id,
597
+ });
598
+ const style: CSSProperties = {
599
+ transform: CSS.Transform.toString(transform),
600
+ transition,
601
+ opacity: isDragging ? 0.5 : 1,
602
+ };
603
+ return (
604
+ <li ref={setNodeRef} style={style} className="bg-white min-w-0">
605
+ <div className="flex items-center gap-2 px-3 py-2 min-w-0">
606
+ <button
607
+ {...attributes}
608
+ {...listeners}
609
+ type="button"
610
+ className="shrink-0 cursor-grab active:cursor-grabbing text-ink/30 hover:text-ink/70 p-1"
611
+ title="Drag to reorder"
612
+ onClick={(e) => e.stopPropagation()}
613
+ >
614
+ <GripVertical className="size-3.5" />
615
+ </button>
616
+ <button
617
+ type="button"
618
+ onClick={onToggle}
619
+ className="flex-1 min-w-0 text-left text-xs flex items-center gap-2"
620
+ >
621
+ {open ? (
622
+ <ChevronDown className="size-3 shrink-0" />
623
+ ) : (
624
+ <ChevronRight className="size-3 shrink-0" />
625
+ )}
626
+ <span className="text-ink/50 shrink-0">#{index + 1}</span>
627
+ <span className="text-ink truncate">{summary}</span>
628
+ </button>
629
+
630
+ <button
631
+ type="button"
632
+ onClick={onMoveUp}
633
+ disabled={index === 0}
634
+ className="shrink-0 p-1 text-ink/50 hover:text-ink disabled:opacity-30"
635
+ title="Move up"
636
+ >
637
+ <ArrowUp className="size-3" />
638
+ </button>
639
+ <button
640
+ type="button"
641
+ onClick={onMoveDown}
642
+ disabled={index === lastIndex}
643
+ className="shrink-0 p-1 text-ink/50 hover:text-ink disabled:opacity-30"
644
+ title="Move down"
645
+ >
646
+ <ArrowDown className="size-3" />
647
+ </button>
648
+ <button
649
+ type="button"
650
+ onClick={onRemove}
651
+ className="shrink-0 p-1 text-ink/50 hover:text-red-600"
652
+ title="Remove"
653
+ >
654
+ <Trash2 className="size-3" />
655
+ </button>
656
+ </div>
657
+ {children}
658
+ </li>
659
+ );
660
+ }
661
+
662
+ /** Best-effort one-line summary for a collapsed list row. */
663
+ export function itemSummary(item: unknown, deps: SectionFormDeps): string {
664
+ const isLocalizedString = makeIsLocalizedString(deps.locales);
665
+ const fallback = deps.defaultLocale;
666
+ if (typeof item === "string") return item.slice(0, 60);
667
+ if (typeof item === "number" || typeof item === "boolean") return String(item);
668
+ if (isLocalizedString(item)) return item[fallback] ?? Object.values(item)[0] ?? "";
669
+ if (isLocalizedImage(item))
670
+ return item.alt?.[fallback] ?? item.src.split("/").pop() ?? "image";
671
+ if (isPlainObject(item)) {
672
+ for (const k of [
673
+ "name",
674
+ "label",
675
+ "title",
676
+ "quote",
677
+ "value",
678
+ "tripNo",
679
+ "courseNo",
680
+ "location",
681
+ ]) {
682
+ const v = item[k];
683
+ if (isLocalizedString(v)) return v[fallback] ?? Object.values(v)[0] ?? "";
684
+ if (typeof v === "string") return v;
685
+ }
686
+ return "…";
687
+ }
688
+ return "";
689
+ }
690
+
691
+ /* -------------------- Object -------------------- */
692
+
693
+ function ObjectField({
694
+ value,
695
+ onChange,
696
+ path,
697
+ depth,
698
+ label,
699
+ }: {
700
+ value: Record<string, unknown>;
701
+ onChange: (v: Record<string, unknown>) => void;
702
+ path: string;
703
+ depth: number;
704
+ label?: string;
705
+ }) {
706
+ const entries = Object.entries(value);
707
+ const content = (
708
+ <div className={depth === 0 ? "space-y-5" : "space-y-4"}>
709
+ {entries.map(([k, v]) => (
710
+ <Node
711
+ key={k}
712
+ value={v}
713
+ onChange={(nv) => onChange({ ...value, [k]: nv })}
714
+ path={path ? `${path}.${k}` : k}
715
+ depth={depth + 1}
716
+ fieldLabel={labelize(k)}
717
+ />
718
+ ))}
719
+ </div>
720
+ );
721
+ if (depth === 0) return content;
722
+ return (
723
+ <Field label={label}>
724
+ <div className="border border-ink/10 bg-white p-4 min-w-0">{content}</div>
725
+ </Field>
726
+ );
727
+ }
728
+
729
+ /* -------------------- Primitive -------------------- */
730
+
731
+ function PrimitiveField({
732
+ value,
733
+ onChange,
734
+ label,
735
+ hint,
736
+ }: {
737
+ value: unknown;
738
+ onChange: (v: unknown) => void;
739
+ label?: string;
740
+ hint?: string;
741
+ }) {
742
+ if (typeof value === "boolean") {
743
+ return (
744
+ <Field label={label}>
745
+ <label className="inline-flex items-center gap-2 text-sm text-ink">
746
+ <input
747
+ type="checkbox"
748
+ checked={value}
749
+ onChange={(e) => onChange(e.target.checked)}
750
+ className="size-4"
751
+ />
752
+ <span className="text-ink/70">{value ? "On" : "Off"}</span>
753
+ </label>
754
+ </Field>
755
+ );
756
+ }
757
+ if (typeof value === "number") {
758
+ return (
759
+ <Field label={label}>
760
+ <input
761
+ type="number"
762
+ min={0}
763
+ value={value}
764
+ onChange={(e) => onChange(e.target.value === "" ? 0 : Number(e.target.value))}
765
+ className="w-full border border-ink/15 p-2 text-sm bg-white text-ink outline-none"
766
+ />
767
+ {hint && <p className="mt-1 text-[0.7rem] leading-snug text-ink/55">{hint}</p>}
768
+ </Field>
769
+ );
770
+ }
771
+ const str = value == null ? "" : String(value);
772
+ const isUrl =
773
+ /^https?:\/\//.test(str) ||
774
+ (label?.toLowerCase().includes("url") ?? false) ||
775
+ (label?.toLowerCase().includes("href") ?? false);
776
+ return (
777
+ <Field label={label}>
778
+ <input
779
+ type="text"
780
+ value={str}
781
+ onChange={(e) => onChange(e.target.value)}
782
+ placeholder={isUrl ? "https://… or /path" : ""}
783
+ className="w-full border border-ink/15 p-2 text-sm bg-white text-ink outline-none"
784
+ />
785
+ </Field>
786
+ );
787
+ }
788
+
789
+ /* -------------------- Field wrapper -------------------- */
790
+
791
+ function Field({ label, children }: { label?: string; children: ReactNode }) {
792
+ if (!label) return <>{children}</>;
793
+ return (
794
+ <div className="min-w-0">
795
+ <div className="mb-1 text-[0.65rem] uppercase tracking-[0.2em] text-ink/60">{label}</div>
796
+ {children}
797
+ </div>
798
+ );
799
+ }