@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,166 @@
1
+ <script setup lang="ts">
2
+ import { ref, computed, watch, onMounted, nextTick } from "vue";
3
+ import { useRoute, useRouter } from "vue-router";
4
+
5
+ const props = withDefaults(
6
+ defineProps<{
7
+ modelValue: string;
8
+ langs: string[];
9
+ errors?: Record<string, string[]>;
10
+ noRouteChange?: boolean;
11
+ /**
12
+ * Number of languages above which the select also shows a dropdown
13
+ * alongside the tab bar (for quick navigation). Default: `8`.
14
+ */
15
+ langThreshold?: number;
16
+ }>(),
17
+ {
18
+ errors: () => ({}),
19
+ noRouteChange: false,
20
+ langThreshold: 8,
21
+ },
22
+ );
23
+
24
+ const emit = defineEmits<{ (e: "update:modelValue", lang: string): void }>();
25
+
26
+ const route = useRoute();
27
+ const router = useRouter();
28
+
29
+ // ─── Tab refs for scrollIntoView ─────────────────────────────────────────────
30
+
31
+ const tabRefs = ref<Record<string, HTMLElement | null>>({});
32
+
33
+ function setTabRef(lang: string, el: Element | null) {
34
+ tabRefs.value[lang] = el as HTMLElement | null;
35
+ }
36
+
37
+ function scrollActiveIntoView(lang: string) {
38
+ nextTick(() => {
39
+ tabRefs.value[lang]?.scrollIntoView({
40
+ behavior: "smooth",
41
+ block: "nearest",
42
+ inline: "nearest",
43
+ });
44
+ });
45
+ }
46
+
47
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
48
+
49
+ function hasErrors(lang: string): boolean {
50
+ const prefix = `translations.${lang}.`;
51
+ return Object.keys(props.errors || {}).some((k) => k.startsWith(prefix));
52
+ }
53
+
54
+ function selectLang(lang: string) {
55
+ emit("update:modelValue", lang);
56
+ if (!props.noRouteChange && route.query.lang !== lang) {
57
+ router.replace({ query: { ...route.query, lang } });
58
+ }
59
+ scrollActiveIntoView(lang);
60
+ }
61
+
62
+ function onSelectChange(v: unknown) {
63
+ const lang =
64
+ typeof v === "object" && v !== null
65
+ ? (v as { value: string }).value
66
+ : (v as string);
67
+ if (lang) selectLang(lang);
68
+ }
69
+
70
+ // ─── Select menu items ────────────────────────────────────────────────────────
71
+
72
+ const selectItems = computed(() =>
73
+ props.langs.map((lang) => ({
74
+ label: lang.toUpperCase(),
75
+ value: lang,
76
+ trailingIcon: hasErrors(lang) ? "i-lucide-alert-circle" : undefined,
77
+ })),
78
+ );
79
+
80
+ // ─── Lifecycle ────────────────────────────────────────────────────────────────
81
+
82
+ onMounted(() => {
83
+ const queryLang = route.query.lang as string | undefined;
84
+ if (
85
+ queryLang &&
86
+ props.langs.includes(queryLang) &&
87
+ queryLang !== props.modelValue
88
+ ) {
89
+ emit("update:modelValue", queryLang);
90
+ }
91
+ scrollActiveIntoView(props.modelValue);
92
+ });
93
+
94
+ watch(
95
+ () => props.modelValue,
96
+ (val) => {
97
+ if (!props.noRouteChange && route.query.lang !== val) {
98
+ router.replace({ query: { ...route.query, lang: val } });
99
+ }
100
+ scrollActiveIntoView(val);
101
+ },
102
+ );
103
+ </script>
104
+
105
+ <template>
106
+ <div
107
+ class="flex items-end gap-0 border-b border-gray-200 dark:border-gray-700 mt-2 mb-4"
108
+ >
109
+ <!-- Language select — always visible, aligned at bottom of row -->
110
+ <USelectMenu
111
+ :model-value="modelValue"
112
+ :items="selectItems"
113
+ value-key="value"
114
+ label-key="label"
115
+ size="sm"
116
+ class="w-28 shrink-0 mb-px"
117
+ @update:model-value="onSelectChange"
118
+ >
119
+ <template #default="{ open }">
120
+ <UButton
121
+ size="sm"
122
+ variant="ghost"
123
+ color="neutral"
124
+ :trailing-icon="
125
+ open ? 'i-lucide-chevron-up' : 'i-lucide-chevron-down'
126
+ "
127
+ class="w-full justify-between font-medium"
128
+ >
129
+ <span class="flex items-center gap-1">
130
+ <span
131
+ v-if="hasErrors(modelValue)"
132
+ class="inline-block h-2 w-2 rounded-full bg-red-500"
133
+ />
134
+ {{ modelValue.toUpperCase() }}
135
+ </span>
136
+ </UButton>
137
+ </template>
138
+ </USelectMenu>
139
+
140
+ <!-- Divider -->
141
+ <div class="h-5 w-px bg-gray-200 dark:bg-gray-700 mx-2 shrink-0" />
142
+
143
+ <!-- Tab bar — always shown, scrollable -->
144
+ <div class="flex gap-1 overflow-x-auto scrollbar-none flex-1">
145
+ <button
146
+ v-for="lang in langs"
147
+ :key="lang"
148
+ :ref="(el) => setTabRef(lang, el as Element | null)"
149
+ type="button"
150
+ class="relative shrink-0 px-4 py-2 text-sm font-medium transition-colors focus:outline-none"
151
+ :class="[
152
+ lang === modelValue
153
+ ? 'text-primary-600 border-b-2 border-primary-600 -mb-px'
154
+ : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300',
155
+ ]"
156
+ @click="selectLang(lang)"
157
+ >
158
+ {{ lang.toUpperCase() }}
159
+ <span
160
+ v-if="hasErrors(lang)"
161
+ class="absolute top-1 right-1 w-2 h-2 rounded-full bg-red-500"
162
+ />
163
+ </button>
164
+ </div>
165
+ </div>
166
+ </template>
@@ -0,0 +1,339 @@
1
+ <script setup lang="ts" generic="T extends object">
2
+ import { ref, computed, watch, useSlots } from "vue";
3
+ import type { Ref } from "vue";
4
+ import type {
5
+ ListColumn,
6
+ FilterDescriptor,
7
+ FilterChoice,
8
+ ActiveFilter,
9
+ ActionDescriptor,
10
+ ListTabItem,
11
+ } from "../types/list.js";
12
+ import type { AnyFieldDescriptor, FieldRegistry } from "@mapomodule/form/types";
13
+ import { debounce } from "@mapomodule/utils";
14
+ import { useRoute, useRouter } from "vue-router";
15
+
16
+ const props = withDefaults(
17
+ defineProps<{
18
+ endpoint?: string;
19
+ /**
20
+ * Offline mode: pass a local array to drive the list entirely in memory.
21
+ * Search, filters, sort, pagination, drag-reorder and delete all happen
22
+ * client-side. Mutations emit `update:items` so the parent owns the array.
23
+ * When set, `endpoint` is ignored.
24
+ */
25
+ items?: T[];
26
+ /**
27
+ * Hybrid mode: with `endpoint` set and `clientSide: true`, the list fetches
28
+ * the full dataset ONCE and runs search/filter/sort/pagination locally.
29
+ * Mutations (delete, drag, quick-edit) still hit the backend, then refetch.
30
+ * Ignored when `items` is provided.
31
+ */
32
+ clientSide?: boolean;
33
+ columns: ListColumn<T>[];
34
+ lookup?: string;
35
+ // Filters
36
+ filters?: FilterDescriptor[];
37
+ // Actions
38
+ actions?: ActionDescriptor<T>[];
39
+ // Tabs
40
+ tabs?: ListTabItem[];
41
+ defaultTab?: string;
42
+ tabQueryParam?: string;
43
+ // Table features
44
+ searchable?: boolean;
45
+ draggable?: boolean;
46
+ positionField?: string;
47
+ // Quick edit
48
+ editFields?: AnyFieldDescriptor<T>[];
49
+ languages?: string[];
50
+ registry?: FieldRegistry;
51
+ /** Base path for the detail page link on each row. E.g. "/news" → links to "/news/42". */
52
+ detailBase?: string;
53
+ /**
54
+ * Django model label used to gate row-level edit and delete buttons via permissions.
55
+ * E.g. `"article"` hides the pencil unless the user has `change_article`, and
56
+ * hides the trash unless the user has `delete_article`. Omit to always show both.
57
+ */
58
+ permissionModel?: string;
59
+ // Pagination
60
+ /** Initial page size. Default: 20. */
61
+ defaultPageSize?: number;
62
+ /** Page size options shown in the per-page selector. Default: [10, 20, 50, 100]. */
63
+ pageSizeOptions?: number[];
64
+ /**
65
+ * Custom response parser. Replaces the built-in DRF / flat-array detection.
66
+ * Return `{ items, total }` from any shape your backend returns.
67
+ * @example (raw) => ({ items: raw.data, total: raw.meta.total })
68
+ */
69
+ responseAdapter?: (raw: unknown) => { items: T[]; total: number };
70
+ /**
71
+ * Custom pagination query params factory. Replaces default `{ page, page_size }`.
72
+ * @example ({ page, pageSize }) => ({ offset: (page - 1) * pageSize, limit: pageSize })
73
+ */
74
+ paginationParams?: (state: {
75
+ page: number;
76
+ pageSize: number;
77
+ }) => Record<string, unknown>;
78
+ }>(),
79
+ {
80
+ endpoint: "",
81
+ items: undefined,
82
+ clientSide: false,
83
+ lookup: "id",
84
+ filters: () => [],
85
+ actions: () => [],
86
+ tabs: () => [],
87
+ tabQueryParam: "tab",
88
+ searchable: true,
89
+ draggable: false,
90
+ positionField: "position",
91
+ editFields: () => [],
92
+ defaultPageSize: 20,
93
+ pageSizeOptions: () => [10, 20, 50, 100],
94
+ },
95
+ );
96
+
97
+ const emit = defineEmits<{
98
+ "update:items": [value: T[]];
99
+ }>();
100
+
101
+ // --- URL state (read once on mount, then write on change) ---
102
+ const route = useRoute();
103
+ const router = useRouter();
104
+
105
+ // --- Selection state ---
106
+ const selection = ref<T[] | "all">([]) as Ref<T[] | "all">;
107
+ const selectionQuery = ref(new URLSearchParams());
108
+
109
+ // --- Tabs state (restored from URL) ---
110
+ function restoreTabFromUrl(): string {
111
+ const urlTab = route.query[props.tabQueryParam] as string | undefined;
112
+ if (urlTab && props.tabs.some((t) => t.value === urlTab)) return urlTab;
113
+ return props.defaultTab ?? props.tabs[0]?.value ?? "";
114
+ }
115
+ const activeTab = ref(restoreTabFromUrl());
116
+
117
+ // --- Filters state (restored from URL) ---
118
+ function restoreFiltersFromUrl(): ActiveFilter[] {
119
+ const result: ActiveFilter[] = [];
120
+ for (const fd of props.filters) {
121
+ const urlVal = route.query[`f_${fd.value}`];
122
+ if (!urlVal) continue;
123
+ const rawValue = String(urlVal);
124
+ let active: FilterChoice[];
125
+ if (fd.datepicker) {
126
+ const parts = rawValue.split(",");
127
+ if (parts.length === 2) {
128
+ active = [
129
+ {
130
+ text: parts
131
+ .map((d) => new Date(d).toLocaleDateString())
132
+ .join(" → "),
133
+ value: rawValue,
134
+ },
135
+ ];
136
+ } else continue;
137
+ } else {
138
+ const rawValues = rawValue.split(",");
139
+ active = rawValues
140
+ .map((rv) => fd.choices?.find((c) => String(c.value) === rv))
141
+ .filter(Boolean) as FilterChoice[];
142
+ }
143
+ if (active.length) result.push({ ...fd, active });
144
+ }
145
+ return result;
146
+ }
147
+ const activeFilters = ref<ActiveFilter[]>(restoreFiltersFromUrl());
148
+
149
+ // Write current tab + filter state back to URL (debounced to avoid history spam).
150
+ const writeUrlState = debounce(() => {
151
+ const query: Record<string, string | undefined> = {
152
+ ...(route.query as Record<string, string>),
153
+ };
154
+ // Tab
155
+ if (props.tabs.length) {
156
+ if (activeTab.value) query[props.tabQueryParam] = activeTab.value;
157
+ else delete query[props.tabQueryParam];
158
+ }
159
+ // Remove stale f_ params, then re-write current ones
160
+ for (const k of Object.keys(query)) {
161
+ if (k.startsWith("f_")) delete query[k];
162
+ }
163
+ for (const f of activeFilters.value) {
164
+ if (!f.active.length) continue;
165
+ query[`f_${f.value}`] = f.active.map((c) => String(c.value)).join(",");
166
+ }
167
+ router.replace({ query });
168
+ }, 150);
169
+
170
+ watch([activeTab, activeFilters], writeUrlState, { deep: true });
171
+
172
+ // --- crudEndpoint: base path for mutations (no query string). ---
173
+ const crudEndpoint = computed(
174
+ () => (props.endpoint ?? "").split("?")[0] || (props.endpoint ?? ""),
175
+ );
176
+
177
+ // --- filterParams: active tab + active filters → backend query params. ---
178
+ // v1 contract: each filter is sent as `filter.value=v1,v2,...` (bare key, comma-joined
179
+ // values). Datepicker ranges are a single `key=start,end` value (no __gte/__lte split).
180
+ // This keeps the backend contract identical to Mapo v1; the `f_` prefix is used only for
181
+ // URL persistence (see writeUrlState), never towards the backend.
182
+ const filterParams = computed<Record<string, unknown>>(() => {
183
+ const params: Record<string, unknown> = {};
184
+ if (props.tabs.length && activeTab.value) {
185
+ params[props.tabQueryParam] = activeTab.value;
186
+ }
187
+ for (const f of activeFilters.value) {
188
+ if (!f.active.length) continue;
189
+ params[f.value] = f.active.map((c) => String(c.value)).join(",");
190
+ }
191
+ return params;
192
+ });
193
+
194
+ // --- Table ref for refresh ---
195
+ const tableRef = ref<{ refresh: () => void } | null>(null);
196
+
197
+ function refresh() {
198
+ tableRef.value?.refresh();
199
+ }
200
+
201
+ defineExpose({ refresh });
202
+
203
+ defineSlots<
204
+ {
205
+ /** Content rendered inside the list head area (title, breadcrumbs, action buttons). */
206
+ head(): unknown;
207
+ /** Extra content rendered alongside the search input in the table toolbar. */
208
+ "dtable.toolbar"(): unknown;
209
+ /** Override for the empty state displayed when no rows are found. */
210
+ "dtable.empty"(): unknown;
211
+ /** Override for the loading skeleton displayed while data is being fetched. */
212
+ "dtable.loading"(): unknown;
213
+ /**
214
+ * Per-filter custom panel content. Slot name: `filter.{filter.value}`
215
+ * (plus `.title` / `.content` / `.icon` sub-slots).
216
+ * Bindings mirror MapoListFilters: `filter` is always provided, the rest
217
+ * varies per sub-slot.
218
+ */
219
+ [K: `filter.${string}`]: (props: {
220
+ filter: FilterDescriptor & { dates?: string[] };
221
+ choice?: FilterChoice;
222
+ toggleChoice?: (filter: FilterDescriptor, choice: FilterChoice) => void;
223
+ removeFilter?: (filter: FilterDescriptor) => void;
224
+ isChoiceActive?: (
225
+ filter: FilterDescriptor,
226
+ choice: FilterChoice,
227
+ ) => boolean;
228
+ }) => unknown;
229
+ /**
230
+ * Extra content rendered below the quick-edit form.
231
+ * Receives `{ model: T }` — the current reactive form model.
232
+ */
233
+ "qedit.extra": (props: { model: T }) => unknown;
234
+ } & {
235
+ /**
236
+ * Per-column cell override. Slot name: `cell.{column.key}`.
237
+ */
238
+ [K in keyof T as `cell.${K & string}`]: (props: {
239
+ item: T;
240
+ value: T[K];
241
+ }) => unknown;
242
+ }
243
+ >();
244
+
245
+ // Loosely-typed slot names for the dynamic forwarding templates below.
246
+ // A `[K: string]` catch-all in defineSlots would make `$slots[name]` indexable,
247
+ // but it degrades the typed `cell.*` slot props to `any` for consumers —
248
+ // so the forwarding iterates over this untyped name list instead.
249
+ const slots = useSlots();
250
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
251
+ const forwardedSlotNames = computed(() => Object.keys(slots) as any[]);
252
+
253
+ // Reset selection when the active tab or filters change
254
+ watch([activeTab, activeFilters], () => {
255
+ selection.value = [];
256
+ });
257
+ </script>
258
+
259
+ <template>
260
+ <div class="mapo-list space-y-4">
261
+ <!-- Head slot -->
262
+ <MapoListHead>
263
+ <template #head>
264
+ <slot name="head" />
265
+ </template>
266
+ </MapoListHead>
267
+
268
+ <!-- Tabs -->
269
+ <MapoListTabs
270
+ v-if="tabs.length"
271
+ :tabs="tabs"
272
+ :model-value="activeTab"
273
+ @update:model-value="activeTab = $event"
274
+ />
275
+
276
+ <!-- Toolbar: filters + actions -->
277
+ <div class="flex flex-wrap items-center gap-2">
278
+ <MapoListFilters
279
+ :filters="filters"
280
+ :model-value="activeFilters"
281
+ @update:model-value="activeFilters = $event"
282
+ >
283
+ <template
284
+ v-for="name in forwardedSlotNames"
285
+ :key="name"
286
+ #[name]="slotProps"
287
+ >
288
+ <slot :name="name" v-bind="slotProps ?? {}" />
289
+ </template>
290
+ </MapoListFilters>
291
+
292
+ <div class="ml-auto">
293
+ <MapoListActions
294
+ :actions="actions"
295
+ :selection="selection"
296
+ :selection-query="selectionQuery"
297
+ :endpoint="crudEndpoint"
298
+ :lookup="lookup"
299
+ @action-completed="refresh"
300
+ />
301
+ </div>
302
+ </div>
303
+
304
+ <!-- Table -->
305
+ <MapoListTable
306
+ ref="tableRef"
307
+ :endpoint="endpoint"
308
+ :items="items"
309
+ :client-side="clientSide"
310
+ :crud-endpoint="crudEndpoint"
311
+ :filter-params="filterParams"
312
+ :columns="columns"
313
+ :lookup="lookup"
314
+ :searchable="searchable"
315
+ :draggable="draggable"
316
+ :position-field="positionField"
317
+ :edit-fields="editFields"
318
+ :languages="languages"
319
+ :registry="registry"
320
+ :detail-base="detailBase"
321
+ :default-page-size="defaultPageSize"
322
+ :page-size-options="pageSizeOptions"
323
+ :response-adapter="responseAdapter"
324
+ :pagination-params="paginationParams"
325
+ :permission-model="permissionModel"
326
+ @update:selection="selection = $event"
327
+ @update:selection-query="selectionQuery = $event"
328
+ @update:items="emit('update:items', $event)"
329
+ >
330
+ <template
331
+ v-for="name in forwardedSlotNames"
332
+ :key="name"
333
+ #[name]="slotProps"
334
+ >
335
+ <slot :name="name" v-bind="slotProps ?? {}" />
336
+ </template>
337
+ </MapoListTable>
338
+ </div>
339
+ </template>
@@ -0,0 +1,152 @@
1
+ <script setup lang="ts" generic="T extends object">
2
+ import { ref, computed } from "vue";
3
+ import type { ActionDescriptor } from "../types/list.js";
4
+ import { useSnackStore } from "@mapomodule/store/runtime/stores/snack";
5
+ import { useConfirmStore } from "@mapomodule/store/runtime/stores/confirm";
6
+ import { usePermissions } from "@mapomodule/store/runtime/composables/usePermissions";
7
+ import { useCrud } from "@mapomodule/core/runtime/api/crud";
8
+
9
+ const props = withDefaults(
10
+ defineProps<{
11
+ actions?: ActionDescriptor<T>[];
12
+ selection: T[] | "all";
13
+ selectionQuery: URLSearchParams;
14
+ endpoint: string;
15
+ lookup?: string;
16
+ }>(),
17
+ {
18
+ actions: () => [],
19
+ lookup: "id",
20
+ },
21
+ );
22
+
23
+ const emit = defineEmits<{ actionCompleted: [] }>();
24
+
25
+ defineSlots<{
26
+ /** Extra content rendered before the action selector (e.g. custom bulk controls). */
27
+ prepend(): any;
28
+ /** Extra content rendered after the Apply button. */
29
+ append(): any;
30
+ }>();
31
+
32
+ const snack = useSnackStore();
33
+ const confirm = useConfirmStore();
34
+ const crud = useCrud<T>(props.endpoint);
35
+
36
+ const isRunning = ref(false);
37
+
38
+ const defaultActions = computed<ActionDescriptor<T>[]>(() => [
39
+ {
40
+ label: "Delete permanently",
41
+ handler: async ({ selection }) => {
42
+ if (!selection) return;
43
+ await Promise.all(
44
+ selection.map((i) =>
45
+ crud.delete(
46
+ (i as Record<string, unknown>)[props.lookup] as string | number,
47
+ ),
48
+ ),
49
+ );
50
+ },
51
+ permissions: "delete",
52
+ handleMultiple: true,
53
+ handleAll: false,
54
+ },
55
+ ]);
56
+
57
+ const allActions = computed(() => [...defaultActions.value, ...props.actions]);
58
+
59
+ const visibleActions = computed(() =>
60
+ allActions.value.filter((a) =>
61
+ props.selection === "all"
62
+ ? (a.handleAll ?? false)
63
+ : (a.handleMultiple ?? true),
64
+ ),
65
+ );
66
+
67
+ // USelect can only model primitive values, so track the selected action by
68
+ // label and resolve the descriptor from the visible list.
69
+ const selectedLabel = ref<string | undefined>(undefined);
70
+ const selectedAction = computed<ActionDescriptor<T> | null>(
71
+ () =>
72
+ visibleActions.value.find((a) => a.label === selectedLabel.value) ?? null,
73
+ );
74
+
75
+ const applyButtonColor = computed(() =>
76
+ selectedAction.value?.dangerous ? "error" : "primary",
77
+ );
78
+
79
+ function canRun(action: ActionDescriptor<T>): boolean {
80
+ const perms = action.permissions
81
+ ? Array.isArray(action.permissions)
82
+ ? action.permissions
83
+ : [action.permissions]
84
+ : [];
85
+ if (!perms.length) return true;
86
+ const { checkPermission } = usePermissions();
87
+ return perms.every((p) => checkPermission(p));
88
+ }
89
+
90
+ async function runAction() {
91
+ if (!selectedAction.value) return;
92
+ const action = selectedAction.value;
93
+
94
+ const ok = await confirm.ask({
95
+ title: action.label,
96
+ message:
97
+ props.selection === "all"
98
+ ? "This action will be applied to all items. Do you want to continue?"
99
+ : `This action will be applied to ${(props.selection as T[]).length} item(s). Do you want to continue?`,
100
+ confirmText: "Confirm",
101
+ dangerous: !!action.dangerous,
102
+ });
103
+ if (!ok) return;
104
+
105
+ isRunning.value = true;
106
+ try {
107
+ await action.handler({
108
+ selection: props.selection === "all" ? null : (props.selection as T[]),
109
+ selectionQuery: props.selectionQuery,
110
+ lookup: props.lookup,
111
+ });
112
+ snack.show("Action completed", "success");
113
+ emit("actionCompleted");
114
+ selectedLabel.value = undefined;
115
+ } catch (err: unknown) {
116
+ const detail = (err as { response?: { data?: { detail?: string } } })
117
+ ?.response?.data?.detail;
118
+ snack.show(detail ?? "Action failed", "error");
119
+ } finally {
120
+ isRunning.value = false;
121
+ }
122
+ }
123
+
124
+ const isActive = computed(
125
+ () => props.selection === "all" || (props.selection as T[]).length > 0,
126
+ );
127
+ </script>
128
+
129
+ <template>
130
+ <div v-if="isActive" class="mapo-list-actions flex items-center gap-2">
131
+ <slot name="prepend" />
132
+ <USelect
133
+ v-model="selectedLabel"
134
+ :items="visibleActions"
135
+ value-key="label"
136
+ label-key="label"
137
+ placeholder="Bulk actions..."
138
+ size="sm"
139
+ class="min-w-48"
140
+ />
141
+ <UButton
142
+ size="sm"
143
+ :color="applyButtonColor"
144
+ :loading="isRunning"
145
+ :disabled="!selectedAction || !canRun(selectedAction)"
146
+ @click="runAction"
147
+ >
148
+ Apply
149
+ </UButton>
150
+ <slot name="append" />
151
+ </div>
152
+ </template>