/
list-o2m-tree-view.vue
336 lines (277 loc) · 7.82 KB
/
list-o2m-tree-view.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
<template>
<v-notice v-if="relation.collection !== relation.related_collection" type="warning">
{{ t('interfaces.list-o2m-tree-view.recursive_only') }}
</v-notice>
<div v-else class="tree-view">
<nested-draggable
:template="template"
:collection="collection"
:tree="stagedValues || []"
:primary-key-field="primaryKeyField.field"
:children-field="relation.meta.one_field"
:parent-field="relation.field"
:disabled="disabled"
root
@change="onDraggableChange"
@input="emitValue"
/>
<div v-if="!disabled" class="actions">
<v-button v-if="enableCreate" @click="addNewActive = true">{{ t('create_new') }}</v-button>
<v-button v-if="enableSelect" @click="selectDrawer = true">
{{ t('add_existing') }}
</v-button>
</div>
<drawer-item
v-if="!disabled"
:active="addNewActive"
:collection="collection"
:primary-key="'+'"
:edits="{}"
:circular-field="relation.field"
@input="addNew"
@update:active="addNewActive = false"
/>
<drawer-collection
v-if="!disabled"
v-model:active="selectDrawer"
:collection="collection"
:selection="[]"
multiple
@input="stageSelection"
/>
</div>
</template>
<script lang="ts">
import { useI18n } from 'vue-i18n';
import { defineComponent, ref, computed, PropType, onMounted, watch } from 'vue';
import { useCollection } from '@directus/shared/composables';
import { useRelationsStore } from '@/stores';
import api from '@/api';
import { getFieldsFromTemplate } from '@directus/shared/utils';
import hideDragImage from '@/utils/hide-drag-image';
import NestedDraggable from './nested-draggable.vue';
import { Relation } from '@directus/shared/types';
import DrawerCollection from '@/views/private/components/drawer-collection';
import DrawerItem from '@/views/private/components/drawer-item';
export default defineComponent({
components: { NestedDraggable, DrawerCollection, DrawerItem },
props: {
value: {
type: Array as PropType<(number | string | Record<string, any>)[]>,
default: null,
},
displayTemplate: {
type: String,
default: undefined,
},
disabled: {
type: Boolean,
default: false,
},
collection: {
type: String,
required: true,
},
field: {
type: String,
required: true,
},
primaryKey: {
type: [String, Number],
default: undefined,
},
enableCreate: {
type: Boolean,
default: true,
},
enableSelect: {
type: Boolean,
default: true,
},
},
emits: ['input'],
setup(props, { emit }) {
const { t } = useI18n();
const relationsStore = useRelationsStore();
const openItems = ref([]);
const { relation } = useRelation();
const { info, primaryKeyField } = useCollection(relation.value.related_collection!);
const { loading, error, stagedValues, fetchValues, emitValue } = useValues();
const { stageSelection, selectDrawer } = useSelection();
const { addNewActive, addNew } = useAddNew();
const template = computed(() => {
return props.displayTemplate || info.value?.meta?.display_template || `{{${primaryKeyField.value?.field}}}`;
});
onMounted(fetchValues);
watch(() => props.primaryKey, fetchValues, { immediate: true });
const dragging = ref(false);
return {
t,
relation,
openItems,
template,
loading,
error,
stagedValues,
fetchValues,
primaryKeyField,
onDraggableChange,
hideDragImage,
dragging,
emitValue,
stageSelection,
selectDrawer,
addNewActive,
addNew,
};
function useValues() {
const loading = ref(false);
const error = ref<any>(null);
const stagedValues = ref<Record<string, any>[]>([]);
return { loading, error, stagedValues, fetchValues, emitValue, getFieldsToFetch };
async function fetchValues() {
if (!props.primaryKey || !relation.value || props.primaryKey === '+') return;
// In case props.value is already an array of edited objects
if (props.value?.length > 0 && props.value.every((item) => typeof item === 'object')) {
stagedValues.value = props.value as Record<string, any>[];
return;
}
loading.value = true;
try {
const response = await api.get(`/items/${props.collection}/${encodeURIComponent(props.primaryKey)}`, {
params: {
fields: getFieldsToFetch(),
},
});
stagedValues.value = response.data.data?.[relation.value.meta!.one_field!] ?? [];
} catch (err: any) {
error.value = err;
} finally {
loading.value = false;
}
}
function getFieldsToFetch() {
const fields = [
...new Set([
primaryKeyField.value?.field,
relation.value.meta!.one_field,
...getFieldsFromTemplate(template.value),
]),
];
const result: string[] = [];
const prefix = `${relation.value.meta!.one_field}.`;
for (let i = 1; i <= 5; i++) {
for (const field of fields) {
result.push(`${prefix.repeat(i)}${field}`);
}
}
return result;
}
function emitValue(value: Record<string, any>[]) {
stagedValues.value = value;
if (relation.value.meta?.sort_field) {
return emit('input', addSort(value));
}
emit('input', value);
function addSort(value: Record<string, any>[]): Record<string, any>[] {
return (value || []).map((item, index) => {
return {
...item,
[relation.value.meta!.sort_field!]: index + 1,
[relation.value.meta!.one_field!]: addSort(item[relation.value.meta!.one_field!]),
};
});
}
}
}
function useRelation() {
const relation = computed<Relation>(() => {
return relationsStore.getRelationsForField(props.collection, props.field)?.[0];
});
return { relation };
}
function onDraggableChange() {
emitValue(stagedValues.value);
}
function useSelection() {
const selectDrawer = ref(false);
const selectedPrimaryKeys = computed<(number | string)[]>(() => {
const pkField = primaryKeyField.value?.field;
if (stagedValues.value === null || !pkField || !props.primaryKey) return [];
return [props.primaryKey, ...getPKs(stagedValues.value)];
function getPKs(values: Record<string, any>[]): (string | number)[] {
const pks = [];
if (pkField)
for (const value of values) {
if (!value[pkField]) continue;
pks.push(value[pkField]);
const childPKs = getPKs(value[relation.value.meta!.one_field!]);
pks.push(...childPKs);
}
return pks;
}
});
return { stageSelection, selectDrawer };
async function stageSelection(newSelection: (number | string)[]) {
loading.value = true;
const selection = newSelection.filter((item) => selectedPrimaryKeys.value.includes(item) === false);
const fields = [
...new Set([
primaryKeyField.value?.field,
relation.value.meta!.one_field,
...getFieldsFromTemplate(template.value),
]),
];
const result: string[] = [];
const prefix = `${relation.value.meta!.one_field}.`;
for (let i = 1; i <= 5; i++) {
for (const field of fields) {
result.push(`${prefix.repeat(i)}${field}`);
}
}
if (!primaryKeyField.value?.field) return;
const response = await api.get(`/items/${props.collection}`, {
params: {
fields: [...fields, ...result],
filter: {
[primaryKeyField.value?.field]: {
_in: selection,
},
},
},
});
const newVal = [...response.data.data, ...stagedValues.value];
if (newVal.length === 0) emitValue([]);
else emitValue(newVal);
loading.value = false;
}
}
function useAddNew() {
const addNewActive = ref(false);
return { addNewActive, addNew };
function addNew(item: Record<string, any>) {
emitValue([...stagedValues.value, item]);
}
}
},
});
</script>
<style scoped>
:deep(ul),
:deep(li) {
list-style: none;
}
:deep(ul) {
margin-left: 24px;
padding-left: 0;
}
.actions {
margin-top: 12px;
}
.actions .v-button + .v-button {
margin-left: 12px;
}
.existing {
margin-left: 12px;
}
</style>