wip:milestone 0 fixes
Some checks failed
CI/CD Pipeline / unit-tests (push) Failing after 1m16s
CI/CD Pipeline / integration-tests (push) Failing after 2m32s
CI/CD Pipeline / lint (push) Successful in 5m22s
CI/CD Pipeline / e2e-tests (push) Has been skipped
CI/CD Pipeline / build (push) Has been skipped

This commit is contained in:
2026-03-15 12:35:42 +02:00
parent 6708cf28a7
commit cffdf8af86
61266 changed files with 4511646 additions and 1938 deletions

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,3 @@
export var gridRowsMetaSelector = function gridRowsMetaSelector(state) {
return state.rowsMeta;
};

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,90 @@
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { createSelector, createSelectorMemoized } from '../../../utils/createSelector';
var gridRowsStateSelector = function gridRowsStateSelector(state) {
return state.rows;
};
export var gridRowCountSelector = createSelector(gridRowsStateSelector, function (rows) {
return rows.totalRowCount;
});
export var gridRowsLoadingSelector = createSelector(gridRowsStateSelector, function (rows) {
return rows.loading;
});
export var gridTopLevelRowCountSelector = createSelector(gridRowsStateSelector, function (rows) {
return rows.totalTopLevelRowCount;
});
// TODO rows v6: Rename
export var gridRowsLookupSelector = createSelector(gridRowsStateSelector, function (rows) {
return rows.dataRowIdToModelLookup;
});
export var gridRowsDataRowIdToIdLookupSelector = createSelector(gridRowsStateSelector, function (rows) {
return rows.dataRowIdToIdLookup;
});
export var gridRowTreeSelector = createSelector(gridRowsStateSelector, function (rows) {
return rows.tree;
});
export var gridRowGroupingNameSelector = createSelector(gridRowsStateSelector, function (rows) {
return rows.groupingName;
});
export var gridRowTreeDepthsSelector = createSelector(gridRowsStateSelector, function (rows) {
return rows.treeDepths;
});
export var gridRowMaximumTreeDepthSelector = createSelectorMemoized(gridRowsStateSelector, function (rows) {
var entries = Object.entries(rows.treeDepths);
if (entries.length === 0) {
return 1;
}
return entries.filter(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
nodeCount = _ref2[1];
return nodeCount > 0;
}).map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 1),
depth = _ref4[0];
return Number(depth);
}).sort(function (a, b) {
return b - a;
})[0] + 1;
});
export var gridDataRowIdsSelector = createSelector(gridRowsStateSelector, function (rows) {
return rows.dataRowIds;
});
/**
* @ignore - do not document.
*/
export var gridAdditionalRowGroupsSelector = createSelector(gridRowsStateSelector, function (rows) {
return rows == null ? void 0 : rows.additionalRowGroups;
});
/**
* @ignore - do not document.
*/
export var gridPinnedRowsSelector = createSelectorMemoized(gridAdditionalRowGroupsSelector, function (additionalRowGroups) {
var _rawPinnedRows$bottom, _rawPinnedRows$top;
var rawPinnedRows = additionalRowGroups == null ? void 0 : additionalRowGroups.pinnedRows;
return {
bottom: rawPinnedRows == null || (_rawPinnedRows$bottom = rawPinnedRows.bottom) == null ? void 0 : _rawPinnedRows$bottom.map(function (rowEntry) {
var _rowEntry$model;
return {
id: rowEntry.id,
model: (_rowEntry$model = rowEntry.model) != null ? _rowEntry$model : {}
};
}),
top: rawPinnedRows == null || (_rawPinnedRows$top = rawPinnedRows.top) == null ? void 0 : _rawPinnedRows$top.map(function (rowEntry) {
var _rowEntry$model2;
return {
id: rowEntry.id,
model: (_rowEntry$model2 = rowEntry.model) != null ? _rowEntry$model2 : {}
};
})
};
});
/**
* @ignore - do not document.
*/
export var gridPinnedRowsCountSelector = createSelector(gridPinnedRowsSelector, function (pinnedRows) {
var _pinnedRows$top, _pinnedRows$bottom;
return ((pinnedRows == null || (_pinnedRows$top = pinnedRows.top) == null ? void 0 : _pinnedRows$top.length) || 0) + ((pinnedRows == null || (_pinnedRows$bottom = pinnedRows.bottom) == null ? void 0 : _pinnedRows$bottom.length) || 0);
});

View File

@@ -0,0 +1,294 @@
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _extends from "@babel/runtime/helpers/esm/extends";
import { gridPinnedRowsSelector } from './gridRowsSelector';
import { gridDensityFactorSelector } from '../density/densitySelector';
export var GRID_ROOT_GROUP_ID = "auto-generated-group-node-root";
export var GRID_ID_AUTOGENERATED = Symbol('mui.id_autogenerated');
export var buildRootGroup = function buildRootGroup() {
return {
type: 'group',
id: GRID_ROOT_GROUP_ID,
depth: -1,
groupingField: null,
groupingKey: null,
isAutoGenerated: true,
children: [],
childrenFromPath: {},
childrenExpanded: true,
parent: null
};
};
/**
* A helper function to check if the id provided is valid.
* @param {GridRowId} id Id as [[GridRowId]].
* @param {GridRowModel | Partial<GridRowModel>} row Row as [[GridRowModel]].
* @param {string} detailErrorMessage A custom error message to display for invalid IDs
*/
export function checkGridRowIdIsValid(id, row) {
var detailErrorMessage = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'A row was provided without id in the rows prop:';
if (id == null) {
throw new Error(['MUI: The data grid component requires all rows to have a unique `id` property.', 'Alternatively, you can use the `getRowId` prop to specify a custom id for each row.', detailErrorMessage, JSON.stringify(row)].join('\n'));
}
}
export var getRowIdFromRowModel = function getRowIdFromRowModel(rowModel, getRowId, detailErrorMessage) {
var id = getRowId ? getRowId(rowModel) : rowModel.id;
checkGridRowIdIsValid(id, rowModel, detailErrorMessage);
return id;
};
export var createRowsInternalCache = function createRowsInternalCache(_ref) {
var rows = _ref.rows,
getRowId = _ref.getRowId,
loading = _ref.loading,
rowCount = _ref.rowCount;
var updates = {
type: 'full',
rows: []
};
var dataRowIdToModelLookup = {};
var dataRowIdToIdLookup = {};
for (var i = 0; i < rows.length; i += 1) {
var model = rows[i];
var _id = getRowIdFromRowModel(model, getRowId);
dataRowIdToModelLookup[_id] = model;
dataRowIdToIdLookup[_id] = _id;
updates.rows.push(_id);
}
return {
rowsBeforePartialUpdates: rows,
loadingPropBeforePartialUpdates: loading,
rowCountPropBeforePartialUpdates: rowCount,
updates: updates,
dataRowIdToIdLookup: dataRowIdToIdLookup,
dataRowIdToModelLookup: dataRowIdToModelLookup
};
};
export var getTopLevelRowCount = function getTopLevelRowCount(_ref2) {
var tree = _ref2.tree,
_ref2$rowCountProp = _ref2.rowCountProp,
rowCountProp = _ref2$rowCountProp === void 0 ? 0 : _ref2$rowCountProp;
var rootGroupNode = tree[GRID_ROOT_GROUP_ID];
return Math.max(rowCountProp, rootGroupNode.children.length + (rootGroupNode.footerId == null ? 0 : 1));
};
export var getRowsStateFromCache = function getRowsStateFromCache(_ref3) {
var apiRef = _ref3.apiRef,
_ref3$rowCountProp = _ref3.rowCountProp,
rowCountProp = _ref3$rowCountProp === void 0 ? 0 : _ref3$rowCountProp,
loadingProp = _ref3.loadingProp,
previousTree = _ref3.previousTree,
previousTreeDepths = _ref3.previousTreeDepths;
var cache = apiRef.current.caches.rows;
// 1. Apply the "rowTreeCreation" family processing.
var _apiRef$current$apply = apiRef.current.applyStrategyProcessor('rowTreeCreation', {
previousTree: previousTree,
previousTreeDepths: previousTreeDepths,
updates: cache.updates,
dataRowIdToIdLookup: cache.dataRowIdToIdLookup,
dataRowIdToModelLookup: cache.dataRowIdToModelLookup
}),
unProcessedTree = _apiRef$current$apply.tree,
unProcessedTreeDepths = _apiRef$current$apply.treeDepths,
unProcessedDataRowIds = _apiRef$current$apply.dataRowIds,
groupingName = _apiRef$current$apply.groupingName;
// 2. Apply the "hydrateRows" pipe-processing.
var groupingParamsWithHydrateRows = apiRef.current.unstable_applyPipeProcessors('hydrateRows', {
tree: unProcessedTree,
treeDepths: unProcessedTreeDepths,
dataRowIdToIdLookup: cache.dataRowIdToIdLookup,
dataRowIds: unProcessedDataRowIds,
dataRowIdToModelLookup: cache.dataRowIdToModelLookup
});
// 3. Reset the cache updates
apiRef.current.caches.rows.updates = {
type: 'partial',
actions: {
insert: [],
modify: [],
remove: []
},
idToActionLookup: {}
};
return _extends({}, groupingParamsWithHydrateRows, {
totalRowCount: Math.max(rowCountProp, groupingParamsWithHydrateRows.dataRowIds.length),
totalTopLevelRowCount: getTopLevelRowCount({
tree: groupingParamsWithHydrateRows.tree,
rowCountProp: rowCountProp
}),
groupingName: groupingName,
loading: loadingProp
});
};
export var isAutoGeneratedRow = function isAutoGeneratedRow(rowNode) {
return rowNode.type === 'skeletonRow' || rowNode.type === 'footer' || rowNode.type === 'group' && rowNode.isAutoGenerated || rowNode.type === 'pinnedRow' && rowNode.isAutoGenerated;
};
export var getTreeNodeDescendants = function getTreeNodeDescendants(tree, parentId, skipAutoGeneratedRows) {
var node = tree[parentId];
if (node.type !== 'group') {
return [];
}
var validDescendants = [];
for (var i = 0; i < node.children.length; i += 1) {
var child = node.children[i];
if (!skipAutoGeneratedRows || !isAutoGeneratedRow(tree[child])) {
validDescendants.push(child);
}
var childDescendants = getTreeNodeDescendants(tree, child, skipAutoGeneratedRows);
for (var j = 0; j < childDescendants.length; j += 1) {
validDescendants.push(childDescendants[j]);
}
}
if (!skipAutoGeneratedRows && node.footerId != null) {
validDescendants.push(node.footerId);
}
return validDescendants;
};
export var updateCacheWithNewRows = function updateCacheWithNewRows(_ref4) {
var _previousCache$update, _previousCache$update2, _previousCache$update3;
var previousCache = _ref4.previousCache,
getRowId = _ref4.getRowId,
updates = _ref4.updates;
if (previousCache.updates.type === 'full') {
throw new Error('MUI: Unable to prepare a partial update if a full update is not applied yet');
}
// Remove duplicate updates.
// A server can batch updates, and send several updates for the same row in one fn call.
var uniqueUpdates = new Map();
updates.forEach(function (update) {
var id = getRowIdFromRowModel(update, getRowId, 'A row was provided without id when calling updateRows():');
if (uniqueUpdates.has(id)) {
uniqueUpdates.set(id, _extends({}, uniqueUpdates.get(id), update));
} else {
uniqueUpdates.set(id, update);
}
});
var partialUpdates = {
type: 'partial',
actions: {
insert: _toConsumableArray((_previousCache$update = previousCache.updates.actions.insert) != null ? _previousCache$update : []),
modify: _toConsumableArray((_previousCache$update2 = previousCache.updates.actions.modify) != null ? _previousCache$update2 : []),
remove: _toConsumableArray((_previousCache$update3 = previousCache.updates.actions.remove) != null ? _previousCache$update3 : [])
},
idToActionLookup: _extends({}, previousCache.updates.idToActionLookup)
};
var dataRowIdToModelLookup = _extends({}, previousCache.dataRowIdToModelLookup);
var dataRowIdToIdLookup = _extends({}, previousCache.dataRowIdToIdLookup);
var alreadyAppliedActionsToRemove = {
insert: {},
modify: {},
remove: {}
};
// Depending on the action already applied to the data row,
// We might want drop the already-applied-update.
// For instance:
// - if you delete then insert, then you don't want to apply the deletion in the tree.
// - if you insert, then modify, then you just want to apply the insertion in the tree.
uniqueUpdates.forEach(function (partialRow, id) {
var actionAlreadyAppliedToRow = partialUpdates.idToActionLookup[id];
// Action === "delete"
// eslint-disable-next-line no-underscore-dangle
if (partialRow._action === 'delete') {
// If the data row has been removed since the last state update,
// Then do nothing.
if (actionAlreadyAppliedToRow === 'remove' || !dataRowIdToModelLookup[id]) {
return;
}
// If the data row has been inserted / modified since the last state update,
// Then drop this "insert" / "modify" update.
if (actionAlreadyAppliedToRow != null) {
alreadyAppliedActionsToRemove[actionAlreadyAppliedToRow][id] = true;
}
// Remove the data row from the lookups and add it to the "delete" update.
partialUpdates.actions.remove.push(id);
delete dataRowIdToModelLookup[id];
delete dataRowIdToIdLookup[id];
return;
}
var oldRow = dataRowIdToModelLookup[id];
// Action === "modify"
if (oldRow) {
// If the data row has been removed since the last state update,
// Then drop this "remove" update and add it to the "modify" update instead.
if (actionAlreadyAppliedToRow === 'remove') {
alreadyAppliedActionsToRemove.remove[id] = true;
partialUpdates.actions.modify.push(id);
}
// If the date has not been inserted / modified since the last state update,
// Then add it to the "modify" update (if it has been inserted it should just remain "inserted").
else if (actionAlreadyAppliedToRow == null) {
partialUpdates.actions.modify.push(id);
}
// Update the data row lookups.
dataRowIdToModelLookup[id] = _extends({}, oldRow, partialRow);
return;
}
// Action === "insert"
// If the data row has been removed since the last state update,
// Then drop the "remove" update and add it to the "insert" update instead.
if (actionAlreadyAppliedToRow === 'remove') {
alreadyAppliedActionsToRemove.remove[id] = true;
partialUpdates.actions.insert.push(id);
}
// If the data row has not been inserted since the last state update,
// Then add it to the "insert" update.
// `actionAlreadyAppliedToRow` can't be equal to "modify", otherwise we would have an `oldRow` above.
else if (actionAlreadyAppliedToRow == null) {
partialUpdates.actions.insert.push(id);
}
// Update the data row lookups.
dataRowIdToModelLookup[id] = partialRow;
dataRowIdToIdLookup[id] = id;
});
var actionTypeWithActionsToRemove = Object.keys(alreadyAppliedActionsToRemove);
var _loop = function _loop() {
var actionType = actionTypeWithActionsToRemove[i];
var idsToRemove = alreadyAppliedActionsToRemove[actionType];
if (Object.keys(idsToRemove).length > 0) {
partialUpdates.actions[actionType] = partialUpdates.actions[actionType].filter(function (id) {
return !idsToRemove[id];
});
}
};
for (var i = 0; i < actionTypeWithActionsToRemove.length; i += 1) {
_loop();
}
return {
dataRowIdToModelLookup: dataRowIdToModelLookup,
dataRowIdToIdLookup: dataRowIdToIdLookup,
updates: partialUpdates,
rowsBeforePartialUpdates: previousCache.rowsBeforePartialUpdates,
loadingPropBeforePartialUpdates: previousCache.loadingPropBeforePartialUpdates,
rowCountPropBeforePartialUpdates: previousCache.rowCountPropBeforePartialUpdates
};
};
export function calculatePinnedRowsHeight(apiRef) {
var _pinnedRows$top, _pinnedRows$bottom;
var pinnedRows = gridPinnedRowsSelector(apiRef);
var topPinnedRowsHeight = (pinnedRows == null || (_pinnedRows$top = pinnedRows.top) == null ? void 0 : _pinnedRows$top.reduce(function (acc, value) {
acc += apiRef.current.unstable_getRowHeight(value.id);
return acc;
}, 0)) || 0;
var bottomPinnedRowsHeight = (pinnedRows == null || (_pinnedRows$bottom = pinnedRows.bottom) == null ? void 0 : _pinnedRows$bottom.reduce(function (acc, value) {
acc += apiRef.current.unstable_getRowHeight(value.id);
return acc;
}, 0)) || 0;
return {
top: topPinnedRowsHeight,
bottom: bottomPinnedRowsHeight
};
}
export function getMinimalContentHeight(apiRef, rowHeight) {
var densityFactor = gridDensityFactorSelector(apiRef);
return "var(--DataGrid-overlayHeight, ".concat(2 * Math.floor(rowHeight * densityFactor), "px)");
}

View File

@@ -0,0 +1,4 @@
export * from './gridRowsMetaSelector';
export * from './gridRowsMetaState';
export { gridRowCountSelector, gridRowsLoadingSelector, gridTopLevelRowCountSelector, gridRowsLookupSelector, gridRowsDataRowIdToIdLookupSelector, gridRowTreeSelector, gridRowGroupingNameSelector, gridRowTreeDepthsSelector, gridRowMaximumTreeDepthSelector, gridDataRowIdsSelector } from './gridRowsSelector';
export { GRID_ROOT_GROUP_ID, checkGridRowIdIsValid } from './gridRowsUtils';

View File

@@ -0,0 +1,175 @@
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _wrapNativeSuper from "@babel/runtime/helpers/esm/wrapNativeSuper";
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
import * as React from 'react';
import { getGridCellElement, getGridColumnHeaderElement, getGridRowElement } from '../../../utils/domUtils';
import { GRID_ID_AUTOGENERATED } from './gridRowsUtils';
import { useGridApiMethod } from '../../utils/useGridApiMethod';
import { gridFocusCellSelector, gridTabIndexCellSelector } from '../focus/gridFocusStateSelector';
export var MissingRowIdError = /*#__PURE__*/function (_Error) {
_inherits(MissingRowIdError, _Error);
function MissingRowIdError() {
_classCallCheck(this, MissingRowIdError);
return _callSuper(this, MissingRowIdError, arguments);
}
return _createClass(MissingRowIdError);
}( /*#__PURE__*/_wrapNativeSuper(Error));
/**
* @requires useGridColumns (method)
* @requires useGridRows (method)
* @requires useGridFocus (state)
* @requires useGridEditing (method)
* TODO: Impossible priority - useGridEditing also needs to be after useGridParamsApi
* TODO: Impossible priority - useGridFocus also needs to be after useGridParamsApi
*/
export function useGridParamsApi(apiRef, props) {
var getRowId = props.getRowId;
var getColumnHeaderParams = React.useCallback(function (field) {
return {
field: field,
colDef: apiRef.current.getColumn(field)
};
}, [apiRef]);
var getRowParams = React.useCallback(function (id) {
var row = apiRef.current.getRow(id);
if (!row) {
throw new MissingRowIdError("No row with id #".concat(id, " found"));
}
var params = {
id: id,
columns: apiRef.current.getAllColumns(),
row: row
};
return params;
}, [apiRef]);
var getBaseCellParams = React.useCallback(function (id, field) {
var row = apiRef.current.getRow(id);
var rowNode = apiRef.current.getRowNode(id);
if (!row || !rowNode) {
throw new MissingRowIdError("No row with id #".concat(id, " found"));
}
var cellFocus = gridFocusCellSelector(apiRef);
var cellTabIndex = gridTabIndexCellSelector(apiRef);
var params = {
id: id,
field: field,
row: row,
rowNode: rowNode,
value: row[field],
colDef: apiRef.current.getColumn(field),
cellMode: apiRef.current.getCellMode(id, field),
api: apiRef.current,
hasFocus: cellFocus !== null && cellFocus.field === field && cellFocus.id === id,
tabIndex: cellTabIndex && cellTabIndex.field === field && cellTabIndex.id === id ? 0 : -1
};
return params;
}, [apiRef]);
var getCellParams = React.useCallback(function (id, field) {
var colDef = apiRef.current.getColumn(field);
var value = apiRef.current.getCellValue(id, field);
var row = apiRef.current.getRow(id);
var rowNode = apiRef.current.getRowNode(id);
if (!row || !rowNode) {
throw new MissingRowIdError("No row with id #".concat(id, " found"));
}
var cellFocus = gridFocusCellSelector(apiRef);
var cellTabIndex = gridTabIndexCellSelector(apiRef);
var params = {
id: id,
field: field,
row: row,
rowNode: rowNode,
colDef: colDef,
cellMode: apiRef.current.getCellMode(id, field),
hasFocus: cellFocus !== null && cellFocus.field === field && cellFocus.id === id,
tabIndex: cellTabIndex && cellTabIndex.field === field && cellTabIndex.id === id ? 0 : -1,
value: value,
formattedValue: value,
isEditable: false
};
if (colDef && colDef.valueFormatter) {
params.formattedValue = colDef.valueFormatter({
id: id,
field: params.field,
value: params.value,
api: apiRef.current
});
}
params.isEditable = colDef && apiRef.current.isCellEditable(params);
return params;
}, [apiRef]);
var getCellValue = React.useCallback(function (id, field) {
var colDef = apiRef.current.getColumn(field);
if (!colDef || !colDef.valueGetter) {
var rowModel = apiRef.current.getRow(id);
if (!rowModel) {
throw new MissingRowIdError("No row with id #".concat(id, " found"));
}
return rowModel[field];
}
return colDef.valueGetter(getBaseCellParams(id, field));
}, [apiRef, getBaseCellParams]);
var getRowValue = React.useCallback(function (row, colDef) {
var _getRowId;
var id = GRID_ID_AUTOGENERATED in row ? row[GRID_ID_AUTOGENERATED] : (_getRowId = getRowId == null ? void 0 : getRowId(row)) != null ? _getRowId : row.id;
var field = colDef.field;
if (!colDef || !colDef.valueGetter) {
return row[field];
}
return colDef.valueGetter(getBaseCellParams(id, field));
}, [getBaseCellParams, getRowId]);
var getRowFormattedValue = React.useCallback(function (row, colDef) {
var _ref;
var value = getRowValue(row, colDef);
if (!colDef || !colDef.valueFormatter) {
return value;
}
var id = (_ref = getRowId ? getRowId(row) : row.id) != null ? _ref : row[GRID_ID_AUTOGENERATED];
var field = colDef.field;
return colDef.valueFormatter({
id: id,
field: field,
value: value,
api: apiRef.current
});
}, [apiRef, getRowId, getRowValue]);
var getColumnHeaderElement = React.useCallback(function (field) {
if (!apiRef.current.rootElementRef.current) {
return null;
}
return getGridColumnHeaderElement(apiRef.current.rootElementRef.current, field);
}, [apiRef]);
var getRowElement = React.useCallback(function (id) {
if (!apiRef.current.rootElementRef.current) {
return null;
}
return getGridRowElement(apiRef.current.rootElementRef.current, id);
}, [apiRef]);
var getCellElement = React.useCallback(function (id, field) {
if (!apiRef.current.rootElementRef.current) {
return null;
}
return getGridCellElement(apiRef.current.rootElementRef.current, {
id: id,
field: field
});
}, [apiRef]);
var paramsApi = {
getCellValue: getCellValue,
getCellParams: getCellParams,
getCellElement: getCellElement,
getRowValue: getRowValue,
getRowFormattedValue: getRowFormattedValue,
getRowParams: getRowParams,
getRowElement: getRowElement,
getColumnHeaderParams: getColumnHeaderParams,
getColumnHeaderElement: getColumnHeaderElement
};
useGridApiMethod(apiRef, paramsApi, 'public');
}

View File

@@ -0,0 +1,469 @@
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import { useGridApiMethod } from '../../utils/useGridApiMethod';
import { useGridLogger } from '../../utils/useGridLogger';
import { gridRowCountSelector, gridRowsLookupSelector, gridRowTreeSelector, gridRowGroupingNameSelector, gridRowTreeDepthsSelector, gridDataRowIdsSelector, gridRowsDataRowIdToIdLookupSelector, gridRowMaximumTreeDepthSelector } from './gridRowsSelector';
import { useTimeout } from '../../utils/useTimeout';
import { GridSignature, useGridApiEventHandler } from '../../utils/useGridApiEventHandler';
import { useGridVisibleRows } from '../../utils/useGridVisibleRows';
import { gridSortedRowIdsSelector } from '../sorting/gridSortingSelector';
import { gridFilteredRowsLookupSelector } from '../filter/gridFilterSelector';
import { getTreeNodeDescendants, createRowsInternalCache, getRowsStateFromCache, isAutoGeneratedRow, GRID_ROOT_GROUP_ID, GRID_ID_AUTOGENERATED, updateCacheWithNewRows, getTopLevelRowCount, getRowIdFromRowModel } from './gridRowsUtils';
import { useGridRegisterPipeApplier } from '../../core/pipeProcessing';
export var rowsStateInitializer = function rowsStateInitializer(state, props, apiRef) {
apiRef.current.caches.rows = createRowsInternalCache({
rows: props.rows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
});
return _extends({}, state, {
rows: getRowsStateFromCache({
apiRef: apiRef,
rowCountProp: props.rowCount,
loadingProp: props.loading,
previousTree: null,
previousTreeDepths: null
})
});
};
export var useGridRows = function useGridRows(apiRef, props) {
if (process.env.NODE_ENV !== 'production') {
try {
// Freeze the `rows` prop so developers have a fast failure if they try to use Array.prototype.push().
Object.freeze(props.rows);
} catch (error) {
// Sometimes, it's impossible to freeze, so we give up on it.
}
}
var logger = useGridLogger(apiRef, 'useGridRows');
var currentPage = useGridVisibleRows(apiRef, props);
var lastUpdateMs = React.useRef(Date.now());
var timeout = useTimeout();
var getRow = React.useCallback(function (id) {
var model = gridRowsLookupSelector(apiRef)[id];
if (model) {
return model;
}
var node = apiRef.current.getRowNode(id);
if (node && isAutoGeneratedRow(node)) {
return _defineProperty({}, GRID_ID_AUTOGENERATED, id);
}
return null;
}, [apiRef]);
var getRowIdProp = props.getRowId;
var getRowId = React.useCallback(function (row) {
if (GRID_ID_AUTOGENERATED in row) {
return row[GRID_ID_AUTOGENERATED];
}
if (getRowIdProp) {
return getRowIdProp(row);
}
return row.id;
}, [getRowIdProp]);
var lookup = React.useMemo(function () {
return currentPage.rows.reduce(function (acc, _ref2, index) {
var id = _ref2.id;
acc[id] = index;
return acc;
}, {});
}, [currentPage.rows]);
var throttledRowsChange = React.useCallback(function (_ref3) {
var cache = _ref3.cache,
throttle = _ref3.throttle;
var run = function run() {
lastUpdateMs.current = Date.now();
apiRef.current.setState(function (state) {
return _extends({}, state, {
rows: getRowsStateFromCache({
apiRef: apiRef,
rowCountProp: props.rowCount,
loadingProp: props.loading,
previousTree: gridRowTreeSelector(apiRef),
previousTreeDepths: gridRowTreeDepthsSelector(apiRef)
})
});
});
apiRef.current.publishEvent('rowsSet');
apiRef.current.forceUpdate();
};
timeout.clear();
apiRef.current.caches.rows = cache;
if (!throttle) {
run();
return;
}
var throttleRemainingTimeMs = props.throttleRowsMs - (Date.now() - lastUpdateMs.current);
if (throttleRemainingTimeMs > 0) {
timeout.start(throttleRemainingTimeMs, run);
return;
}
run();
}, [props.throttleRowsMs, props.rowCount, props.loading, apiRef, timeout]);
/**
* API METHODS
*/
var setRows = React.useCallback(function (rows) {
logger.debug("Updating all rows, new length ".concat(rows.length));
var cache = createRowsInternalCache({
rows: rows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
});
var prevCache = apiRef.current.caches.rows;
cache.rowsBeforePartialUpdates = prevCache.rowsBeforePartialUpdates;
throttledRowsChange({
cache: cache,
throttle: true
});
}, [logger, props.getRowId, props.loading, props.rowCount, throttledRowsChange, apiRef]);
var updateRows = React.useCallback(function (updates) {
if (props.signature === GridSignature.DataGrid && updates.length > 1) {
throw new Error(["MUI: You can't update several rows at once in `apiRef.current.updateRows` on the DataGrid.", 'You need to upgrade to DataGridPro or DataGridPremium component to unlock this feature.'].join('\n'));
}
var nonPinnedRowsUpdates = [];
updates.forEach(function (update) {
var id = getRowIdFromRowModel(update, props.getRowId, 'A row was provided without id when calling updateRows():');
var rowNode = apiRef.current.getRowNode(id);
if ((rowNode == null ? void 0 : rowNode.type) === 'pinnedRow') {
// @ts-ignore because otherwise `release:build` doesn't work
var pinnedRowsCache = apiRef.current.caches.pinnedRows;
var prevModel = pinnedRowsCache.idLookup[id];
if (prevModel) {
pinnedRowsCache.idLookup[id] = _extends({}, prevModel, update);
}
} else {
nonPinnedRowsUpdates.push(update);
}
});
var cache = updateCacheWithNewRows({
updates: nonPinnedRowsUpdates,
getRowId: props.getRowId,
previousCache: apiRef.current.caches.rows
});
throttledRowsChange({
cache: cache,
throttle: true
});
}, [props.signature, props.getRowId, throttledRowsChange, apiRef]);
var getRowModels = React.useCallback(function () {
var dataRows = gridDataRowIdsSelector(apiRef);
var idRowsLookup = gridRowsLookupSelector(apiRef);
return new Map(dataRows.map(function (id) {
var _idRowsLookup$id;
return [id, (_idRowsLookup$id = idRowsLookup[id]) != null ? _idRowsLookup$id : {}];
}));
}, [apiRef]);
var getRowsCount = React.useCallback(function () {
return gridRowCountSelector(apiRef);
}, [apiRef]);
var getAllRowIds = React.useCallback(function () {
return gridDataRowIdsSelector(apiRef);
}, [apiRef]);
var getRowIndexRelativeToVisibleRows = React.useCallback(function (id) {
return lookup[id];
}, [lookup]);
var setRowChildrenExpansion = React.useCallback(function (id, isExpanded) {
var currentNode = apiRef.current.getRowNode(id);
if (!currentNode) {
throw new Error("MUI: No row with id #".concat(id, " found"));
}
if (currentNode.type !== 'group') {
throw new Error('MUI: Only group nodes can be expanded or collapsed');
}
var newNode = _extends({}, currentNode, {
childrenExpanded: isExpanded
});
apiRef.current.setState(function (state) {
return _extends({}, state, {
rows: _extends({}, state.rows, {
tree: _extends({}, state.rows.tree, _defineProperty({}, id, newNode))
})
});
});
apiRef.current.forceUpdate();
apiRef.current.publishEvent('rowExpansionChange', newNode);
}, [apiRef]);
var getRowNode = React.useCallback(function (id) {
var _ref4;
return (_ref4 = gridRowTreeSelector(apiRef)[id]) != null ? _ref4 : null;
}, [apiRef]);
var getRowGroupChildren = React.useCallback(function (_ref5) {
var _ref5$skipAutoGenerat = _ref5.skipAutoGeneratedRows,
skipAutoGeneratedRows = _ref5$skipAutoGenerat === void 0 ? true : _ref5$skipAutoGenerat,
groupId = _ref5.groupId,
applySorting = _ref5.applySorting,
applyFiltering = _ref5.applyFiltering;
var tree = gridRowTreeSelector(apiRef);
var children;
if (applySorting) {
var groupNode = tree[groupId];
if (!groupNode) {
return [];
}
var sortedRowIds = gridSortedRowIdsSelector(apiRef);
children = [];
var startIndex = sortedRowIds.findIndex(function (id) {
return id === groupId;
}) + 1;
for (var index = startIndex; index < sortedRowIds.length && tree[sortedRowIds[index]].depth > groupNode.depth; index += 1) {
var id = sortedRowIds[index];
if (!skipAutoGeneratedRows || !isAutoGeneratedRow(tree[id])) {
children.push(id);
}
}
} else {
children = getTreeNodeDescendants(tree, groupId, skipAutoGeneratedRows);
}
if (applyFiltering) {
var filteredRowsLookup = gridFilteredRowsLookupSelector(apiRef);
children = children.filter(function (childId) {
return filteredRowsLookup[childId] !== false;
});
}
return children;
}, [apiRef]);
var setRowIndex = React.useCallback(function (rowId, targetIndex) {
var node = apiRef.current.getRowNode(rowId);
if (!node) {
throw new Error("MUI: No row with id #".concat(rowId, " found"));
}
if (node.parent !== GRID_ROOT_GROUP_ID) {
throw new Error("MUI: The row reordering do not support reordering of grouped rows yet");
}
if (node.type !== 'leaf') {
throw new Error("MUI: The row reordering do not support reordering of footer or grouping rows");
}
apiRef.current.setState(function (state) {
var group = gridRowTreeSelector(state, apiRef.current.instanceId)[GRID_ROOT_GROUP_ID];
var allRows = group.children;
var oldIndex = allRows.findIndex(function (row) {
return row === rowId;
});
if (oldIndex === -1 || oldIndex === targetIndex) {
return state;
}
logger.debug("Moving row ".concat(rowId, " to index ").concat(targetIndex));
var updatedRows = _toConsumableArray(allRows);
updatedRows.splice(targetIndex, 0, updatedRows.splice(oldIndex, 1)[0]);
return _extends({}, state, {
rows: _extends({}, state.rows, {
tree: _extends({}, state.rows.tree, _defineProperty({}, GRID_ROOT_GROUP_ID, _extends({}, group, {
children: updatedRows
})))
})
});
});
apiRef.current.publishEvent('rowsSet');
}, [apiRef, logger]);
var replaceRows = React.useCallback(function (firstRowToRender, newRows) {
if (props.signature === GridSignature.DataGrid && newRows.length > 1) {
throw new Error(["MUI: You can't replace rows using `apiRef.current.unstable_replaceRows` on the DataGrid.", 'You need to upgrade to DataGridPro or DataGridPremium component to unlock this feature.'].join('\n'));
}
if (newRows.length === 0) {
return;
}
var treeDepth = gridRowMaximumTreeDepthSelector(apiRef);
if (treeDepth > 1) {
throw new Error('`apiRef.current.unstable_replaceRows` is not compatible with tree data and row grouping');
}
var tree = _extends({}, gridRowTreeSelector(apiRef));
var dataRowIdToModelLookup = _extends({}, gridRowsLookupSelector(apiRef));
var dataRowIdToIdLookup = _extends({}, gridRowsDataRowIdToIdLookupSelector(apiRef));
var rootGroup = tree[GRID_ROOT_GROUP_ID];
var rootGroupChildren = _toConsumableArray(rootGroup.children);
var seenIds = new Set();
for (var i = 0; i < newRows.length; i += 1) {
var rowModel = newRows[i];
var rowId = getRowIdFromRowModel(rowModel, props.getRowId, 'A row was provided without id when calling replaceRows().');
var _rootGroupChildren$sp = rootGroupChildren.splice(firstRowToRender + i, 1, rowId),
_rootGroupChildren$sp2 = _slicedToArray(_rootGroupChildren$sp, 1),
removedRowId = _rootGroupChildren$sp2[0];
if (!seenIds.has(removedRowId)) {
delete dataRowIdToModelLookup[removedRowId];
delete dataRowIdToIdLookup[removedRowId];
delete tree[removedRowId];
}
var rowTreeNodeConfig = {
id: rowId,
depth: 0,
parent: GRID_ROOT_GROUP_ID,
type: 'leaf',
groupingKey: null
};
dataRowIdToModelLookup[rowId] = rowModel;
dataRowIdToIdLookup[rowId] = rowId;
tree[rowId] = rowTreeNodeConfig;
seenIds.add(rowId);
}
tree[GRID_ROOT_GROUP_ID] = _extends({}, rootGroup, {
children: rootGroupChildren
});
// Removes potential remaining skeleton rows from the dataRowIds.
var dataRowIds = rootGroupChildren.filter(function (childId) {
return tree[childId].type === 'leaf';
});
apiRef.current.caches.rows.dataRowIdToModelLookup = dataRowIdToModelLookup;
apiRef.current.caches.rows.dataRowIdToIdLookup = dataRowIdToIdLookup;
apiRef.current.setState(function (state) {
return _extends({}, state, {
rows: _extends({}, state.rows, {
dataRowIdToModelLookup: dataRowIdToModelLookup,
dataRowIdToIdLookup: dataRowIdToIdLookup,
dataRowIds: dataRowIds,
tree: tree
})
});
});
apiRef.current.publishEvent('rowsSet');
}, [apiRef, props.signature, props.getRowId]);
var rowApi = {
getRow: getRow,
getRowId: getRowId,
getRowModels: getRowModels,
getRowsCount: getRowsCount,
getAllRowIds: getAllRowIds,
setRows: setRows,
updateRows: updateRows,
getRowNode: getRowNode,
getRowIndexRelativeToVisibleRows: getRowIndexRelativeToVisibleRows,
unstable_replaceRows: replaceRows
};
var rowProApi = {
setRowIndex: setRowIndex,
setRowChildrenExpansion: setRowChildrenExpansion,
getRowGroupChildren: getRowGroupChildren
};
/**
* EVENTS
*/
var groupRows = React.useCallback(function () {
logger.info("Row grouping pre-processing have changed, regenerating the row tree");
var cache;
if (apiRef.current.caches.rows.rowsBeforePartialUpdates === props.rows) {
// The `props.rows` did not change since the last row grouping
// We can use the current rows cache which contains the partial updates done recently.
cache = _extends({}, apiRef.current.caches.rows, {
updates: {
type: 'full',
rows: gridDataRowIdsSelector(apiRef)
}
});
} else {
// The `props.rows` has changed since the last row grouping
// We must use the new `props.rows` on the new grouping
// This occurs because this event is triggered before the `useEffect` on the rows when both the grouping pre-processing and the rows changes on the same render
cache = createRowsInternalCache({
rows: props.rows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
});
}
throttledRowsChange({
cache: cache,
throttle: false
});
}, [logger, apiRef, props.rows, props.getRowId, props.loading, props.rowCount, throttledRowsChange]);
var handleStrategyProcessorChange = React.useCallback(function (methodName) {
if (methodName === 'rowTreeCreation') {
groupRows();
}
}, [groupRows]);
var handleStrategyActivityChange = React.useCallback(function () {
// `rowTreeCreation` is the only processor ran when `strategyAvailabilityChange` is fired.
// All the other processors listen to `rowsSet` which will be published by the `groupRows` method below.
if (apiRef.current.getActiveStrategy('rowTree') !== gridRowGroupingNameSelector(apiRef)) {
groupRows();
}
}, [apiRef, groupRows]);
useGridApiEventHandler(apiRef, 'activeStrategyProcessorChange', handleStrategyProcessorChange);
useGridApiEventHandler(apiRef, 'strategyAvailabilityChange', handleStrategyActivityChange);
/**
* APPLIERS
*/
var applyHydrateRowsProcessor = React.useCallback(function () {
apiRef.current.setState(function (state) {
var response = apiRef.current.unstable_applyPipeProcessors('hydrateRows', {
tree: gridRowTreeSelector(state, apiRef.current.instanceId),
treeDepths: gridRowTreeDepthsSelector(state, apiRef.current.instanceId),
dataRowIds: gridDataRowIdsSelector(state, apiRef.current.instanceId),
dataRowIdToModelLookup: gridRowsLookupSelector(state, apiRef.current.instanceId),
dataRowIdToIdLookup: gridRowsDataRowIdToIdLookupSelector(state, apiRef.current.instanceId)
});
return _extends({}, state, {
rows: _extends({}, state.rows, response, {
totalTopLevelRowCount: getTopLevelRowCount({
tree: response.tree,
rowCountProp: props.rowCount
})
})
});
});
apiRef.current.publishEvent('rowsSet');
apiRef.current.forceUpdate();
}, [apiRef, props.rowCount]);
useGridRegisterPipeApplier(apiRef, 'hydrateRows', applyHydrateRowsProcessor);
useGridApiMethod(apiRef, rowApi, 'public');
useGridApiMethod(apiRef, rowProApi, props.signature === GridSignature.DataGrid ? 'private' : 'public');
// The effect do not track any value defined synchronously during the 1st render by hooks called after `useGridRows`
// As a consequence, the state generated by the 1st run of this useEffect will always be equal to the initialization one
var isFirstRender = React.useRef(true);
React.useEffect(function () {
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}
var areNewRowsAlreadyInState = apiRef.current.caches.rows.rowsBeforePartialUpdates === props.rows;
var isNewLoadingAlreadyInState = apiRef.current.caches.rows.loadingPropBeforePartialUpdates === props.loading;
var isNewRowCountAlreadyInState = apiRef.current.caches.rows.rowCountPropBeforePartialUpdates === props.rowCount;
// The new rows have already been applied (most likely in the `'rowGroupsPreProcessingChange'` listener)
if (areNewRowsAlreadyInState) {
// If the loading prop has changed, we need to update its value in the state because it won't be done by `throttledRowsChange`
if (!isNewLoadingAlreadyInState) {
apiRef.current.setState(function (state) {
return _extends({}, state, {
rows: _extends({}, state.rows, {
loading: props.loading
})
});
});
apiRef.current.caches.rows.loadingPropBeforePartialUpdates = props.loading;
apiRef.current.forceUpdate();
}
if (!isNewRowCountAlreadyInState) {
apiRef.current.setState(function (state) {
return _extends({}, state, {
rows: _extends({}, state.rows, {
totalRowCount: Math.max(props.rowCount || 0, state.rows.totalRowCount),
totalTopLevelRowCount: Math.max(props.rowCount || 0, state.rows.totalTopLevelRowCount)
})
});
});
apiRef.current.caches.rows.rowCountPropBeforePartialUpdates = props.rowCount;
apiRef.current.forceUpdate();
}
return;
}
logger.debug("Updating all rows, new length ".concat(props.rows.length));
throttledRowsChange({
cache: createRowsInternalCache({
rows: props.rows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
}),
throttle: false
});
}, [props.rows, props.rowCount, props.getRowId, props.loading, logger, throttledRowsChange, apiRef]);
};

View File

@@ -0,0 +1,233 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import { unstable_debounce as debounce, unstable_capitalize as capitalize } from '@mui/utils';
import { useGridVisibleRows } from '../../utils/useGridVisibleRows';
import { useGridApiMethod } from '../../utils/useGridApiMethod';
import { useGridSelector } from '../../utils/useGridSelector';
import { gridDensityFactorSelector } from '../density/densitySelector';
import { gridFilterModelSelector } from '../filter/gridFilterSelector';
import { gridPaginationSelector } from '../pagination/gridPaginationSelector';
import { gridSortModelSelector } from '../sorting/gridSortingSelector';
import { useGridRegisterPipeApplier } from '../../core/pipeProcessing';
import { gridPinnedRowsSelector } from './gridRowsSelector';
import { DATA_GRID_PROPS_DEFAULT_VALUES } from '../../../DataGrid/useDataGridProps';
export var rowsMetaStateInitializer = function rowsMetaStateInitializer(state) {
return _extends({}, state, {
rowsMeta: {
currentPageTotalHeight: 0,
positions: []
}
});
};
var warnedOnceInvalidRowHeight = false;
var getValidRowHeight = function getValidRowHeight(rowHeightProp, defaultRowHeight, warningMessage) {
if (typeof rowHeightProp === 'number' && rowHeightProp > 0) {
return rowHeightProp;
}
if (process.env.NODE_ENV !== 'production' && !warnedOnceInvalidRowHeight && typeof rowHeightProp !== 'undefined' && rowHeightProp !== null) {
console.warn(warningMessage);
warnedOnceInvalidRowHeight = true;
}
return defaultRowHeight;
};
var rowHeightWarning = ["MUI: The `rowHeight` prop should be a number greater than 0.", "The default value will be used instead."].join('\n');
var getRowHeightWarning = ["MUI: The `getRowHeight` prop should return a number greater than 0 or 'auto'.", "The default value will be used instead."].join('\n');
/**
* @requires useGridPageSize (method)
* @requires useGridPage (method)
*/
export var useGridRowsMeta = function useGridRowsMeta(apiRef, props) {
var getRowHeightProp = props.getRowHeight,
getRowSpacing = props.getRowSpacing,
getEstimatedRowHeight = props.getEstimatedRowHeight;
var rowsHeightLookup = React.useRef(Object.create(null));
// Inspired by https://github.com/bvaughn/react-virtualized/blob/master/source/Grid/utils/CellSizeAndPositionManager.js
var lastMeasuredRowIndex = React.useRef(-1);
var hasRowWithAutoHeight = React.useRef(false);
var densityFactor = useGridSelector(apiRef, gridDensityFactorSelector);
var filterModel = useGridSelector(apiRef, gridFilterModelSelector);
var paginationState = useGridSelector(apiRef, gridPaginationSelector);
var sortModel = useGridSelector(apiRef, gridSortModelSelector);
var currentPage = useGridVisibleRows(apiRef, props);
var pinnedRows = useGridSelector(apiRef, gridPinnedRowsSelector);
var validRowHeight = getValidRowHeight(props.rowHeight, DATA_GRID_PROPS_DEFAULT_VALUES.rowHeight, rowHeightWarning);
var rowHeight = Math.floor(validRowHeight * densityFactor);
var hydrateRowsMeta = React.useCallback(function () {
var _pinnedRows$top, _pinnedRows$bottom;
hasRowWithAutoHeight.current = false;
var calculateRowProcessedSizes = function calculateRowProcessedSizes(row) {
if (!rowsHeightLookup.current[row.id]) {
rowsHeightLookup.current[row.id] = {
sizes: {
baseCenter: rowHeight
},
isResized: false,
autoHeight: false,
needsFirstMeasurement: true // Assume all rows will need to be measured by default
};
}
var _rowsHeightLookup$cur = rowsHeightLookup.current[row.id],
isResized = _rowsHeightLookup$cur.isResized,
needsFirstMeasurement = _rowsHeightLookup$cur.needsFirstMeasurement,
sizes = _rowsHeightLookup$cur.sizes;
var baseRowHeight = typeof rowHeight === 'number' && rowHeight > 0 ? rowHeight : 52;
var existingBaseRowHeight = sizes.baseCenter;
if (isResized) {
// Do not recalculate resized row height and use the value from the lookup
baseRowHeight = existingBaseRowHeight;
} else if (getRowHeightProp) {
var rowHeightFromUser = getRowHeightProp(_extends({}, row, {
densityFactor: densityFactor
}));
if (rowHeightFromUser === 'auto') {
if (needsFirstMeasurement) {
var estimatedRowHeight = getEstimatedRowHeight ? getEstimatedRowHeight(_extends({}, row, {
densityFactor: densityFactor
})) : rowHeight;
// If the row was not measured yet use the estimated row height
baseRowHeight = estimatedRowHeight != null ? estimatedRowHeight : rowHeight;
} else {
baseRowHeight = existingBaseRowHeight;
}
hasRowWithAutoHeight.current = true;
rowsHeightLookup.current[row.id].autoHeight = true;
} else {
// Default back to base rowHeight if getRowHeight returns invalid value.
baseRowHeight = getValidRowHeight(rowHeightFromUser, rowHeight, getRowHeightWarning);
rowsHeightLookup.current[row.id].needsFirstMeasurement = false;
rowsHeightLookup.current[row.id].autoHeight = false;
}
} else {
rowsHeightLookup.current[row.id].needsFirstMeasurement = false;
}
var initialHeights = {};
/* eslint-disable-next-line no-restricted-syntax */
for (var _key in sizes) {
if (/^base[A-Z]/.test(_key)) {
initialHeights[_key] = sizes[_key];
}
}
initialHeights.baseCenter = baseRowHeight;
if (getRowSpacing) {
var _spacing$top, _spacing$bottom;
var indexRelativeToCurrentPage = apiRef.current.getRowIndexRelativeToVisibleRows(row.id);
var spacing = getRowSpacing(_extends({}, row, {
isFirstVisible: indexRelativeToCurrentPage === 0,
isLastVisible: indexRelativeToCurrentPage === currentPage.rows.length - 1,
indexRelativeToCurrentPage: indexRelativeToCurrentPage
}));
initialHeights.spacingTop = (_spacing$top = spacing.top) != null ? _spacing$top : 0;
initialHeights.spacingBottom = (_spacing$bottom = spacing.bottom) != null ? _spacing$bottom : 0;
}
var processedSizes = apiRef.current.unstable_applyPipeProcessors('rowHeight', initialHeights, row);
rowsHeightLookup.current[row.id].sizes = processedSizes;
return processedSizes;
};
var positions = [];
var currentPageTotalHeight = currentPage.rows.reduce(function (acc, row) {
positions.push(acc);
var maximumBaseSize = 0;
var otherSizes = 0;
var processedSizes = calculateRowProcessedSizes(row);
/* eslint-disable-next-line no-restricted-syntax, guard-for-in */
for (var _key2 in processedSizes) {
var value = processedSizes[_key2];
if (/^base[A-Z]/.test(_key2)) {
maximumBaseSize = value > maximumBaseSize ? value : maximumBaseSize;
} else {
otherSizes += value;
}
}
return acc + maximumBaseSize + otherSizes;
}, 0);
pinnedRows == null || (_pinnedRows$top = pinnedRows.top) == null || _pinnedRows$top.forEach(function (row) {
calculateRowProcessedSizes(row);
});
pinnedRows == null || (_pinnedRows$bottom = pinnedRows.bottom) == null || _pinnedRows$bottom.forEach(function (row) {
calculateRowProcessedSizes(row);
});
apiRef.current.setState(function (state) {
return _extends({}, state, {
rowsMeta: {
currentPageTotalHeight: currentPageTotalHeight,
positions: positions
}
});
});
if (!hasRowWithAutoHeight.current) {
// No row has height=auto, so all rows are already measured
lastMeasuredRowIndex.current = Infinity;
}
apiRef.current.forceUpdate();
}, [apiRef, currentPage.rows, rowHeight, getRowHeightProp, getRowSpacing, getEstimatedRowHeight, pinnedRows, densityFactor]);
var getRowHeight = React.useCallback(function (rowId) {
var height = rowsHeightLookup.current[rowId];
return height ? height.sizes.baseCenter : rowHeight;
}, [rowHeight]);
var getRowInternalSizes = function getRowInternalSizes(rowId) {
var _rowsHeightLookup$cur2;
return (_rowsHeightLookup$cur2 = rowsHeightLookup.current[rowId]) == null ? void 0 : _rowsHeightLookup$cur2.sizes;
};
var setRowHeight = React.useCallback(function (id, height) {
rowsHeightLookup.current[id].sizes.baseCenter = height;
rowsHeightLookup.current[id].isResized = true;
rowsHeightLookup.current[id].needsFirstMeasurement = false;
hydrateRowsMeta();
}, [hydrateRowsMeta]);
var debouncedHydrateRowsMeta = React.useMemo(function () {
return debounce(hydrateRowsMeta, props.rowPositionsDebounceMs);
}, [hydrateRowsMeta, props.rowPositionsDebounceMs]);
var storeMeasuredRowHeight = React.useCallback(function (id, height, position) {
if (!rowsHeightLookup.current[id] || !rowsHeightLookup.current[id].autoHeight) {
return;
}
// Only trigger hydration if the value is different, otherwise we trigger a loop
var needsHydration = rowsHeightLookup.current[id].sizes["base".concat(capitalize(position))] !== height;
rowsHeightLookup.current[id].needsFirstMeasurement = false;
rowsHeightLookup.current[id].sizes["base".concat(capitalize(position))] = height;
if (needsHydration) {
debouncedHydrateRowsMeta();
}
}, [debouncedHydrateRowsMeta]);
var rowHasAutoHeight = React.useCallback(function (id) {
var _rowsHeightLookup$cur3;
return ((_rowsHeightLookup$cur3 = rowsHeightLookup.current[id]) == null ? void 0 : _rowsHeightLookup$cur3.autoHeight) || false;
}, []);
var getLastMeasuredRowIndex = React.useCallback(function () {
return lastMeasuredRowIndex.current;
}, []);
var setLastMeasuredRowIndex = React.useCallback(function (index) {
if (hasRowWithAutoHeight.current && index > lastMeasuredRowIndex.current) {
lastMeasuredRowIndex.current = index;
}
}, []);
var resetRowHeights = React.useCallback(function () {
rowsHeightLookup.current = {};
hydrateRowsMeta();
}, [hydrateRowsMeta]);
// The effect is used to build the rows meta data - currentPageTotalHeight and positions.
// Because of variable row height this is needed for the virtualization
React.useEffect(function () {
hydrateRowsMeta();
}, [rowHeight, filterModel, paginationState, sortModel, hydrateRowsMeta]);
useGridRegisterPipeApplier(apiRef, 'rowHeight', hydrateRowsMeta);
var rowsMetaApi = {
unstable_setLastMeasuredRowIndex: setLastMeasuredRowIndex,
unstable_getRowHeight: getRowHeight,
unstable_getRowInternalSizes: getRowInternalSizes,
unstable_setRowHeight: setRowHeight,
unstable_storeRowHeightMeasurement: storeMeasuredRowHeight,
resetRowHeights: resetRowHeights
};
var rowsMetaPrivateApi = {
getLastMeasuredRowIndex: getLastMeasuredRowIndex,
rowHasAutoHeight: rowHasAutoHeight
};
useGridApiMethod(apiRef, rowsMetaApi, 'public');
useGridApiMethod(apiRef, rowsMetaPrivateApi, 'private');
};

View File

@@ -0,0 +1,82 @@
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _extends from "@babel/runtime/helpers/esm/extends";
import { GRID_DEFAULT_STRATEGY, useGridRegisterStrategyProcessor } from '../../core/strategyProcessing';
import { buildRootGroup, GRID_ROOT_GROUP_ID } from './gridRowsUtils';
var createFlatRowTree = function createFlatRowTree(rows) {
var tree = _defineProperty({}, GRID_ROOT_GROUP_ID, _extends({}, buildRootGroup(), {
children: rows
}));
for (var i = 0; i < rows.length; i += 1) {
var rowId = rows[i];
tree[rowId] = {
id: rowId,
depth: 0,
parent: GRID_ROOT_GROUP_ID,
type: 'leaf',
groupingKey: null
};
}
return {
groupingName: GRID_DEFAULT_STRATEGY,
tree: tree,
treeDepths: {
0: rows.length
},
dataRowIds: rows
};
};
var updateFlatRowTree = function updateFlatRowTree(_ref) {
var previousTree = _ref.previousTree,
actions = _ref.actions;
var tree = _extends({}, previousTree);
var idsToRemoveFromRootGroup = {};
for (var i = 0; i < actions.remove.length; i += 1) {
var idToDelete = actions.remove[i];
idsToRemoveFromRootGroup[idToDelete] = true;
delete tree[idToDelete];
}
for (var _i = 0; _i < actions.insert.length; _i += 1) {
var idToInsert = actions.insert[_i];
tree[idToInsert] = {
id: idToInsert,
depth: 0,
parent: GRID_ROOT_GROUP_ID,
type: 'leaf',
groupingKey: null
};
}
// TODO rows v6: Support row unpinning
var rootGroup = tree[GRID_ROOT_GROUP_ID];
var rootGroupChildren = [].concat(_toConsumableArray(rootGroup.children), _toConsumableArray(actions.insert));
if (Object.values(idsToRemoveFromRootGroup).length) {
rootGroupChildren = rootGroupChildren.filter(function (id) {
return !idsToRemoveFromRootGroup[id];
});
}
tree[GRID_ROOT_GROUP_ID] = _extends({}, rootGroup, {
children: rootGroupChildren
});
return {
groupingName: GRID_DEFAULT_STRATEGY,
tree: tree,
treeDepths: {
0: rootGroupChildren.length
},
dataRowIds: rootGroupChildren
};
};
var flatRowTreeCreationMethod = function flatRowTreeCreationMethod(params) {
if (params.updates.type === 'full') {
return createFlatRowTree(params.updates.rows);
}
return updateFlatRowTree({
previousTree: params.previousTree,
actions: params.updates.actions
});
};
export var useGridRowsPreProcessors = function useGridRowsPreProcessors(apiRef) {
useGridRegisterStrategyProcessor(apiRef, GRID_DEFAULT_STRATEGY, 'rowTreeCreation', flatRowTreeCreationMethod);
};