@mapomodule/uikit 2.0.0-beta.6 → 2.0.0-beta.8

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 (115) hide show
  1. package/dist/index.d.mts +1 -0
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/module.d.mts +1 -0
  6. package/dist/module.d.ts.map +1 -1
  7. package/dist/module.json +1 -1
  8. package/dist/module.mjs +13 -2
  9. package/dist/runtime/components/MapoConfirmDialog.vue +5 -3
  10. package/dist/runtime/components/MapoConfirmDialog.vue.d.ts.map +1 -1
  11. package/dist/runtime/components/MapoDetail.vue +40 -32
  12. package/dist/runtime/components/MapoDetail.vue.d.ts.map +1 -1
  13. package/dist/runtime/components/MapoDetailLangSwitch.vue +1 -1
  14. package/dist/runtime/components/MapoDropArea.vue +5 -1
  15. package/dist/runtime/components/MapoDropArea.vue.d.ts.map +1 -1
  16. package/dist/runtime/components/MapoLangSwitcher.vue +39 -0
  17. package/dist/runtime/components/MapoLangSwitcher.vue.d.ts +18 -0
  18. package/dist/runtime/components/MapoLangSwitcher.vue.d.ts.map +1 -0
  19. package/dist/runtime/components/MapoList.vue +2 -2
  20. package/dist/runtime/components/MapoListActions.vue +15 -8
  21. package/dist/runtime/components/MapoListActions.vue.d.ts.map +1 -1
  22. package/dist/runtime/components/MapoListFilters.vue +4 -2
  23. package/dist/runtime/components/MapoListFilters.vue.d.ts.map +1 -1
  24. package/dist/runtime/components/MapoListQuickEdit.vue +13 -9
  25. package/dist/runtime/components/MapoListQuickEdit.vue.d.ts.map +1 -1
  26. package/dist/runtime/components/MapoListTable.vue +26 -21
  27. package/dist/runtime/components/MapoListTable.vue.d.ts.map +1 -1
  28. package/dist/runtime/components/MapoLogin.vue +13 -10
  29. package/dist/runtime/components/MapoLogin.vue.d.ts.map +1 -1
  30. package/dist/runtime/components/MapoLogoutButton.vue +4 -2
  31. package/dist/runtime/components/MapoLogoutButton.vue.d.ts.map +1 -1
  32. package/dist/runtime/components/MapoMediaBreadcrumbs.vue +3 -1
  33. package/dist/runtime/components/MapoMediaBreadcrumbs.vue.d.ts.map +1 -1
  34. package/dist/runtime/components/MapoMediaEditor.vue +26 -16
  35. package/dist/runtime/components/MapoMediaEditor.vue.d.ts.map +1 -1
  36. package/dist/runtime/components/MapoMediaFileChanger.vue +8 -4
  37. package/dist/runtime/components/MapoMediaFileChanger.vue.d.ts.map +1 -1
  38. package/dist/runtime/components/MapoMediaFolders.vue +36 -14
  39. package/dist/runtime/components/MapoMediaFolders.vue.d.ts.map +1 -1
  40. package/dist/runtime/components/MapoMediaGallery.vue +15 -5
  41. package/dist/runtime/components/MapoMediaGallery.vue.d.ts.map +1 -1
  42. package/dist/runtime/components/MapoMediaManager.vue +18 -8
  43. package/dist/runtime/components/MapoMediaManager.vue.d.ts.map +1 -1
  44. package/dist/runtime/components/MapoMediaManagerDialog.vue +9 -5
  45. package/dist/runtime/components/MapoMediaManagerDialog.vue.d.ts.map +1 -1
  46. package/dist/runtime/components/MapoMediaPreview.vue +1 -1
  47. package/dist/runtime/components/MapoMediaUploader.vue +40 -16
  48. package/dist/runtime/components/MapoMediaUploader.vue.d.ts.map +1 -1
  49. package/dist/runtime/components/MapoMenuManager.vue +273 -0
  50. package/dist/runtime/components/MapoMenuManager.vue.d.ts +92 -0
  51. package/dist/runtime/components/MapoMenuManager.vue.d.ts.map +1 -0
  52. package/dist/runtime/components/MapoMenuNodeEditor.vue +201 -0
  53. package/dist/runtime/components/MapoMenuNodeEditor.vue.d.ts +61 -0
  54. package/dist/runtime/components/MapoMenuNodeEditor.vue.d.ts.map +1 -0
  55. package/dist/runtime/components/MapoMenuTreeview.vue +181 -0
  56. package/dist/runtime/components/MapoMenuTreeview.vue.d.ts +57 -0
  57. package/dist/runtime/components/MapoMenuTreeview.vue.d.ts.map +1 -0
  58. package/dist/runtime/components/MapoMenuTreeviewNode.vue +175 -0
  59. package/dist/runtime/components/MapoMenuTreeviewNode.vue.d.ts +27 -0
  60. package/dist/runtime/components/MapoMenuTreeviewNode.vue.d.ts.map +1 -0
  61. package/dist/runtime/components/MapoSidebar.vue +3 -1
  62. package/dist/runtime/components/MapoSidebar.vue.d.ts.map +1 -1
  63. package/dist/runtime/components/MapoSidebarList.vue +1 -1
  64. package/dist/runtime/components/MapoSidebarProfile.vue +6 -2
  65. package/dist/runtime/components/MapoSidebarProfile.vue.d.ts.map +1 -1
  66. package/dist/runtime/components/MapoThemeToggle.vue +5 -1
  67. package/dist/runtime/components/MapoThemeToggle.vue.d.ts.map +1 -1
  68. package/dist/runtime/components/menuDndContext.d.ts +19 -0
  69. package/dist/runtime/components/menuDndContext.d.ts.map +1 -0
  70. package/dist/runtime/components/menuDndContext.js +3 -0
  71. package/dist/runtime/pages/index.vue +4 -2
  72. package/dist/runtime/pages/index.vue.d.ts.map +1 -1
  73. package/dist/runtime/plugins/media-adapter.d.ts.map +1 -1
  74. package/dist/runtime/plugins/media-adapter.js +2 -1
  75. package/dist/runtime/stores/media.d.ts.map +1 -1
  76. package/dist/runtime/stores/media.js +36 -14
  77. package/dist/runtime/types/menu.d.ts +66 -0
  78. package/dist/runtime/types/menu.d.ts.map +1 -0
  79. package/dist/runtime/types/menu.js +30 -0
  80. package/package.json +11 -8
  81. package/src/index.ts +12 -0
  82. package/src/module.ts +17 -0
  83. package/src/runtime/components/MapoConfirmDialog.vue +5 -3
  84. package/src/runtime/components/MapoDetail.vue +39 -36
  85. package/src/runtime/components/MapoDetailLangSwitch.vue +1 -1
  86. package/src/runtime/components/MapoDropArea.vue +6 -1
  87. package/src/runtime/components/MapoLangSwitcher.vue +74 -0
  88. package/src/runtime/components/MapoList.vue +1 -1
  89. package/src/runtime/components/MapoListActions.vue +16 -10
  90. package/src/runtime/components/MapoListFilters.vue +5 -2
  91. package/src/runtime/components/MapoListQuickEdit.vue +12 -9
  92. package/src/runtime/components/MapoListTable.vue +26 -21
  93. package/src/runtime/components/MapoLogin.vue +13 -10
  94. package/src/runtime/components/MapoLogoutButton.vue +4 -2
  95. package/src/runtime/components/MapoMediaBreadcrumbs.vue +3 -1
  96. package/src/runtime/components/MapoMediaEditor.vue +26 -16
  97. package/src/runtime/components/MapoMediaFileChanger.vue +8 -3
  98. package/src/runtime/components/MapoMediaFolders.vue +37 -15
  99. package/src/runtime/components/MapoMediaGallery.vue +17 -5
  100. package/src/runtime/components/MapoMediaManager.vue +17 -7
  101. package/src/runtime/components/MapoMediaManagerDialog.vue +10 -4
  102. package/src/runtime/components/MapoMediaUploader.vue +43 -16
  103. package/src/runtime/components/MapoMenuManager.vue +402 -0
  104. package/src/runtime/components/MapoMenuNodeEditor.vue +282 -0
  105. package/src/runtime/components/MapoMenuTreeview.vue +264 -0
  106. package/src/runtime/components/MapoMenuTreeviewNode.vue +234 -0
  107. package/src/runtime/components/MapoSidebar.vue +3 -1
  108. package/src/runtime/components/MapoSidebarList.vue +1 -1
  109. package/src/runtime/components/MapoSidebarProfile.vue +6 -2
  110. package/src/runtime/components/MapoThemeToggle.vue +5 -1
  111. package/src/runtime/components/menuDndContext.ts +22 -0
  112. package/src/runtime/pages/index.vue +5 -2
  113. package/src/runtime/plugins/media-adapter.ts +9 -5
  114. package/src/runtime/stores/media.ts +51 -15
  115. package/src/runtime/types/menu.ts +105 -0
@@ -0,0 +1,402 @@
1
+ <script setup lang="ts">
2
+ import { ref, computed, watch, onMounted } from "vue";
3
+ import { useI18n } from "vue-i18n";
4
+ import { useCrud } from "@mapomodule/core/runtime/api/crud";
5
+ import {
6
+ getErrorData,
7
+ getErrorDetail,
8
+ getErrorStatus,
9
+ } from "@mapomodule/core/runtime/utils/fetchError";
10
+ import { useSnackStore } from "@mapomodule/store/runtime/stores/snack";
11
+ import { usePermissions } from "@mapomodule/store/runtime/composables/usePermissions";
12
+ import { deepClone, objectDiff } from "@mapomodule/utils";
13
+ import type { AnyFieldDescriptor } from "@mapomodule/form/types";
14
+ import {
15
+ findMenuNode,
16
+ type MapoMenu,
17
+ type MenuTreeNode,
18
+ } from "../types/menu.js";
19
+ import MapoMenuTreeview from "./MapoMenuTreeview.vue";
20
+ import MapoMenuNodeEditor from "./MapoMenuNodeEditor.vue";
21
+
22
+ /**
23
+ * Menu Manager shell — split-pane editor for hierarchical navigation menus.
24
+ *
25
+ * Left: drag & drop node tree (`MapoMenuTreeview`).
26
+ * Right: form editor for the selected node (`MapoMenuNodeEditor`).
27
+ *
28
+ * Loads the menu from `endpoint`/`identifier` on mount (v1 parity), keeps
29
+ * per-language node trees when `translatable`, and saves the whole structure
30
+ * with `create`/`update`/`partialUpdate` depending on state and `usePatch`.
31
+ *
32
+ * @example
33
+ * <MapoMenuManager
34
+ * endpoint="/api/menus"
35
+ * :identifier="route.params.id"
36
+ * :languages="['it', 'en']"
37
+ * :max-depth="5"
38
+ * />
39
+ */
40
+ const props = withDefaults(
41
+ defineProps<{
42
+ /** Menu CRUD endpoint (e.g. `/api/menus`). */
43
+ endpoint: string;
44
+ /** Menu id to load, or `"new"` to start from an empty menu. */
45
+ identifier?: string | number;
46
+ /** Menu payload (v-model). Used as the initial model when `identifier` is `"new"`. */
47
+ modelValue?: MapoMenu | null;
48
+ /** Manage one node tree per language under `translations`. */
49
+ translatable?: boolean;
50
+ /** Active editing language (v-model:lang). Defaults to the first of `languages`. */
51
+ lang?: string;
52
+ /** Translation language codes (e.g. `['it', 'en']`). */
53
+ languages?: string[];
54
+ /** Save with `partialUpdate` sending only the changed keys. */
55
+ usePatch?: boolean;
56
+ /** Max nesting depth; `-1` = unlimited. */
57
+ maxDepth?: number;
58
+ /**
59
+ * Django model used for permission gating (`add_<model>` / `change_<model>`).
60
+ * When the user lacks the permission the manager renders read-only.
61
+ */
62
+ permissionModel?: string;
63
+ /** Force read-only mode. */
64
+ readonly?: boolean;
65
+ /** Replaces the node editor's default core fields. */
66
+ coreFields?: AnyFieldDescriptor[] | null;
67
+ /** Extra node editor fields appended after the core ones. */
68
+ additionalFields?: AnyFieldDescriptor[];
69
+ /** CSS classes offered by the node `style` select, as `{ label: cssClass }`. */
70
+ availableClasses?: Record<string, string>;
71
+ }>(),
72
+ {
73
+ identifier: "new",
74
+ modelValue: null,
75
+ translatable: true,
76
+ lang: undefined,
77
+ languages: () => [],
78
+ usePatch: false,
79
+ maxDepth: -1,
80
+ permissionModel: undefined,
81
+ readonly: false,
82
+ coreFields: null,
83
+ additionalFields: () => [],
84
+ availableClasses: () => ({}),
85
+ },
86
+ );
87
+
88
+ const emit = defineEmits<{
89
+ "update:modelValue": [menu: MapoMenu];
90
+ "update:lang": [lang: string];
91
+ /** Emitted after a successful save with the server response. */
92
+ saved: [menu: MapoMenu];
93
+ }>();
94
+
95
+ defineSlots<{
96
+ /** Rendered when no node is selected (right pane placeholder). */
97
+ empty(): unknown;
98
+ /** Content above the node editor form. */
99
+ "editor-form-top"(props: Record<string, unknown>): unknown;
100
+ /** Replaces the node editor form. */
101
+ "editor-form"(props: Record<string, unknown>): unknown;
102
+ /** Content below the node editor form. */
103
+ "editor-form-bottom"(props: Record<string, unknown>): unknown;
104
+ }>();
105
+
106
+ const { t } = useI18n();
107
+ const snack = useSnackStore();
108
+ const crud = useCrud<MapoMenu>(props.endpoint);
109
+
110
+ // ─── State ────────────────────────────────────────────────────────────────────
111
+
112
+ const model = ref<MapoMenu>(
113
+ props.modelValue ?? { key: "", nodes: [], translations: {} },
114
+ );
115
+ let backup: MapoMenu = deepClone(model.value);
116
+
117
+ const selected = ref<MenuTreeNode | null>(null);
118
+ const currentLang = ref(props.lang ?? props.languages[0] ?? "");
119
+ const isLoading = ref(String(props.identifier) !== "new");
120
+ const isSaving = ref(false);
121
+
122
+ const isNew = computed(() => String(props.identifier) === "new");
123
+ const translationsActive = computed(
124
+ () => props.translatable && props.languages.length > 0,
125
+ );
126
+
127
+ // ─── Permissions ─────────────────────────────────────────────────────────────
128
+
129
+ const { canAdd, canChange } = usePermissions();
130
+ const effectiveReadonly = computed(() => {
131
+ if (props.readonly) return true;
132
+ if (!props.permissionModel) return false;
133
+ return isNew.value
134
+ ? !canAdd(props.permissionModel)
135
+ : !canChange(props.permissionModel);
136
+ });
137
+
138
+ // ─── Language handling ───────────────────────────────────────────────────────
139
+
140
+ watch(
141
+ () => props.lang,
142
+ (val) => {
143
+ if (val && props.languages.includes(val)) currentLang.value = val;
144
+ },
145
+ );
146
+
147
+ watch(currentLang, (val) => {
148
+ // Nodes are per-language: the old selection does not exist in the new tree.
149
+ selected.value = null;
150
+ emit("update:lang", val);
151
+ });
152
+
153
+ // ─── Active node tree (translations-aware) ───────────────────────────────────
154
+ // The container the active tree lives in is created eagerly by a watcher rather
155
+ // than lazily inside the `nodes` computed: the tree is mutated in place by the
156
+ // drag & drop lists, so it must be a stable reactive array, and a computed that
157
+ // writes to the model on read would be a side effect.
158
+
159
+ function ensureTree() {
160
+ if (translationsActive.value) {
161
+ model.value.translations ??= {};
162
+ const lang = currentLang.value;
163
+ model.value.translations[lang] ??= { nodes: [] };
164
+ model.value.translations[lang].nodes ??= [];
165
+ } else {
166
+ model.value.nodes ??= [];
167
+ }
168
+ }
169
+
170
+ watch([model, currentLang, translationsActive], ensureTree, {
171
+ immediate: true,
172
+ });
173
+
174
+ const nodes = computed<MenuTreeNode[]>(() => {
175
+ if (translationsActive.value) {
176
+ return model.value.translations?.[currentLang.value]?.nodes ?? [];
177
+ }
178
+ return model.value.nodes ?? [];
179
+ });
180
+
181
+ // ─── Load ────────────────────────────────────────────────────────────────────
182
+
183
+ watch(
184
+ () => props.modelValue,
185
+ (val) => {
186
+ if (val) model.value = val;
187
+ },
188
+ );
189
+
190
+ watch(model, (val) => emit("update:modelValue", val));
191
+
192
+ onMounted(async () => {
193
+ if (isNew.value) return;
194
+ isLoading.value = true;
195
+ try {
196
+ model.value = await crud.detail(props.identifier);
197
+ backup = deepClone(model.value);
198
+ } catch (err: unknown) {
199
+ snack.show(getErrorDetail(err) ?? t("mapo.loadItemError"), "error");
200
+ } finally {
201
+ isLoading.value = false;
202
+ }
203
+ });
204
+
205
+ // ─── Save ────────────────────────────────────────────────────────────────────
206
+
207
+ async function save() {
208
+ if (effectiveReadonly.value) return;
209
+ clearErrors();
210
+ isSaving.value = true;
211
+ try {
212
+ let response: MapoMenu;
213
+ if (!model.value.id) {
214
+ response = await crud.create(model.value);
215
+ } else if (props.usePatch) {
216
+ const diff = objectDiff(backup, model.value) as Partial<MapoMenu>;
217
+ response = await crud.partialUpdate(model.value.id, diff);
218
+ } else {
219
+ response = await crud.update(model.value.id, model.value);
220
+ }
221
+ model.value = response;
222
+ backup = deepClone(response);
223
+ selected.value = null;
224
+ snack.show(
225
+ isNew.value ? t("mapo.createSuccess") : t("mapo.saveSuccess"),
226
+ "success",
227
+ );
228
+ emit("saved", response);
229
+ } catch (err: unknown) {
230
+ const data = getErrorData(err);
231
+ if (getErrorStatus(err) === 400 && data) parseErrors(data);
232
+ snack.show(getErrorDetail(err) ?? t("mapo.genericError"), "error");
233
+ } finally {
234
+ isSaving.value = false;
235
+ }
236
+ }
237
+
238
+ // ─── Backend error mapping ───────────────────────────────────────────────────
239
+ // DRF mirrors the payload shape: errors for nested nodes arrive at the same
240
+ // position in a nested `nodes` array. Walk both trees in parallel and attach
241
+ // the node-level errors; select the first errored node in the active tree.
242
+
243
+ function clearErrors() {
244
+ const walk = (list: MenuTreeNode[]) => {
245
+ for (const node of list) {
246
+ if (node.errors) delete node.errors;
247
+ walk(node.nodes ?? []);
248
+ }
249
+ };
250
+ if (model.value.nodes) walk(model.value.nodes);
251
+ for (const tr of Object.values(model.value.translations ?? {})) {
252
+ walk(tr.nodes ?? []);
253
+ }
254
+ }
255
+
256
+ function parseErrors(data: Record<string, unknown>) {
257
+ const attach = (
258
+ list: MenuTreeNode[],
259
+ errors: unknown[],
260
+ inActiveTree: boolean,
261
+ ) => {
262
+ errors.forEach((err, i) => {
263
+ const node = list[i];
264
+ if (!node || !err || typeof err !== "object") return;
265
+ const { nodes: childErrors, ...nodeErrors } = err as Record<
266
+ string,
267
+ unknown
268
+ >;
269
+ if (Object.keys(nodeErrors).length > 0) {
270
+ node.errors = nodeErrors as Record<string, string[]>;
271
+ if (inActiveTree && !selected.value) selected.value = node;
272
+ }
273
+ if (Array.isArray(childErrors)) {
274
+ attach(node.nodes ?? [], childErrors, inActiveTree);
275
+ }
276
+ });
277
+ };
278
+
279
+ if (translationsActive.value) {
280
+ const translations = data.translations as
281
+ | Record<string, { nodes?: unknown[] }>
282
+ | undefined;
283
+ for (const [lang, trErrors] of Object.entries(translations ?? {})) {
284
+ const tree = model.value.translations?.[lang]?.nodes ?? [];
285
+ if (Array.isArray(trErrors?.nodes)) {
286
+ attach(tree, trErrors.nodes, lang === currentLang.value);
287
+ }
288
+ }
289
+ } else if (Array.isArray(data.nodes)) {
290
+ attach(model.value.nodes ?? [], data.nodes, true);
291
+ }
292
+ }
293
+
294
+ // ─── Editor errors for the lang switch ───────────────────────────────────────
295
+ // MapoDetailLangSwitch highlights languages whose keys start with
296
+ // `translations.<lang>.` — build that map from the per-node errors.
297
+
298
+ const langErrors = computed<Record<string, string[]>>(() => {
299
+ const map: Record<string, string[]> = {};
300
+ const hasErrors = (list: MenuTreeNode[]): boolean =>
301
+ list.some(
302
+ (n) =>
303
+ (n.errors && Object.keys(n.errors).length > 0) ||
304
+ hasErrors(n.nodes ?? []),
305
+ );
306
+ for (const [lang, tr] of Object.entries(model.value.translations ?? {})) {
307
+ if (hasErrors(tr.nodes ?? [])) {
308
+ map[`translations.${lang}.nodes`] = [t("mapo.fixErrors")];
309
+ }
310
+ }
311
+ return map;
312
+ });
313
+
314
+ const treeview = ref<InstanceType<typeof MapoMenuTreeview> | null>(null);
315
+ </script>
316
+
317
+ <template>
318
+ <div class="mapo-menu-manager flex h-full min-h-0 overflow-hidden">
319
+ <!-- Left pane: tree -->
320
+ <div class="flex w-72 shrink-0 flex-col border-r border-default bg-default">
321
+ <MapoMenuTreeview
322
+ ref="treeview"
323
+ v-model="selected"
324
+ :nodes="nodes"
325
+ :title="`${t('mapo.menuManager.menu')}: ${model.key || '—'}`"
326
+ :max-depth="maxDepth"
327
+ :readonly="effectiveReadonly"
328
+ :loading="isLoading"
329
+ >
330
+ <template v-if="translationsActive" #top>
331
+ <div class="border-b border-default px-2 pt-2">
332
+ <MapoDetailLangSwitch
333
+ v-model="currentLang"
334
+ :langs="languages"
335
+ :errors="langErrors"
336
+ no-route-change
337
+ />
338
+ </div>
339
+ </template>
340
+ <template #bottom>
341
+ <div class="border-t border-default p-2">
342
+ <UButton
343
+ v-if="!effectiveReadonly"
344
+ block
345
+ icon="i-lucide-save"
346
+ :loading="isSaving"
347
+ @click="save"
348
+ >
349
+ {{ t("mapo.save") }}
350
+ </UButton>
351
+ </div>
352
+ </template>
353
+ </MapoMenuTreeview>
354
+ </div>
355
+
356
+ <!-- Right pane -->
357
+ <div v-if="isLoading" class="flex flex-1 items-center justify-center">
358
+ <UIcon
359
+ name="i-lucide-loader-circle"
360
+ class="size-8 animate-spin text-muted"
361
+ />
362
+ </div>
363
+
364
+ <MapoMenuNodeEditor
365
+ v-else-if="selected"
366
+ :model-value="selected"
367
+ :nodes="nodes"
368
+ :menu-endpoint="endpoint"
369
+ :core-fields="coreFields"
370
+ :additional-fields="additionalFields"
371
+ :available-classes="availableClasses"
372
+ :readonly="effectiveReadonly"
373
+ @update:model-value="
374
+ selected = findMenuNode(nodes, $event.id)?.node ?? $event
375
+ "
376
+ @delete="treeview?.deleteSelectedNode()"
377
+ >
378
+ <template #form-top="slotProps">
379
+ <slot name="editor-form-top" v-bind="slotProps" />
380
+ </template>
381
+ <template v-if="$slots['editor-form']" #form="slotProps">
382
+ <slot name="editor-form" v-bind="slotProps" />
383
+ </template>
384
+ <template #form-bottom="slotProps">
385
+ <slot name="editor-form-bottom" v-bind="slotProps" />
386
+ </template>
387
+ </MapoMenuNodeEditor>
388
+
389
+ <!-- Empty state -->
390
+ <div
391
+ v-else
392
+ class="flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center"
393
+ >
394
+ <slot name="empty">
395
+ <UIcon name="i-lucide-network" class="size-12 text-dimmed" />
396
+ <p class="max-w-xs text-sm text-muted">
397
+ {{ t("mapo.menuManager.noSelectedNode") }}
398
+ </p>
399
+ </slot>
400
+ </div>
401
+ </div>
402
+ </template>
@@ -0,0 +1,282 @@
1
+ <script setup lang="ts">
2
+ import { ref, computed, watch, resolveComponent } from "vue";
3
+ import { useI18n } from "vue-i18n";
4
+ import { useCrud } from "@mapomodule/core/runtime/api/crud";
5
+ import type { AnyFieldDescriptor } from "@mapomodule/form/types";
6
+ import { findMenuNode, type MenuTreeNode } from "../types/menu.js";
7
+
8
+ /**
9
+ * Right pane of `MapoMenuManager`: edits the selected node with a `MapoForm`.
10
+ *
11
+ * The default field set matches v1/Camomilla (title, link type, style,
12
+ * new-tab flag, relational page picker, static URL). Consumers can replace it
13
+ * entirely (`core-fields`) or append their own (`additional-fields`).
14
+ */
15
+ const props = withDefaults(
16
+ defineProps<{
17
+ /** Selected node (v-model). Mutated in place — the tree owns the data. */
18
+ modelValue: MenuTreeNode;
19
+ /** Full node tree, used to compute the breadcrumb trail. */
20
+ nodes?: MenuTreeNode[];
21
+ /** Menu CRUD endpoint; `<endpoint>/page_types` feeds the relational picker. */
22
+ menuEndpoint?: string;
23
+ /** Replaces the default core field set entirely. */
24
+ coreFields?: AnyFieldDescriptor[] | null;
25
+ /** Extra fields appended after the core ones. */
26
+ additionalFields?: AnyFieldDescriptor[];
27
+ /** CSS classes offered by the `style` select, as `{ label: cssClass }`. */
28
+ availableClasses?: Record<string, string>;
29
+ readonly?: boolean;
30
+ }>(),
31
+ {
32
+ nodes: () => [],
33
+ menuEndpoint: "",
34
+ coreFields: null,
35
+ additionalFields: () => [],
36
+ availableClasses: () => ({}),
37
+ readonly: false,
38
+ },
39
+ );
40
+
41
+ const emit = defineEmits<{
42
+ "update:modelValue": [node: MenuTreeNode];
43
+ /** Delete-node button pressed. */
44
+ delete: [];
45
+ }>();
46
+
47
+ defineSlots<{
48
+ /** Content above the form. Receives the slot bindings. */
49
+ "form-top"(props: SlotBindings): unknown;
50
+ /** Replaces the whole form. Receives the slot bindings. */
51
+ form(props: SlotBindings): unknown;
52
+ /** Content below the form. Receives the slot bindings. */
53
+ "form-bottom"(props: SlotBindings): unknown;
54
+ }>();
55
+
56
+ interface SlotBindings {
57
+ model: MenuTreeNode;
58
+ fields: AnyFieldDescriptor[];
59
+ errors: Record<string, string[]>;
60
+ readonly: boolean;
61
+ }
62
+
63
+ const { t } = useI18n();
64
+
65
+ // ─── Relational page picker ──────────────────────────────────────────────────
66
+ // `<menuEndpoint>/page_types` lists the content types; its detail returns the
67
+ // routable pages of that type (Camomilla contract, v1 parity).
68
+
69
+ const pageTypesEndpoint = computed(
70
+ () => `${props.menuEndpoint.replace(/\/$/, "")}/page_types`,
71
+ );
72
+
73
+ interface AvailablePage {
74
+ name: string;
75
+ url_node_id: number | string;
76
+ }
77
+
78
+ const availablePages = ref<AvailablePage[]>([]);
79
+
80
+ async function loadPages() {
81
+ const contentType = props.modelValue?.link?.content_type;
82
+ if (!contentType || !props.menuEndpoint) {
83
+ availablePages.value = [];
84
+ return;
85
+ }
86
+ try {
87
+ const crud = useCrud<AvailablePage[]>(pageTypesEndpoint.value);
88
+ const id =
89
+ typeof contentType === "object"
90
+ ? ((contentType as { id?: number | string }).id ?? "")
91
+ : contentType;
92
+ availablePages.value = (await crud.detail(
93
+ id,
94
+ )) as unknown as AvailablePage[];
95
+ } catch {
96
+ availablePages.value = [];
97
+ }
98
+ }
99
+
100
+ watch(() => props.modelValue?.id, loadPages, { immediate: true });
101
+
102
+ // ─── Fields ──────────────────────────────────────────────────────────────────
103
+
104
+ const defaultCoreFields = computed<AnyFieldDescriptor[]>(() => [
105
+ {
106
+ key: "title",
107
+ label: t("mapo.menuNodeEditor.title"),
108
+ type: "text",
109
+ required: true,
110
+ },
111
+ {
112
+ key: "link.link_type",
113
+ label: t("mapo.menuNodeEditor.linkTypeLabel"),
114
+ type: "select",
115
+ cols: { md: 4 },
116
+ attrs: {
117
+ items: [
118
+ { label: t("mapo.menuNodeEditor.relational"), value: "RE" },
119
+ { label: t("mapo.menuNodeEditor.static"), value: "ST" },
120
+ ],
121
+ },
122
+ },
123
+ ...(Object.keys(props.availableClasses).length
124
+ ? [
125
+ {
126
+ key: "meta.style",
127
+ label: t("mapo.menuNodeEditor.styleLabel"),
128
+ type: "select",
129
+ cols: { md: 4 },
130
+ attrs: {
131
+ items: Object.entries(props.availableClasses).map(
132
+ ([label, value]) => ({ label, value }),
133
+ ),
134
+ },
135
+ } as AnyFieldDescriptor,
136
+ ]
137
+ : []),
138
+ {
139
+ // `target_bank` keeps the v1/Camomilla meta key for data compatibility.
140
+ key: "meta.target_bank",
141
+ label: t("mapo.menuNodeEditor.openInNewTabLabel"),
142
+ type: "switch",
143
+ cols: { md: 4 },
144
+ },
145
+ {
146
+ key: "link.content_type",
147
+ label: t("mapo.menuNodeEditor.relContentTypeLabel"),
148
+ type: "fks",
149
+ cols: { md: 6 },
150
+ show: ({ model }) => (model as MenuTreeNode).link?.link_type === "RE",
151
+ onChange: () => loadPages(),
152
+ attrs: {
153
+ endpoint: pageTypesEndpoint.value,
154
+ itemText: "verbose_name_plural",
155
+ itemValue: "id",
156
+ returnObject: false,
157
+ multiple: false,
158
+ },
159
+ },
160
+ {
161
+ key: "link.url_node",
162
+ label: t("mapo.menuNodeEditor.relPageIdLabel"),
163
+ type: "select",
164
+ cols: { md: 6 },
165
+ show: ({ model }) => (model as MenuTreeNode).link?.link_type === "RE",
166
+ attrs: {
167
+ items: availablePages.value.map((p) => ({
168
+ label: p.name,
169
+ value: p.url_node_id,
170
+ })),
171
+ },
172
+ },
173
+ {
174
+ key: "link.static",
175
+ label: t("mapo.menuNodeEditor.staticLabel"),
176
+ type: "text",
177
+ show: ({ model }) => (model as MenuTreeNode).link?.link_type === "ST",
178
+ },
179
+ ]);
180
+
181
+ const fields = computed<AnyFieldDescriptor[]>(() => [
182
+ ...(props.coreFields ?? defaultCoreFields.value),
183
+ ...props.additionalFields,
184
+ ]);
185
+
186
+ // ─── Breadcrumbs ─────────────────────────────────────────────────────────────
187
+
188
+ const breadcrumbs = computed<MenuTreeNode[]>(() => {
189
+ const found = findMenuNode(props.nodes, props.modelValue.id);
190
+ return found ? [...found.parents, found.node] : [props.modelValue];
191
+ });
192
+
193
+ // ─── Errors ──────────────────────────────────────────────────────────────────
194
+ // Node errors arrive nested from the backend ({ title: [...], link: {...} });
195
+ // MapoForm expects a flat dot-notation Record<string, string[]>.
196
+
197
+ const errors = computed<Record<string, string[]>>(() => {
198
+ const flat: Record<string, string[]> = {};
199
+ const walk = (obj: unknown, prefix: string) => {
200
+ if (Array.isArray(obj)) {
201
+ flat[prefix] = obj.map(String);
202
+ } else if (obj && typeof obj === "object") {
203
+ for (const [k, v] of Object.entries(obj)) {
204
+ walk(v, prefix ? `${prefix}.${k}` : k);
205
+ }
206
+ }
207
+ };
208
+ walk(props.modelValue?.errors ?? {}, "");
209
+ return flat;
210
+ });
211
+
212
+ const slotBindings = computed<SlotBindings>(() => ({
213
+ model: props.modelValue,
214
+ fields: fields.value,
215
+ errors: errors.value,
216
+ readonly: props.readonly,
217
+ }));
218
+
219
+ // MapoForm is globally registered by @mapomodule/form.
220
+ const MapoForm = resolveComponent("MapoForm");
221
+ </script>
222
+
223
+ <template>
224
+ <div class="mapo-menu-node-editor flex h-full min-w-0 flex-1 flex-col">
225
+ <!-- Top bar: breadcrumbs + delete -->
226
+ <div
227
+ class="flex items-center justify-between gap-2 border-b border-default px-4 py-2"
228
+ >
229
+ <p class="flex min-w-0 items-center gap-1 truncate text-sm">
230
+ <span class="shrink-0 text-dimmed"
231
+ >{{ t("mapo.menuNodeEditor.editNode") }}:</span
232
+ >
233
+ <template v-for="(node, i) in breadcrumbs" :key="node.id">
234
+ <button
235
+ type="button"
236
+ class="max-w-40 truncate hover:underline"
237
+ :class="
238
+ i === breadcrumbs.length - 1
239
+ ? 'font-medium text-highlighted'
240
+ : 'text-muted'
241
+ "
242
+ @click="emit('update:modelValue', node)"
243
+ >
244
+ {{ node.title || "…" }}
245
+ </button>
246
+ <UIcon
247
+ v-if="i !== breadcrumbs.length - 1"
248
+ name="i-lucide-chevron-right"
249
+ class="size-3 shrink-0 text-dimmed"
250
+ />
251
+ </template>
252
+ </p>
253
+ <UButton
254
+ v-if="!readonly"
255
+ icon="i-lucide-trash-2"
256
+ size="xs"
257
+ color="error"
258
+ variant="soft"
259
+ @click="emit('delete')"
260
+ >
261
+ {{ t("mapo.delete") }}
262
+ </UButton>
263
+ </div>
264
+
265
+ <!-- Form -->
266
+ <div class="flex-1 overflow-y-auto p-4">
267
+ <slot name="form-top" v-bind="slotBindings" />
268
+ <slot name="form" v-bind="slotBindings">
269
+ <component
270
+ :is="MapoForm"
271
+ :model-value="modelValue"
272
+ :fields="fields"
273
+ :errors="errors"
274
+ :readonly="readonly"
275
+ immediate
276
+ @update:model-value="emit('update:modelValue', $event)"
277
+ />
278
+ </slot>
279
+ <slot name="form-bottom" v-bind="slotBindings" />
280
+ </div>
281
+ </div>
282
+ </template>