@mapomodule/uikit 1.0.0-alpha.9 → 2.0.0-beta.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.
Files changed (94) hide show
  1. package/README.md +167 -0
  2. package/dist/index.d.cts +2 -0
  3. package/dist/index.d.mts +2 -0
  4. package/dist/index.d.ts +2 -0
  5. package/dist/index.mjs +18 -0
  6. package/dist/module.d.cts +2 -0
  7. package/dist/module.d.mts +2 -0
  8. package/dist/module.d.ts +2 -0
  9. package/dist/module.json +9 -0
  10. package/dist/module.mjs +18 -0
  11. package/dist/types.d.mts +13 -0
  12. package/package.json +63 -10
  13. package/src/index.ts +10 -0
  14. package/src/module.ts +181 -0
  15. package/src/runtime/assets/main.css +59 -0
  16. package/src/runtime/components/MapoConfirmDialog.vue +34 -0
  17. package/src/runtime/components/MapoDetail.vue +861 -0
  18. package/src/runtime/components/MapoDetailLangSwitch.vue +166 -0
  19. package/src/runtime/components/MapoList.vue +339 -0
  20. package/src/runtime/components/MapoListActions.vue +152 -0
  21. package/src/runtime/components/MapoListFilters.vue +289 -0
  22. package/src/runtime/components/MapoListHead.vue +12 -0
  23. package/src/runtime/components/MapoListQuickEdit.vue +163 -0
  24. package/src/runtime/components/MapoListTable.vue +926 -0
  25. package/src/runtime/components/MapoListTabs.vue +48 -0
  26. package/src/runtime/components/MapoLogin.vue +209 -0
  27. package/src/runtime/components/MapoLogoutButton.vue +46 -0
  28. package/src/runtime/components/MapoRootComponents.vue +9 -0
  29. package/src/runtime/components/MapoSidebar.vue +112 -0
  30. package/src/runtime/components/MapoSidebarList.vue +35 -0
  31. package/src/runtime/components/MapoSidebarListItem.vue +79 -0
  32. package/src/runtime/components/MapoSidebarProfile.vue +57 -0
  33. package/src/runtime/components/MapoSnackBar.vue +42 -0
  34. package/src/runtime/components/MapoThemeToggle.vue +23 -0
  35. package/src/runtime/components/MapoTopbar.vue +36 -0
  36. package/src/runtime/layouts/default.vue +53 -0
  37. package/src/runtime/layouts/empty.vue +9 -0
  38. package/src/runtime/page-meta.nuxt.d.ts +45 -0
  39. package/src/runtime/pages/index.vue +14 -0
  40. package/src/runtime/pages/login.vue +7 -0
  41. package/src/runtime/types/list.ts +64 -0
  42. package/CHANGELOG.md +0 -177
  43. package/LICENSE.md +0 -20
  44. package/assets/mixins.scss +0 -22
  45. package/assets/variables.scss +0 -18
  46. package/components/ConfirmDialog.vue +0 -152
  47. package/components/Detail/Detail.vue +0 -566
  48. package/components/Detail/DetailField.vue +0 -142
  49. package/components/Detail/DetailLangSwitch.vue +0 -72
  50. package/components/Detail/defaults.js +0 -57
  51. package/components/DropArea.vue +0 -250
  52. package/components/List/List.vue +0 -254
  53. package/components/List/ListActions.vue +0 -164
  54. package/components/List/ListFilters.vue +0 -334
  55. package/components/List/ListHead.vue +0 -67
  56. package/components/List/ListQuickEdit.vue +0 -302
  57. package/components/List/ListTable.vue +0 -406
  58. package/components/List/ListTabs.vue +0 -65
  59. package/components/Login.vue +0 -124
  60. package/components/Logo.vue +0 -79
  61. package/components/LogoutButton.vue +0 -39
  62. package/components/MediaManager/MediaEditor.vue +0 -309
  63. package/components/MediaManager/MediaFolders.vue +0 -263
  64. package/components/MediaManager/MediaGallery.vue +0 -206
  65. package/components/MediaManager/MediaManager.vue +0 -233
  66. package/components/MediaManager/MediaManagerDialog.vue +0 -96
  67. package/components/MediaManager/MediaPreview.vue +0 -180
  68. package/components/MediaManager/MediaUploader.vue +0 -165
  69. package/components/RootComponents.vue +0 -25
  70. package/components/SnackBar.vue +0 -70
  71. package/components/fields/DateField.vue +0 -74
  72. package/components/fields/FksField.vue +0 -60
  73. package/components/fields/MediaField.vue +0 -213
  74. package/components/fields/MediaM2mField.vue +0 -243
  75. package/components/fields/SeoPreview.vue +0 -89
  76. package/components/fields/wygEditor/defaults.js +0 -55
  77. package/components/fields/wygEditor/utils/events.js +0 -64
  78. package/components/fields/wygEditor/utils/mapomedia.plugin.js +0 -31
  79. package/components/fields/wygEditor/utils/script.injector.js +0 -29
  80. package/components/fields/wygEditor/wygEditor.vue +0 -196
  81. package/components/layout/Sidebar/Sidebar.vue +0 -80
  82. package/components/layout/Sidebar/SidebarFooter.vue +0 -71
  83. package/components/layout/Sidebar/SidebarList.vue +0 -44
  84. package/components/layout/Sidebar/SidebarListItem.vue +0 -144
  85. package/components/layout/Topbar/Topbar.vue +0 -27
  86. package/components/layout/routebuilder.js +0 -48
  87. package/defaults.js +0 -29
  88. package/layouts/default.vue +0 -21
  89. package/layouts/empty.vue +0 -6
  90. package/layouts/error.vue +0 -45
  91. package/module.js +0 -78
  92. package/pages/index.vue +0 -35
  93. package/pages/login.vue +0 -10
  94. package/static/favicon.ico +0 -0
@@ -0,0 +1,861 @@
1
+ <script setup lang="ts" generic="T extends object">
2
+ import {
3
+ ref,
4
+ computed,
5
+ toRaw,
6
+ watch,
7
+ useSlots,
8
+ onMounted,
9
+ onBeforeUnmount,
10
+ provide,
11
+ type Ref,
12
+ type VNode,
13
+ } from "vue";
14
+ import { useRouter, onBeforeRouteLeave } from "vue-router";
15
+ import { useNuxtApp } from "#app";
16
+ import { objectDiff, debounce, deepClone } from "@mapomodule/utils";
17
+ import { useCrud } from "@mapomodule/core/runtime/api/crud";
18
+ import { useSnackStore } from "@mapomodule/store/runtime/stores/snack";
19
+ import { useConfirmStore } from "@mapomodule/store/runtime/stores/confirm";
20
+ import type { AnyFieldDescriptor, FieldRegistry } from "@mapomodule/form/types";
21
+ import { usePermissions } from "@mapomodule/store/runtime/composables/usePermissions";
22
+ import type { MultipartPolicy } from "@mapomodule/core";
23
+
24
+ // ─── Props ────────────────────────────────────────────────────────────────────
25
+
26
+ const props = withDefaults(
27
+ defineProps<{
28
+ /** REST endpoint passed to useCrud. */
29
+ endpoint: string;
30
+ /** Record id. Pass `'new'` to create. */
31
+ id: string | number;
32
+ /** Fields for the main body form. */
33
+ fields: AnyFieldDescriptor<T>[];
34
+ /** Fields for the sidebar form (optional). */
35
+ sidebarFields?: AnyFieldDescriptor<T>[];
36
+ /** Translation language codes (e.g. ['it', 'en']). */
37
+ languages?: string[];
38
+ /** Human readable model name shown in the page title. */
39
+ modelName?: string | null;
40
+ /** Sidebar column span (1–11 in a 12-col grid). */
41
+ sidebarCols?: number;
42
+ /** Keep sidebar sticky while scrolling. */
43
+ sticky?: boolean;
44
+ /** Send PATCH (diff only) on update instead of PUT. */
45
+ usePatch?: boolean;
46
+ /** Force read-only mode. */
47
+ readonly?: boolean;
48
+ /** Field registry. Falls back to $mapoFormRegistry if omitted. */
49
+ registry?: FieldRegistry | null;
50
+ /**
51
+ * Enable automatic draft persistence to localStorage.
52
+ * When `true`, the key is auto-generated as `${endpoint}:${id}`.
53
+ * Provide `draftKey` to override with a custom key.
54
+ * Drafts expire after 24 h. The built-in banner handles restore/discard.
55
+ */
56
+ draft?: boolean;
57
+ /**
58
+ * Custom localStorage key for draft persistence. Requires `draft: true`.
59
+ * Key is prefixed with `mapo:draft:`.
60
+ * Example: `"article:42"` → `mapo:draft:article:42`.
61
+ * Falls back to `${endpoint}:${id}` when omitted.
62
+ */
63
+ draftKey?: string;
64
+ /**
65
+ * Multipart upload policy passed to every CRUD mutation.
66
+ * - `"auto"` (default): sends FormData only when File/Blob fields are present.
67
+ * - `"force"`: always sends FormData.
68
+ * - `"disable"`: always sends JSON.
69
+ */
70
+ multipart?: MultipartPolicy;
71
+ /**
72
+ * Django model name for permission gating (e.g. `"article"`).
73
+ * When provided, Save/Create is hidden for users lacking `add`/`change`,
74
+ * and Delete is hidden for users lacking `delete`.
75
+ * Superusers are never restricted.
76
+ */
77
+ permissionModel?: string;
78
+ /**
79
+ * Field name on the model whose value is used as the preview URL.
80
+ * When set, a "Preview" button appears in the sidebar that opens the URL in an iframe modal.
81
+ */
82
+ previewField?: string;
83
+ /**
84
+ * Override the language list regardless of what `lang_info.site_languages`
85
+ * returns from the backend. Takes precedence over both `languages` prop and
86
+ * the auto-derived list.
87
+ */
88
+ forceLanguages?: string[];
89
+ }>(),
90
+ {
91
+ sidebarFields: () => [],
92
+ languages: () => [],
93
+ sidebarCols: 4,
94
+ sticky: true,
95
+ usePatch: true,
96
+ readonly: false,
97
+ modelName: null,
98
+ registry: null,
99
+ draft: false,
100
+ draftKey: undefined,
101
+ multipart: "auto",
102
+ permissionModel: undefined,
103
+ previewField: undefined,
104
+ forceLanguages: undefined,
105
+ },
106
+ );
107
+
108
+ const emit = defineEmits<{
109
+ (e: "saved", model: T): void;
110
+ (e: "deleted"): void;
111
+ /**
112
+ * Fired after fetching when a valid, non-expired draft is found in localStorage.
113
+ * Call `restore()` to apply the draft to the model, or `discard()` to delete it.
114
+ */
115
+ (
116
+ e: "draft-found",
117
+ draft: T,
118
+ savedAt: Date,
119
+ restore: () => void,
120
+ discard: () => void,
121
+ ): void;
122
+ }>();
123
+
124
+ // ─── State ───────────────────────────────────────────────────────────────────
125
+
126
+ const { $mapoFormRegistry } = useNuxtApp() as unknown as {
127
+ $mapoFormRegistry: FieldRegistry;
128
+ };
129
+ const registry = computed(() => props.registry ?? $mapoFormRegistry);
130
+
131
+ const router = useRouter();
132
+ const snack = useSnackStore();
133
+ const confirm = useConfirmStore();
134
+ const crud = useCrud<T>(props.endpoint);
135
+
136
+ type ValidateClientFn = () => {
137
+ valid: boolean;
138
+ errors: Record<string, string>;
139
+ };
140
+ const formValidators: ValidateClientFn[] = [];
141
+
142
+ provide("mapoDetailRegisterValidator", (fn: ValidateClientFn) => {
143
+ formValidators.push(fn);
144
+ return () => {
145
+ const idx = formValidators.indexOf(fn);
146
+ if (idx >= 0) formValidators.splice(idx, 1);
147
+ };
148
+ });
149
+
150
+ const isNew = computed(() => String(props.id) === "new");
151
+ // Cast keeps the generic exact: `ref<T>` would expose `UnwrapRef<T>`, which
152
+ // TS cannot prove to extend `object` when forwarding to MapoForm.
153
+ const model = ref({} as T) as Ref<T>;
154
+
155
+ // T is only constrained to `object`; the record id is read structurally.
156
+ function recordId(): string | number {
157
+ return (model.value as { id?: string | number }).id as string | number;
158
+ }
159
+ const backup = ref<T | null>(null);
160
+ const errors = ref<Record<string, string[]>>({});
161
+ // Start in loading state for existing items so MapoForm is never mounted with
162
+ // empty data and then immediately unmounted when the spinner appears on mount.
163
+ const isLoading = ref(String(props.id) !== "new");
164
+ const isSaving = ref(false);
165
+ const isDeleting = ref(false);
166
+ const currentLang = ref(props.languages[0] ?? "");
167
+ const draftBanner = ref<{
168
+ savedAt: Date;
169
+ restore: () => void;
170
+ discard: () => void;
171
+ } | null>(null);
172
+
173
+ const isDirty = computed(
174
+ () =>
175
+ backup.value !== null &&
176
+ Object.keys(objectDiff(backup.value, model.value)).length > 0,
177
+ );
178
+ const mainCols = computed(() => 12 - props.sidebarCols);
179
+
180
+ // ─── Languages (auto-derive from lang_info) ──────────────────────────────────
181
+ // Backends like Camomilla embed site_languages inside the fetched model.
182
+ // We read them after the first successful fetch so the host page doesn't need
183
+ // to hard-code the language list. forceLanguages > props.languages > derived.
184
+ const derivedLangs = ref<string[]>([]);
185
+ const activeLangs = computed<string[]>(() => {
186
+ if (props.forceLanguages?.length) return props.forceLanguages;
187
+ if (props.languages.length) return props.languages;
188
+ return derivedLangs.value;
189
+ });
190
+ watch(
191
+ activeLangs,
192
+ (langs) => {
193
+ if (!currentLang.value && langs.length) currentLang.value = langs[0]!;
194
+ },
195
+ { immediate: true },
196
+ );
197
+
198
+ // ─── Permissions ─────────────────────────────────────────────────────────────
199
+ // When permissionModel is set, save/create buttons are hidden for users who
200
+ // lack the add (new) or change (existing) permission, and the delete button is
201
+ // hidden for users who lack the delete permission.
202
+ const { canAdd, canChange, canDelete: canDeletePerm } = usePermissions();
203
+ const effectiveReadonly = computed(() => {
204
+ if (props.readonly) return true;
205
+ if (!props.permissionModel) return false;
206
+ return isNew.value
207
+ ? !canAdd(props.permissionModel)
208
+ : !canChange(props.permissionModel);
209
+ });
210
+ const canDeleteItem = computed(
211
+ () => !props.permissionModel || canDeletePerm(props.permissionModel),
212
+ );
213
+
214
+ // ─── Preview ─────────────────────────────────────────────────────────────────
215
+ // When previewField is set, the value of that field on the model is used as the
216
+ // URL opened in an iframe modal via the Preview button in the sidebar.
217
+ const previewOpen = ref(false);
218
+ const previewUrl = computed<string | null>(() => {
219
+ if (!props.previewField) return null;
220
+ const url = (model.value as Record<string, unknown>)[props.previewField];
221
+ return typeof url === "string" ? url : null;
222
+ });
223
+
224
+ // When all sidebarFields are flat (no group), we wrap them in a UCard for visual structure.
225
+ // When groups are present, MapoFormGroup already renders its own card-like container.
226
+ const sidebarHasGroups = computed(() =>
227
+ (props.sidebarFields ?? []).some((f) => f.group != null),
228
+ );
229
+ const sidebarStyle = computed(() =>
230
+ props.sticky
231
+ ? {
232
+ position: "sticky" as const,
233
+ top: "var(--mapo-topbar-height, 64px)",
234
+ }
235
+ : {},
236
+ );
237
+
238
+ // Tailwind v4 requires static class strings — dynamic template literals are not scanned by the CSS scanner.
239
+ const MD_COL_SPAN: Record<number, string> = {
240
+ 1: "md:col-span-1",
241
+ 2: "md:col-span-2",
242
+ 3: "md:col-span-3",
243
+ 4: "md:col-span-4",
244
+ 5: "md:col-span-5",
245
+ 6: "md:col-span-6",
246
+ 7: "md:col-span-7",
247
+ 8: "md:col-span-8",
248
+ 9: "md:col-span-9",
249
+ 10: "md:col-span-10",
250
+ 11: "md:col-span-11",
251
+ 12: "md:col-span-12",
252
+ };
253
+ const mainColsClass = computed(
254
+ () => `col-span-12 ${MD_COL_SPAN[mainCols.value] ?? "md:col-span-8"}`,
255
+ );
256
+ const sidebarColsClass = computed(
257
+ () => `col-span-12 ${MD_COL_SPAN[props.sidebarCols] ?? "md:col-span-4"}`,
258
+ );
259
+
260
+ // ─── Draft persistence ────────────────────────────────────────────────────────
261
+
262
+ const DRAFT_TTL = 86_400_000; // 24h
263
+
264
+ function draftStorageKey() {
265
+ if (!props.draft && !props.draftKey) return null;
266
+ const key = props.draftKey ?? `${props.endpoint}:${props.id}`;
267
+ return `mapo:draft:${key}`;
268
+ }
269
+
270
+ function clearDraft() {
271
+ const key = draftStorageKey();
272
+ if (key && typeof localStorage !== "undefined") localStorage.removeItem(key);
273
+ }
274
+
275
+ function checkDraft() {
276
+ const key = draftStorageKey();
277
+ if (!key || typeof localStorage === "undefined") return;
278
+ try {
279
+ const raw = localStorage.getItem(key);
280
+ if (!raw) return;
281
+ const entry = JSON.parse(raw) as { model: T; savedAt: number };
282
+ if (Date.now() - entry.savedAt > DRAFT_TTL) {
283
+ localStorage.removeItem(key);
284
+ return;
285
+ }
286
+ const savedAt = new Date(entry.savedAt);
287
+ const restore = () => {
288
+ Object.assign(model.value, entry.model);
289
+ draftBanner.value = null;
290
+ };
291
+ const discard = () => {
292
+ localStorage.removeItem(key);
293
+ draftBanner.value = null;
294
+ };
295
+ draftBanner.value = { savedAt, restore, discard };
296
+ emit("draft-found", entry.model, savedAt, restore, discard);
297
+ } catch {
298
+ /* corrupted entry — ignore */
299
+ }
300
+ }
301
+
302
+ // Auto-save draft debounced whenever model changes and form is dirty.
303
+ if (props.draft || props.draftKey) {
304
+ const saveDraft = debounce(() => {
305
+ const key = draftStorageKey();
306
+ if (!key || !isDirty.value || typeof localStorage === "undefined") return;
307
+ try {
308
+ localStorage.setItem(
309
+ key,
310
+ JSON.stringify({ model: toRaw(model.value), savedAt: Date.now() }),
311
+ );
312
+ } catch {
313
+ /* quota exceeded — ignore */
314
+ }
315
+ }, 2000);
316
+ watch(model, saveDraft, { deep: true });
317
+ }
318
+
319
+ // ─── Fetch ───────────────────────────────────────────────────────────────────
320
+
321
+ async function fetchModel() {
322
+ if (isNew.value) {
323
+ backup.value = null;
324
+ checkDraft();
325
+ return;
326
+ }
327
+ isLoading.value = true;
328
+ try {
329
+ model.value = await crud.detail(props.id);
330
+ backup.value = deepClone(model.value) as T;
331
+ // Auto-derive languages from the backend response when the host page does
332
+ // not hard-code them. Camomilla embeds site_languages inside lang_info.
333
+ const langInfo = (model.value as Record<string, unknown>)?.lang_info as
334
+ | Record<string, unknown>
335
+ | undefined;
336
+ const siteLangs = langInfo?.site_languages as string[] | undefined;
337
+ if (
338
+ siteLangs?.length &&
339
+ !props.languages.length &&
340
+ !props.forceLanguages?.length
341
+ ) {
342
+ derivedLangs.value = siteLangs;
343
+ }
344
+ checkDraft();
345
+ } catch (err: unknown) {
346
+ const status = (err as { response?: { status?: number } })?.response
347
+ ?.status;
348
+ const detail = (err as { response?: { data?: { detail?: string } } })
349
+ ?.response?.data?.detail;
350
+ snack.show(detail ?? "Failed to load item", "error");
351
+ if (status === 404) router.back();
352
+ } finally {
353
+ isLoading.value = false;
354
+ }
355
+ }
356
+
357
+ // ─── Save ────────────────────────────────────────────────────────────────────
358
+
359
+ async function save(andBack = false) {
360
+ const validationResults = formValidators.map((fn) => fn());
361
+ const allValid = validationResults.every((r) => r.valid);
362
+ if (!allValid) {
363
+ const fieldErrors = validationResults.flatMap((r) =>
364
+ Object.entries(r.errors),
365
+ );
366
+ const message = fieldErrors.length
367
+ ? fieldErrors.map(([field, msg]) => `${field}: ${msg}`).join("\n")
368
+ : "Please fix the errors before saving.";
369
+ snack.show(message, "error");
370
+ return;
371
+ }
372
+
373
+ errors.value = {};
374
+ isSaving.value = true;
375
+ try {
376
+ const multipartOpts = { multipart: props.multipart };
377
+ let result: T;
378
+ if (isNew.value) {
379
+ result = await crud.create(model.value, undefined, multipartOpts);
380
+ } else if (props.usePatch) {
381
+ const patch = getPatch();
382
+ result = await crud.partialUpdate(
383
+ recordId(),
384
+ patch,
385
+ undefined,
386
+ multipartOpts,
387
+ );
388
+ } else {
389
+ result = await crud.update(
390
+ recordId(),
391
+ model.value,
392
+ undefined,
393
+ multipartOpts,
394
+ );
395
+ }
396
+ Object.assign(model.value, result);
397
+ backup.value = deepClone(model.value) as T;
398
+ clearDraft();
399
+ snack.show(
400
+ isNew.value ? "Created successfully" : "Saved successfully",
401
+ "success",
402
+ );
403
+ emit("saved", model.value);
404
+ if (isNew.value && result && "id" in result) {
405
+ const id = (result as unknown as { id: string | number }).id;
406
+ await router.replace({
407
+ params: { id },
408
+ });
409
+ }
410
+ if (andBack) back();
411
+ } catch (err: unknown) {
412
+ const response = (err as { response?: { status?: number; data?: unknown } })
413
+ ?.response;
414
+ const data = response?.data;
415
+ if (response?.status === 400 && data && typeof data === "object") {
416
+ errors.value = data as Record<string, string[]>;
417
+ // Field-level errors: the useMapoForm watcher shows the detailed toast.
418
+ // Only surface a toast here if the response carries a top-level detail message.
419
+ const detail = (data as { detail?: string }).detail;
420
+ if (detail) snack.show(detail, "error");
421
+ } else {
422
+ const detail = (data as { detail?: string } | undefined)?.detail;
423
+ snack.show(detail ?? "Failed to save", "error");
424
+ }
425
+ } finally {
426
+ isSaving.value = false;
427
+ }
428
+ }
429
+
430
+ function getPatch(): Partial<T> {
431
+ if (!backup.value) return { ...model.value };
432
+ return objectDiff(backup.value, model.value) as Partial<T>;
433
+ }
434
+
435
+ // ─── Delete ──────────────────────────────────────────────────────────────────
436
+
437
+ async function deleteItem() {
438
+ const ok = await confirm.ask({
439
+ title: "Delete",
440
+ message:
441
+ "Are you sure you want to delete this item? This action cannot be undone.",
442
+ confirmText: "Delete",
443
+ dangerous: true,
444
+ });
445
+ if (!ok) return;
446
+ isDeleting.value = true;
447
+ try {
448
+ await crud.delete(recordId());
449
+ backup.value = deepClone(model.value) as T; // clear dirty so guard doesn't fire
450
+ snack.show("Deleted successfully", "success");
451
+ emit("deleted");
452
+ back();
453
+ } catch (err: unknown) {
454
+ const detail = (err as { response?: { data?: { detail?: string } } })
455
+ ?.response?.data?.detail;
456
+ snack.show(detail ?? "Failed to delete", "error");
457
+ } finally {
458
+ isDeleting.value = false;
459
+ }
460
+ }
461
+
462
+ // ─── Navigation guard ────────────────────────────────────────────────────────
463
+
464
+ function back() {
465
+ router.back();
466
+ }
467
+
468
+ async function guardUnsaved(): Promise<boolean> {
469
+ if (!isDirty.value) return true;
470
+ return confirm.ask({
471
+ title: "Unsaved changes",
472
+ message: "You have unsaved changes. Do you want to leave without saving?",
473
+ confirmText: "Leave",
474
+ dangerous: true,
475
+ });
476
+ }
477
+
478
+ onBeforeRouteLeave(
479
+ (_to: unknown, _from: unknown, next: (ok: boolean) => void) => {
480
+ guardUnsaved().then((ok) => next(ok));
481
+ },
482
+ );
483
+
484
+ function preventWindowClose(e: Event) {
485
+ if (isDirty.value && typeof globalThis !== "undefined") {
486
+ e.preventDefault();
487
+ if ("returnValue" in e) {
488
+ (e as BeforeUnloadEvent).returnValue = "";
489
+ }
490
+ }
491
+ }
492
+
493
+ onMounted(() => {
494
+ if (typeof globalThis !== "undefined" && "addEventListener" in globalThis) {
495
+ (globalThis as typeof globalThis & EventTarget).addEventListener(
496
+ "beforeunload",
497
+ preventWindowClose,
498
+ );
499
+ }
500
+ fetchModel();
501
+ });
502
+
503
+ onBeforeUnmount(() => {
504
+ if (
505
+ typeof globalThis !== "undefined" &&
506
+ "removeEventListener" in globalThis
507
+ ) {
508
+ (globalThis as typeof globalThis & EventTarget).removeEventListener(
509
+ "beforeunload",
510
+ preventWindowClose,
511
+ );
512
+ }
513
+ });
514
+
515
+ // ─── Slot bindings ───────────────────────────────────────────────────────────
516
+
517
+ // Forward field-level (`field.*`), group-level (`group.*`) and tab-level (`tab.*`,
518
+ // `tab-bar-end`) slots to MapoForm. Host-level slots (title, body, side-buttons, etc.)
519
+ // must not be injected into MapoForm to prevent duplicate or recursive rendering.
520
+ const slots = useSlots();
521
+ const formSlotNames = computed(() =>
522
+ Object.keys(slots).filter(
523
+ (name) =>
524
+ name.startsWith("field.") ||
525
+ name.startsWith("group.") ||
526
+ name.startsWith("tab.") ||
527
+ name === "tab-bar-end",
528
+ ),
529
+ );
530
+
531
+ const slotBindings = computed(() => ({
532
+ model: model.value,
533
+ errors: errors.value,
534
+ currentLang: currentLang.value,
535
+ isNew: isNew.value,
536
+ isLoading: isLoading.value,
537
+ isSaving: isSaving.value,
538
+ isDeleting: isDeleting.value,
539
+ isDirty: isDirty.value,
540
+ draftBanner: draftBanner.value,
541
+ readonly: effectiveReadonly.value,
542
+ canDelete: canDeleteItem.value,
543
+ save,
544
+ deleteItem,
545
+ back,
546
+ }));
547
+
548
+ type DraftBannerState = {
549
+ savedAt: Date;
550
+ restore: () => void;
551
+ discard: () => void;
552
+ } | null;
553
+
554
+ type SlotBindings = {
555
+ model: T;
556
+ errors: Record<string, string[]>;
557
+ currentLang: string;
558
+ isNew: boolean;
559
+ isLoading: boolean;
560
+ isSaving: boolean;
561
+ isDeleting: boolean;
562
+ isDirty: boolean;
563
+ draftBanner: DraftBannerState;
564
+ readonly: boolean;
565
+ canDelete: boolean;
566
+ save: (andBack?: boolean) => Promise<void>;
567
+ deleteItem: () => Promise<void>;
568
+ back: () => void;
569
+ };
570
+
571
+ defineSlots<{
572
+ /** Page title area. Receives full slot bindings. */
573
+ title(props: SlotBindings): VNode[];
574
+ /** Replaces the language switcher in the main column. */
575
+ "body-lang"(props: SlotBindings): VNode[];
576
+ /**
577
+ * Draft restore banner shown when a localStorage draft is found.
578
+ * Receives `draftBanner` (with `savedAt`, `restore`, `discard`) plus the full slot bindings.
579
+ * Override to render a completely custom banner; set to an empty slot to suppress it.
580
+ */
581
+ "draft-banner"(props: SlotBindings): VNode[];
582
+ /** Extra content above the main form. */
583
+ "body-top"(props: SlotBindings): VNode[];
584
+ /** Replaces the entire main form. */
585
+ body(props: SlotBindings): VNode[];
586
+ /** Extra content below the main form. */
587
+ "body-bottom"(props: SlotBindings): VNode[];
588
+ /** Replaces the entire sidebar action card (save/delete/back buttons). */
589
+ "side-buttons"(props: SlotBindings): VNode[];
590
+ /** Override just the Save button. */
591
+ "button-save"(props: SlotBindings): VNode[];
592
+ /** Override just the Save & continue button. */
593
+ "button-savecontinue"(props: SlotBindings): VNode[];
594
+ /** Override just the Back button. */
595
+ "button-back"(props: SlotBindings): VNode[];
596
+ /** Override just the Delete button. */
597
+ "button-delete"(props: SlotBindings): VNode[];
598
+ /** Extra content at the top of the sidebar (below action buttons). */
599
+ "side-top"(props: SlotBindings): VNode[];
600
+ /** Extra content at the bottom of the sidebar, above the danger zone. */
601
+ "side-bottom"(props: SlotBindings): VNode[];
602
+ /**
603
+ * Danger-zone card at the very bottom of the sidebar (delete action).
604
+ * Rendered only for existing records (`!isNew`). Override to replace or suppress it.
605
+ */
606
+ "side-danger"(props: SlotBindings): VNode[];
607
+ /** Per-field slot. Slot name: `field.{key}`, `field.{key}.before`, `field.{key}.after`. */
608
+ [K: `field.${string}`]: (props: {
609
+ field: AnyFieldDescriptor<T>;
610
+ model: T;
611
+ currentLang: string;
612
+ }) => VNode[];
613
+ /** Per-group slot. Slot name: `group.{name}.before`, `group.{name}.after`. */
614
+ [K: `group.${string}`]: (props: Record<string, never>) => VNode[];
615
+ /** Catch-all for slots forwarded dynamically to the inner MapoForm. */
616
+ [K: string]: (...args: any[]) => any;
617
+ }>();
618
+ </script>
619
+
620
+ <template>
621
+ <!-- Loading state -->
622
+ <div v-if="isLoading" class="flex items-center justify-center py-24">
623
+ <UIcon
624
+ name="i-lucide-loader-2"
625
+ class="w-8 h-8 animate-spin text-gray-400"
626
+ />
627
+ </div>
628
+
629
+ <div v-else>
630
+ <!-- Draft banner -->
631
+ <slot name="draft-banner" v-bind="slotBindings">
632
+ <Transition name="slide-down">
633
+ <UAlert
634
+ v-if="draftBanner"
635
+ icon="i-lucide-history"
636
+ color="warning"
637
+ variant="subtle"
638
+ class="mb-3"
639
+ :title="`Unsaved draft found — last edited ${draftBanner.savedAt.toLocaleString()}`"
640
+ description="You have a local draft that was not saved. Do you want to restore it or discard it?"
641
+ >
642
+ <template #actions>
643
+ <UButton size="xs" color="warning" @click="draftBanner?.restore()">
644
+ Restore draft
645
+ </UButton>
646
+ <UButton
647
+ size="xs"
648
+ color="neutral"
649
+ variant="ghost"
650
+ @click="draftBanner?.discard()"
651
+ >
652
+ Discard
653
+ </UButton>
654
+ </template>
655
+ </UAlert>
656
+ </Transition>
657
+ </slot>
658
+
659
+ <!-- Title -->
660
+ <slot name="title" v-bind="slotBindings">
661
+ <h1 class="text-2xl font-bold text-gray-900 dark:text-white mb-6">
662
+ {{ isNew ? "New" : "Edit" }}
663
+ <span v-if="modelName"> {{ modelName }}</span>
664
+ </h1>
665
+ </slot>
666
+
667
+ <div class="grid grid-cols-12 gap-6 items-start">
668
+ <!-- Main column -->
669
+ <div :class="[mainColsClass, 'space-y-4']">
670
+ <!-- Lang switch -->
671
+ <slot name="body-lang" v-bind="slotBindings">
672
+ <MapoDetailLangSwitch
673
+ v-if="activeLangs.length > 1"
674
+ v-model="currentLang"
675
+ :langs="activeLangs"
676
+ :errors="errors"
677
+ />
678
+ </slot>
679
+
680
+ <slot name="body-top" v-bind="slotBindings" />
681
+
682
+ <!-- Main form -->
683
+ <slot name="body" v-bind="slotBindings">
684
+ <MapoForm
685
+ v-model="model"
686
+ :fields="fields"
687
+ :errors="errors"
688
+ :languages="activeLangs"
689
+ :current-lang="currentLang"
690
+ :registry="registry"
691
+ :readonly="effectiveReadonly"
692
+ >
693
+ <template
694
+ v-for="slotName in formSlotNames"
695
+ :key="slotName"
696
+ #[slotName]="slotProps"
697
+ >
698
+ <slot :name="slotName" v-bind="slotProps ?? {}" />
699
+ </template>
700
+ </MapoForm>
701
+ </slot>
702
+
703
+ <slot name="body-bottom" v-bind="slotBindings" />
704
+ </div>
705
+
706
+ <!-- Sidebar column -->
707
+ <div :class="sidebarColsClass">
708
+ <div :style="sidebarStyle" class="space-y-4">
709
+ <!-- Action buttons (Save / Save&continue / Back — no delete here) -->
710
+ <slot name="side-buttons" v-bind="slotBindings">
711
+ <UCard>
712
+ <div class="flex flex-col gap-2">
713
+ <slot name="button-save" v-bind="slotBindings">
714
+ <UButton
715
+ v-if="!effectiveReadonly"
716
+ block
717
+ :loading="isSaving"
718
+ icon="i-lucide-save"
719
+ @click="save(true)"
720
+ >
721
+ {{ isNew ? "Create" : "Save" }}
722
+ </UButton>
723
+ </slot>
724
+
725
+ <slot name="button-savecontinue" v-bind="slotBindings">
726
+ <UButton
727
+ v-if="!effectiveReadonly"
728
+ block
729
+ variant="soft"
730
+ :loading="isSaving"
731
+ icon="i-lucide-save"
732
+ @click="save(false)"
733
+ >
734
+ {{ isNew ? "Create and continue" : "Save and continue" }}
735
+ </UButton>
736
+ </slot>
737
+
738
+ <slot name="button-back" v-bind="slotBindings">
739
+ <UButton
740
+ block
741
+ variant="ghost"
742
+ icon="i-lucide-arrow-left"
743
+ @click="back"
744
+ >
745
+ Back
746
+ </UButton>
747
+ </slot>
748
+ </div>
749
+ </UCard>
750
+ </slot>
751
+
752
+ <slot name="side-top" v-bind="slotBindings" />
753
+
754
+ <!-- Sidebar fields form.
755
+ Flat fields (no group) get a UCard wrapper for visual structure.
756
+ Grouped fields render their own group cards, so no outer wrapper. -->
757
+ <template v-if="sidebarFields && sidebarFields.length">
758
+ <UCard v-if="!sidebarHasGroups">
759
+ <MapoForm
760
+ v-model="model"
761
+ :fields="sidebarFields"
762
+ :errors="errors"
763
+ :languages="activeLangs"
764
+ :current-lang="currentLang"
765
+ :registry="registry"
766
+ :readonly="effectiveReadonly"
767
+ >
768
+ <template
769
+ v-for="slotName in formSlotNames"
770
+ :key="slotName"
771
+ #[slotName]="slotProps"
772
+ >
773
+ <slot :name="slotName" v-bind="slotProps ?? {}" />
774
+ </template>
775
+ </MapoForm>
776
+ </UCard>
777
+ <MapoForm
778
+ v-else
779
+ v-model="model"
780
+ :fields="sidebarFields"
781
+ :errors="errors"
782
+ :languages="activeLangs"
783
+ :current-lang="currentLang"
784
+ :registry="registry"
785
+ :readonly="effectiveReadonly"
786
+ >
787
+ <template
788
+ v-for="slotName in formSlotNames"
789
+ :key="slotName"
790
+ #[slotName]="slotProps"
791
+ >
792
+ <slot :name="slotName" v-bind="slotProps ?? {}" />
793
+ </template>
794
+ </MapoForm>
795
+ </template>
796
+
797
+ <slot name="side-bottom" v-bind="slotBindings" />
798
+
799
+ <!-- Preview button — shown when previewField resolves to a URL -->
800
+ <UButton
801
+ v-if="previewUrl"
802
+ block
803
+ variant="outline"
804
+ color="neutral"
805
+ icon="i-lucide-eye"
806
+ @click="previewOpen = true"
807
+ >
808
+ Preview
809
+ </UButton>
810
+
811
+ <!-- Danger zone: delete action, visually separated from save actions -->
812
+ <slot name="side-danger" v-bind="slotBindings">
813
+ <UCard v-if="!isNew && canDeleteItem">
814
+ <slot name="button-delete" v-bind="slotBindings">
815
+ <UButton
816
+ block
817
+ color="error"
818
+ variant="soft"
819
+ :loading="isDeleting"
820
+ icon="i-lucide-trash-2"
821
+ @click="deleteItem"
822
+ >
823
+ Delete
824
+ </UButton>
825
+ </slot>
826
+ </UCard>
827
+ </slot>
828
+ </div>
829
+ </div>
830
+ </div>
831
+
832
+ <!-- Preview iframe modal -->
833
+ <UModal
834
+ v-if="previewField"
835
+ v-model:open="previewOpen"
836
+ :ui="{ content: 'max-w-5xl' }"
837
+ >
838
+ <template #content>
839
+ <div class="flex flex-col" style="height: 80vh">
840
+ <div
841
+ class="flex items-center justify-between px-4 py-2 border-b border-default"
842
+ >
843
+ <span class="text-sm font-medium truncate">{{ previewUrl }}</span>
844
+ <UButton
845
+ size="xs"
846
+ variant="ghost"
847
+ color="neutral"
848
+ icon="i-lucide-x"
849
+ @click="previewOpen = false"
850
+ />
851
+ </div>
852
+ <iframe
853
+ :src="previewUrl ?? ''"
854
+ class="flex-1 w-full border-0"
855
+ sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
856
+ />
857
+ </div>
858
+ </template>
859
+ </UModal>
860
+ </div>
861
+ </template>