@mui/x-data-grid-generator 8.13.1 → 8.14.1

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,7 +4,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.processTreeDataRows = exports.processRowGroupingRows = exports.loadServerRows = exports.disableDelay = exports.DEFAULT_SERVER_OPTIONS = void 0;
7
+ exports.processTreeDataRows = exports.processRowGroupingRows = exports.processPivotingRows = exports.loadServerRows = exports.disableDelay = exports.DEFAULT_SERVER_OPTIONS = void 0;
8
8
  var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
9
9
  var _xDataGridPremium = require("@mui/x-data-grid-premium");
10
10
  var _randomGenerator = require("../services/random-generator");
@@ -34,7 +34,7 @@ const getRowComparator = (sortModel, aggregationModel, columnsWithDefaultColDef)
34
34
  return comparator;
35
35
  }
36
36
  const sortOperators = sortModel.map(sortItem => {
37
- const columnField = aggregationModel?.[sortItem.field] ? `${sortItem.field}Aggregate` : sortItem.field;
37
+ const columnField = sortItem.field;
38
38
  const colDef = columnsWithDefaultColDef.find(({
39
39
  field
40
40
  }) => field === sortItem.field);
@@ -194,7 +194,7 @@ const applyAggregation = (aggregationModel, colDefs, rows, groupId = 'root') =>
194
194
  return;
195
195
  }
196
196
  const values = rows.map(row => row[field]);
197
- aggregateValues[`${field}Aggregate`] = aggregationFunction.apply({
197
+ aggregateValues[field] = aggregationFunction.apply({
198
198
  values,
199
199
  field,
200
200
  groupId
@@ -202,6 +202,49 @@ const applyAggregation = (aggregationModel, colDefs, rows, groupId = 'root') =>
202
202
  });
203
203
  return aggregateValues;
204
204
  };
205
+ const generateParentRows = pathsToAutogenerate => {
206
+ return Array.from(pathsToAutogenerate).map(path => {
207
+ const pathArray = path.split(',');
208
+ return {
209
+ id: `auto-generated-parent-${pathArray.join('-')}`,
210
+ path: pathArray.slice(0, pathArray.length),
211
+ group: pathArray.slice(-1)[0]
212
+ };
213
+ });
214
+ };
215
+
216
+ /**
217
+ * Computes pivot aggregations for given pivot column keys
218
+ */
219
+ const computePivotAggregations = (pivotColumnKeys, rows, visibleValues, columnTypeMap, groupId = 'root', columnGroupIdSeparator = '>->') => {
220
+ const pivotAggregations = {};
221
+ pivotColumnKeys.forEach(pivotColumnKey => {
222
+ const values = rows.map(row => row[pivotColumnKey]).filter(v => v !== undefined);
223
+ if (values.length > 0) {
224
+ // Find the corresponding pivot value configuration
225
+ const pivotValueConfig = visibleValues.find(v => {
226
+ if (visibleValues.length === 0 || !visibleValues[0].field) {
227
+ return v.field === pivotColumnKey;
228
+ }
229
+ // For pivot columns with column grouping, extract the value field from the column name
230
+ const columnParts = pivotColumnKey.split(columnGroupIdSeparator);
231
+ return columnParts[columnParts.length - 1] === v.field;
232
+ });
233
+ if (pivotValueConfig) {
234
+ const availableAggregationFunctions = getAvailableAggregationFunctions(columnTypeMap.get(pivotValueConfig.field));
235
+ const aggregationFunction = availableAggregationFunctions.get(pivotValueConfig.aggFunc);
236
+ if (aggregationFunction) {
237
+ pivotAggregations[pivotColumnKey] = aggregationFunction.apply({
238
+ values,
239
+ field: pivotValueConfig.field,
240
+ groupId
241
+ });
242
+ }
243
+ }
244
+ }
245
+ });
246
+ return pivotAggregations;
247
+ };
205
248
 
206
249
  /**
207
250
  * Simulates server data loading
@@ -444,7 +487,10 @@ const processRowGroupingRows = (rows, queryOptions, serverOptions, columnsWithDe
444
487
  field: f
445
488
  }) => f === field);
446
489
  if (colDef?.groupingValueGetter) {
447
- return colDef.groupingValueGetter(row[field], row, colDef, apiRef);
490
+ return String(colDef.groupingValueGetter(row[field], row, colDef, apiRef));
491
+ }
492
+ if (colDef?.valueGetter) {
493
+ return String(colDef.valueGetter(row[field], row, colDef, apiRef));
448
494
  }
449
495
  return String(row[field]);
450
496
  });
@@ -474,14 +520,7 @@ const processRowGroupingRows = (rows, queryOptions, serverOptions, columnsWithDe
474
520
  path: ['']
475
521
  }));
476
522
  }
477
- const autogeneratedRows = Array.from(pathsToAutogenerate).map(path => {
478
- const pathArray = path.split(',');
479
- return {
480
- id: `auto-generated-parent-${pathArray.join('-')}`,
481
- path: pathArray.slice(0, pathArray.length),
482
- group: pathArray.slice(-1)[0]
483
- };
484
- });
523
+ const autogeneratedRows = generateParentRows(pathsToAutogenerate);
485
524
 
486
525
  // apply plain filtering
487
526
  const filteredRows = getTreeDataFilteredRows([...autogeneratedRows, ...rowsWithPaths, ...rowsWithMissingGroups], queryOptions.filterModel, columnsWithDefaultColDef);
@@ -543,4 +582,272 @@ const processRowGroupingRows = (rows, queryOptions, serverOptions, columnsWithDe
543
582
  }, delay); // simulate network latency
544
583
  });
545
584
  };
546
- exports.processRowGroupingRows = processRowGroupingRows;
585
+
586
+ /**
587
+ * Simulates server data for pivoting feature
588
+ */
589
+ exports.processRowGroupingRows = processRowGroupingRows;
590
+ const processPivotingRows = (rows, queryOptions, serverOptions, columnsWithDefaultColDef) => {
591
+ const {
592
+ minDelay = 100,
593
+ maxDelay = 300
594
+ } = serverOptions;
595
+ if (maxDelay < minDelay) {
596
+ throw new Error('serverOptions.minDelay is larger than serverOptions.maxDelay ');
597
+ }
598
+ if (!queryOptions.pivotModel) {
599
+ throw new Error('queryOptions.pivotModel must be defined to compute pivoting data');
600
+ }
601
+ const delay = (0, _randomGenerator.randomInt)(minDelay, maxDelay);
602
+ const {
603
+ pivotModel
604
+ } = queryOptions;
605
+ const visibleColumns = pivotModel.columns.filter(column => !column.hidden);
606
+ const visibleRows = pivotModel.rows.filter(row => !row.hidden);
607
+ const visibleValues = pivotModel.values.filter(value => !value.hidden);
608
+
609
+ // Create column lookup map for O(1) access
610
+ const columnLookup = new Map();
611
+ for (const column of columnsWithDefaultColDef) {
612
+ columnLookup.set(column.field, column);
613
+ }
614
+ if (visibleRows.length === 0) {
615
+ return new Promise(resolve => {
616
+ setTimeout(() => {
617
+ resolve({
618
+ rows: [],
619
+ rootRowCount: 0,
620
+ pivotColumns: []
621
+ });
622
+ }, delay); // simulate network latency
623
+ });
624
+ }
625
+
626
+ // Apply filtering if provided
627
+ let filteredRows = rows;
628
+ if (queryOptions.filterModel) {
629
+ filteredRows = getFilteredRows(rows, queryOptions.filterModel, columnsWithDefaultColDef);
630
+ }
631
+
632
+ // Create pivot columns based on the pivot model
633
+ const columnGroupIdSeparator = '>->';
634
+ const pivotColumns = [];
635
+ const uniqueColumnGroups = new Map();
636
+
637
+ // Generate pivot column names based on pivot model columns
638
+ if (visibleColumns.length > 0 || visibleValues.length > 0) {
639
+ // Create column groups based on unique combinations of row values
640
+
641
+ filteredRows = filteredRows.map(row => {
642
+ const columnGroupPath = [];
643
+ const updatedRow = (0, _extends2.default)({}, row);
644
+ for (let i = 0; i < visibleColumns.length; i += 1) {
645
+ const {
646
+ field: colGroupField
647
+ } = visibleColumns[i];
648
+ const column = columnLookup.get(colGroupField);
649
+ if (!column) {
650
+ continue;
651
+ }
652
+ if (!column.valueGetter && !column.valueFormatter) {
653
+ columnGroupPath.push(row[colGroupField]);
654
+ } else {
655
+ columnGroupPath.push({
656
+ [colGroupField]: column.valueGetter ? column.valueGetter(row[colGroupField], row, column, apiRef) : row[colGroupField]
657
+ });
658
+ }
659
+ }
660
+
661
+ // Create pivot columns for each value field within this column group
662
+ visibleValues.forEach(pivotValue => {
663
+ let valueKey = pivotValue.field;
664
+ const column = columnLookup.get(valueKey);
665
+ if (!column) {
666
+ return;
667
+ }
668
+ if (visibleColumns.length > 0) {
669
+ const columnGroupPathValue = columnGroupPath.map((path, pathIndex) => {
670
+ const value = path[visibleColumns[pathIndex].field];
671
+ if (value instanceof Date) {
672
+ return value.toLocaleDateString();
673
+ }
674
+ return value;
675
+ });
676
+ valueKey = `${columnGroupPathValue.join(columnGroupIdSeparator)}${columnGroupIdSeparator}${pivotValue.field}`;
677
+ }
678
+ uniqueColumnGroups.set(valueKey, [...columnGroupPath, pivotValue.field]);
679
+ updatedRow[valueKey] = column.valueGetter ? column.valueGetter(row[pivotValue.field], row, column, apiRef) : row[pivotValue.field];
680
+ });
681
+ return updatedRow;
682
+ });
683
+
684
+ // Convert uniqueColumnGroups to the pivot column structure
685
+ const columnGroupMap = new Map();
686
+ uniqueColumnGroups.forEach(columnGroupPath => {
687
+ let currentLevel = columnGroupMap;
688
+ let currentPath = '';
689
+ for (let i = 0; i < columnGroupPath.length - 1; i += 1) {
690
+ const groupValue = columnGroupPath[i];
691
+ let groupKey = typeof groupValue === 'string' ? groupValue : groupValue[visibleColumns[i].field];
692
+ if (groupKey instanceof Date) {
693
+ groupKey = groupKey.toLocaleDateString();
694
+ }
695
+ const pathKey = currentPath ? `${currentPath}-${groupKey}` : groupKey;
696
+ if (!currentLevel.has(groupKey)) {
697
+ currentLevel.set(groupKey, {
698
+ group: groupValue,
699
+ children: new Map()
700
+ });
701
+ }
702
+ const group = currentLevel.get(groupKey);
703
+ currentLevel = group.children;
704
+ currentPath = pathKey;
705
+ }
706
+ });
707
+ const convertMapToArray = map => {
708
+ return Array.from(map.entries()).map(([key, group]) => (0, _extends2.default)({
709
+ key,
710
+ group: group.group
711
+ }, group.children.size > 0 ? {
712
+ children: convertMapToArray(group.children)
713
+ } : {}));
714
+ };
715
+ pivotColumns.push(...convertMapToArray(columnGroupMap));
716
+ }
717
+ const pivotColumnKeys = Array.from(uniqueColumnGroups.keys());
718
+
719
+ // Add paths and generate parent rows based on `visibleRows` (pivot row fields)
720
+ const pathsToAutogenerate = new Set();
721
+ let rowsWithPaths = filteredRows;
722
+ const rowsWithMissingGroups = [];
723
+ if (visibleRows.length > 0) {
724
+ rowsWithPaths = filteredRows.reduce((acc, row) => {
725
+ const partialPath = visibleRows.map(pivotRow => {
726
+ const field = pivotRow.field;
727
+ const colDef = columnLookup.get(field);
728
+ if (colDef?.groupingValueGetter) {
729
+ return String(colDef.groupingValueGetter(row[field], row, colDef, apiRef));
730
+ }
731
+ if (colDef?.valueGetter) {
732
+ return String(colDef.valueGetter(row[field], row, colDef, apiRef));
733
+ }
734
+ return String(row[field]);
735
+ });
736
+ for (let index = 0; index < partialPath.length; index += 1) {
737
+ const value = partialPath[index];
738
+ if (value === undefined) {
739
+ if (index === 0) {
740
+ rowsWithMissingGroups.push((0, _extends2.default)({}, row, {
741
+ group: false
742
+ }));
743
+ }
744
+ return acc;
745
+ }
746
+ const parentPath = partialPath.slice(0, index + 1);
747
+ const stringifiedPath = parentPath.join(',');
748
+ if (!pathsToAutogenerate.has(stringifiedPath)) {
749
+ pathsToAutogenerate.add(stringifiedPath);
750
+ }
751
+ }
752
+ acc.push((0, _extends2.default)({}, row, {
753
+ path: [...partialPath, '']
754
+ }));
755
+ return acc;
756
+ }, []);
757
+ } else {
758
+ rowsWithPaths = filteredRows.map(row => (0, _extends2.default)({}, row, {
759
+ path: ['']
760
+ }));
761
+ }
762
+ const autogeneratedRows = generateParentRows(pathsToAutogenerate);
763
+
764
+ // Apply tree data filtering to include missing parents and children
765
+ const filteredRowsWithGroups = getTreeDataFilteredRows([...autogeneratedRows, ...rowsWithPaths, ...rowsWithMissingGroups], queryOptions.filterModel, columnsWithDefaultColDef);
766
+
767
+ // Get root rows
768
+ const rootRows = findTreeDataRowChildren(filteredRowsWithGroups, []);
769
+ const rootRowCount = rootRows.length;
770
+ let filteredRowsWithMissingGroups = [];
771
+ let childRows = rootRows;
772
+ if (queryOptions.groupKeys?.length === 0) {
773
+ filteredRowsWithMissingGroups = filteredRowsWithGroups.filter(({
774
+ group
775
+ }) => group === false);
776
+ } else {
777
+ childRows = findTreeDataRowChildren(filteredRowsWithGroups, queryOptions.groupKeys || []);
778
+ }
779
+ const columnTypeMap = new Map();
780
+ for (const column of columnsWithDefaultColDef) {
781
+ if (column.type) {
782
+ columnTypeMap.set(column.field, column.type);
783
+ }
784
+ }
785
+ let childRowsWithDescendantCounts = childRows.map(row => {
786
+ const descendants = findTreeDataRowChildren(filteredRowsWithGroups, row.path, 'path', -1, ({
787
+ id
788
+ }) => typeof id !== 'string' || !id.startsWith('auto-generated-parent-'));
789
+ const descendantCount = descendants.length;
790
+ if (descendantCount > 0) {
791
+ // Parent row, compute aggregation for both regular aggregation model and pivot values
792
+ const regularAggregation = applyAggregation(queryOptions.pivotModel.values.map(value => ({
793
+ [value.field]: value.aggFunc
794
+ })), columnsWithDefaultColDef, descendants, row.id);
795
+
796
+ // Compute aggregations for each pivot column
797
+ const pivotAggregations = computePivotAggregations(pivotColumnKeys, descendants, visibleValues, columnTypeMap, row.id, columnGroupIdSeparator);
798
+ return (0, _extends2.default)({}, row, {
799
+ descendantCount
800
+ }, regularAggregation, pivotAggregations);
801
+ }
802
+ return (0, _extends2.default)({}, row, {
803
+ descendantCount
804
+ });
805
+ });
806
+
807
+ // Apply sorting if provided
808
+ if (queryOptions.sortModel) {
809
+ const rowComparator = getRowComparator(queryOptions.sortModel, {}, pivotColumnKeys.map(key => ({
810
+ field: key,
811
+ type: 'number',
812
+ sortComparator: _xDataGridPremium.gridStringOrNumberComparator
813
+ })));
814
+ const sortedMissingGroups = [...filteredRowsWithMissingGroups].sort(rowComparator);
815
+ const sortedChildRows = [...childRowsWithDescendantCounts].sort(rowComparator);
816
+ childRowsWithDescendantCounts = [...sortedMissingGroups, ...sortedChildRows];
817
+ }
818
+
819
+ // Apply pagination if provided
820
+ if (queryOptions.paginationModel && queryOptions.groupKeys?.length === 0) {
821
+ // Only paginate root rows, grid should refetch root rows when `paginationModel` updates
822
+ const {
823
+ pageSize,
824
+ page
825
+ } = queryOptions.paginationModel;
826
+ if (pageSize < childRowsWithDescendantCounts.length) {
827
+ childRowsWithDescendantCounts = childRowsWithDescendantCounts.slice(page * pageSize, (page + 1) * pageSize);
828
+ }
829
+ }
830
+
831
+ // Compute aggregate row if pivot values are provided
832
+ let aggregateRow;
833
+ if (visibleValues.length > 0) {
834
+ const regularAggregation = applyAggregation(visibleValues.map(value => ({
835
+ [value.field]: value.aggFunc
836
+ })), columnsWithDefaultColDef, filteredRowsWithGroups);
837
+
838
+ // Compute aggregations for each pivot column for the entire dataset
839
+ const pivotAggregations = computePivotAggregations(pivotColumnKeys, filteredRowsWithGroups.filter(row => typeof row.id !== 'string' || !row.id.startsWith('auto-generated-parent-')), visibleValues, columnTypeMap, 'root', columnGroupIdSeparator);
840
+ aggregateRow = (0, _extends2.default)({}, regularAggregation, pivotAggregations);
841
+ }
842
+ return new Promise(resolve => {
843
+ setTimeout(() => {
844
+ resolve({
845
+ rows: childRowsWithDescendantCounts,
846
+ rootRowCount,
847
+ pivotColumns,
848
+ aggregateRow
849
+ });
850
+ }, delay); // simulate network latency
851
+ });
852
+ };
853
+ exports.processPivotingRows = processPivotingRows;
@@ -23,7 +23,7 @@ interface UseMockServerOptions {
23
23
  visibleFields?: string[];
24
24
  editable?: boolean;
25
25
  treeData?: AddPathToDemoDataOptions;
26
- rowGrouping?: boolean;
26
+ derivedColumns?: boolean;
27
27
  }
28
28
  export declare const useMockServer: <T extends GridGetRowsResponse>(dataSetOptions?: Partial<UseMockServerOptions>, serverOptions?: ServerOptions & {
29
29
  verbose?: boolean;
@@ -24,11 +24,11 @@ const dataCache = new _lruCache.LRUCache({
24
24
  ttl: 60 * 5 * 1e3 // 5 minutes
25
25
  });
26
26
  const BASE_URL = exports.BASE_URL = 'https://mui.com/x/api/data-grid';
27
- const GET_DEFAULT_DATASET_OPTIONS = isRowGrouping => ({
28
- dataSet: isRowGrouping ? 'Movies' : 'Commodity',
29
- rowLength: isRowGrouping ? (0, _useMovieData.getMovieRows)().length : 100,
27
+ const GET_DEFAULT_DATASET_OPTIONS = {
28
+ dataSet: 'Commodity',
29
+ rowLength: 100,
30
30
  maxColumns: 6
31
- });
31
+ };
32
32
  const getColumnsFromOptions = options => {
33
33
  let columns;
34
34
  switch (options.dataSet) {
@@ -52,6 +52,28 @@ const getColumnsFromOptions = options => {
52
52
  if (options.maxColumns) {
53
53
  columns = columns.slice(0, options.maxColumns);
54
54
  }
55
+ if (options.derivedColumns) {
56
+ columns = columns.reduce((acc, col) => {
57
+ acc.push(col);
58
+ if (col.type === 'date' || col.type === 'dateTime') {
59
+ acc.push({
60
+ type: 'date',
61
+ field: `${col.field}-year`,
62
+ generateData: row => new Date(row[col.field].getFullYear(), 0, 1),
63
+ editable: false,
64
+ derivedFrom: col.field
65
+ });
66
+ acc.push({
67
+ type: 'date',
68
+ field: `${col.field}-month`,
69
+ generateData: row => new Date(row[col.field].getFullYear(), row[col.field].getMonth(), 1),
70
+ editable: false,
71
+ derivedFrom: col.field
72
+ });
73
+ }
74
+ return acc;
75
+ }, []);
76
+ }
55
77
  return columns;
56
78
  };
57
79
  function decodeParams(url) {
@@ -102,19 +124,20 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail, nested
102
124
  shouldRequestsFailRef.current = shouldRequestsFail;
103
125
  }
104
126
  }, [shouldRequestsFail]);
105
- const isRowGrouping = dataSetOptions?.rowGrouping ?? false;
106
- const options = (0, _extends2.default)({}, GET_DEFAULT_DATASET_OPTIONS(isRowGrouping), dataSetOptions);
127
+ const options = (0, _extends2.default)({}, GET_DEFAULT_DATASET_OPTIONS, dataSetOptions);
107
128
  const isTreeData = options.treeData?.groupingField != null;
108
129
  const columns = React.useMemo(() => {
109
130
  return getColumnsFromOptions({
110
131
  dataSet: options.dataSet,
111
132
  editable: options.editable,
112
133
  maxColumns: options.maxColumns,
113
- visibleFields: options.visibleFields
134
+ visibleFields: options.visibleFields,
135
+ derivedColumns: options.derivedColumns
114
136
  });
115
- }, [options.dataSet, options.editable, options.maxColumns, options.visibleFields]);
137
+ }, [options.dataSet, options.editable, options.maxColumns, options.visibleFields, options.derivedColumns]);
116
138
  const initialState = React.useMemo(() => getInitialState(columns, options.treeData?.groupingField), [columns, options.treeData?.groupingField]);
117
- const columnsWithDefaultColDef = React.useMemo(() => columns.map(column => (0, _extends2.default)({}, defaultColDef[column.type || 'string'], column)), [columns]);
139
+ const columnsWithDerivedColDef = React.useMemo(() => columns.map(column => (0, _extends2.default)({}, defaultColDef[column.type || 'string'], column)), [columns]);
140
+ const columnsWithDefaultColDef = React.useMemo(() => columnsWithDerivedColDef.filter(column => !column.derivedFrom), [columnsWithDerivedColDef]);
118
141
  const getGroupKey = React.useMemo(() => {
119
142
  if (isTreeData) {
120
143
  return row => row[options.treeData.groupingField];
@@ -153,7 +176,7 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail, nested
153
176
  (async () => {
154
177
  let rowData;
155
178
  const rowLength = options.rowLength;
156
- if (rowLength > 1000) {
179
+ if (rowLength > 1000 && !options.derivedColumns) {
157
180
  rowData = await (0, _realDataService.getRealGridData)(1000, columns);
158
181
  rowData = await (0, _useDemoData.extrapolateSeed)(rowLength, rowData);
159
182
  } else {
@@ -179,9 +202,25 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail, nested
179
202
  return () => {
180
203
  active = false;
181
204
  };
182
- }, [columns, isTreeData, options.rowLength, options.treeData?.maxDepth, options.treeData?.groupingField, options.treeData?.averageChildren, options.dataSet, options.maxColumns, index]);
205
+ }, [columns, isTreeData, options.rowLength, options.treeData?.maxDepth, options.treeData?.groupingField, options.treeData?.averageChildren, options.dataSet, options.maxColumns, options.derivedColumns, index]);
183
206
  const fetchRows = React.useCallback(async requestUrl => {
184
- if (!requestUrl || !isDataReady) {
207
+ let dataDelay = 0;
208
+ const waitInterval = 10;
209
+ const waitTimeout = 500 * waitInterval; // 5 seconds
210
+ // wait until data is ready
211
+ while (dataRef.current === null) {
212
+ // prevent infinite loop with a timeout
213
+ if (dataDelay > waitTimeout) {
214
+ return sendEmptyResponse();
215
+ }
216
+
217
+ // eslint-disable-next-line no-await-in-loop
218
+ await new Promise(resolve => {
219
+ setTimeout(resolve, waitInterval);
220
+ });
221
+ dataDelay += waitInterval;
222
+ }
223
+ if (!requestUrl) {
185
224
  return sendEmptyResponse();
186
225
  }
187
226
  const params = decodeParams(requestUrl);
@@ -198,10 +237,9 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail, nested
198
237
  useCursorPagination: serverOptions?.useCursorPagination ?? _serverUtils.DEFAULT_SERVER_OPTIONS.useCursorPagination
199
238
  };
200
239
  if (shouldRequestsFailRef.current) {
201
- const {
202
- minDelay,
203
- maxDelay
204
- } = serverOptionsWithDefault;
240
+ // substract the delay made by waiting for data to be ready
241
+ const minDelay = Math.max(0, serverOptionsWithDefault.minDelay - dataDelay);
242
+ const maxDelay = Math.max(0, serverOptionsWithDefault.maxDelay - dataDelay);
205
243
  const delay = (0, _services.randomInt)(minDelay, maxDelay);
206
244
  return new Promise((_, reject) => {
207
245
  if (verbose) {
@@ -224,7 +262,20 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail, nested
224
262
  }, aggregateRow ? {
225
263
  aggregateRow
226
264
  } : {});
227
- } else if (isRowGrouping) {
265
+ } else if (typeof params.pivotModel === 'object' && params.pivotModel.columns && params.pivotModel.rows && params.pivotModel.values) {
266
+ const {
267
+ rows,
268
+ rootRowCount,
269
+ pivotColumns,
270
+ aggregateRow
271
+ } = await (0, _serverUtils.processPivotingRows)(dataRef.current?.rows ?? [], params, serverOptionsWithDefault, columnsWithDerivedColDef);
272
+ getRowsResponse = {
273
+ rows: rows.slice(),
274
+ rowCount: rootRowCount,
275
+ pivotColumns,
276
+ aggregateRow
277
+ };
278
+ } else if (params.groupFields && params.groupFields.length > 0) {
228
279
  const {
229
280
  rows,
230
281
  rootRowCount,
@@ -261,7 +312,7 @@ const useMockServer = (dataSetOptions, serverOptions, shouldRequestsFail, nested
261
312
  }
262
313
  resolve(getRowsResponse);
263
314
  });
264
- }, [dataRef, isDataReady, serverOptions?.verbose, serverOptions?.minDelay, serverOptions?.maxDelay, serverOptions?.useCursorPagination, isTreeData, columnsWithDefaultColDef, nestedPagination, isRowGrouping]);
315
+ }, [dataRef, serverOptions?.verbose, serverOptions?.minDelay, serverOptions?.maxDelay, serverOptions?.useCursorPagination, isTreeData, columnsWithDefaultColDef, columnsWithDerivedColDef, nestedPagination]);
265
316
  const editRow = React.useCallback(async (rowId, updatedRow) => {
266
317
  return new Promise((resolve, reject) => {
267
318
  const minDelay = serverOptions?.minDelay ?? _serverUtils.DEFAULT_SERVER_OPTIONS.minDelay;
@@ -56,6 +56,7 @@ export declare const createFakeServer: (dataSetOptions?: Partial<UseDemoDataOpti
56
56
  generateData?: (row: any, context: import("../index.js").GridDataGeneratorContext) => any;
57
57
  dataGeneratorUniquenessEnabled?: boolean;
58
58
  hide?: boolean;
59
+ derivedFrom?: string;
59
60
  } | {
60
61
  type: "actions";
61
62
  getActions: (params: import("@mui/x-data-grid").GridRowParams<any>) => readonly React.ReactElement<import("@mui/x-data-grid").GridActionsCellItemProps>[];
@@ -109,6 +110,7 @@ export declare const createFakeServer: (dataSetOptions?: Partial<UseDemoDataOpti
109
110
  generateData?: (row: any, context: import("../index.js").GridDataGeneratorContext) => any;
110
111
  dataGeneratorUniquenessEnabled?: boolean;
111
112
  hide?: boolean;
113
+ derivedFrom?: string;
112
114
  } | {
113
115
  type: "singleSelect";
114
116
  valueOptions?: import("@mui/x-data-grid").ValueOptions[] | ((params: import("@mui/x-data-grid").GridValueOptionsParams<any>) => Array<import("@mui/x-data-grid").ValueOptions>) | undefined;
@@ -164,6 +166,7 @@ export declare const createFakeServer: (dataSetOptions?: Partial<UseDemoDataOpti
164
166
  generateData?: (row: any, context: import("../index.js").GridDataGeneratorContext) => any;
165
167
  dataGeneratorUniquenessEnabled?: boolean;
166
168
  hide?: boolean;
169
+ derivedFrom?: string;
167
170
  })[];
168
171
  initialState: {
169
172
  columns: {
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @mui/x-data-grid-generator v8.13.1
2
+ * @mui/x-data-grid-generator v8.14.1
3
3
  *
4
4
  * @license UNLICENSED
5
5
  * This source code is licensed under the UNLICENSED license found in the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mui/x-data-grid-generator",
3
- "version": "8.13.1",
3
+ "version": "8.14.1",
4
4
  "author": "MUI Team",
5
5
  "description": "Generate fake data for demo purposes only.",
6
6
  "license": "UNLICENSED",
@@ -25,10 +25,10 @@
25
25
  "chance": "^1.1.13",
26
26
  "clsx": "^2.1.1",
27
27
  "lru-cache": "^11.2.2",
28
- "@mui/x-data-grid": "8.13.1",
29
- "@mui/x-internals": "8.13.1",
30
- "@mui/x-data-grid-pro": "8.13.1",
31
- "@mui/x-data-grid-premium": "8.13.1"
28
+ "@mui/x-data-grid": "8.14.1",
29
+ "@mui/x-data-grid-pro": "8.14.1",
30
+ "@mui/x-data-grid-premium": "8.14.1",
31
+ "@mui/x-internals": "8.14.0"
32
32
  },
33
33
  "peerDependencies": {
34
34
  "@emotion/react": "^11.9.0",
@@ -1,3 +1,3 @@
1
1
  import * as React from 'react';
2
2
  import { GridRenderCellParams } from '@mui/x-data-grid-premium';
3
- export declare function renderProgress(params: GridRenderCellParams<any, number, any>): "" | React.JSX.Element | null;
3
+ export declare function renderProgress(params: GridRenderCellParams<any, number, any>): string | React.JSX.Element | null;
@@ -65,6 +65,9 @@ function renderProgress(params) {
65
65
  if (params.value == null) {
66
66
  return '';
67
67
  }
68
+ if (params.rowNode.type === 'group') {
69
+ return `${(params.value * 100).toLocaleString()} %`;
70
+ }
68
71
 
69
72
  // If the aggregated value does not have the same unit as the other cell
70
73
  // Then we fall back to the default rendering based on `valueGetter` instead of rendering a progress bar.
@@ -22,9 +22,17 @@ const Value = (0, _styles.styled)('div')(({
22
22
  alignItems: 'center',
23
23
  justifyContent: 'flex-end',
24
24
  '&.good': {
25
- backgroundColor: theme.vars ? `rgba(${theme.vars.palette.success.mainChannel} / 0.3)` : (0, _styles.alpha)(theme.palette.success.main, 0.3)
25
+ color: theme.vars ? `rgb(${theme.vars.palette.success.mainChannel})` : theme.palette.success.main
26
26
  },
27
27
  '&.bad': {
28
+ color: theme.vars ? `rgb(${theme.vars.palette.error.mainChannel})` : theme.palette.error.main
29
+ },
30
+ '&.filled.good': {
31
+ color: 'inherit',
32
+ backgroundColor: theme.vars ? `rgba(${theme.vars.palette.success.mainChannel} / 0.3)` : (0, _styles.alpha)(theme.palette.success.main, 0.3)
33
+ },
34
+ '&.filled.bad': {
35
+ color: 'inherit',
28
36
  backgroundColor: theme.vars ? `rgba(${theme.vars.palette.error.mainChannel} / 0.3)` : (0, _styles.alpha)(theme.palette.error.main, 0.3)
29
37
  }
30
38
  }));
@@ -34,10 +42,11 @@ const currencyFormatter = new Intl.NumberFormat('en-US', {
34
42
  });
35
43
  const TotalPrice = /*#__PURE__*/React.memo(function TotalPrice(props) {
36
44
  const {
37
- value
45
+ value,
46
+ grouped
38
47
  } = props;
39
48
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(Value, {
40
- className: (0, _clsx.default)(value > 1000000 && "good", value < 1000000 && "bad"),
49
+ className: (0, _clsx.default)(value > 1000000 && "good", value < 1000000 && "bad", !grouped && "filled"),
41
50
  children: currencyFormatter.format(value)
42
51
  });
43
52
  });
@@ -53,6 +62,7 @@ function renderTotalPrice(params) {
53
62
  return null;
54
63
  }
55
64
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(TotalPrice, {
56
- value: params.value
65
+ value: params.value,
66
+ grouped: params.rowNode.type === 'group'
57
67
  });
58
68
  }
@@ -20,4 +20,8 @@ export type GridColDefGenerator = GridColDef & {
20
20
  * If `true`, the column will be marked as hidden in the `columnVisibilityModel`.
21
21
  */
22
22
  hide?: boolean;
23
+ /**
24
+ * Reference to the field this column was derived from.
25
+ */
26
+ derivedFrom?: string;
23
27
  };