-
Notifications
You must be signed in to change notification settings - Fork 11.7k
/
Table.tsx
411 lines (364 loc) · 13 KB
/
Table.tsx
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
import React, { CSSProperties, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
Cell,
TableState,
useAbsoluteLayout,
useFilters,
usePagination,
useResizeColumns,
useSortBy,
useTable,
} from 'react-table';
import { FixedSizeList } from 'react-window';
import { DataFrame, getFieldDisplayName, Field } from '@grafana/data';
import { useStyles2, useTheme2 } from '../../themes';
import { CustomScrollbar } from '../CustomScrollbar/CustomScrollbar';
import { Pagination } from '../Pagination/Pagination';
import { FooterRow } from './FooterRow';
import { HeaderRow } from './HeaderRow';
import { TableCell } from './TableCell';
import { getTableStyles } from './styles';
import {
TableColumnResizeActionCallback,
TableFilterActionCallback,
FooterItem,
TableSortByActionCallback,
TableSortByFieldState,
TableFooterCalc,
GrafanaTableColumn,
} from './types';
import { getColumns, sortCaseInsensitive, sortNumber, getFooterItems, createFooterCalculationValues } from './utils';
const COLUMN_MIN_WIDTH = 150;
export interface Props {
ariaLabel?: string;
data: DataFrame;
width: number;
height: number;
/** Minimal column width specified in pixels */
columnMinWidth?: number;
noHeader?: boolean;
showTypeIcons?: boolean;
resizable?: boolean;
initialSortBy?: TableSortByFieldState[];
onColumnResize?: TableColumnResizeActionCallback;
onSortByChange?: TableSortByActionCallback;
onCellFilterAdded?: TableFilterActionCallback;
footerOptions?: TableFooterCalc;
footerValues?: FooterItem[];
enablePagination?: boolean;
}
function useTableStateReducer({ onColumnResize, onSortByChange, data }: Props) {
return useCallback(
(newState: TableState, action: { type: string }) => {
switch (action.type) {
case 'columnDoneResizing':
if (onColumnResize) {
const info = (newState.columnResizing.headerIdWidths as any)[0];
const columnIdString = info[0];
const fieldIndex = parseInt(columnIdString, 10);
const width = Math.round(newState.columnResizing.columnWidths[columnIdString] as number);
const field = data.fields[fieldIndex];
if (!field) {
return newState;
}
const fieldDisplayName = getFieldDisplayName(field, data);
onColumnResize(fieldDisplayName, width);
}
case 'toggleSortBy':
if (onSortByChange) {
const sortByFields: TableSortByFieldState[] = [];
for (const sortItem of newState.sortBy) {
const field = data.fields[parseInt(sortItem.id, 10)];
if (!field) {
continue;
}
sortByFields.push({
displayName: getFieldDisplayName(field, data),
desc: sortItem.desc,
});
}
onSortByChange(sortByFields);
}
break;
}
return newState;
},
[data, onColumnResize, onSortByChange]
);
}
function getInitialState(initialSortBy: Props['initialSortBy'], columns: GrafanaTableColumn[]): Partial<TableState> {
const state: Partial<TableState> = {};
if (initialSortBy) {
state.sortBy = [];
for (const sortBy of initialSortBy) {
for (const col of columns) {
if (col.Header === sortBy.displayName) {
state.sortBy.push({ id: col.id!, desc: sortBy.desc });
}
}
}
}
return state;
}
export const Table = memo((props: Props) => {
const {
ariaLabel,
data,
height,
onCellFilterAdded,
width,
columnMinWidth = COLUMN_MIN_WIDTH,
noHeader,
resizable = true,
initialSortBy,
footerOptions,
showTypeIcons,
footerValues,
enablePagination,
} = props;
const listRef = useRef<FixedSizeList>(null);
const tableDivRef = useRef<HTMLDivElement>(null);
const fixedSizeListScrollbarRef = useRef<HTMLDivElement>(null);
const tableStyles = useStyles2(getTableStyles);
const theme = useTheme2();
const headerHeight = noHeader ? 0 : tableStyles.cellHeight;
const [footerItems, setFooterItems] = useState<FooterItem[] | undefined>(footerValues);
const footerHeight = useMemo(() => {
const EXTENDED_ROW_HEIGHT = 33;
let length = 0;
if (!footerItems) {
return 0;
}
for (const fv of footerItems) {
if (Array.isArray(fv) && fv.length > length) {
length = fv.length;
}
}
if (length > 1) {
return EXTENDED_ROW_HEIGHT * length;
}
return EXTENDED_ROW_HEIGHT;
}, [footerItems]);
// React table data array. This data acts just like a dummy array to let react-table know how many rows exist
// The cells use the field to look up values
const memoizedData = useMemo(() => {
if (!data.fields.length) {
return [];
}
// as we only use this to fake the length of our data set for react-table we need to make sure we always return an array
// filled with values at each index otherwise we'll end up trying to call accessRow for null|undefined value in
// https://github.com/tannerlinsley/react-table/blob/7be2fc9d8b5e223fc998af88865ae86a88792fdb/src/hooks/useTable.js#L585
return Array(data.length).fill(0);
}, [data]);
// React-table column definitions
const memoizedColumns = useMemo(
() => getColumns(data, width, columnMinWidth, footerItems, footerOptions?.countAll),
[data, width, columnMinWidth, footerItems, footerOptions]
);
// Internal react table state reducer
const stateReducer = useTableStateReducer(props);
const options: any = useMemo(
() => ({
columns: memoizedColumns,
data: memoizedData,
disableResizing: !resizable,
stateReducer: stateReducer,
initialState: getInitialState(initialSortBy, memoizedColumns),
autoResetFilters: false,
sortTypes: {
number: sortNumber, // the builtin number type on react-table does not handle NaN values
'alphanumeric-insensitive': sortCaseInsensitive, // should be replace with the builtin string when react-table is upgraded, see https://github.com/tannerlinsley/react-table/pull/3235
},
}),
[initialSortBy, memoizedColumns, memoizedData, resizable, stateReducer]
);
const {
getTableProps,
headerGroups,
rows,
prepareRow,
totalColumnsWidth,
footerGroups,
page,
state,
gotoPage,
setPageSize,
pageOptions,
} = useTable(options, useFilters, useSortBy, usePagination, useAbsoluteLayout, useResizeColumns);
/*
Footer value calculation is being moved in the Table component and the footerValues prop will be deprecated.
The footerValues prop is still used in the Table component for backwards compatibility. Adding the
footerOptions prop will switch the Table component to use the new footer calculation. Using both props will
result in the footerValues prop being ignored.
*/
useEffect(() => {
if (!footerOptions) {
setFooterItems(footerValues);
}
}, [footerValues, footerOptions]);
useEffect(() => {
if (!footerOptions) {
return;
}
if (footerOptions.show) {
const footerItems = getFooterItems(
headerGroups[0].headers as unknown as Array<{ field: Field }>,
createFooterCalculationValues(rows),
footerOptions,
theme
);
if (footerOptions.countAll && footerItems) {
const maxCount = footerItems.reduce((max, item) => {
if (typeof item === 'string' && !isNaN(+item)) {
return Math.max(max, +item);
}
return max;
}, 0);
const footerItemsCountAll: FooterItem[] = new Array(footerItems.length).fill(undefined);
footerItemsCountAll[0] = maxCount.toString();
console.log(footerItemsCountAll);
setFooterItems(footerItemsCountAll);
} else {
setFooterItems(footerItems);
}
} else {
setFooterItems(undefined);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [footerOptions, theme, state.filters, data]);
let listHeight = height - (headerHeight + footerHeight);
if (enablePagination) {
listHeight -= tableStyles.cellHeight;
}
const pageSize = Math.round(listHeight / tableStyles.cellHeight) - 1;
useEffect(() => {
// Don't update the page size if it is less than 1
if (pageSize <= 0) {
return;
}
setPageSize(pageSize);
}, [pageSize, setPageSize]);
useEffect(() => {
// To have the custom vertical scrollbar always visible (https://github.com/grafana/grafana/issues/52136),
// we need to bring the element from the FixedSizeList scope to the outer Table container scope,
// because the FixedSizeList scope has overflow. By moving scrollbar to container scope we will have
// it always visible since the entire width is in view.
// Select the scrollbar element from the FixedSizeList scope
const listVerticalScrollbarHTML = (fixedSizeListScrollbarRef.current as HTMLDivElement)?.querySelector(
'.track-vertical'
);
// Select Table custom scrollbars
const tableScrollbarView = (tableDivRef.current as HTMLDivElement)?.firstChild;
//If they exists, move the scrollbar element to the Table container scope
if (tableScrollbarView && listVerticalScrollbarHTML) {
listVerticalScrollbarHTML?.remove();
(tableScrollbarView as HTMLDivElement).querySelector(':scope > .track-vertical')?.remove();
(tableScrollbarView as HTMLDivElement).append(listVerticalScrollbarHTML as Node);
}
});
const RenderRow = React.useCallback(
({ index: rowIndex, style }: { index: number; style: CSSProperties }) => {
let row = rows[rowIndex];
if (enablePagination) {
row = page[rowIndex];
}
prepareRow(row);
return (
<div {...row.getRowProps({ style })} className={tableStyles.row}>
{row.cells.map((cell: Cell, index: number) => (
<TableCell
key={index}
tableStyles={tableStyles}
cell={cell}
onCellFilterAdded={onCellFilterAdded}
columnIndex={index}
columnCount={row.cells.length}
/>
))}
</div>
);
},
[onCellFilterAdded, page, enablePagination, prepareRow, rows, tableStyles]
);
const onNavigate = useCallback(
(toPage: number) => {
gotoPage(toPage - 1);
},
[gotoPage]
);
const itemCount = enablePagination ? page.length : rows.length;
let paginationEl = null;
if (enablePagination) {
const itemsRangeStart = state.pageIndex * state.pageSize + 1;
let itemsRangeEnd = itemsRangeStart + state.pageSize - 1;
const isSmall = width < 550;
if (itemsRangeEnd > data.length) {
itemsRangeEnd = data.length;
}
paginationEl = (
<div className={tableStyles.paginationWrapper}>
{isSmall ? null : <div className={tableStyles.paginationItem} />}
<div className={tableStyles.paginationCenterItem}>
<Pagination
currentPage={state.pageIndex + 1}
numberOfPages={pageOptions.length}
showSmallVersion={isSmall}
onNavigate={onNavigate}
/>
</div>
{isSmall ? null : (
<div className={tableStyles.paginationSummary}>
{itemsRangeStart} - {itemsRangeEnd} of {data.length} rows
</div>
)}
</div>
);
}
const handleScroll: React.UIEventHandler = (event) => {
const { scrollTop } = event.target as HTMLDivElement;
if (listRef.current !== null) {
listRef.current.scrollTo(scrollTop);
}
};
return (
<div {...getTableProps()} className={tableStyles.table} aria-label={ariaLabel} role="table" ref={tableDivRef}>
<CustomScrollbar hideVerticalTrack={true}>
<div className={tableStyles.tableContentWrapper(totalColumnsWidth)}>
{!noHeader && <HeaderRow headerGroups={headerGroups} showTypeIcons={showTypeIcons} />}
{itemCount > 0 ? (
<div ref={fixedSizeListScrollbarRef}>
<CustomScrollbar onScroll={handleScroll} hideHorizontalTrack={true}>
<FixedSizeList
height={listHeight}
itemCount={itemCount}
itemSize={tableStyles.rowHeight}
width={'100%'}
ref={listRef}
style={{ overflow: undefined }}
>
{RenderRow}
</FixedSizeList>
</CustomScrollbar>
</div>
) : (
<div style={{ height: height - headerHeight }} className={tableStyles.noData}>
No data
</div>
)}
{footerItems && (
<FooterRow
height={footerHeight}
isPaginationVisible={Boolean(enablePagination)}
isCountAllSet={Boolean(props.footerOptions?.countAll)}
footerValues={footerItems}
footerGroups={footerGroups}
totalColumnsWidth={totalColumnsWidth}
/>
)}
</div>
</CustomScrollbar>
{paginationEl}
</div>
);
});
Table.displayName = 'Table';