@mapomodule/uikit 2.0.0-beta.8 → 2.0.0-experimental.2

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 (133) hide show
  1. package/README.md +47 -174
  2. package/dist/__tests__/MapoConfirmDialog.component.test.d.ts +2 -0
  3. package/dist/__tests__/MapoConfirmDialog.component.test.d.ts.map +1 -0
  4. package/dist/__tests__/MapoDetail.component.test.d.ts +2 -0
  5. package/dist/__tests__/MapoDetail.component.test.d.ts.map +1 -0
  6. package/dist/__tests__/MapoDetailLangSwitch.component.test.d.ts +2 -0
  7. package/dist/__tests__/MapoDetailLangSwitch.component.test.d.ts.map +1 -0
  8. package/dist/__tests__/MapoListActions.component.test.d.ts +2 -0
  9. package/dist/__tests__/MapoListActions.component.test.d.ts.map +1 -0
  10. package/dist/__tests__/MapoListTable.component.test.d.ts +2 -0
  11. package/dist/__tests__/MapoListTable.component.test.d.ts.map +1 -0
  12. package/dist/__tests__/MapoSnackBar.component.test.d.ts +2 -0
  13. package/dist/__tests__/MapoSnackBar.component.test.d.ts.map +1 -0
  14. package/dist/__tests__/__mocks__/nuxt-app.d.ts +9 -0
  15. package/dist/__tests__/__mocks__/nuxt-app.d.ts.map +1 -0
  16. package/dist/__tests__/formValues.test.d.ts +2 -0
  17. package/dist/__tests__/formValues.test.d.ts.map +1 -0
  18. package/dist/__tests__/langInfo.test.d.ts +2 -0
  19. package/dist/__tests__/langInfo.test.d.ts.map +1 -0
  20. package/dist/__tests__/listTable.test.d.ts +2 -0
  21. package/dist/__tests__/listTable.test.d.ts.map +1 -0
  22. package/dist/__tests__/mediaLanguages.test.d.ts +2 -0
  23. package/dist/__tests__/mediaLanguages.test.d.ts.map +1 -0
  24. package/dist/__tests__/runtimePages.test.d.ts +2 -0
  25. package/dist/__tests__/runtimePages.test.d.ts.map +1 -0
  26. package/dist/index.d.mts +1 -0
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/module.d.mts +1 -0
  30. package/dist/module.d.ts.map +1 -1
  31. package/dist/module.json +1 -1
  32. package/dist/module.mjs +10 -0
  33. package/dist/runtime/assets/main.css +1 -1
  34. package/dist/runtime/components/MapoConfirmDialog.vue +18 -1
  35. package/dist/runtime/components/MapoConfirmDialog.vue.d.ts.map +1 -1
  36. package/dist/runtime/components/MapoDetail.vue +263 -33
  37. package/dist/runtime/components/MapoDetail.vue.d.ts +191 -9
  38. package/dist/runtime/components/MapoDetail.vue.d.ts.map +1 -1
  39. package/dist/runtime/components/MapoDetailExtensions.vue +24 -0
  40. package/dist/runtime/components/MapoDetailExtensions.vue.d.ts +15 -0
  41. package/dist/runtime/components/MapoDetailExtensions.vue.d.ts.map +1 -0
  42. package/dist/runtime/components/MapoDetailLangSwitch.vue +21 -25
  43. package/dist/runtime/components/MapoDetailLangSwitch.vue.d.ts +4 -3
  44. package/dist/runtime/components/MapoDetailLangSwitch.vue.d.ts.map +1 -1
  45. package/dist/runtime/components/MapoDropArea.vue.d.ts +1 -1
  46. package/dist/runtime/components/MapoDropArea.vue.d.ts.map +1 -1
  47. package/dist/runtime/components/MapoList.vue +7 -3
  48. package/dist/runtime/components/MapoList.vue.d.ts +14 -4
  49. package/dist/runtime/components/MapoList.vue.d.ts.map +1 -1
  50. package/dist/runtime/components/MapoListActions.vue +12 -5
  51. package/dist/runtime/components/MapoListActions.vue.d.ts +4 -0
  52. package/dist/runtime/components/MapoListActions.vue.d.ts.map +1 -1
  53. package/dist/runtime/components/MapoListQuickEdit.vue +1 -1
  54. package/dist/runtime/components/MapoListTable.vue +99 -33
  55. package/dist/runtime/components/MapoListTable.vue.d.ts +11 -6
  56. package/dist/runtime/components/MapoListTable.vue.d.ts.map +1 -1
  57. package/dist/runtime/components/MapoMediaEditor.vue +10 -4
  58. package/dist/runtime/components/MapoMediaEditor.vue.d.ts +1 -0
  59. package/dist/runtime/components/MapoMediaEditor.vue.d.ts.map +1 -1
  60. package/dist/runtime/components/MapoMediaFileChanger.vue +1 -1
  61. package/dist/runtime/components/MapoMediaManager.vue +1 -1
  62. package/dist/runtime/components/MapoMediaManagerDialog.vue +1 -1
  63. package/dist/runtime/components/MapoMediaPreview.vue +1 -1
  64. package/dist/runtime/components/MapoMediaUploader.vue +21 -21
  65. package/dist/runtime/components/MapoMediaUploader.vue.d.ts.map +1 -1
  66. package/dist/runtime/components/MapoMenuManager.vue +23 -3
  67. package/dist/runtime/components/MapoMenuManager.vue.d.ts +2 -2
  68. package/dist/runtime/components/MapoMenuManager.vue.d.ts.map +1 -1
  69. package/dist/runtime/components/MapoMenuTreeview.vue.d.ts +1 -1
  70. package/dist/runtime/components/MapoMenuTreeview.vue.d.ts.map +1 -1
  71. package/dist/runtime/components/MapoMenuTreeviewNode.vue.d.ts +2 -2
  72. package/dist/runtime/components/MapoSnackBar.vue +11 -0
  73. package/dist/runtime/components/MapoSnackBar.vue.d.ts.map +1 -1
  74. package/dist/runtime/composables/defineDetailExtension.d.ts +32 -0
  75. package/dist/runtime/composables/defineDetailExtension.d.ts.map +1 -0
  76. package/dist/runtime/composables/defineDetailExtension.js +34 -0
  77. package/dist/runtime/composables/useMapoDetail.d.ts +18 -0
  78. package/dist/runtime/composables/useMapoDetail.d.ts.map +1 -0
  79. package/dist/runtime/composables/useMapoDetail.js +5 -0
  80. package/dist/runtime/page-meta.nuxt.d.ts +4 -0
  81. package/dist/runtime/stores/media.d.ts +8 -2
  82. package/dist/runtime/stores/media.d.ts.map +1 -1
  83. package/dist/runtime/stores/media.js +16 -0
  84. package/dist/runtime/types/detail.d.ts +167 -0
  85. package/dist/runtime/types/detail.d.ts.map +1 -0
  86. package/dist/runtime/types/detail.js +0 -0
  87. package/dist/runtime/types/list.d.ts +10 -2
  88. package/dist/runtime/types/list.d.ts.map +1 -1
  89. package/dist/runtime/utils/formValues.d.ts +8 -0
  90. package/dist/runtime/utils/formValues.d.ts.map +1 -0
  91. package/dist/runtime/utils/formValues.js +19 -0
  92. package/dist/runtime/utils/langInfo.d.ts +30 -0
  93. package/dist/runtime/utils/langInfo.d.ts.map +1 -0
  94. package/dist/runtime/utils/langInfo.js +8 -0
  95. package/dist/runtime/utils/listTable.d.ts +29 -0
  96. package/dist/runtime/utils/listTable.d.ts.map +1 -0
  97. package/dist/runtime/utils/listTable.js +21 -0
  98. package/package.json +7 -8
  99. package/src/__tests__/MapoConfirmDialog.component.test.ts +165 -0
  100. package/src/__tests__/MapoDetail.component.test.ts +1107 -0
  101. package/src/__tests__/MapoDetailLangSwitch.component.test.ts +145 -0
  102. package/src/__tests__/MapoListActions.component.test.ts +175 -0
  103. package/src/__tests__/MapoListTable.component.test.ts +504 -0
  104. package/src/__tests__/MapoSnackBar.component.test.ts +79 -0
  105. package/src/__tests__/__mocks__/nuxt-app.ts +8 -0
  106. package/src/__tests__/formValues.test.ts +31 -0
  107. package/src/__tests__/langInfo.test.ts +48 -0
  108. package/src/__tests__/listTable.test.ts +82 -0
  109. package/src/__tests__/mediaLanguages.test.ts +66 -0
  110. package/src/__tests__/runtimePages.test.ts +17 -0
  111. package/src/index.ts +8 -0
  112. package/src/module.ts +12 -0
  113. package/src/runtime/assets/main.css +13 -0
  114. package/src/runtime/components/MapoConfirmDialog.vue +28 -1
  115. package/src/runtime/components/MapoDetail.vue +481 -53
  116. package/src/runtime/components/MapoDetailExtensions.vue +39 -0
  117. package/src/runtime/components/MapoDetailLangSwitch.vue +26 -27
  118. package/src/runtime/components/MapoList.vue +20 -5
  119. package/src/runtime/components/MapoListActions.vue +16 -4
  120. package/src/runtime/components/MapoListTable.vue +128 -41
  121. package/src/runtime/components/MapoMediaEditor.vue +17 -4
  122. package/src/runtime/components/MapoMediaUploader.vue +25 -21
  123. package/src/runtime/components/MapoMenuManager.vue +38 -3
  124. package/src/runtime/components/MapoSnackBar.vue +12 -0
  125. package/src/runtime/composables/defineDetailExtension.ts +78 -0
  126. package/src/runtime/composables/useMapoDetail.ts +24 -0
  127. package/src/runtime/page-meta.nuxt.d.ts +4 -0
  128. package/src/runtime/stores/media.ts +32 -0
  129. package/src/runtime/types/detail.ts +178 -0
  130. package/src/runtime/types/list.ts +10 -2
  131. package/src/runtime/utils/formValues.ts +28 -0
  132. package/src/runtime/utils/langInfo.ts +38 -0
  133. package/src/runtime/utils/listTable.ts +54 -0
@@ -10,10 +10,18 @@ import {
10
10
  provide,
11
11
  type Ref,
12
12
  type VNode,
13
+ shallowRef,
14
+ getCurrentScope,
15
+ onScopeDispose,
13
16
  } from "vue";
14
17
  import { useRouter, onBeforeRouteLeave, useNuxtApp } from "#app";
15
18
  import { useI18n } from "vue-i18n";
16
- import { objectDiff, debounce, deepClone } from "@mapomodule/utils";
19
+ import {
20
+ objectDiff,
21
+ debounce,
22
+ deepClone,
23
+ metadataToJsonSchema,
24
+ } from "@mapomodule/utils";
17
25
  import { useCrud } from "@mapomodule/core/runtime/api/crud";
18
26
  import {
19
27
  getErrorData,
@@ -22,8 +30,21 @@ import {
22
30
  } from "@mapomodule/core/runtime/utils/fetchError";
23
31
  import { useSnackStore } from "@mapomodule/store/runtime/stores/snack";
24
32
  import { useConfirmStore } from "@mapomodule/store/runtime/stores/confirm";
25
- import type { AnyFieldDescriptor, FieldRegistry } from "@mapomodule/form/types";
33
+ import { useAuthStore } from "@mapomodule/store/runtime/stores/auth";
34
+ import type {
35
+ AnyFieldDescriptor,
36
+ FieldAnnotations,
37
+ FieldRegistry,
38
+ UseFormFromSchemaOptions,
39
+ } from "@mapomodule/form/types";
26
40
  import { usePermissions } from "@mapomodule/store/runtime/composables/usePermissions";
41
+ import { languagesFromMetadata } from "../utils/langInfo";
42
+ import { holdsFormValue } from "../utils/formValues";
43
+ import { DETAIL_KEY } from "../composables/useMapoDetail";
44
+ import type { MapoDetailContext, MapoDetailDraftPart } from "../types/detail";
45
+ import { useFormFromSchema } from "@mapomodule/form/runtime/composables/useFormFromSchema";
46
+ import { modelForDraft } from "@mapomodule/form/runtime/utils/draft";
47
+ import type { JSONSchema } from "@mapomodule/utils";
27
48
  import type { MultipartPolicy } from "@mapomodule/core";
28
49
 
29
50
  // ─── Props ────────────────────────────────────────────────────────────────────
@@ -34,12 +55,51 @@ const props = withDefaults(
34
55
  endpoint: string;
35
56
  /** Record id. Pass `'new'` to create. */
36
57
  id: string | number;
37
- /** Fields for the main body form. */
38
- fields: AnyFieldDescriptor<T>[];
58
+ /**
59
+ * Fields for the main body form.
60
+ *
61
+ * Optional only so `experimentalFieldsFromSchema` can supply them; pass them
62
+ * explicitly for any form you care about the layout of.
63
+ */
64
+ fields?: AnyFieldDescriptor<T>[];
65
+ /**
66
+ * EXPERIMENTAL. Build the body fields from the endpoint's OPTIONS response
67
+ * when `fields` is not given.
68
+ *
69
+ * Off by default and deliberately opt-in: a derived form knows types,
70
+ * labels, relations and what is read-only, but nothing editorial — no tabs,
71
+ * no column widths, no rich-text vs textarea, no sidebar split, and no
72
+ * opinion about field order beyond the serializer's. Treat it as a
73
+ * scaffold to start from, not a finished panel.
74
+ *
75
+ * Reads the `schema` the endpoint publishes on OPTIONS (camomilla >= 6.6)
76
+ * or, without one, Django REST Framework's standard metadata
77
+ * (`actions.POST`, which DRF serves to users who can create).
78
+ * `schemaFromMetadata` changes how.
79
+ */
80
+ experimentalFieldsFromSchema?: boolean;
81
+ /**
82
+ * Turns the OPTIONS response into the JSON Schema the body fields are
83
+ * built from, with `experimentalFieldsFromSchema`. Default:
84
+ * `metadataToJsonSchema` from `@mapomodule/utils`, which reads a published
85
+ * `schema`, then DRF metadata. Call it with options, or return your own
86
+ * schema; `undefined` derives no fields.
87
+ */
88
+ schemaFromMetadata?: (
89
+ metadata: Record<string, unknown>,
90
+ ) => JSONSchema | undefined;
91
+ /** Passed straight to useFormFromSchema when deriving. */
92
+ schemaFieldOptions?: UseFormFromSchemaOptions;
39
93
  /** Fields for the sidebar form (optional). */
40
94
  sidebarFields?: AnyFieldDescriptor<T>[];
41
95
  /** Translation language codes (e.g. ['it', 'en']). */
42
96
  languages?: string[];
97
+ /**
98
+ * Number of languages above which the language switcher adds a searchable
99
+ * select next to its tabs. Default `8` (from MapoDetailLangSwitch); `0`
100
+ * always shows it.
101
+ */
102
+ langThreshold?: number;
43
103
  /** Human readable model name shown in the page title. */
44
104
  modelName?: string | null;
45
105
  /** Sidebar column span (1–11 in a 12-col grid). */
@@ -56,13 +116,16 @@ const props = withDefaults(
56
116
  * Enable automatic draft persistence to localStorage.
57
117
  * When `true`, the key is auto-generated as `${endpoint}:${id}`.
58
118
  * Provide `draftKey` to override with a custom key.
59
- * Drafts expire after 24 h. The built-in banner handles restore/discard.
119
+ * Drafts are kept per user, leave out the fields marked `noDraft`, and
120
+ * expire after 24 h. A new record is saved as a draft once it holds a
121
+ * value. The built-in banner handles restore/discard.
60
122
  */
61
123
  draft?: boolean;
62
124
  /**
63
- * Custom localStorage key for draft persistence. Requires `draft: true`.
64
- * Key is prefixed with `mapo:draft:`.
65
- * Example: `"article:42"` → `mapo:draft:article:42`.
125
+ * Custom localStorage key for draft persistence; setting it also turns
126
+ * drafts on. Key is prefixed with `mapo:draft:` and the signed-in
127
+ * user's id (`anonymous` without one).
128
+ * Example: `"article:42"` → `mapo:draft:1:article:42` for the user with id `1`.
66
129
  * Falls back to `${endpoint}:${id}` when omitted.
67
130
  */
68
131
  draftKey?: string;
@@ -91,10 +154,26 @@ const props = withDefaults(
91
154
  * the auto-derived list.
92
155
  */
93
156
  forceLanguages?: string[];
157
+ /**
158
+ * Marks shown next to the field labels and counted on the tabs, in the body
159
+ * and in the sidebar forms, keyed by the path of the value (`title`,
160
+ * `translations.it.title`, `blocks.0.title`). See `MapoForm`.
161
+ */
162
+ annotations?: FieldAnnotations;
163
+ /**
164
+ * Which extensions registered with `defineDetailExtension()` the page
165
+ * shows: all (`true`), none (`false`) or the listed keys.
166
+ */
167
+ extensions?: boolean | string[];
94
168
  }>(),
95
169
  {
170
+ fields: undefined,
171
+ experimentalFieldsFromSchema: false,
172
+ schemaFromMetadata: undefined,
173
+ schemaFieldOptions: undefined,
96
174
  sidebarFields: () => [],
97
175
  languages: () => [],
176
+ langThreshold: undefined,
98
177
  sidebarCols: 4,
99
178
  sticky: true,
100
179
  usePatch: true,
@@ -107,6 +186,8 @@ const props = withDefaults(
107
186
  permissionModel: undefined,
108
187
  previewField: undefined,
109
188
  forceLanguages: undefined,
189
+ annotations: undefined,
190
+ extensions: true,
110
191
  },
111
192
  );
112
193
 
@@ -137,6 +218,7 @@ const { t } = useI18n();
137
218
  const router = useRouter();
138
219
  const snack = useSnackStore();
139
220
  const confirm = useConfirmStore();
221
+ const auth = useAuthStore();
140
222
  const crud = useCrud<T>(props.endpoint);
141
223
 
142
224
  type ValidateClientFn = () => {
@@ -153,6 +235,31 @@ provide("mapoDetailRegisterValidator", (fn: ValidateClientFn) => {
153
235
  };
154
236
  });
155
237
 
238
+ // Each form inside, the body's and the sidebar's, a slot's own included,
239
+ // brings its fields into view: `revealField()` asks them in turn.
240
+ type RevealFieldFn = (path: string) => Promise<boolean>;
241
+ const formRevealers: RevealFieldFn[] = [];
242
+
243
+ provide("mapoDetailRegisterReveal", (fn: RevealFieldFn) => {
244
+ formRevealers.push(fn);
245
+ return () => {
246
+ const at = formRevealers.indexOf(fn);
247
+ if (at >= 0) formRevealers.splice(at, 1);
248
+ };
249
+ });
250
+
251
+ /**
252
+ * Brings a field into view through the form that holds it: its tab, group
253
+ * and repeater item open, and its control takes the focus. A form without
254
+ * the field answers `false` at once, so the next one is asked.
255
+ */
256
+ async function revealField(path: string): Promise<boolean> {
257
+ for (const reveal of [...formRevealers]) {
258
+ if (await reveal(path)) return true;
259
+ }
260
+ return false;
261
+ }
262
+
156
263
  const isNew = computed(() => String(props.id) === "new");
157
264
  // Cast keeps the generic exact: `ref<T>` would expose `UnwrapRef<T>`, which
158
265
  // TS cannot prove to extend `object` when forwarding to MapoForm.
@@ -167,8 +274,21 @@ const errors = ref<Record<string, string[]>>({});
167
274
  // Start in loading state for existing items so MapoForm is never mounted with
168
275
  // empty data and then immediately unmounted when the spinner appears on mount.
169
276
  const isLoading = ref(String(props.id) !== "new");
170
- const isSaving = ref(false);
171
- const isDeleting = ref(false);
277
+
278
+ /**
279
+ * The action under way, from the click until its work is done, navigation
280
+ * included: one at a time, so a second click cannot save again or go back one
281
+ * more step in the history. Named after the buttons.
282
+ */
283
+ type DetailAction = "save" | "saveContinue" | "delete" | "back";
284
+ const pendingAction = ref<DetailAction | null>(null);
285
+ const isBusy = computed(() => pendingAction.value !== null);
286
+ const isSaving = computed(() => {
287
+ const savingAndLeaving = pendingAction.value === "save";
288
+ const savingAndStaying = pendingAction.value === "saveContinue";
289
+ return savingAndLeaving || savingAndStaying;
290
+ });
291
+ const isDeleting = computed(() => pendingAction.value === "delete");
172
292
  const currentLang = ref(props.languages[0] ?? "");
173
293
  const draftBanner = ref<{
174
294
  savedAt: Date;
@@ -176,17 +296,34 @@ const draftBanner = ref<{
176
296
  discard: () => void;
177
297
  } | null>(null);
178
298
 
179
- const isDirty = computed(
180
- () =>
181
- backup.value !== null &&
182
- Object.keys(objectDiff(backup.value, model.value)).length > 0,
183
- );
299
+ /**
300
+ * What a new record held when the page opened, as the page and the
301
+ * components inside it set it up: none of it is the operator's change.
302
+ */
303
+ const opened = ref<T | null>(null);
304
+
305
+ /**
306
+ * The record differs from the one loaded or last saved. A new record has
307
+ * none to differ from: it counts as changed once it holds a value it did
308
+ * not hold when the page opened, so it gets a draft and the warnings on
309
+ * leaving, as an existing record does.
310
+ */
311
+ const isDirty = computed(() => {
312
+ if (backup.value !== null) {
313
+ return Object.keys(objectDiff(backup.value, model.value)).length > 0;
314
+ }
315
+ if (!isNew.value) return false;
316
+ const start = opened.value ?? ({} as T);
317
+ return holdsFormValue(objectDiff(start, model.value));
318
+ });
184
319
  const mainCols = computed(() => 12 - props.sidebarCols);
185
320
 
186
321
  // ─── Languages (auto-derive from lang_info) ──────────────────────────────────
187
- // Backends like Camomilla embed site_languages inside the fetched model.
188
- // We read them after the first successful fetch so the host page doesn't need
189
- // to hard-code the language list. forceLanguages > props.languages > derived.
322
+ // Camomilla describes the MODEL's language situation in the endpoint's OPTIONS
323
+ // metadata, so the host page doesn't hard-code a language list — and a model
324
+ // that is not registered for translation shows no switcher at all, rather than
325
+ // tabs whose extra values the backend would drop.
326
+ // forceLanguages > props.languages > derived.
190
327
  const derivedLangs = ref<string[]>([]);
191
328
  const activeLangs = computed<string[]>(() => {
192
329
  if (props.forceLanguages?.length) return props.forceLanguages;
@@ -267,13 +404,32 @@ const sidebarColsClass = computed(
267
404
 
268
405
  const DRAFT_TTL = 86_400_000; // 24h
269
406
 
270
- function draftStorageKey() {
407
+ /** The page's own key of the draft, without the prefix; `null` with drafts off. */
408
+ function draftName(): string | null {
271
409
  if (!props.draft && !props.draftKey) return null;
272
- const key = props.draftKey ?? `${props.endpoint}:${props.id}`;
273
- return `mapo:draft:${key}`;
410
+ return props.draftKey ?? `${props.endpoint}:${props.id}`;
411
+ }
412
+
413
+ /** Where the draft is kept: one per user, so accounts on a browser never share one. */
414
+ function draftStorageKey(): string | null {
415
+ const name = draftName();
416
+ if (name === null) return null;
417
+ const userId = auth.info?.id ?? "anonymous";
418
+ return `mapo:draft:${userId}:${name}`;
419
+ }
420
+
421
+ /**
422
+ * Removes a draft kept before drafts were kept per user: nobody can say
423
+ * whose it is, so it is never offered.
424
+ */
425
+ function removeUnownedDraft(): void {
426
+ const name = draftName();
427
+ if (name === null) return;
428
+ localStorage.removeItem(`mapo:draft:${name}`);
274
429
  }
275
430
 
276
431
  function clearDraft() {
432
+ unclaimedParts.clear();
277
433
  const key = draftStorageKey();
278
434
  if (key && typeof localStorage !== "undefined") localStorage.removeItem(key);
279
435
  }
@@ -282,9 +438,14 @@ function checkDraft() {
282
438
  const key = draftStorageKey();
283
439
  if (!key || typeof localStorage === "undefined") return;
284
440
  try {
441
+ removeUnownedDraft();
285
442
  const raw = localStorage.getItem(key);
286
443
  if (!raw) return;
287
- const entry = JSON.parse(raw) as { model: T; savedAt: number };
444
+ const entry = JSON.parse(raw) as {
445
+ model: T;
446
+ savedAt: number;
447
+ parts?: unknown;
448
+ };
288
449
  if (Date.now() - entry.savedAt > DRAFT_TTL) {
289
450
  localStorage.removeItem(key);
290
451
  return;
@@ -292,6 +453,7 @@ function checkDraft() {
292
453
  const savedAt = new Date(entry.savedAt);
293
454
  const restore = () => {
294
455
  Object.assign(model.value, entry.model);
456
+ restoreParts(entry.parts);
295
457
  draftBanner.value = null;
296
458
  };
297
459
  const discard = () => {
@@ -305,28 +467,157 @@ function checkDraft() {
305
467
  }
306
468
  }
307
469
 
470
+ // ─── Draft parts ─────────────────────────────────────────────────────────────
471
+ // A component inside the detail keeps a state of its own in the draft, beside
472
+ // the record's values: the context's `draft`.
473
+
474
+ const draftParts = new Map<string, MapoDetailDraftPart>();
475
+ /** Data of a restored draft whose part was not there yet: it gets it when it comes. */
476
+ const unclaimedParts = new Map<string, unknown>();
477
+
478
+ function addDraftPart(key: string, part: MapoDetailDraftPart): () => void {
479
+ draftParts.set(key, part);
480
+ if (unclaimedParts.has(key)) {
481
+ const data = unclaimedParts.get(key);
482
+ unclaimedParts.delete(key);
483
+ restorePart(part, data);
484
+ }
485
+ const remove = () => {
486
+ if (draftParts.get(key) === part) draftParts.delete(key);
487
+ };
488
+ if (getCurrentScope()) onScopeDispose(remove);
489
+ return remove;
490
+ }
491
+
492
+ function restorePart(part: MapoDetailDraftPart, data: unknown): void {
493
+ try {
494
+ part.restore(data);
495
+ } catch {
496
+ // A component's failure leaves the record's values restored.
497
+ }
498
+ }
499
+
500
+ /**
501
+ * Puts back each part of a restored draft, as read from the storage: a
502
+ * part the draft holds nothing for starts again from nothing.
503
+ */
504
+ function restoreParts(parts: unknown): void {
505
+ const isRecord =
506
+ typeof parts === "object" && parts !== null && !Array.isArray(parts);
507
+ const kept = new Map(isRecord ? Object.entries(parts) : []);
508
+ for (const [key, part] of draftParts) {
509
+ restorePart(part, kept.get(key));
510
+ kept.delete(key);
511
+ }
512
+ for (const [key, data] of kept) unclaimedParts.set(key, data);
513
+ }
514
+
515
+ /** What the parts keep, by key; `undefined` when none keeps anything. */
516
+ function keptParts(): Record<string, unknown> | undefined {
517
+ const kept: Record<string, unknown> = {};
518
+ for (const [key, part] of draftParts) {
519
+ let data: unknown;
520
+ try {
521
+ data = part.save();
522
+ } catch {
523
+ continue;
524
+ }
525
+ if (data !== undefined) kept[key] = data;
526
+ }
527
+ return Object.keys(kept).length > 0 ? kept : undefined;
528
+ }
529
+
530
+ /** Saves the draft two seconds after the last change; nothing with drafts off. */
531
+ let saveDraftSoon: () => void = () => {};
532
+
308
533
  // Auto-save draft debounced whenever model changes and form is dirty.
309
534
  if (props.draft || props.draftKey) {
535
+ /** This page wrote the draft: once nothing is left to keep, it goes. */
536
+ let isWritten = false;
310
537
  const saveDraft = debounce(() => {
311
538
  const key = draftStorageKey();
312
- if (!key || !isDirty.value || typeof localStorage === "undefined") return;
539
+ if (!key || typeof localStorage === "undefined") return;
313
540
  try {
314
- localStorage.setItem(
315
- key,
316
- JSON.stringify({ model: toRaw(model.value), savedAt: Date.now() }),
317
- );
541
+ const parts = keptParts();
542
+ // Back as loaded, and no part keeps anything: a draft written by an
543
+ // earlier visit stays on offer, the one this page wrote goes.
544
+ const hasParts = parts !== undefined;
545
+ if (!isDirty.value && !hasParts) {
546
+ if (isWritten) localStorage.removeItem(key);
547
+ isWritten = false;
548
+ return;
549
+ }
550
+ // The fields marked `noDraft` hold nothing in the draft, at any path.
551
+ const fields = [...activeFields.value, ...(props.sidebarFields ?? [])];
552
+ const values = modelForDraft(toRaw(model.value), fields);
553
+ const entry = { model: values, savedAt: Date.now(), parts };
554
+ localStorage.setItem(key, JSON.stringify(entry));
555
+ isWritten = true;
318
556
  } catch {
319
- /* quota exceeded — ignore */
557
+ /* quota exceeded, or a value with no JSON form — ignore */
320
558
  }
321
559
  }, 2000);
322
560
  watch(model, saveDraft, { deep: true });
561
+ saveDraftSoon = () => saveDraft();
323
562
  }
324
563
 
325
564
  // ─── Fetch ───────────────────────────────────────────────────────────────────
326
565
 
566
+ /**
567
+ * Body fields derived from the OPTIONS schema; empty unless opted in.
568
+ *
569
+ * shallowRef, not ref: the array is replaced wholesale, never mutated in place,
570
+ * and deep reactivity over descriptors (which carry functions) buys nothing.
571
+ * It also keeps the generic intact — ref()'s UnwrapRef erases the T in
572
+ * `key: DeepKeyOf<T>`.
573
+ */
574
+ const derivedFields = shallowRef<AnyFieldDescriptor<T>[]>([]);
575
+
576
+ /**
577
+ * The fields actually rendered. An explicit `fields` prop always wins — the
578
+ * derived set is a scaffold, never an override of a hand-built form.
579
+ */
580
+ const activeFields = computed<AnyFieldDescriptor<T>[]>(() =>
581
+ props.fields?.length ? props.fields : derivedFields.value,
582
+ );
583
+
584
+ /**
585
+ * Ask the endpoint to describe itself, ONCE, and take from that answer both the
586
+ * languages and (when opted in) the fields.
587
+ *
588
+ * Runs for existing records as well as new ones: the metadata lives on OPTIONS
589
+ * only, so reading the fetched record would leave an edit form with no tabs.
590
+ */
591
+ async function describeEndpoint() {
592
+ const wantsLangs = !props.languages.length && !props.forceLanguages?.length;
593
+ const wantsFields =
594
+ props.experimentalFieldsFromSchema && !props.fields?.length;
595
+ if (!wantsLangs && !wantsFields) return;
596
+
597
+ const metadata = await describe();
598
+ // A backend without OPTIONS metadata is not an error worth surfacing: it
599
+ // just means nothing is auto-derived.
600
+ if (!metadata) return;
601
+
602
+ if (wantsLangs) derivedLangs.value = languagesFromMetadata(metadata);
603
+ if (wantsFields) {
604
+ const toSchema = props.schemaFromMetadata ?? metadataToJsonSchema;
605
+ const schema = toSchema(metadata);
606
+ if (schema?.properties) {
607
+ derivedFields.value = useFormFromSchema(
608
+ schema,
609
+ props.schemaFieldOptions,
610
+ ) as AnyFieldDescriptor<T>[];
611
+ }
612
+ }
613
+ }
614
+
327
615
  async function fetchModel() {
328
616
  if (isNew.value) {
329
617
  backup.value = null;
618
+ // The components inside are set up by now: what they and the page put
619
+ // in is where the record starts.
620
+ opened.value = deepClone(model.value) as T;
330
621
  checkDraft();
331
622
  return;
332
623
  }
@@ -334,19 +625,6 @@ async function fetchModel() {
334
625
  try {
335
626
  model.value = await crud.detail(props.id);
336
627
  backup.value = deepClone(model.value) as T;
337
- // Auto-derive languages from the backend response when the host page does
338
- // not hard-code them. Camomilla embeds site_languages inside lang_info.
339
- const langInfo = (model.value as Record<string, unknown>)?.lang_info as
340
- | Record<string, unknown>
341
- | undefined;
342
- const siteLangs = langInfo?.site_languages as string[] | undefined;
343
- if (
344
- siteLangs?.length &&
345
- !props.languages.length &&
346
- !props.forceLanguages?.length
347
- ) {
348
- derivedLangs.value = siteLangs;
349
- }
350
628
  checkDraft();
351
629
  } catch (err: unknown) {
352
630
  snack.show(getErrorDetail(err) ?? t("mapo.loadItemError"), "error");
@@ -356,9 +634,38 @@ async function fetchModel() {
356
634
  }
357
635
  }
358
636
 
637
+ // ─── Saved ───────────────────────────────────────────────────────────────────
638
+ // The components inside hear of each save that succeeds before the page
639
+ // moves: a new record's page gives way to the record's own address.
640
+
641
+ const savedHandlers = new Set<(record: T) => void>();
642
+
643
+ function onSaved(handler: (record: T) => void): () => void {
644
+ savedHandlers.add(handler);
645
+ const remove = () => {
646
+ savedHandlers.delete(handler);
647
+ };
648
+ if (getCurrentScope()) onScopeDispose(remove);
649
+ return remove;
650
+ }
651
+
652
+ function notifySaved(record: T): void {
653
+ for (const handler of [...savedHandlers]) {
654
+ try {
655
+ handler(record);
656
+ } catch {
657
+ // A component's failure leaves the save done.
658
+ }
659
+ }
660
+ }
661
+
359
662
  // ─── Save ────────────────────────────────────────────────────────────────────
360
663
 
361
664
  async function save(andBack = false) {
665
+ // The built-in buttons are disabled meanwhile; a custom one bound to `save`
666
+ // may not be.
667
+ if (isBusy.value) return;
668
+
362
669
  const validationResults = formValidators.map((fn) => fn());
363
670
  const allValid = validationResults.every((r) => r.valid);
364
671
  if (!allValid) {
@@ -373,7 +680,8 @@ async function save(andBack = false) {
373
680
  }
374
681
 
375
682
  errors.value = {};
376
- isSaving.value = true;
683
+ pendingAction.value = andBack ? "save" : "saveContinue";
684
+ let leaving = false;
377
685
  try {
378
686
  const multipartOpts = { multipart: props.multipart };
379
687
  let result: T;
@@ -403,13 +711,14 @@ async function save(andBack = false) {
403
711
  "success",
404
712
  );
405
713
  emit("saved", model.value);
714
+ notifySaved(model.value);
406
715
  if (isNew.value && result && "id" in result) {
407
716
  const id = (result as unknown as { id: string | number }).id;
408
717
  await router.replace({
409
718
  params: { id },
410
719
  });
411
720
  }
412
- if (andBack) back();
721
+ if (andBack) leaving = leave();
413
722
  } catch (err: unknown) {
414
723
  const data = getErrorData(err);
415
724
  if (getErrorStatus(err) === 400 && data && typeof data === "object") {
@@ -423,7 +732,8 @@ async function save(andBack = false) {
423
732
  snack.show(detail ?? t("mapo.saveError"), "error");
424
733
  }
425
734
  } finally {
426
- isSaving.value = false;
735
+ // Going back: still busy until the page is gone (see leave()).
736
+ if (!leaving) pendingAction.value = null;
427
737
  }
428
738
  }
429
739
 
@@ -435,6 +745,7 @@ function getPatch(): Partial<T> {
435
745
  // ─── Delete ──────────────────────────────────────────────────────────────────
436
746
 
437
747
  async function deleteItem() {
748
+ if (isBusy.value) return;
438
749
  const ok = await confirm.ask({
439
750
  title: t("mapo.delete"),
440
751
  message: t("mapo.detail.deleteQuestion"),
@@ -442,24 +753,52 @@ async function deleteItem() {
442
753
  dangerous: true,
443
754
  });
444
755
  if (!ok) return;
445
- isDeleting.value = true;
756
+ pendingAction.value = "delete";
757
+ let leaving = false;
446
758
  try {
447
759
  await crud.delete(recordId());
448
760
  backup.value = deepClone(model.value) as T; // clear dirty so guard doesn't fire
449
761
  snack.show(t("mapo.deleteSuccess"), "success");
450
762
  emit("deleted");
451
- back();
763
+ leaving = leave();
452
764
  } catch (err: unknown) {
453
765
  snack.show(getErrorDetail(err) ?? t("mapo.deleteError"), "error");
454
766
  } finally {
455
- isDeleting.value = false;
767
+ if (!leaving) pendingAction.value = null;
456
768
  }
457
769
  }
458
770
 
459
771
  // ─── Navigation guard ────────────────────────────────────────────────────────
460
772
 
461
773
  function back() {
774
+ if (isBusy.value) return;
775
+ pendingAction.value = "back";
776
+ const leaving = leave();
777
+ if (!leaving) pendingAction.value = null;
778
+ }
779
+
780
+ /**
781
+ * Goes back one step and tells whether that is a navigation inside the app.
782
+ *
783
+ * router.back() does not wait for the navigation, and this page stays on screen
784
+ * until the previous route is ready. So the caller keeps its action pending
785
+ * until the page is gone; if the navigation fails (a guard kept the page, such
786
+ * as the unsaved-changes one), the action is released and the buttons work
787
+ * again.
788
+ */
789
+ function leave(): boolean {
790
+ // Opened directly (a new tab, a bookmark): no page of the app to go back to,
791
+ // router.back() leaves the app or does nothing, and nothing would release
792
+ // the buttons.
793
+ const hasPreviousPage = router.options.history.state.back != null;
794
+ if (hasPreviousPage) {
795
+ const stopWatching = router.afterEach((_to, _from, failure) => {
796
+ stopWatching();
797
+ if (failure) pendingAction.value = null;
798
+ });
799
+ }
462
800
  router.back();
801
+ return hasPreviousPage;
463
802
  }
464
803
 
465
804
  async function guardUnsaved(): Promise<boolean> {
@@ -494,6 +833,9 @@ onMounted(() => {
494
833
  preventWindowClose,
495
834
  );
496
835
  }
836
+ // Independent of the record fetch: languages come from OPTIONS either way,
837
+ // and a new record has no fetch to piggyback on.
838
+ describeEndpoint();
497
839
  fetchModel();
498
840
  });
499
841
 
@@ -509,6 +851,61 @@ onBeforeUnmount(() => {
509
851
  }
510
852
  });
511
853
 
854
+ // ─── Context ─────────────────────────────────────────────────────────────────
855
+ // What the components inside the detail read with useMapoDetail(): its slots,
856
+ // its forms and the extensions registered with defineDetailExtension().
857
+
858
+ /** Marks set from inside the detail; the `annotations` prop wins on a path. */
859
+ const innerAnnotations = ref<FieldAnnotations>({});
860
+ const formAnnotations = computed<FieldAnnotations>(() => ({
861
+ ...innerAnnotations.value,
862
+ ...(props.annotations ?? {}),
863
+ }));
864
+
865
+ let metadataRequest: Promise<Record<string, unknown> | undefined> | undefined;
866
+
867
+ /** The endpoint's OPTIONS response, requested once and shared. */
868
+ function describe(): Promise<Record<string, unknown> | undefined> {
869
+ metadataRequest ??= crud.options().then(
870
+ (response) =>
871
+ typeof response === "object" && response !== null
872
+ ? (response as Record<string, unknown>)
873
+ : undefined,
874
+ () => undefined,
875
+ );
876
+ return metadataRequest;
877
+ }
878
+
879
+ const context: MapoDetailContext<T> = {
880
+ endpoint: computed(() => props.endpoint),
881
+ id: computed(() => props.id),
882
+ isNew,
883
+ modelName: computed(() => props.modelName ?? null),
884
+ permissionModel: computed(() => props.permissionModel),
885
+ model,
886
+ fields: activeFields,
887
+ sidebarFields: computed(() => props.sidebarFields ?? []),
888
+ languages: activeLangs,
889
+ currentLang,
890
+ registry,
891
+ errors,
892
+ readonly: effectiveReadonly,
893
+ isLoading,
894
+ isSaving,
895
+ isBusy,
896
+ isDirty,
897
+ annotations: innerAnnotations,
898
+ extensions: computed(() => props.extensions),
899
+ save,
900
+ back,
901
+ metadata: describe,
902
+ schemaFromMetadata: computed(() => props.schemaFromMetadata),
903
+ onSaved,
904
+ draft: { part: addDraftPart, touch: () => saveDraftSoon() },
905
+ revealField,
906
+ };
907
+ provide(DETAIL_KEY, context as unknown as MapoDetailContext);
908
+
512
909
  // ─── Slot bindings ───────────────────────────────────────────────────────────
513
910
 
514
911
  // Forward field-level (`field.*`), group-level (`group.*`) and tab-level (`tab.*`,
@@ -527,6 +924,8 @@ const formSlotNames = computed(() =>
527
924
 
528
925
  const slotBindings = computed(() => ({
529
926
  model: model.value,
927
+ fields: activeFields.value,
928
+ sidebarFields: props.sidebarFields ?? [],
530
929
  errors: errors.value,
531
930
  currentLang: currentLang.value,
532
931
  isNew: isNew.value,
@@ -550,18 +949,27 @@ type DraftBannerState = {
550
949
 
551
950
  type SlotBindings = {
552
951
  model: T;
952
+ /** The body fields rendered: the `fields` prop, or the ones derived from the schema. */
953
+ fields: AnyFieldDescriptor<T>[];
954
+ /** The sidebar fields rendered. */
955
+ sidebarFields: AnyFieldDescriptor<T>[];
553
956
  errors: Record<string, string[]>;
554
957
  currentLang: string;
555
958
  isNew: boolean;
556
959
  isLoading: boolean;
960
+ /** From the click until the save is done; after `save(true)`, until the page has gone back. */
557
961
  isSaving: boolean;
962
+ /** From the confirmation until the delete is done and the page has gone back. */
558
963
  isDeleting: boolean;
559
964
  isDirty: boolean;
560
965
  draftBanner: DraftBannerState;
561
966
  readonly: boolean;
562
967
  canDelete: boolean;
968
+ /** Ignored while a save, a delete or a navigation back is under way. */
563
969
  save: (andBack?: boolean) => Promise<void>;
970
+ /** Ignored while a save, a delete or a navigation back is under way. */
564
971
  deleteItem: () => Promise<void>;
972
+ /** Ignored while a save, a delete or a navigation back is under way. */
565
973
  back: () => void;
566
974
  };
567
975
 
@@ -573,7 +981,9 @@ defineSlots<{
573
981
  /**
574
982
  * Draft restore banner shown when a localStorage draft is found.
575
983
  * Receives `draftBanner` (with `savedAt`, `restore`, `discard`) plus the full slot bindings.
576
- * Override to render a completely custom banner; set to an empty slot to suppress it.
984
+ * Override to render a completely custom banner. To hide it, render an
985
+ * element of your own, such as `<span hidden />`: a slot that gives no
986
+ * element, an empty one included, renders the built-in banner.
577
987
  */
578
988
  "draft-banner"(props: SlotBindings): VNode[];
579
989
  /** Extra content above the main form. */
@@ -598,7 +1008,9 @@ defineSlots<{
598
1008
  "side-bottom"(props: SlotBindings): VNode[];
599
1009
  /**
600
1010
  * Danger-zone card at the very bottom of the sidebar (delete action).
601
- * Rendered only for existing records (`!isNew`). Override to replace or suppress it.
1011
+ * Rendered only for existing records (`!isNew`). Override to replace it;
1012
+ * to hide it, render an element of your own, such as `<span hidden />`: a
1013
+ * slot that gives no element, an empty one included, renders the built-in card.
602
1014
  */
603
1015
  "side-danger"(props: SlotBindings): VNode[];
604
1016
  /** Per-field slot. Slot name: `field.{key}`, `field.{key}.before`, `field.{key}.after`. */
@@ -675,21 +1087,25 @@ defineSlots<{
675
1087
  v-model="currentLang"
676
1088
  :langs="activeLangs"
677
1089
  :errors="errors"
1090
+ :lang-threshold="langThreshold"
678
1091
  />
679
1092
  </slot>
680
1093
 
1094
+ <MapoDetailExtensions placement="body-top" />
1095
+
681
1096
  <slot name="body-top" v-bind="slotBindings" />
682
1097
 
683
1098
  <!-- Main form -->
684
1099
  <slot name="body" v-bind="slotBindings">
685
1100
  <MapoForm
686
1101
  v-model="model"
687
- :fields="fields"
1102
+ :fields="activeFields"
688
1103
  :errors="errors"
689
1104
  :languages="activeLangs"
690
1105
  :current-lang="currentLang"
691
1106
  :registry="registry"
692
1107
  :readonly="effectiveReadonly"
1108
+ :annotations="formAnnotations"
693
1109
  >
694
1110
  <template
695
1111
  v-for="slotName in formSlotNames"
@@ -707,15 +1123,19 @@ defineSlots<{
707
1123
  <!-- Sidebar column -->
708
1124
  <div :class="sidebarColsClass">
709
1125
  <div :style="sidebarStyle" class="space-y-4">
710
- <!-- Action buttons (Save / Save&continue / Back — no delete here) -->
1126
+ <!-- Action buttons (Save / Save&continue / Back — no delete here).
1127
+ While one works, it spins and all of them are disabled. -->
711
1128
  <slot name="side-buttons" v-bind="slotBindings">
712
1129
  <UCard>
713
1130
  <div class="flex flex-col gap-2">
1131
+ <MapoDetailExtensions placement="actions" />
1132
+
714
1133
  <slot name="button-save" v-bind="slotBindings">
715
1134
  <UButton
716
1135
  v-if="!effectiveReadonly"
717
1136
  block
718
- :loading="isSaving"
1137
+ :loading="pendingAction === 'save'"
1138
+ :disabled="isBusy"
719
1139
  icon="i-lucide-save"
720
1140
  @click="save(true)"
721
1141
  >
@@ -728,7 +1148,8 @@ defineSlots<{
728
1148
  v-if="!effectiveReadonly"
729
1149
  block
730
1150
  variant="soft"
731
- :loading="isSaving"
1151
+ :loading="pendingAction === 'saveContinue'"
1152
+ :disabled="isBusy"
732
1153
  icon="i-lucide-save"
733
1154
  @click="save(false)"
734
1155
  >
@@ -743,6 +1164,8 @@ defineSlots<{
743
1164
  block
744
1165
  variant="ghost"
745
1166
  icon="i-lucide-arrow-left"
1167
+ :loading="pendingAction === 'back'"
1168
+ :disabled="isBusy"
746
1169
  @click="back"
747
1170
  >
748
1171
  {{ t("mapo.back") }}
@@ -767,6 +1190,8 @@ defineSlots<{
767
1190
  :current-lang="currentLang"
768
1191
  :registry="registry"
769
1192
  :readonly="effectiveReadonly"
1193
+ :annotations="formAnnotations"
1194
+ :notify-errors="false"
770
1195
  >
771
1196
  <template
772
1197
  v-for="slotName in formSlotNames"
@@ -786,6 +1211,8 @@ defineSlots<{
786
1211
  :current-lang="currentLang"
787
1212
  :registry="registry"
788
1213
  :readonly="effectiveReadonly"
1214
+ :annotations="formAnnotations"
1215
+ :notify-errors="false"
789
1216
  >
790
1217
  <template
791
1218
  v-for="slotName in formSlotNames"
@@ -820,6 +1247,7 @@ defineSlots<{
820
1247
  color="error"
821
1248
  variant="soft"
822
1249
  :loading="isDeleting"
1250
+ :disabled="isBusy"
823
1251
  icon="i-lucide-trash-2"
824
1252
  @click="deleteItem"
825
1253
  >