@bygghammar/cms-platform 0.13.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.13.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
+ }
@@ -2,11 +2,11 @@
2
2
  * Host platform contract.
3
3
  *
4
4
  * Blocks and inspectors already reach the host through `../host`. Backoffice
5
- * *screens* additionally need data: pages, forms, media, SEO and audit access.
6
- * Those calls are per-site (each site owns its own database, server functions
7
- * and auth), while the screens themselves are identical everywhere — so the
8
- * package declares the contract here and each site registers an adapter at
9
- * startup.
5
+ * *screens* additionally need data: pages, global sections, forms, submissions,
6
+ * media, SEO, redirects and audit access. Those calls are per-site (each site
7
+ * owns its own database, server functions and auth), while the screens
8
+ * themselves are identical everywhere — so the package declares the contract
9
+ * here and each site registers an adapter at startup.
10
10
  *
11
11
  * Adapters return plain data. No Supabase client, request or response object
12
12
  * ever crosses this boundary, which keeps the package usable by a site that is
@@ -15,17 +15,60 @@
15
15
 
16
16
  import type { Json } from "../i18n/json";
17
17
 
18
+ /** Contract revision. Bump when a required member is added or changed. */
19
+ export const PLATFORM_DATA_VERSION = 2;
20
+
21
+ export type BlockInstanceLike = {
22
+ id: string;
23
+ type: string;
24
+ name?: string;
25
+ props?: Record<string, unknown>;
26
+ visible?: boolean;
27
+ };
28
+
18
29
  export type PageSummary = {
30
+ id: string;
19
31
  key: string;
20
- title: string;
32
+ name: string;
33
+ isSystem: boolean;
34
+ status: string;
21
35
  updatedAt: string | null;
22
- published: boolean;
36
+ currentVersionId: string | null;
23
37
  };
24
38
 
25
- export type PageDraft = {
26
- key: string;
39
+ export type PageEditState = {
40
+ page: {
41
+ id: string;
42
+ key: string;
43
+ name: string;
44
+ isSystem: boolean;
45
+ status: string;
46
+ currentVersionId: string | null;
47
+ };
48
+ blocks: BlockInstanceLike[];
49
+ };
50
+
51
+ export type PageVersionSummary = {
52
+ id: string;
27
53
  versionNo: number;
28
- blocks: Json;
54
+ note: string | null;
55
+ createdAt: string | null;
56
+ createdByEmail: string | null;
57
+ };
58
+
59
+ export type SavePageVersionInput = {
60
+ pageId: string;
61
+ blocks: BlockInstanceLike[];
62
+ publish?: boolean;
63
+ note?: string;
64
+ };
65
+
66
+ export type GlobalSectionSummary = {
67
+ id: string;
68
+ key: string;
69
+ name: string;
70
+ kind: string | null;
71
+ updatedAt: string | null;
29
72
  };
30
73
 
31
74
  export type MediaEntry = {
@@ -36,17 +79,102 @@ export type MediaEntry = {
36
79
  updatedAt: string | null;
37
80
  };
38
81
 
82
+ /** A file in the site's media bin (soft-deleted, restorable by id). */
83
+ export type MediaTrashEntry = {
84
+ id: string;
85
+ originalPath: string;
86
+ size: number;
87
+ contentType: string | null;
88
+ deletedAt: string | null;
89
+ url: string;
90
+ };
91
+
92
+ export type RedirectEntry = {
93
+ id?: string;
94
+ fromPath: string;
95
+ toPath: string;
96
+ /** 301 or 302. */
97
+ status: number;
98
+ };
99
+
100
+ /**
101
+ * SEO overrides are stored per page key, with per-locale slug and meta maps —
102
+ * one row covers every locale of a page.
103
+ */
104
+ export type PageSeoRow = {
105
+ pageKey: string;
106
+ /** locale -> slug */
107
+ slugs: Json;
108
+ /** locale -> meta values */
109
+ seo: Json;
110
+ };
111
+
112
+ export type FormSummary = {
113
+ id: string;
114
+ key: string;
115
+ name: string;
116
+ updatedAt: string | null;
117
+ };
118
+
119
+ export type SubmissionSummary = {
120
+ id: string;
121
+ formKey: string;
122
+ status: string | null;
123
+ createdAt: string | null;
124
+ payload: Json;
125
+ };
126
+
127
+ export type SubmissionQuery = {
128
+ formKey?: string;
129
+ status?: string;
130
+ page?: number;
131
+ pageSize?: number;
132
+ };
133
+
134
+ export type SubmissionPage = {
135
+ rows: SubmissionSummary[];
136
+ total: number;
137
+ };
138
+
39
139
  /** Data access the shared backoffice screens need from the host site. */
40
140
  export type PlatformData = {
41
141
  pages: {
42
142
  list: () => Promise<PageSummary[]>;
43
- loadDraft: (key: string) => Promise<PageDraft | null>;
44
- saveDraft: (input: PageDraft) => Promise<{ versionNo: number }>;
45
- publish: (key: string, versionNo: number) => Promise<void>;
143
+ loadForEdit: (key: string) => Promise<PageEditState>;
144
+ saveVersion: (input: SavePageVersionInput) => Promise<{ versionId: string; versionNo: number }>;
145
+ listVersions?: (pageId: string) => Promise<PageVersionSummary[]>;
146
+ restoreVersion?: (input: { pageId: string; versionId: string }) => Promise<void>;
147
+ create?: (input: { key: string; name: string }) => Promise<{ id: string }>;
148
+ rename?: (input: { id: string; name: string }) => Promise<void>;
149
+ remove?: (id: string) => Promise<void>;
150
+ };
151
+ globalSections?: {
152
+ list: () => Promise<GlobalSectionSummary[]>;
153
+ loadForEdit: (key: string) => Promise<PageEditState>;
154
+ saveVersion: (input: SavePageVersionInput) => Promise<{ versionId: string; versionNo: number }>;
46
155
  };
47
156
  media: {
48
157
  list: () => Promise<MediaEntry[]>;
49
- remove: (paths: string[]) => Promise<void>;
158
+ /** Soft delete a single library path (variants included by the host). */
159
+ remove: (path: string) => Promise<void>;
160
+ listTrash?: () => Promise<MediaTrashEntry[]>;
161
+ restore?: (trashId: string) => Promise<void>;
162
+ purge?: (trashId: string) => Promise<void>;
163
+ };
164
+ seo?: {
165
+ list: () => Promise<PageSeoRow[]>;
166
+ save: (row: PageSeoRow) => Promise<void>;
167
+ removeOverride: (input: { pageKey: string }) => Promise<void>;
168
+ };
169
+ redirects?: {
170
+ list: () => Promise<RedirectEntry[]>;
171
+ save: (entry: RedirectEntry) => Promise<void>;
172
+ remove: (id: string) => Promise<void>;
173
+ };
174
+ forms?: {
175
+ list: () => Promise<FormSummary[]>;
176
+ listSubmissions: (query?: SubmissionQuery) => Promise<SubmissionPage>;
177
+ setSubmissionStatus: (input: { ids: string[]; status: string }) => Promise<void>;
50
178
  };
51
179
  audit?: {
52
180
  log: (event: { action: string; target: string; detail?: Json }) => Promise<void>;
@@ -61,6 +189,8 @@ export type PlatformSite = {
61
189
  backofficeBasePath: string;
62
190
  /** Public site origin, used for preview links. */
63
191
  publicOrigin?: string;
192
+ /** Locales the site authors content in; first entry is the default. */
193
+ locales?: string[];
64
194
  };
65
195
 
66
196
  export type HostPlatform = {
@@ -88,3 +218,32 @@ export function getHostPlatform(): HostPlatform {
88
218
  export function hasHostPlatform(): boolean {
89
219
  return platform !== null;
90
220
  }
221
+
222
+ /** Required members every adapter must implement, used by host-side tests. */
223
+ export const REQUIRED_PLATFORM_DATA: Record<string, readonly string[]> = {
224
+ pages: ["list", "loadForEdit", "saveVersion"],
225
+ media: ["list", "remove"],
226
+ };
227
+
228
+ /**
229
+ * Assert an adapter implements every required member. Sites call this in a test
230
+ * (or at startup) so a contract bump fails loudly instead of at click time.
231
+ */
232
+ export function assertPlatformData(data: PlatformData): void {
233
+ const missing: string[] = [];
234
+ for (const [group, members] of Object.entries(REQUIRED_PLATFORM_DATA)) {
235
+ const bag = (data as unknown as Record<string, Record<string, unknown> | undefined>)[group];
236
+ if (!bag) {
237
+ missing.push(group);
238
+ continue;
239
+ }
240
+ for (const member of members) {
241
+ if (typeof bag[member] !== "function") missing.push(`${group}.${member}`);
242
+ }
243
+ }
244
+ if (missing.length > 0) {
245
+ throw new Error(
246
+ `@bygghammar/cms-platform: host platform adapter is missing ${missing.join(", ")}`,
247
+ );
248
+ }
249
+ }