-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathindex.vue
496 lines (480 loc) · 14.9 KB
/
index.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
<template>
<div>
<DataTable
v-if="!loading"
ref="dataTable"
v-loading="loading"
:config="iConfig"
v-bind="$attrs"
v-on="$listeners"
@filter-change="filterChange"
/>
<ColumnSettingPopover
:current-columns="popoverColumns.currentCols"
:default-columns="popoverColumns.defaultCols"
:min-columns="popoverColumns.minCols"
:total-columns-list="popoverColumns.totalColumnsList"
:url="config.url"
@columnsUpdate="handlePopoverColumnsChange"
/>
</div>
</template>
<script type="text/jsx">
import DataTable from '@/components/Table/DataTable/index.vue'
import {
ActionsFormatter, ArrayFormatter, ChoicesFormatter, DateFormatter, DetailFormatter, DisplayFormatter,
ObjectRelatedFormatter
} from '@/components/Table/TableFormatters'
import i18n from '@/i18n/i18n'
import { newURL, replaceAllUUID, toSentenceCase } from '@/utils/common'
import ColumnSettingPopover from './components/ColumnSettingPopover.vue'
import LabelsFormatter from '@/components/Table/TableFormatters/LabelsFormatter.vue'
export default {
name: 'AutoDataTable',
components: {
DataTable,
ColumnSettingPopover
},
props: {
config: {
type: Object,
default: () => ({})
},
filterTable: {
type: Function,
default: () => ({})
}
},
data() {
return {
loading: true,
method: 'get',
autoConfig: {},
iConfig: {},
meta: {},
cleanedColumnsShow: {},
totalColumns: [],
popoverColumns: {
totalColumnsList: [],
minCols: [],
currentCols: [],
defaultCols: []
},
isDeactivated: false
}
},
computed: {},
watch: {
config: {
handler: _.debounce(function(iNew, iOld) {
if (this.isDeactivated) {
return
}
try {
if (JSON.stringify(iNew) === JSON.stringify(iOld)) {
return
}
} catch (error) {
this.$log.error('JsonStringify Error: ', error)
}
this.optionUrlMetaAndGenCols()
this.$log.debug('AutoDataTable Config change found, ', this.isDeactivated)
}, 200)
}
},
created() {
this.optionUrlMetaAndGenCols()
},
deactivated() {
this.isDeactivated = true
},
activated() {
this.isDeactivated = false
},
methods: {
async optionUrlMetaAndGenCols() {
if (this.config.url === '') {
return
}
const url = (this.config.url.indexOf('?') === -1)
? `${this.config.url}?draw=1&display=1`
: `${this.config.url}&draw=1&display=1`
this.$store.dispatch('common/getUrlMeta', { url: url }).then(data => {
const method = this.method.toUpperCase()
this.meta = data.actions && data.actions[method] ? data.actions[method] : {}
this.generateTotalColumns()
}).then(() => {
// 根据当前列重新生成最终渲染表格
this.filterShowColumns()
}).then(() => {
// 生成给子组件使用的TotalColList
this.generatePopoverColumns()
}).catch((error) => {
this.$log.error('Error occur: ', error)
}).finally(() => {
this.loading = false
})
},
generateColumnByName(name, col) {
switch (name) {
case 'name':
col.formatter = DetailFormatter
col.sortable = 'custom'
col.showOverflowTooltip = true
col.minWidth = '150px'
break
case 'actions':
col = {
prop: 'actions',
label: i18n.t('Actions'),
align: 'center',
width: '100px',
formatter: ActionsFormatter,
fixed: 'right',
formatterArgs: {}
}
break
case 'is_valid':
col.label = i18n.t('Valid')
col.formatter = ChoicesFormatter
col.formatterArgs = {
textChoices: {
true: i18n.t('Yes'),
false: i18n.t('No')
}
}
col.width = '80px'
break
case 'is_active':
col.formatter = ChoicesFormatter
col.formatterArgs = {
textChoices: {
true: i18n.t('Active'),
false: i18n.t('Inactive')
}
}
col.width = '100px'
break
case 'datetime':
case 'date_start':
col.formatter = DateFormatter
break
case 'labels':
col.formatter = LabelsFormatter
col.width = '200px'
break
case 'comment':
col.showOverflowTooltip = true
}
return col
},
generateColumnByType(type, col, meta) {
switch (type) {
case 'choice':
col.sortable = 'custom'
col.formatter = DisplayFormatter
break
case 'labeled_choice':
col.sortable = 'custom'
col.formatter = ChoicesFormatter
break
case 'boolean':
col.formatter = ChoicesFormatter
// col.width = '80px'
break
case 'datetime':
col.formatter = DateFormatter
col.width = '175px'
break
case 'object_related_field':
col.formatter = ObjectRelatedFormatter
break
case 'm2m_related_field':
col.formatter = ObjectRelatedFormatter
break
case 'list':
col.formatter = ArrayFormatter
break
case 'json':
case 'field':
if (meta.child && meta.child.type === 'nested object') {
col.formatter = ObjectRelatedFormatter
}
break
}
// this.$log.debug('Field: ', type, col.prop, col)
return col
},
addHelpTipIfNeed(col) {
const helpTip = col.helpTip
if (!helpTip) {
return col
}
col.renderHeader = (h, { column, $index }) => {
const binds = {
props: {
placement: 'bottom',
effect: 'dark',
openDelay: 500,
popperClass: 'help-tips'
}
}
return (
<span>{column.label}
<el-tooltip {...binds}>
<div slot='content' v-sanitize={helpTip}/>
<i class='fa fa-question-circle-o help-tip-icon' style='padding-left: 2px'/>
</el-tooltip>
</span>
)
}
return col
},
addFilterIfNeed(col) {
if (col.prop) {
const column = this.meta[col.prop] || {}
if (!column.filter) {
return col
}
if (column.type === 'boolean') {
col.filters = [
{ text: i18n.t('Yes'), value: true },
{ text: i18n.t('No'), value: false }
]
col.sortable = false
col['column-key'] = col.prop
}
if (column.type === 'choice' && column.choices) {
col.filters = column.choices.map(item => {
if (typeof (item.value) === 'boolean') {
if (item.value) {
return { text: item['label'], value: 'True' }
} else {
return { text: item['label'], value: 'False' }
}
}
return { text: item['label'], value: item.value }
})
col.sortable = false
col['column-key'] = col.prop
}
}
return col
},
addOrderingIfNeed(col) {
if (col.prop) {
const column = this.meta[col.prop] || {}
if (column.order) {
col.sortable = 'custom'
col['column-key'] = col.prop
}
}
return col
},
setDefaultFormatterIfNeed(col) {
if (!col.formatter) {
col.formatter = (row, column, cellValue) => {
let value = cellValue
let padding = '0'
const excludes = [undefined, null, '']
if (excludes.indexOf(value) !== -1) {
padding = '6px'
value = '-'
}
return <span style={{ marginLeft: padding }}>{value}</span>
}
}
return col
},
setDefaultWidthIfNeed(col) {
const lang = this.$i18n.locale
let factor = 10
if (lang === 'zh') {
factor = 20
}
let [sortable, filters] = [0, 0]
if (col && col?.sortable === 'custom') {
sortable = 10
}
if (col && col?.filters?.length > 0) {
filters = 12
}
if (col && !col.width && col.label && !col.minWidth) {
col.minWidth = `${col.label.length * factor + sortable + filters + 30}px`
}
return col
},
generateColumn(name) {
const colMeta = this.meta[name] || {}
const customMeta = this.config.columnsMeta ? this.config.columnsMeta[name] : {}
let col = { prop: name, label: colMeta.label, showOverflowTooltip: true }
col = this.generateColumnByType(colMeta.type, col, colMeta)
col = this.generateColumnByName(name, col)
col = this.setDefaultFormatterIfNeed(col)
col = Object.assign(col, customMeta)
col = this.addHelpTipIfNeed(col)
col = this.addFilterIfNeed(col)
col = this.addOrderingIfNeed(col)
col = this.updateLabelIfNeed(col)
col = this.setDefaultWidthIfNeed(col)
return col
},
updateLabelIfNeed(col) {
if (!col.label) {
return col
}
col.label = col.label
.replace(' Amount', '')
.replace(' amount', '')
.replace('数量', '')
if (col.label.startsWith('Is ')) {
col.label = col.label.replace('Is ', '')
}
col.label = toSentenceCase(col.label)
return col
},
generateTotalColumns() {
const config = _.cloneDeep(this.config)
let columns = []
const allColumnNames = Object.entries(this.meta)
.filter(([name, meta]) => !meta['write_only'])
.map(([name, meta]) => name)
.concat(config.columnsExtra || [])
let configColumns = config.columns || allColumnNames
const columnsExclude = config.columnsExclude || []
const columnsAdd = config.columnsAdd || []
configColumns = configColumns.concat(columnsAdd)
configColumns = configColumns.filter(item => !columnsExclude.includes(item))
// 解决后端 API 返回字段中包含 actions 的问题;
const hasColumnActions = configColumns.findIndex(item => item?.prop === 'actions') !== -1
if (!hasColumnActions) {
configColumns = [...configColumns.filter(i => i !== 'actions'), 'actions']
}
for (let col of configColumns) {
if (typeof col === 'object') {
columns.push(col)
} else if (typeof col === 'string') {
col = this.generateColumn(col)
columns.push(col)
}
}
columns = columns.filter(item => {
if (item?.showFullContent) {
item.className = 'show-full-content'
}
let has = item.has
if (has === undefined) {
has = true
} else if (typeof has === 'function') {
has = has()
}
return has
})
columns = this.orderingColumns(columns)
// 第一次初始化时记录 totalColumns
this.totalColumns = columns
config.columns = columns
this.iConfig = config
},
orderingColumns(columns) {
const cols = _.cloneDeep(this.config.columns)
const defaults = _.get(this.config, 'columnsShow.default')
const ordering = (cols || defaults || []).map(item => {
let prop = item
if (typeof item === 'object') {
prop = item.prop
}
return prop
})
return _.sortBy(columns, (item) => {
if (item.prop === 'actions') {
return 1000
}
const i = ordering.indexOf(item.prop)
return i === -1 ? 999 : i
})
},
// 生成给子组件使用的TotalColList
cleanColumnsShow() {
const totalColumnsNames = this.totalColumns.map(obj => obj.prop)
// 默认列
let defaultColumnsNames = _.get(this.iConfig, 'columnsShow.default', [])
if (defaultColumnsNames.length === 0) {
defaultColumnsNames = totalColumnsNames
}
// Clean it
defaultColumnsNames = totalColumnsNames.filter(n => defaultColumnsNames.indexOf(n) > -1)
// 最小列
const minColumnsNames = _.get(this.iConfig, 'columnsShow.min', ['actions', 'id'])
.filter(n => totalColumnsNames.includes(n))
// 应该显示的列
const _tableConfig = localStorage.getItem('tableConfig')
? JSON.parse(localStorage.getItem('tableConfig'))
: {}
let tableName = this.config.name || this.$route.name + '_' + newURL(this.config.url).pathname
tableName = replaceAllUUID(tableName)
const configShowColumnsNames = _.get(_tableConfig[tableName], 'showColumns', null)
let showColumnsNames = configShowColumnsNames || defaultColumnsNames
if (showColumnsNames.length === 0) {
showColumnsNames = totalColumnsNames
}
// 校对显示的列,是不是包含最小列
minColumnsNames.forEach((v, i) => {
if (showColumnsNames.indexOf(v) === -1) {
showColumnsNames.push(v)
}
})
// Clean it
showColumnsNames = totalColumnsNames.filter(n => showColumnsNames.indexOf(n) > -1)
this.cleanedColumnsShow = {
default: defaultColumnsNames,
show: showColumnsNames,
min: minColumnsNames,
configShow: configShowColumnsNames
}
this.$log.debug('Cleaned columns show: ', this.cleanedColumnsShow)
},
filterShowColumns() {
this.cleanColumnsShow()
this.iConfig.columns = this.totalColumns.filter(obj => {
return this.cleanedColumnsShow.show.indexOf(obj.prop) > -1
})
},
generatePopoverColumns() {
this.popoverColumns.totalColumnsList = this.totalColumns.filter(obj => {
if (obj.label) {
return { prop: obj.prop, label: obj.label }
}
})
this.popoverColumns.currentCols = this.cleanedColumnsShow.show
this.popoverColumns.minCols = this.cleanedColumnsShow.min
this.popoverColumns.defaultCols = this.cleanedColumnsShow.default
this.$log.debug('Popover cols: ', this.popoverColumns)
},
handlePopoverColumnsChange({ columns, url }) {
this.$log.debug('Columns change: ', columns)
if (columns === null) {
columns = this.cleanedColumnsShow.default
}
this.popoverColumns.currentCols = columns
const _tableConfig = localStorage.getItem('tableConfig')
? JSON.parse(localStorage.getItem('tableConfig'))
: {}
let tableName = this.config.name || this.$route.name + '_' + newURL(url).pathname
// 替换url中的uuid,避免同一个类型接口生成多个key,localStorage中的数据无法共用.
tableName = replaceAllUUID(tableName)
_tableConfig[tableName] = {
'showColumns': columns
}
localStorage.setItem('tableConfig', JSON.stringify(_tableConfig))
this.filterShowColumns()
},
filterChange(filters) {
const key = Object.keys(filters)[0]
const attr = {}
attr[key] = filters[key][0]
this.filterTable(attr)
}
}
}
</script>