-
-
Notifications
You must be signed in to change notification settings - Fork 311
/
DataGrid.tsx
398 lines (354 loc) · 10.8 KB
/
DataGrid.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
import {
DataGridProProps,
DataGridPro,
GridToolbar,
GridColumnResizeParams,
GridColumns,
GridRowsProp,
GridColumnOrderChangeParams,
useGridApiContext,
gridColumnsTotalWidthSelector,
gridColumnPositionsSelector,
gridDensityRowHeightSelector,
GridSelectionModel,
GridValueFormatterParams,
GridColDef,
GridValueGetterParams,
useGridApiRef,
} from '@mui/x-data-grid-pro';
import * as React from 'react';
import { useNode, createComponent } from '@mui/toolpad-core';
import { Box, debounce, LinearProgress, Skeleton, styled } from '@mui/material';
import { getObjectKey } from '@mui/toolpad-core/objectKey';
// Pseudo random number. See https://stackoverflow.com/a/47593316
function mulberry32(a: number): () => number {
return () => {
/* eslint-disable */
let t = (a += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
/* eslint-enable */
};
}
function randomBetween(seed: number, min: number, max: number): () => number {
const random = mulberry32(seed);
return () => min + (max - min) * random();
}
const SkeletonCell = styled(Box)(({ theme }) => ({
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
borderBottom: `1px solid ${theme.palette.divider}`,
}));
function SkeletonLoadingOverlay() {
const apiRef = useGridApiContext();
const dimensions = apiRef.current?.getRootDimensions();
const viewportHeight = dimensions?.viewportInnerSize.height ?? 0;
const rowHeight = gridDensityRowHeightSelector(apiRef);
const skeletonRowsCount = Math.ceil(viewportHeight / rowHeight);
const totalWidth = gridColumnsTotalWidthSelector(apiRef);
const positions = gridColumnPositionsSelector(apiRef);
const inViewportCount = React.useMemo(
() => positions.filter((value) => value <= totalWidth).length,
[totalWidth, positions],
);
const columns = apiRef.current.getVisibleColumns().slice(0, inViewportCount);
const children = React.useMemo(() => {
// reseed random number generator to create stable lines betwen renders
const random = randomBetween(12345, 25, 75);
const array: React.ReactNode[] = [];
for (let i = 0; i < skeletonRowsCount; i += 1) {
for (const column of columns) {
const width = Math.round(random());
array.push(
<SkeletonCell key={`col-${column.field}-${i}`} sx={{ justifyContent: column.align }}>
<Skeleton sx={{ mx: 1 }} width={`${width}%`} />
</SkeletonCell>,
);
}
array.push(<SkeletonCell key={`fill-${i}`} />);
}
return array;
}, [skeletonRowsCount, columns]);
const rowsCount = apiRef.current.getRowsCount();
return rowsCount > 0 ? (
<LinearProgress />
) : (
<div
style={{
display: 'grid',
gridTemplateColumns: `${columns
.map(({ computedWidth }) => `${computedWidth}px`)
.join(' ')} 1fr`,
gridAutoRows: `${rowHeight}px`,
}}
>
{children}
</div>
);
}
function inferColumnType(value: unknown): string {
if (value instanceof Date) {
return 'dateTime';
}
const valueType = typeof value;
switch (typeof value) {
case 'number':
case 'boolean':
case 'string':
return valueType;
case 'object':
return 'json';
default:
return 'string';
}
}
const DEFAULT_TYPES = new Set([
'string',
'number',
'date',
'dateTime',
'boolean',
'singleSelect',
'actions',
]);
function dateValueGetter({ value }: GridValueGetterParams<any, any>) {
return typeof value === 'number' ? new Date(value) : value;
}
const COLUMN_TYPES: Record<string, Omit<GridColDef, 'field'>> = {
json: {
valueFormatter: ({ value: cellValue }: GridValueFormatterParams) => JSON.stringify(cellValue),
},
date: {
valueGetter: dateValueGetter,
},
dateTime: {
valueGetter: dateValueGetter,
},
};
export type SerializableGridColumns = { field: string; type: string }[];
export function inferColumns(rows: GridRowsProp): SerializableGridColumns {
if (rows.length < 1) {
return [];
}
// Naive implementation that checks only the first row
const firstRow = rows[0];
return Object.entries(firstRow).map(([field, value]) => {
return {
field,
type: inferColumnType(value),
};
});
}
export function parseColumns(columns: SerializableGridColumns): GridColumns {
return columns.map(({ type, ...column }) => ({
type: DEFAULT_TYPES.has(type) ? type : undefined,
...column,
...COLUMN_TYPES[type],
}));
}
const EMPTY_ROWS: GridRowsProp = [];
interface Selection {
id?: any;
}
interface OnDeleteEvent {
row: GridRowsProp[number];
}
interface ToolpadDataGridProps extends Omit<DataGridProProps, 'columns' | 'rows' | 'error'> {
rows?: GridRowsProp;
columns?: SerializableGridColumns;
height?: number;
rowIdField?: string;
error?: Error | string;
selection?: Selection | null;
onSelectionChange?: (newSelection?: Selection | null) => void;
onDelete?: (event: OnDeleteEvent) => void;
hideToolbar?: boolean;
}
const DataGridComponent = React.forwardRef(function DataGridComponent(
{
columns: columnsProp,
rows: rowsProp,
height: heightProp,
rowIdField: rowIdFieldProp,
error: errorProp,
selection,
onSelectionChange,
hideToolbar,
...props
}: ToolpadDataGridProps,
ref: React.ForwardedRef<HTMLDivElement>,
) {
const nodeRuntime = useNode<ToolpadDataGridProps>();
const handleResize = React.useMemo(
() =>
debounce((params: GridColumnResizeParams) => {
if (!nodeRuntime) {
return;
}
nodeRuntime.updateAppDomConstProp('columns', (columns) =>
columns?.map((column) =>
column.field === params.colDef.field ? { ...column, width: params.width } : column,
),
);
}, 500),
[nodeRuntime],
);
React.useEffect(() => handleResize.clear(), [handleResize]);
const handleColumnOrderChange = React.useMemo(
() =>
debounce((params: GridColumnOrderChangeParams) => {
if (!nodeRuntime) {
return;
}
nodeRuntime.updateAppDomConstProp('columns', (columns) => {
if (!columns) {
return columns;
}
const old = columns.find((colDef) => colDef.field === params.field);
if (!old) {
return columns;
}
const withoutOld = columns.filter((column) => column.field !== params.field);
return [
...withoutOld.slice(0, params.targetIndex),
old,
...withoutOld.slice(params.targetIndex),
];
});
}, 500),
[nodeRuntime],
);
React.useEffect(() => handleColumnOrderChange.clear(), [handleColumnOrderChange]);
const rowsInput = rowsProp || EMPTY_ROWS;
const hasExplicitRowId: boolean = React.useMemo(() => {
const hasRowIdField: boolean = !!(rowIdFieldProp && rowIdFieldProp !== 'id');
const parsedRows = rowsInput;
return parsedRows.length === 0 || hasRowIdField || !!parsedRows[0].id;
}, [rowIdFieldProp, rowsInput]);
const rows: GridRowsProp = React.useMemo(
() => (hasExplicitRowId ? rowsInput : rowsInput.map((row, id) => ({ ...row, id }))),
[hasExplicitRowId, rowsInput],
);
const columnsInitRef = React.useRef(false);
const hasColumnsDefined = columnsProp && columnsProp.length > 0;
React.useEffect(() => {
if (!nodeRuntime || hasColumnsDefined || rows.length <= 0 || columnsInitRef.current) {
return;
}
let inferredColumns = inferColumns(rows);
if (!hasExplicitRowId) {
inferredColumns = inferredColumns.filter((column) => column.field !== 'id');
}
nodeRuntime.updateAppDomConstProp('columns', inferredColumns);
columnsInitRef.current = true;
}, [hasColumnsDefined, rows, nodeRuntime, hasExplicitRowId]);
const getRowId = React.useCallback(
(row: any) => {
return rowIdFieldProp && row[rowIdFieldProp] ? row[rowIdFieldProp] : row.id;
},
[rowIdFieldProp],
);
const onSelectionModelChange = React.useCallback(
(ids: GridSelectionModel) => {
onSelectionChange?.(ids.length > 0 ? rows.find((row) => row.id === ids[0]) : null);
},
[rows, onSelectionChange],
);
const selectionModel = React.useMemo(
() => (selection?.id ? [selection.id] : []),
[selection?.id],
);
const columns: GridColumns = React.useMemo(
() => (columnsProp ? parseColumns(columnsProp) : []),
[columnsProp],
);
const apiRef = useGridApiRef();
React.useEffect(() => apiRef.current.updateColumns(columns), [apiRef, columns]);
// The grid doesn't update when the getRowId or columns properties change, so it needs to be remounted
// TODO: remove columns from this equation once https://github.com/mui/mui-x/issues/5970 gets resolved
const gridKey = React.useMemo(
() => [getObjectKey(getRowId), getObjectKey(columns)].join('::'),
[getRowId, columns],
);
return (
<div ref={ref} style={{ height: heightProp, minHeight: '100%', width: '100%' }}>
<DataGridPro
apiRef={apiRef}
components={{
Toolbar: hideToolbar ? null : GridToolbar,
LoadingOverlay: SkeletonLoadingOverlay,
}}
onColumnResize={handleResize}
onColumnOrderChange={handleColumnOrderChange}
rows={rows}
columns={columns}
key={gridKey}
getRowId={getRowId}
onSelectionModelChange={onSelectionModelChange}
selectionModel={selectionModel}
error={errorProp}
componentsProps={{
errorOverlay: {
message: typeof errorProp === 'string' ? errorProp : errorProp?.message,
},
}}
{...props}
/>
</div>
);
});
export default createComponent(DataGridComponent, {
errorProp: 'error',
loadingPropSource: ['rows', 'columns'],
loadingProp: 'loading',
resizableHeightProp: 'height',
argTypes: {
rows: {
typeDef: { type: 'array', schema: '/schemas/DataGridRows.json' },
},
columns: {
typeDef: { type: 'array', schema: '/schemas/DataGridColumns.json' },
control: { type: 'GridColumns' },
},
rowIdField: {
typeDef: { type: 'string' },
control: { type: 'RowIdFieldSelect' },
label: 'Id field',
},
selection: {
typeDef: { type: 'object' },
onChangeProp: 'onSelectionChange',
defaultValue: null,
},
density: {
typeDef: { type: 'string', enum: ['compact', 'standard', 'comfortable'] },
defaultValue: 'compact',
},
height: {
typeDef: { type: 'number' },
defaultValue: 350,
},
loading: {
typeDef: { type: 'boolean' },
},
hideToolbar: {
typeDef: { type: 'boolean' },
},
sx: {
typeDef: { type: 'object' },
},
onDelete: {
typeDef: {
type: 'event',
arguments: [
{
name: 'event',
tsType: `{ row: ThisComponent['rows'][number] }`,
},
],
},
},
},
});