-
Notifications
You must be signed in to change notification settings - Fork 690
Expand file tree
/
Copy pathTable.ts
More file actions
311 lines (284 loc) · 8.95 KB
/
Table.ts
File metadata and controls
311 lines (284 loc) · 8.95 KB
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
import { BaseChart, type ChartAxis, type ChartData } from '@/views/chat/component/BaseChart.ts'
import {
copyToClipboard,
type S2DataConfig,
S2Event,
type S2MountContainer,
type S2Options,
type SortMethod,
TableSheet,
type SortFuncParam,
} from '@antv/s2'
import { debounce, filter } from 'lodash-es'
import { i18n } from '@/i18n'
import '@antv/s2/dist/s2.min.css'
const { t } = i18n.global
const createSmartSortFunc = (sortMethod: string) => {
const compareNumericString = (a: string, b: string): number => {
const isNegA = a.startsWith('-')
const isNegB = b.startsWith('-')
// 负数 < 正数
if (isNegA && !isNegB) return -1
if (!isNegA && isNegB) return 1
const [intA, decA = ''] = isNegA ? a.slice(1).split('.') : a.split('.')
const [intB, decB = ''] = isNegB ? b.slice(1).split('.') : b.split('.')
// 都是正数
if (!isNegA && !isNegB) {
if (intA.length !== intB.length) return intA.length - intB.length
const intCmp = intA.localeCompare(intB)
if (intCmp !== 0) return intCmp
if (decA && decB) return decA.localeCompare(decB)
return decA ? 1 : decB ? -1 : 0
}
// 都是负数:绝对值大的实际值小,比较结果取反
if (intA.length !== intB.length) return -(intA.length - intB.length)
const intCmp = intA.localeCompare(intB)
if (intCmp !== 0) return -intCmp
if (decA && decB) return -decA.localeCompare(decB)
return decA ? 1 : decB ? -1 : 0
}
return (params: SortFuncParam) => {
const { data, sortFieldId } = params
if (!data || data.length === 0) return data
const isAsc = sortMethod.toLowerCase() === 'asc'
return [...data].sort((a: any, b: any) => {
const valA = a[sortFieldId],
valB = b[sortFieldId]
if (valA == null) return isAsc ? -1 : 1
if (valB == null) return isAsc ? 1 : -1
const strA = String(valA),
strB = String(valB)
const isNumA = !isNaN(Number(strA)) && strA.trim() !== ''
const isNumB = !isNaN(Number(strB)) && strB.trim() !== ''
if (isNumA && !isNumB) return isAsc ? -1 : 1
if (!isNumA && isNumB) return isAsc ? 1 : -1
if (isNumA && isNumB) {
const cmp = compareNumericString(strA, strB)
return isAsc ? cmp : -cmp
}
const cmp = strA.localeCompare(strB)
return isAsc ? cmp : -cmp
})
}
}
export class Table extends BaseChart {
table?: TableSheet = undefined
container: S2MountContainer | null = null
debounceRender: any
resizeObserver: ResizeObserver
constructor(id: string) {
super(id, 'table')
this.container = document.getElementById(id)
this.debounceRender = debounce(async (width?: number, height?: number) => {
if (this.table) {
this.table.changeSheetSize(width, height)
await this.table.render(false)
}
}, 200)
this.resizeObserver = new ResizeObserver(([entry] = []) => {
const [size] = entry.borderBoxSize || []
this.debounceRender(size.inlineSize, size.blockSize)
})
if (this.container?.parentElement) {
this.resizeObserver.observe(this.container.parentElement)
}
}
init(axis: Array<ChartAxis>, data: Array<ChartData>) {
super.init(
filter(axis, (a) => !a.hidden), //隐藏多指标的other-info列
data
)
const s2DataConfig: S2DataConfig = {
sortParams:
this.axis?.map((a) => {
return {
sortFieldId: a.value,
}
}) ?? [],
fields: {
columns: this.axis?.map((a) => a.value) ?? [],
},
meta:
this.axis?.map((a) => {
return {
field: a.value,
name: a.name,
}
}) ?? [],
data: this.data,
}
const sortState: Record<string, string> = {}
const handleSortClick = (params: any) => {
const { meta } = params
const s2 = meta.spreadsheet
if (s2 && meta.isLeaf) {
const fieldId = meta.field
const currentMethod = sortState[fieldId] || 'none'
const sortOrder = ['none', 'desc', 'asc']
const nextMethod = sortOrder[(sortOrder.indexOf(currentMethod) + 1) % sortOrder.length]
sortState[fieldId] = nextMethod
if (nextMethod === 'none') {
s2.emit(S2Event.RANGE_SORT, [{ sortFieldId: fieldId, sortMethod: 'none' as SortMethod }])
} else {
s2.emit(S2Event.RANGE_SORT, [
{
sortFieldId: fieldId,
sortMethod: nextMethod as SortMethod,
sortFunc: createSmartSortFunc(nextMethod),
},
])
}
s2.render()
}
}
const s2Options: S2Options = {
width: 600,
height: 360,
showDefaultHeaderActionIcon: false,
headerActionIcons: [
{
icons: ['GlobalDesc'],
belongsCell: 'colCell',
displayCondition: (node: any) => node.isLeaf && sortState[node.field] === 'desc',
onClick: handleSortClick,
},
{
icons: ['GlobalAsc'],
belongsCell: 'colCell',
displayCondition: (node: any) => node.isLeaf && sortState[node.field] === 'asc',
onClick: handleSortClick,
},
{
icons: ['SortDown'],
belongsCell: 'colCell',
displayCondition: (node: any) =>
node.isLeaf && (!sortState[node.field] || sortState[node.field] === 'none'),
onClick: handleSortClick,
},
],
tooltip: {
operation: {
sort: true,
},
dataCell: {
enable: true,
content: (cell) => {
const meta = cell.getMeta()
const container = document.createElement('div')
container.style.padding = '8px 0'
container.style.minWidth = '100px'
container.style.maxWidth = '400px'
container.style.display = 'flex'
container.style.alignItems = 'center'
container.style.padding = '8px 16px'
container.style.cursor = 'pointer'
container.style.color = '#606266'
container.style.fontSize = '14px'
container.style.whiteSpace = 'pre-wrap'
const text = document.createTextNode(meta.fieldValue)
container.appendChild(text)
return container
},
},
},
// 如果有省略号, 复制到的是完整文本
interaction: {
copy: {
enable: true,
withFormat: true,
withHeader: true,
},
brushSelection: {
dataCell: true,
rowCell: true,
colCell: true,
},
},
placeholder: {
cell: '-',
empty: {
icon: 'Empty',
description: 'No Data',
},
},
}
if (this.container) {
this.table = new TableSheet(this.container, s2DataConfig, s2Options)
// right click
this.table.on(S2Event.GLOBAL_COPIED, (data) => {
ElMessage.success(t('qa.copied'))
console.debug('copied: ', data)
})
this.table.getCanvasElement().addEventListener('contextmenu', (event) => {
event.preventDefault()
})
this.table.on(S2Event.GLOBAL_CONTEXT_MENU, (event) => copyData(event, this.table))
// this.table.on(S2Event.RANGE_SORT, (sortParams) => {
// console.log('sortParams:', sortParams)
// })
}
}
render() {
this.table?.render()
}
destroy() {
this.table?.destroy()
this.resizeObserver?.disconnect()
}
}
function copyData(event: any, s2?: TableSheet) {
event.preventDefault()
if (!s2) {
return
}
const cells = s2.interaction.getCells()
if (cells.length == 0) {
return
} else if (cells.length == 1) {
const c = cells[0]
const cellMeta = s2.facet.getCellMeta(c.rowIndex, c.colIndex)
if (cellMeta) {
let value = cellMeta.fieldValue
if (value === null || value === undefined) {
value = '-'
}
value = value + ''
copyToClipboard(value).finally(() => {
ElMessage.success(t('qa.copied'))
console.debug('copied:', cellMeta.fieldValue)
})
}
return
} else {
let currentRowIndex = -1
let currentRowData: Array<string> = []
const rowData: Array<string> = []
for (let i = 0; i < cells.length; i++) {
const c = cells[i]
const cellMeta = s2.facet.getCellMeta(c.rowIndex, c.colIndex)
if (!cellMeta) {
continue
}
if (currentRowIndex == -1) {
currentRowIndex = c.rowIndex
}
if (c.rowIndex !== currentRowIndex) {
rowData.push(currentRowData.join('\t'))
currentRowData = []
currentRowIndex = c.rowIndex
}
let value = cellMeta.fieldValue
if (value === null || value === undefined) {
value = '-'
}
value = value + ''
currentRowData.push(value)
}
rowData.push(currentRowData.join('\t'))
const finalValue = rowData.join('\n')
copyToClipboard(finalValue).finally(() => {
ElMessage.success(t('qa.copied'))
console.debug('copied:\n', finalValue)
})
}
}