@mui/x-data-grid-premium
Version:
The Premium plan edition of the MUI X Data Grid Components.
163 lines (159 loc) • 8.96 kB
JavaScript
'use client';
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import { isDeepEqual } from '@mui/x-internals/isDeepEqual';
import { useGridEvent as addEventHandler, useGridApiMethod, GRID_ROOT_GROUP_ID, useGridEvent, gridRowTreeSelector } from '@mui/x-data-grid-pro';
import { useGridDataSourceBasePro, useGridRegisterStrategyProcessor, useGridRegisterPipeProcessor, gridPivotInitialColumnsSelector, runIf, gridPivotActiveSelector, GridStrategyGroup, DataSourceRowsUpdateStrategy, getGroupKeys } from '@mui/x-data-grid-pro/internals';
import { gridPivotModelSelector } from "../pivoting/gridPivotingSelectors.mjs";
import { getPropsOverrides, fetchParents } from "./utils.mjs";
import { gridRowGroupingSanitizedModelSelector } from "../rowGrouping/gridRowGroupingSelector.mjs";
import { gridAggregationModelSelector } from "../aggregation/gridAggregationSelectors.mjs";
function getKeyPremium(params) {
return JSON.stringify([params.filterModel, params.sortModel, params.groupKeys, params.groupFields, params.start, params.end, params.pivotModel ? {} : params.aggregationModel, params.pivotModel]);
}
const options = {
cacheOptions: {
getKey: getKeyPremium
}
};
const getStrategies = (props, groupingModelSize) => {
const previousStrategies = new Set([DataSourceRowsUpdateStrategy.Default, DataSourceRowsUpdateStrategy.GroupedData, DataSourceRowsUpdateStrategy.LazyLoadedGroupedData]);
let currentStrategy = DataSourceRowsUpdateStrategy.Default;
if (props.treeData || !props.disableRowGrouping && groupingModelSize > 0) {
currentStrategy = props.lazyLoading ? DataSourceRowsUpdateStrategy.LazyLoadedGroupedData : DataSourceRowsUpdateStrategy.GroupedData;
}
previousStrategies.delete(currentStrategy);
return {
currentStrategy,
previousStrategies: Array.from(previousStrategies)
};
};
export const useGridDataSourcePremium = (apiRef, props) => {
const aggregationModel = gridAggregationModelSelector(apiRef);
const groupingModelSize = gridRowGroupingSanitizedModelSelector(apiRef).length;
const setStrategyAvailability = React.useCallback(() => {
const {
currentStrategy,
previousStrategies
} = getStrategies({
treeData: props.treeData,
lazyLoading: props.lazyLoading,
disableRowGrouping: props.disableRowGrouping
}, groupingModelSize);
previousStrategies.forEach(strategy => {
apiRef.current.setStrategyAvailability(GridStrategyGroup.DataSource, strategy, () => false);
});
apiRef.current.setStrategyAvailability(GridStrategyGroup.DataSource, currentStrategy, props.dataSource ? () => true : () => false);
}, [apiRef, props.dataSource, props.lazyLoading, props.treeData, props.disableRowGrouping, groupingModelSize]);
const handleEditRowWithAggregation = React.useCallback((params, updatedRow) => {
const rowTree = gridRowTreeSelector(apiRef);
if (updatedRow && !isDeepEqual(updatedRow, params.previousRow)) {
// Reset the outdated cache, only if the row is _actually_ updated
apiRef.current.dataSource.cache.clear();
}
const groupKeys = getGroupKeys(rowTree, params.rowId);
apiRef.current.updateNestedRows([updatedRow], groupKeys);
// To refresh the aggregation values of all parent rows and the footer row, recursively re-fetch all parent levels
fetchParents(rowTree, params.rowId, apiRef.current.dataSource.fetchRows);
}, [apiRef]);
const {
api,
debouncedFetchRows,
flatTreeStrategyProcessor,
groupedDataStrategyProcessor,
nestedDataStrategyProcessor,
events,
stopPolling
} = useGridDataSourceBasePro(apiRef, props, _extends({}, !props.disableAggregation && Object.keys(aggregationModel).length > 0 ? {
handleEditRow: handleEditRowWithAggregation
} : {}, options));
const aggregateRowRef = React.useRef({});
const initialColumns = gridPivotInitialColumnsSelector(apiRef);
const pivotActive = gridPivotActiveSelector(apiRef);
const pivotModel = gridPivotModelSelector(apiRef);
const processDataSourceRows = React.useCallback(({
params,
response
}, applyRowHydration) => {
if (response.aggregateRow) {
aggregateRowRef.current = response.aggregateRow;
}
if (Object.keys(params.aggregationModel || {}).length > 0) {
if (applyRowHydration) {
apiRef.current.requestPipeProcessorsApplication('hydrateRows');
}
apiRef.current.applyAggregation();
}
if (response.pivotColumns) {
const pivotingColDef = props.pivotingColDef;
if (!pivotingColDef || typeof pivotingColDef !== 'function') {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No \`pivotingColDef()\` prop provided with to the Data Grid, but response contains \`pivotColumns\`.
You need a callback to return at least a field column prop for each generated pivot column.
See [server-side pivoting](https://mui.com/x/react-data-grid/server-side-data/pivoting/) documentation for more details.` : _formatErrorMessage(119));
}
// Update the grid state with new columns and column grouping model
const partialPropsOverrides = getPropsOverrides(response.pivotColumns, pivotingColDef, pivotModel, initialColumns, apiRef);
apiRef.current.setState(state => {
return _extends({}, state, {
pivoting: _extends({}, state.pivoting, {
propsOverrides: _extends({}, state.pivoting.propsOverrides, partialPropsOverrides)
})
});
});
}
return {
params,
response
};
}, [apiRef, props.pivotingColDef, initialColumns, pivotModel]);
const resolveGroupAggregation = React.useCallback((groupId, field) => {
if (groupId === GRID_ROOT_GROUP_ID) {
return props.dataSource?.getAggregatedValue?.(aggregateRowRef.current, field);
}
const row = apiRef.current.getRow(groupId);
return props.dataSource?.getAggregatedValue?.(row, field);
}, [apiRef, props.dataSource]);
const handleRowGroupingModelChange = React.useCallback(() => {
// Clear the rows on every grouping model change to match the pre-fix behavior on
// non-standard strategies (e.g. lazy loading) where `setRows([])` is required to
// reset the existing grouping state. `dataSourceKeepPreviousData` is intentionally
// not honored here: changing the grouping model implies the `GroupedData` strategy
// is (about to be) active, and skipping the synchronous clear would render rows in
// stale sort order (https://github.com/mui/mui-x/pull/21619).
apiRef.current.setRows([]);
// The event listener is wired regardless of the active strategy
// (see `runIf(!pivotActive && !!props.dataSource, ...)` below), so we have to gate the
// `setLoading(true)` here. `fetchRows` only clears the loading flag when a standard
// strategy is active, and we don't want to leave the overlay stuck on lazy-loading or
// other non-standard strategies. Order matters too: `setRows([])` above rebuilds
// `state.rows` from `props.loading`, so the `setLoading(true)` call must come after
// it to survive the rebuild.
const currentStrategy = apiRef.current.getActiveStrategy(GridStrategyGroup.DataSource);
const isStandardStrategyActive = currentStrategy === DataSourceRowsUpdateStrategy.Default || currentStrategy === DataSourceRowsUpdateStrategy.GroupedData;
if (isStandardStrategyActive) {
apiRef.current.setLoading(true);
}
stopPolling();
debouncedFetchRows();
}, [apiRef, debouncedFetchRows, stopPolling]);
const privateApi = _extends({}, api.private, {
resolveGroupAggregation
});
useGridApiMethod(apiRef, api.public, 'public');
useGridApiMethod(apiRef, privateApi, 'private');
useGridRegisterStrategyProcessor(apiRef, flatTreeStrategyProcessor.strategyName, flatTreeStrategyProcessor.group, flatTreeStrategyProcessor.processor);
useGridRegisterStrategyProcessor(apiRef, groupedDataStrategyProcessor.strategyName, groupedDataStrategyProcessor.group, groupedDataStrategyProcessor.processor);
useGridRegisterStrategyProcessor(apiRef, nestedDataStrategyProcessor.strategyName, nestedDataStrategyProcessor.group, nestedDataStrategyProcessor.processor);
useGridRegisterPipeProcessor(apiRef, 'processDataSourceRows', processDataSourceRows);
Object.entries(events).forEach(([event, handler]) => {
addEventHandler(apiRef, event, handler);
});
useGridEvent(apiRef, 'rowGroupingModelChange', runIf(!pivotActive && !!props.dataSource, handleRowGroupingModelChange));
useGridEvent(apiRef, 'aggregationModelChange', runIf(!pivotActive, () => debouncedFetchRows()));
useGridEvent(apiRef, 'pivotModeChange', runIf(!pivotActive, () => debouncedFetchRows()));
useGridEvent(apiRef, 'pivotModelChange', runIf(pivotActive, () => debouncedFetchRows()));
React.useEffect(() => {
setStrategyAvailability();
}, [setStrategyAvailability]);
};