-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathBaseTable.js
More file actions
396 lines (363 loc) · 11.5 KB
/
BaseTable.js
File metadata and controls
396 lines (363 loc) · 11.5 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
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
import {
flexRender,
getCoreRowModel,
useReactTable,
} from '@tanstack/react-table';
import {
Box,
Collapse,
Flex,
Grid,
Table,
TableHeader,
TableBody,
TableRow,
TableCell,
TableScrollbar,
Text,
TextLabel,
useColorMode,
useTheme,
} from '@tonic-ui/react';
import { dataAttr } from '@tonic-ui/utils';
import { Fragment, forwardRef, useEffect, useState } from 'react';
import AutoSizer from 'react-virtualized-auto-sizer';
/**
* Assign a value to a ref function or object.
*
* @param ref the ref to assign to
* @param value the value
*/
const assignRef = (ref, value) => {
if (ref === null || ref === undefined) {
return;
}
if (typeof ref === 'function') {
ref(value);
return;
}
try {
ref.current = value;
} catch {
throw new Error(`Cannot assign value '${value}' to ref '${ref}'`);
}
};
/**
* Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
*
* @param {String} text The text to be rendered.
* @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
*
* @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
*/
const getTextWidth = (text, font) => {
// re-use canvas object for better performance
const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement('canvas'));
const context = canvas.getContext('2d');
context.font = font;
const metrics = context.measureText(text);
return metrics.width || 0;
};
const ConditionalWrapper = ({
children,
condition,
wrapper,
}) => {
return condition ? wrapper(children) : children;
};
const BaseTable = forwardRef((
{
columns,
data,
layout = 'flexbox', // One of: 'flexbox', 'table'
variant = 'default', // One of: 'default', 'outline'
// TanStack Table
tableOptions,
tableRef,
...rest
},
ref,
) => {
const [colorMode] = useColorMode();
const theme = useTheme();
const hoverBackgroundColor = {
dark: 'rgba(255, 255, 255, 0.12)',
light: 'rgba(0, 0, 0, 0.12)',
}[colorMode];
const selectedBackgroundColor = {
dark: 'rgba(255, 255, 255, 0.08)',
light: 'rgba(0, 0, 0, 0.08)',
}[colorMode];
const renderExpandedRow = ({ row }) => {
const tableBorderColor = {
dark: 'gray:70',
light: 'gray:30',
}[colorMode];
const dividerColor = {
dark: 'gray:60',
light: 'gray:30',
}[colorMode];
const entries = Object.entries(row.original);
const renderValue = (value) => {
if (Array.isArray(value)) {
return value.map(item => <Text key={item}>{item}</Text>);
}
if (typeof value === 'boolean') {
return value.toString();
}
return value;
};
return (
<Flex
borderBottom={1}
borderBottomColor={tableBorderColor}
>
<Box width="12x" borderRight={2} borderRightColor={dividerColor} />
<Box as="pre" fontFamily="mono" m={0} px="3x" py="2x">
<Grid
templateColumns="auto auto"
columnGap="10x"
rowGap="1x"
>
{entries.map(([key, value]) => {
return (
<Fragment key={key}>
<TextLabel>
{key}
</TextLabel>
<Text>
{renderValue(value)}
</Text>
</Fragment>
);
})}
</Grid>
</Box>
</Flex>
);
};
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
...tableOptions,
});
if (tableRef) {
assignRef(tableRef, table);
}
const [tableWidth, setTableWidth] = useState(0);
useEffect(() => {
if (!tableWidth) {
return;
}
const gutterWidth = 12 + 12; // 12px padding on each side of the cell
const tableHeaderCellFont = [
theme.fontWeights.semibold,
theme.fontSizes.sm,
theme.fonts.base,
].join(' '); // => '600 14px "Segoe UI",-apple-system,BlinkMacSystemFont,"Helvetica Neue",Helvetica,Arial,sans-serif'
// Fixed columns are columns with a fixed size (e.g. 100 or '10%')
const fixedColumns = table.getAllColumns()
.filter(column => column.columnDef.size !== 'auto')
.map(column => {
const { id, columnDef } = column;
const { minSize, size } = columnDef;
// If the column size is a number, return the original size value
if (typeof size === 'number') {
return {
id,
size,
};
}
// If the column size is a percentage, return the computed size value
if (typeof size === 'string' && size.endsWith('%')) {
const textWidth = (typeof columnDef.header === 'string')
? getTextWidth(columnDef.header, tableHeaderCellFont)
: 0;
const percentageWidth = tableWidth * parseFloat(size) / 100;
return {
id,
size: Math.max(
percentageWidth, // percentage of table width
textWidth + gutterWidth, // text width with padding
minSize, // minimum size (e.g. 40px)
),
};
}
// Otherwise, return the minimum size value
return {
id,
size: minSize,
};
});
// Flexible columns are columns with a flexible size (e.g. 'auto')
const flexColumns = table.getAllColumns()
.filter(column => column.columnDef.size === 'auto')
.map(column => {
const { id, columnDef } = column;
const { minSize } = columnDef;
const textWidth = (typeof columnDef.header === 'string')
? getTextWidth(columnDef.header, tableHeaderCellFont)
: 0;
return {
id,
size: Math.max(
textWidth + gutterWidth, // text width with padding
minSize, // minimum size (e.g. 40px)
),
};
});
const totalFixedColumnSize = fixedColumns.reduce((acc, column) => acc + column.size, 0);
const totalFlexColumnSize = flexColumns.reduce((acc, column) => acc + column.size, 0);
let extraSpaceLeft = tableWidth - totalFixedColumnSize;
// Distribute extra space to fixed columns if flex columns are not present
if ((flexColumns.length === 0) && (extraSpaceLeft > 0)) {
const extraSpacePerColumn = extraSpaceLeft / fixedColumns.length;
fixedColumns.forEach(column => {
column.size += extraSpacePerColumn;
});
extraSpaceLeft = 0;
}
// Distribute extra space to flex columns if flex columns are present
if ((flexColumns.length > 0) && (extraSpaceLeft > totalFlexColumnSize)) {
/**
* Assume that the extra space is 500px and the total flex column size is 400px:
* > extraSpaceLeft = 500
* > flexColumns = [ { size: 250 }, { size: 150 } ] // => Total size: 400px
*
* Iteration #0:
* > column.size = Math.max(500 / (2 - 0), 250) = Math.max(250, 250) = 250
* > extraSpaceLeft = 500 - 250 = 250
*
* Iteration #1:
* > column.size = Math.max(250 / (2 - 1), 150) = Math.max(250, 150) = 250
* > extraSpaceLeft = 250 - 250 = 0
*/
flexColumns.forEach((column, index) => {
column.size = Math.max(
extraSpaceLeft / (flexColumns.length - index),
column.size,
);
extraSpaceLeft -= column.size;
});
}
const columnSizing = {};
for (let i = 0; i < fixedColumns.length; i++) {
const column = fixedColumns[i];
columnSizing[column.id] = column.size;
}
for (let i = 0; i < flexColumns.length; i++) {
const column = flexColumns[i];
columnSizing[column.id] = column.size;
}
table.setColumnSizing(columnSizing);
}, [columns, table, tableWidth, theme]);
return (
<AutoSizer
onResize={({ width }) => {
if (tableWidth !== width) {
setTableWidth(width);
}
}}
>
{({ width, height }) => {
return (
<Table
layout={layout}
variant={variant}
width={width}
height={height}
{...rest}
>
<TableHeader>
{table.getHeaderGroups().map(headerGroup => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map(header => {
const styleProps = {
minWidth: header.column.columnDef.minSize,
width: header.getSize(),
...header.column.columnDef.style,
};
return (
<TableCell
key={header.id}
{...styleProps}
>
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
</TableCell>
);
})}
</TableRow>
))}
</TableHeader>
<ConditionalWrapper
condition={layout === 'flexbox'}
wrapper={children => (
<TableScrollbar
height="100%"
overflow="visible" // Make the scrollbar visible
>
{children}
</TableScrollbar>
)}
>
<TableBody>
{table.getRowModel().rows.map(row => (
<Fragment key={row.id}>
<TableRow
data-selected={dataAttr(row.getIsSelected())}
_hover={{
backgroundColor: hoverBackgroundColor,
}}
_selected={{
backgroundColor: selectedBackgroundColor,
}}
>
{row.getVisibleCells().map(cell => {
const styleProps = {
minWidth: cell.column.columnDef.minSize,
width: cell.column.getSize(),
...cell.column.columnDef.style,
};
return (
<TableCell
key={cell.id}
{...styleProps}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
);
})}
</TableRow>
{(row.getCanExpand() && layout === 'flexbox') && (
<Collapse in={row.getIsExpanded()}>
{renderExpandedRow({ row })}
</Collapse>
)}
{(row.getCanExpand() && layout === 'table') && (
<TableRow>
<TableCell
padding={0}
borderBottom={0}
colSpan={row.getVisibleCells().length}
>
<Collapse in={row.getIsExpanded()}>
{renderExpandedRow({ row })}
</Collapse>
</TableCell>
</TableRow>
)}
</Fragment>
))}
</TableBody>
</ConditionalWrapper>
</Table>
);
}}
</AutoSizer>
);
});
BaseTable.displayName = 'BaseTable';
export default BaseTable;