@mui/x-data-grid-generator 7.20.0 → 7.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,15 +4,10 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.processTreeDataRows = exports.loadServerRows = exports.disableDelay = exports.DEFAULT_SERVER_OPTIONS = exports.DEFAULT_DATASET_OPTIONS = void 0;
7
+ exports.processTreeDataRows = exports.processRowGroupingRows = exports.loadServerRows = exports.disableDelay = exports.DEFAULT_SERVER_OPTIONS = void 0;
8
8
  var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
9
9
  var _xDataGridPro = require("@mui/x-data-grid-pro");
10
10
  var _randomGenerator = require("../services/random-generator");
11
- const DEFAULT_DATASET_OPTIONS = exports.DEFAULT_DATASET_OPTIONS = {
12
- dataSet: 'Commodity',
13
- rowLength: 100,
14
- maxColumns: 6
15
- };
16
11
  const disableDelay = exports.disableDelay = typeof DISABLE_CHANCE_RANDOM !== 'undefined' && DISABLE_CHANCE_RANDOM;
17
12
  const DEFAULT_SERVER_OPTIONS = exports.DEFAULT_SERVER_OPTIONS = {
18
13
  minDelay: disableDelay ? 0 : 100,
@@ -221,8 +216,7 @@ const loadServerRows = (rows, queryOptions, serverOptions, columnsWithDefaultCol
221
216
  });
222
217
  };
223
218
  exports.loadServerRows = loadServerRows;
224
- const findTreeDataRowChildren = (allRows, parentPath, pathKey = 'path', depth = 1 // the depth of the children to find relative to parentDepth, `-1` to find all
225
- ) => {
219
+ const findTreeDataRowChildren = (allRows, parentPath, pathKey = 'path', depth = 1, rowQualifier) => {
226
220
  const parentDepth = parentPath.length;
227
221
  const children = [];
228
222
  for (let i = 0; i < allRows.length; i += 1) {
@@ -232,7 +226,9 @@ const findTreeDataRowChildren = (allRows, parentPath, pathKey = 'path', depth =
232
226
  continue;
233
227
  }
234
228
  if ((depth < 0 && rowPath.length > parentDepth || rowPath.length === parentDepth + depth) && parentPath.every((value, index) => value === rowPath[index])) {
235
- children.push(row);
229
+ if (!rowQualifier || rowQualifier(row)) {
230
+ children.push(row);
231
+ }
236
232
  }
237
233
  }
238
234
  return children;
@@ -295,7 +291,7 @@ const getTreeDataFilteredRows = (rows, filterModel, columnsWithDefaultColDef) =>
295
291
  };
296
292
 
297
293
  /**
298
- * Simulates server data loading
294
+ * Simulates server data for tree-data feature
299
295
  */
300
296
  const processTreeDataRows = (rows, queryOptions, serverOptions, columnsWithDefaultColDef) => {
301
297
  const {
@@ -351,4 +347,118 @@ const processTreeDataRows = (rows, queryOptions, serverOptions, columnsWithDefau
351
347
  }, delay); // simulate network latency
352
348
  });
353
349
  };
354
- exports.processTreeDataRows = processTreeDataRows;
350
+
351
+ /**
352
+ * Simulates server data for row grouping feature
353
+ */
354
+ exports.processTreeDataRows = processTreeDataRows;
355
+ const processRowGroupingRows = (rows, queryOptions, serverOptions, columnsWithDefaultColDef) => {
356
+ const {
357
+ minDelay = 100,
358
+ maxDelay = 300
359
+ } = serverOptions;
360
+ const pathKey = 'path';
361
+ if (maxDelay < minDelay) {
362
+ throw new Error('serverOptions.minDelay is larger than serverOptions.maxDelay ');
363
+ }
364
+ if (queryOptions.groupKeys == null) {
365
+ throw new Error('serverOptions.groupKeys must be defined to compute row grouping data');
366
+ }
367
+ if (queryOptions.groupFields == null) {
368
+ throw new Error('serverOptions.groupFields must be defined to compute row grouping data');
369
+ }
370
+ const delay = (0, _randomGenerator.randomInt)(minDelay, maxDelay);
371
+ const pathsToAutogenerate = new Set();
372
+ let rowsWithPaths = rows;
373
+ const rowsWithMissingGroups = [];
374
+
375
+ // add paths and generate parent rows based on `groupFields`
376
+ const groupFields = queryOptions.groupFields;
377
+ if (groupFields.length > 0) {
378
+ rowsWithPaths = rows.reduce((acc, row) => {
379
+ const partialPath = groupFields.map(field => String(row[field]));
380
+ for (let index = 0; index < partialPath.length; index += 1) {
381
+ const value = partialPath[index];
382
+ if (value === undefined) {
383
+ if (index === 0) {
384
+ rowsWithMissingGroups.push((0, _extends2.default)({}, row, {
385
+ group: false
386
+ }));
387
+ }
388
+ return acc;
389
+ }
390
+ const parentPath = partialPath.slice(0, index + 1);
391
+ const strigifiedPath = parentPath.join(',');
392
+ if (!pathsToAutogenerate.has(strigifiedPath)) {
393
+ pathsToAutogenerate.add(strigifiedPath);
394
+ }
395
+ }
396
+ acc.push((0, _extends2.default)({}, row, {
397
+ path: [...partialPath, '']
398
+ }));
399
+ return acc;
400
+ }, []);
401
+ } else {
402
+ rowsWithPaths = rows.map(row => (0, _extends2.default)({}, row, {
403
+ path: ['']
404
+ }));
405
+ }
406
+ const autogeneratedRows = Array.from(pathsToAutogenerate).map(path => {
407
+ const pathArray = path.split(',');
408
+ return {
409
+ id: `auto-generated-parent-${pathArray.join('-')}`,
410
+ path: pathArray.slice(0, pathArray.length),
411
+ group: pathArray.slice(-1)[0]
412
+ };
413
+ });
414
+
415
+ // apply plain filtering
416
+ const filteredRows = getTreeDataFilteredRows([...autogeneratedRows, ...rowsWithPaths, ...rowsWithMissingGroups], queryOptions.filterModel, columnsWithDefaultColDef);
417
+
418
+ // get root row count
419
+ const rootRows = findTreeDataRowChildren(filteredRows, []);
420
+ const rootRowCount = rootRows.length;
421
+ let filteredRowsWithMissingGroups = [];
422
+ let childRows = rootRows;
423
+ if (queryOptions.groupKeys.length === 0) {
424
+ filteredRowsWithMissingGroups = filteredRows.filter(({
425
+ group
426
+ }) => group === false);
427
+ } else {
428
+ childRows = findTreeDataRowChildren(filteredRows, queryOptions.groupKeys);
429
+ }
430
+ let childRowsWithDescendantCounts = childRows.map(row => {
431
+ const descendants = findTreeDataRowChildren(filteredRows, row[pathKey], pathKey, -1, ({
432
+ id
433
+ }) => typeof id !== 'string' || !id.startsWith('auto-generated-parent-'));
434
+ const descendantCount = descendants.length;
435
+ return (0, _extends2.default)({}, row, {
436
+ descendantCount
437
+ });
438
+ });
439
+ if (queryOptions.sortModel) {
440
+ const rowComparator = getRowComparator(queryOptions.sortModel, columnsWithDefaultColDef);
441
+ const sortedMissingGroups = [...filteredRowsWithMissingGroups].sort(rowComparator);
442
+ const sortedChildRows = [...childRowsWithDescendantCounts].sort(rowComparator);
443
+ childRowsWithDescendantCounts = [...sortedMissingGroups, ...sortedChildRows];
444
+ }
445
+ if (queryOptions.paginationModel && queryOptions.groupKeys.length === 0) {
446
+ // Only paginate root rows, grid should refetch root rows when `paginationModel` updates
447
+ const {
448
+ pageSize,
449
+ page
450
+ } = queryOptions.paginationModel;
451
+ if (pageSize < childRowsWithDescendantCounts.length) {
452
+ childRowsWithDescendantCounts = childRowsWithDescendantCounts.slice(page * pageSize, (page + 1) * pageSize);
453
+ }
454
+ }
455
+ return new Promise(resolve => {
456
+ setTimeout(() => {
457
+ resolve({
458
+ rows: childRowsWithDescendantCounts,
459
+ rootRowCount
460
+ });
461
+ }, delay); // simulate network latency
462
+ });
463
+ };
464
+ exports.processRowGroupingRows = processRowGroupingRows;
@@ -11,15 +11,48 @@ var React = _interopRequireWildcard(require("react"));
11
11
  var _lruCache = require("lru-cache");
12
12
  var _xDataGridPro = require("@mui/x-data-grid-pro");
13
13
  var _useDemoData = require("./useDemoData");
14
+ var _commodities = require("../columns/commodities.columns");
15
+ var _employees = require("../columns/employees.columns");
14
16
  var _realDataService = require("../services/real-data-service");
15
17
  var _treeDataGenerator = require("../services/tree-data-generator");
16
18
  var _serverUtils = require("./serverUtils");
17
19
  var _services = require("../services");
20
+ var _useMovieData = require("./useMovieData");
18
21
  const dataCache = new _lruCache.LRUCache({
19
22
  max: 10,
20
23
  ttl: 60 * 5 * 1e3 // 5 minutes
21
24
  });
22
25
  const BASE_URL = exports.BASE_URL = 'https://mui.com/x/api/data-grid';
26
+ const GET_DEFAULT_DATASET_OPTIONS = isRowGrouping => ({
27
+ dataSet: isRowGrouping ? 'Movies' : 'Commodity',
28
+ rowLength: isRowGrouping ? (0, _useMovieData.getMovieRows)().length : 100,
29
+ maxColumns: 6
30
+ });
31
+ const getColumnsFromOptions = options => {
32
+ let columns;
33
+ switch (options.dataSet) {
34
+ case 'Commodity':
35
+ columns = (0, _commodities.getCommodityColumns)(options.editable);
36
+ break;
37
+ case 'Employee':
38
+ columns = (0, _employees.getEmployeeColumns)();
39
+ break;
40
+ case 'Movies':
41
+ columns = (0, _useMovieData.getMovieColumns)();
42
+ break;
43
+ default:
44
+ throw new Error('Unknown dataset');
45
+ }
46
+ if (options.visibleFields) {
47
+ columns = columns.map(col => options.visibleFields?.includes(col.field) ? col : (0, _extends2.default)({}, col, {
48
+ hide: true
49
+ }));
50
+ }
51
+ if (options.maxColumns) {
52
+ columns = columns.slice(0, options.maxColumns);
53
+ }
54
+ return columns;
55
+ };
23
56
  function decodeParams(url) {
24
57
  const params = new URL(url).searchParams;
25
58
  const decodedParams = {};
@@ -50,6 +83,14 @@ const getInitialState = (columns, groupingField) => {
50
83
  };
51
84
  };
52
85
  const defaultColDef = (0, _xDataGridPro.getGridDefaultColumnTypes)();
86
+ function sendEmptyResponse() {
87
+ return new Promise(resolve => {
88
+ resolve({
89
+ rows: [],
90
+ rowCount: 0
91
+ });
92
+ });
93
+ }
53
94
  const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail) => {
54
95
  const [data, setData] = React.useState();
55
96
  const [index, setIndex] = React.useState(0);
@@ -59,9 +100,11 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail) => {
59
100
  shouldRequestsFailRef.current = shouldRequestsFail;
60
101
  }
61
102
  }, [shouldRequestsFail]);
62
- const options = (0, _extends2.default)({}, _serverUtils.DEFAULT_DATASET_OPTIONS, dataSetOptions);
103
+ const isRowGrouping = dataSetOptions?.rowGrouping ?? false;
104
+ const options = (0, _extends2.default)({}, GET_DEFAULT_DATASET_OPTIONS(isRowGrouping), dataSetOptions);
105
+ const isTreeData = options.treeData?.groupingField != null;
63
106
  const columns = React.useMemo(() => {
64
- return (0, _useDemoData.getColumnsFromOptions)({
107
+ return getColumnsFromOptions({
65
108
  dataSet: options.dataSet,
66
109
  editable: options.editable,
67
110
  maxColumns: options.maxColumns,
@@ -70,7 +113,6 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail) => {
70
113
  }, [options.dataSet, options.editable, options.maxColumns, options.visibleFields]);
71
114
  const initialState = React.useMemo(() => getInitialState(columns, options.treeData?.groupingField), [columns, options.treeData?.groupingField]);
72
115
  const columnsWithDefaultColDef = React.useMemo(() => columns.map(column => (0, _extends2.default)({}, defaultColDef[column.type || 'string'], column)), [columns]);
73
- const isTreeData = options.treeData?.groupingField != null;
74
116
  const getGroupKey = React.useMemo(() => {
75
117
  if (isTreeData) {
76
118
  return row => row[options.treeData.groupingField];
@@ -94,6 +136,15 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail) => {
94
136
  setData(newData);
95
137
  return undefined;
96
138
  }
139
+ if (options.dataSet === 'Movies') {
140
+ const rowsData = {
141
+ rows: (0, _useMovieData.getMovieRows)(),
142
+ columns
143
+ };
144
+ setData(rowsData);
145
+ dataCache.set(cacheKey, rowsData);
146
+ return undefined;
147
+ }
97
148
  let active = true;
98
149
  (async () => {
99
150
  let rowData;
@@ -125,13 +176,8 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail) => {
125
176
  };
126
177
  }, [columns, isTreeData, options.rowLength, options.treeData?.maxDepth, options.treeData?.groupingField, options.treeData?.averageChildren, options.dataSet, options.maxColumns, index]);
127
178
  const fetchRows = React.useCallback(async requestUrl => {
128
- if (!data || !requestUrl) {
129
- return new Promise(resolve => {
130
- resolve({
131
- rows: [],
132
- rowCount: 0
133
- });
134
- });
179
+ if (!requestUrl || !data?.rows) {
180
+ return sendEmptyResponse();
135
181
  }
136
182
  const params = decodeParams(requestUrl);
137
183
  const verbose = serverOptions?.verbose ?? true;
@@ -159,11 +205,22 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail) => {
159
205
  setTimeout(() => reject(new Error('Could not fetch the data')), delay);
160
206
  });
161
207
  }
162
- if (isTreeData /* || TODO: `isRowGrouping` */) {
208
+ if (isTreeData) {
209
+ const {
210
+ rows,
211
+ rootRowCount
212
+ } = await (0, _serverUtils.processTreeDataRows)(data?.rows ?? [], params, serverOptionsWithDefault, columnsWithDefaultColDef);
213
+ getRowsResponse = {
214
+ rows: rows.slice().map(row => (0, _extends2.default)({}, row, {
215
+ path: undefined
216
+ })),
217
+ rowCount: rootRowCount
218
+ };
219
+ } else if (isRowGrouping) {
163
220
  const {
164
221
  rows,
165
222
  rootRowCount
166
- } = await (0, _serverUtils.processTreeDataRows)(data.rows, params, serverOptionsWithDefault, columnsWithDefaultColDef);
223
+ } = await (0, _serverUtils.processRowGroupingRows)(data?.rows ?? [], params, serverOptionsWithDefault, columnsWithDefaultColDef);
167
224
  getRowsResponse = {
168
225
  rows: rows.slice().map(row => (0, _extends2.default)({}, row, {
169
226
  path: undefined
@@ -171,12 +228,11 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail) => {
171
228
  rowCount: rootRowCount
172
229
  };
173
230
  } else {
174
- // plain data
175
231
  const {
176
232
  returnedRows,
177
233
  nextCursor,
178
234
  totalRowCount
179
- } = await (0, _serverUtils.loadServerRows)(data.rows, (0, _extends2.default)({}, params, params.paginationModel), serverOptionsWithDefault, columnsWithDefaultColDef);
235
+ } = await (0, _serverUtils.loadServerRows)(data?.rows ?? [], (0, _extends2.default)({}, params, params.paginationModel), serverOptionsWithDefault, columnsWithDefaultColDef);
180
236
  getRowsResponse = {
181
237
  rows: returnedRows,
182
238
  rowCount: totalRowCount,
@@ -191,10 +247,10 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail) => {
191
247
  }
192
248
  resolve(getRowsResponse);
193
249
  });
194
- }, [data, serverOptions?.verbose, serverOptions?.minDelay, serverOptions?.maxDelay, serverOptions?.useCursorPagination, isTreeData, columnsWithDefaultColDef]);
250
+ }, [data, serverOptions?.verbose, serverOptions?.minDelay, serverOptions?.maxDelay, serverOptions?.useCursorPagination, isTreeData, columnsWithDefaultColDef, isRowGrouping]);
195
251
  return {
196
252
  columns: columnsWithDefaultColDef,
197
- initialState,
253
+ initialState: options.dataSet === 'Movies' ? {} : initialState,
198
254
  getGroupKey,
199
255
  getChildrenCount,
200
256
  fetchRows,
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.useMovieData = void 0;
6
+ exports.useMovieData = exports.getMovieRows = exports.getMovieColumns = void 0;
7
7
  const currencyFormatter = new Intl.NumberFormat('en-US', {
8
8
  style: 'currency',
9
9
  currency: 'USD',
@@ -496,6 +496,10 @@ const ROWS = [{
496
496
  name: 'Randy Newman'
497
497
  }
498
498
  }];
499
+ const getMovieColumns = () => COLUMNS;
500
+ exports.getMovieColumns = getMovieColumns;
501
+ const getMovieRows = () => ROWS;
502
+ exports.getMovieRows = getMovieRows;
499
503
  const useMovieData = () => {
500
504
  return {
501
505
  rows: ROWS,
@@ -12,8 +12,13 @@ var _xDataGridPro = require("@mui/x-data-grid-pro");
12
12
  var _internals = require("@mui/x-data-grid/internals");
13
13
  var _useDemoData = require("./useDemoData");
14
14
  var _serverUtils = require("./serverUtils");
15
+ const DEFAULT_DATASET_OPTIONS = {
16
+ dataSet: 'Commodity',
17
+ rowLength: 100,
18
+ maxColumns: 6
19
+ };
15
20
  const createFakeServer = (dataSetOptions, serverOptions) => {
16
- const dataSetOptionsWithDefault = (0, _extends2.default)({}, _serverUtils.DEFAULT_DATASET_OPTIONS, dataSetOptions);
21
+ const dataSetOptionsWithDefault = (0, _extends2.default)({}, DEFAULT_DATASET_OPTIONS, dataSetOptions);
17
22
  const serverOptionsWithDefault = (0, _extends2.default)({}, _serverUtils.DEFAULT_SERVER_OPTIONS, serverOptions);
18
23
  const columns = (0, _useDemoData.getColumnsFromOptions)(dataSetOptionsWithDefault);
19
24
  const initialState = (0, _useDemoData.getInitialState)(dataSetOptionsWithDefault, columns);
package/node/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @mui/x-data-grid-generator v7.20.0
2
+ * @mui/x-data-grid-generator v7.22.0
3
3
  *
4
4
  * @license MUI X Commercial
5
5
  * This source code is licensed under the commercial license found in the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mui/x-data-grid-generator",
3
- "version": "7.20.0",
3
+ "version": "7.22.0",
4
4
  "description": "Generate fake data for demo purposes only.",
5
5
  "author": "MUI Team",
6
6
  "main": "./node/index.js",
@@ -27,7 +27,7 @@
27
27
  "chance": "^1.1.12",
28
28
  "clsx": "^2.1.1",
29
29
  "lru-cache": "^11.0.1",
30
- "@mui/x-data-grid-premium": "7.20.0"
30
+ "@mui/x-data-grid-premium": "7.22.0"
31
31
  },
32
32
  "peerDependencies": {
33
33
  "@emotion/react": "^11.9.0",