neue Homepage auf react basis

This commit is contained in:
2026-08-07 21:39:30 +02:00
parent 164bdd19ad
commit ee89442c04
52191 changed files with 1230242 additions and 58 deletions
@@ -0,0 +1,10 @@
import type { GridStateCommunity } from "../../models/gridStateCommunity.mjs";
import type { GridRowId } from "../../models/gridRows.mjs";
/**
* Get the row id for a given row
* @param apiRef - The grid api reference
* @param {GridRowModel} row - The row to get the id for
* @returns {GridRowId} The row id
*/
export declare const gridRowIdSelector: import("@mui/x-data-grid").OutputSelector<GridStateCommunity, import("@mui/x-data-grid").GridValidRowModel, GridRowId>;
export declare const gridRowSelectableSelector: import("@mui/x-data-grid").OutputSelector<GridStateCommunity, unknown, ((params: import("@mui/x-data-grid").GridRowParams<any>) => boolean) | undefined>;
@@ -0,0 +1,10 @@
import type { GridStateCommunity } from "../../models/gridStateCommunity.js";
import type { GridRowId } from "../../models/gridRows.js";
/**
* Get the row id for a given row
* @param apiRef - The grid api reference
* @param {GridRowModel} row - The row to get the id for
* @returns {GridRowId} The row id
*/
export declare const gridRowIdSelector: import("@mui/x-data-grid").OutputSelector<GridStateCommunity, import("@mui/x-data-grid").GridValidRowModel, GridRowId>;
export declare const gridRowSelectableSelector: import("@mui/x-data-grid").OutputSelector<GridStateCommunity, unknown, ((params: import("@mui/x-data-grid").GridRowParams<any>) => boolean) | undefined>;
+23
View File
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.gridRowSelectableSelector = exports.gridRowIdSelector = void 0;
var _gridRowsUtils = require("../features/rows/gridRowsUtils");
var _createSelector = require("../../utils/createSelector");
/**
* Get the row id for a given row
* @param apiRef - The grid api reference
* @param {GridRowModel} row - The row to get the id for
* @returns {GridRowId} The row id
*/
const gridRowIdSelector = exports.gridRowIdSelector = (0, _createSelector.createRootSelector)((state, row) => {
if (_gridRowsUtils.GRID_ID_AUTOGENERATED in row) {
return row[_gridRowsUtils.GRID_ID_AUTOGENERATED];
}
return state.props.getRowId ? state.props.getRowId(row) : row.id;
});
const gridRowSelectableSelector = exports.gridRowSelectableSelector = (0, _createSelector.createRootSelector)(state => {
return state.props.isRowSelectable;
});
@@ -0,0 +1,18 @@
import { GRID_ID_AUTOGENERATED } from "../features/rows/gridRowsUtils.mjs";
import { createRootSelector } from "../../utils/createSelector.mjs";
/**
* Get the row id for a given row
* @param apiRef - The grid api reference
* @param {GridRowModel} row - The row to get the id for
* @returns {GridRowId} The row id
*/
export const gridRowIdSelector = createRootSelector((state, row) => {
if (GRID_ID_AUTOGENERATED in row) {
return row[GRID_ID_AUTOGENERATED];
}
return state.props.getRowId ? state.props.getRowId(row) : row.id;
});
export const gridRowSelectableSelector = createRootSelector(state => {
return state.props.isRowSelectable;
});
+2
View File
@@ -0,0 +1,2 @@
export type { GridPipeProcessingLookup } from "./pipeProcessing/index.mjs";
export { gridRowIdSelector } from "./gridPropsSelectors.mjs";
+2
View File
@@ -0,0 +1,2 @@
export type { GridPipeProcessingLookup } from "./pipeProcessing/index.js";
export { gridRowIdSelector } from "./gridPropsSelectors.js";
+12
View File
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "gridRowIdSelector", {
enumerable: true,
get: function () {
return _gridPropsSelectors.gridRowIdSelector;
}
});
var _gridPropsSelectors = require("./gridPropsSelectors");
+1
View File
@@ -0,0 +1 @@
export { gridRowIdSelector } from "./gridPropsSelectors.mjs";
@@ -0,0 +1,163 @@
import type * as React from 'react';
import type { GridCellIndexCoordinates, GridScrollParams, GridColDef, GridCellCoordinates, GridCellParams, GridEditMode } from "../../../models/index.mjs";
import type { GridInitialStateCommunity } from "../../../models/gridStateCommunity.mjs";
import type { GridExportStateParams, GridRestoreStatePreProcessingContext, GridRestoreStatePreProcessingValue } from "../../features/statePersistence/gridStatePersistenceInterface.mjs";
import type { GridHydrateColumnsValue, GridPinnedColumnPosition } from "../../features/columns/gridColumnsInterfaces.mjs";
import type { GridRowEntry, GridRowId } from "../../../models/gridRows.mjs";
import type { GridHydrateRowsValue } from "../../features/rows/gridRowsInterfaces.mjs";
import type { GridPreferencePanelsValue } from "../../features/preferencesPanel/index.mjs";
import type { GridGetRowsParams, GridGetRowsResponse } from "../../../models/gridDataSource.mjs";
import type { HeightEntry } from "../../features/rows/gridRowsMetaInterfaces.mjs";
import type { RowReorderDropPosition } from "../../../models/api/gridRowApi.mjs";
export type GridPipeProcessorGroup = keyof GridPipeProcessingLookup;
export interface GridPipeProcessingLookup {
columnMenu: {
value: Array<string>;
context: GridColDef;
};
exportState: {
value: GridInitialStateCommunity;
context: GridExportStateParams;
};
getRowsParams: {
value: Partial<GridGetRowsParams>;
};
hydrateColumns: {
value: GridHydrateColumnsValue;
};
hydrateRows: {
value: GridHydrateRowsValue;
};
exportMenu: {
value: {
component: React.ReactElement<any>;
componentName: string;
}[];
context: any;
};
preferencePanel: {
value: React.ReactNode;
context: GridPreferencePanelsValue;
};
restoreState: {
value: GridRestoreStatePreProcessingValue;
context: GridRestoreStatePreProcessingContext<GridInitialStateCommunity>;
};
rowHeight: {
value: HeightEntry;
context: GridRowEntry;
};
scrollToIndexes: {
value: Partial<GridScrollParams>;
context: Partial<GridCellIndexCoordinates>;
};
rowClassName: {
value: string[];
context: GridRowId;
};
cellClassName: {
value: string[];
context: GridCellCoordinates;
};
isCellSelected: {
value: boolean;
context: GridCellCoordinates;
};
canUpdateFocus: {
value: boolean;
context: {
event: MouseEvent | React.KeyboardEvent;
cell: GridCellParams | null;
};
};
clipboardCopy: {
value: string;
};
canStartEditing: {
value: boolean;
context: {
event: React.KeyboardEvent;
cellParams: GridCellParams;
editMode: GridEditMode;
};
};
isColumnPinned: {
value: GridPinnedColumnPosition | false;
context: string;
};
processDataSourceRows: {
value: {
params: GridGetRowsParams;
response: GridGetRowsResponse;
};
context: boolean;
};
/**
* Does validation of the current reorder operation.
* If the reorder is valid, it returns the position index of the drop indicator.
* - For example before first row is `0` and after the last row is `rows.length`.
* If the reorder is invalid, it returns `-1`.
*/
isRowReorderValid: {
value: boolean;
context: {
sourceRowId: GridRowId;
targetRowId: GridRowId;
dropPosition: RowReorderDropPosition;
dragDirection: 'up' | 'down';
};
};
}
export type GridPipeProcessor<P extends GridPipeProcessorGroup> = (value: GridPipeProcessingLookup[P]['value'], context: GridPipeProcessingLookup[P] extends {
context: any;
} ? GridPipeProcessingLookup[P]['context'] : undefined) => GridPipeProcessingLookup[P]['value'];
type GridPipeProcessorsApplierArgs<P extends GridPipeProcessorGroup, T extends {
value: any;
}> = T extends {
context: any;
} ? [P, T['value'], T['context']] : [P, T['value']];
type GridPipeProcessorsApplier = <P extends GridPipeProcessorGroup>(...params: GridPipeProcessorsApplierArgs<P, GridPipeProcessingLookup[P]>) => GridPipeProcessingLookup[P]['value'];
export interface GridPipeProcessingApi {
/**
* Run all the processors registered for the given group.
* @template T
* @param {GridPipeProcessorGroup} group The group from which we want to apply the processors.
* @param {T['value']} value The initial value to pass to the first processor.
* @param {T['context]} context Context object that will be passed to each processor.
* @returns {T['value]} The value after passing through all pre-processors.
* @ignore - do not document.
*/
unstable_applyPipeProcessors: GridPipeProcessorsApplier;
}
export interface GridPipeProcessingPrivateApi {
/**
* Register a processor and run all the appliers of the group.
* @param {GridPipeProcessorGroup} group The group on which this processor should be applied.
* @param {string} id An unique and static identifier of the processor.
* @param {GridPipeProcessor} processor The processor to register.
* @returns {() => void} A function to unregister the processor.
*/
registerPipeProcessor: <G extends GridPipeProcessorGroup>(group: GridPipeProcessorGroup, id: string, processor: GridPipeProcessor<G>) => () => void;
/**
* Register an applier.
* @param {GridPipeProcessorGroup} group The group of this applier
* @param {string} id An unique and static identifier of the applier.
* @param {() => void} applier The applier to register.
* @returns {() => void} A function to unregister the applier.
*/
registerPipeApplier: (group: GridPipeProcessorGroup, id: string, applier: () => void) => () => void;
/**
* Imperatively run all the appliers of a group.
* Most of the time, the applier should run because a processor is re-registered,
* but sometimes we want to re-apply the processing even if the processor deps have not changed.
* This may occur when the change requires a `isDeepEqual` check.
* @param {GridPipeProcessorGroup} group The group to apply.
*/
requestPipeProcessorsApplication: (group: GridPipeProcessorGroup) => void;
/**
* Checks of there are any processors that have been updated and runs appliers for them.
* It is intended to be called in a useEffect in the top-level data grid hook (`useDataGridComponent`).
*/
runAppliersForPendingProcessors: () => void;
}
export {};
@@ -0,0 +1,163 @@
import type * as React from 'react';
import type { GridCellIndexCoordinates, GridScrollParams, GridColDef, GridCellCoordinates, GridCellParams, GridEditMode } from "../../../models/index.js";
import type { GridInitialStateCommunity } from "../../../models/gridStateCommunity.js";
import type { GridExportStateParams, GridRestoreStatePreProcessingContext, GridRestoreStatePreProcessingValue } from "../../features/statePersistence/gridStatePersistenceInterface.js";
import type { GridHydrateColumnsValue, GridPinnedColumnPosition } from "../../features/columns/gridColumnsInterfaces.js";
import type { GridRowEntry, GridRowId } from "../../../models/gridRows.js";
import type { GridHydrateRowsValue } from "../../features/rows/gridRowsInterfaces.js";
import type { GridPreferencePanelsValue } from "../../features/preferencesPanel/index.js";
import type { GridGetRowsParams, GridGetRowsResponse } from "../../../models/gridDataSource.js";
import type { HeightEntry } from "../../features/rows/gridRowsMetaInterfaces.js";
import type { RowReorderDropPosition } from "../../../models/api/gridRowApi.js";
export type GridPipeProcessorGroup = keyof GridPipeProcessingLookup;
export interface GridPipeProcessingLookup {
columnMenu: {
value: Array<string>;
context: GridColDef;
};
exportState: {
value: GridInitialStateCommunity;
context: GridExportStateParams;
};
getRowsParams: {
value: Partial<GridGetRowsParams>;
};
hydrateColumns: {
value: GridHydrateColumnsValue;
};
hydrateRows: {
value: GridHydrateRowsValue;
};
exportMenu: {
value: {
component: React.ReactElement<any>;
componentName: string;
}[];
context: any;
};
preferencePanel: {
value: React.ReactNode;
context: GridPreferencePanelsValue;
};
restoreState: {
value: GridRestoreStatePreProcessingValue;
context: GridRestoreStatePreProcessingContext<GridInitialStateCommunity>;
};
rowHeight: {
value: HeightEntry;
context: GridRowEntry;
};
scrollToIndexes: {
value: Partial<GridScrollParams>;
context: Partial<GridCellIndexCoordinates>;
};
rowClassName: {
value: string[];
context: GridRowId;
};
cellClassName: {
value: string[];
context: GridCellCoordinates;
};
isCellSelected: {
value: boolean;
context: GridCellCoordinates;
};
canUpdateFocus: {
value: boolean;
context: {
event: MouseEvent | React.KeyboardEvent;
cell: GridCellParams | null;
};
};
clipboardCopy: {
value: string;
};
canStartEditing: {
value: boolean;
context: {
event: React.KeyboardEvent;
cellParams: GridCellParams;
editMode: GridEditMode;
};
};
isColumnPinned: {
value: GridPinnedColumnPosition | false;
context: string;
};
processDataSourceRows: {
value: {
params: GridGetRowsParams;
response: GridGetRowsResponse;
};
context: boolean;
};
/**
* Does validation of the current reorder operation.
* If the reorder is valid, it returns the position index of the drop indicator.
* - For example before first row is `0` and after the last row is `rows.length`.
* If the reorder is invalid, it returns `-1`.
*/
isRowReorderValid: {
value: boolean;
context: {
sourceRowId: GridRowId;
targetRowId: GridRowId;
dropPosition: RowReorderDropPosition;
dragDirection: 'up' | 'down';
};
};
}
export type GridPipeProcessor<P extends GridPipeProcessorGroup> = (value: GridPipeProcessingLookup[P]['value'], context: GridPipeProcessingLookup[P] extends {
context: any;
} ? GridPipeProcessingLookup[P]['context'] : undefined) => GridPipeProcessingLookup[P]['value'];
type GridPipeProcessorsApplierArgs<P extends GridPipeProcessorGroup, T extends {
value: any;
}> = T extends {
context: any;
} ? [P, T['value'], T['context']] : [P, T['value']];
type GridPipeProcessorsApplier = <P extends GridPipeProcessorGroup>(...params: GridPipeProcessorsApplierArgs<P, GridPipeProcessingLookup[P]>) => GridPipeProcessingLookup[P]['value'];
export interface GridPipeProcessingApi {
/**
* Run all the processors registered for the given group.
* @template T
* @param {GridPipeProcessorGroup} group The group from which we want to apply the processors.
* @param {T['value']} value The initial value to pass to the first processor.
* @param {T['context]} context Context object that will be passed to each processor.
* @returns {T['value]} The value after passing through all pre-processors.
* @ignore - do not document.
*/
unstable_applyPipeProcessors: GridPipeProcessorsApplier;
}
export interface GridPipeProcessingPrivateApi {
/**
* Register a processor and run all the appliers of the group.
* @param {GridPipeProcessorGroup} group The group on which this processor should be applied.
* @param {string} id An unique and static identifier of the processor.
* @param {GridPipeProcessor} processor The processor to register.
* @returns {() => void} A function to unregister the processor.
*/
registerPipeProcessor: <G extends GridPipeProcessorGroup>(group: GridPipeProcessorGroup, id: string, processor: GridPipeProcessor<G>) => () => void;
/**
* Register an applier.
* @param {GridPipeProcessorGroup} group The group of this applier
* @param {string} id An unique and static identifier of the applier.
* @param {() => void} applier The applier to register.
* @returns {() => void} A function to unregister the applier.
*/
registerPipeApplier: (group: GridPipeProcessorGroup, id: string, applier: () => void) => () => void;
/**
* Imperatively run all the appliers of a group.
* Most of the time, the applier should run because a processor is re-registered,
* but sometimes we want to re-apply the processing even if the processor deps have not changed.
* This may occur when the change requires a `isDeepEqual` check.
* @param {GridPipeProcessorGroup} group The group to apply.
*/
requestPipeProcessorsApplication: (group: GridPipeProcessorGroup) => void;
/**
* Checks of there are any processors that have been updated and runs appliers for them.
* It is intended to be called in a useEffect in the top-level data grid hook (`useDataGridComponent`).
*/
runAppliersForPendingProcessors: () => void;
}
export {};
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,4 @@
export * from "./gridPipeProcessingApi.mjs";
export * from "./useGridPipeProcessing.mjs";
export * from "./useGridRegisterPipeProcessor.mjs";
export * from "./useGridRegisterPipeApplier.mjs";
@@ -0,0 +1,4 @@
export * from "./gridPipeProcessingApi.js";
export * from "./useGridPipeProcessing.js";
export * from "./useGridRegisterPipeProcessor.js";
export * from "./useGridRegisterPipeApplier.js";
@@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _gridPipeProcessingApi = require("./gridPipeProcessingApi");
Object.keys(_gridPipeProcessingApi).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _gridPipeProcessingApi[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _gridPipeProcessingApi[key];
}
});
});
var _useGridPipeProcessing = require("./useGridPipeProcessing");
Object.keys(_useGridPipeProcessing).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _useGridPipeProcessing[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _useGridPipeProcessing[key];
}
});
});
var _useGridRegisterPipeProcessor = require("./useGridRegisterPipeProcessor");
Object.keys(_useGridRegisterPipeProcessor).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _useGridRegisterPipeProcessor[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _useGridRegisterPipeProcessor[key];
}
});
});
var _useGridRegisterPipeApplier = require("./useGridRegisterPipeApplier");
Object.keys(_useGridRegisterPipeApplier).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _useGridRegisterPipeApplier[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _useGridRegisterPipeApplier[key];
}
});
});
@@ -0,0 +1,4 @@
export * from "./gridPipeProcessingApi.mjs";
export * from "./useGridPipeProcessing.mjs";
export * from "./useGridRegisterPipeProcessor.mjs";
export * from "./useGridRegisterPipeApplier.mjs";
@@ -0,0 +1,32 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../../models/api/gridApiCommon.mjs";
/**
* Implement the Pipeline Pattern
*
* More information and detailed example in (TODO add link to technical doc when ready)
*
* Some plugins contains custom logic to enrich data provided by other plugins or components.
* For instance, the row grouping plugin needs to add / remove the grouping columns when the grid columns are updated.
*
* =====================================================================================================================
*
* The plugin containing the custom logic must use:
*
* - `useGridRegisterPipeProcessor` to register their processor.
*
* - `apiRef.current.requestPipeProcessorsApplication` to imperatively re-apply a group.
* This method should be used in last resort.
* Most of the time, the application should be triggered by an update on the deps of the processor.
*
* =====================================================================================================================
*
* The plugin or component that needs to enrich its data must use:
*
* - `apiRef.current.unstable_applyPipeProcessors` to run in chain all the processors of a given group.
*
* - `useGridRegisterPipeApplier` to re-apply the whole pipe when requested.
* The applier will be called when:
* * a processor is registered.
* * `apiRef.current.requestPipeProcessorsApplication` is called for the given group.
*/
export declare const useGridPipeProcessing: (apiRef: RefObject<GridPrivateApiCommon>) => void;
@@ -0,0 +1,32 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../../models/api/gridApiCommon.js";
/**
* Implement the Pipeline Pattern
*
* More information and detailed example in (TODO add link to technical doc when ready)
*
* Some plugins contains custom logic to enrich data provided by other plugins or components.
* For instance, the row grouping plugin needs to add / remove the grouping columns when the grid columns are updated.
*
* =====================================================================================================================
*
* The plugin containing the custom logic must use:
*
* - `useGridRegisterPipeProcessor` to register their processor.
*
* - `apiRef.current.requestPipeProcessorsApplication` to imperatively re-apply a group.
* This method should be used in last resort.
* Most of the time, the application should be triggered by an update on the deps of the processor.
*
* =====================================================================================================================
*
* The plugin or component that needs to enrich its data must use:
*
* - `apiRef.current.unstable_applyPipeProcessors` to run in chain all the processors of a given group.
*
* - `useGridRegisterPipeApplier` to re-apply the whole pipe when requested.
* The applier will be called when:
* * a processor is registered.
* * `apiRef.current.requestPipeProcessorsApplication` is called for the given group.
*/
export declare const useGridPipeProcessing: (apiRef: RefObject<GridPrivateApiCommon>) => void;
@@ -0,0 +1,132 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridPipeProcessing = void 0;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _toPropertyKey2 = _interopRequireDefault(require("@babel/runtime/helpers/toPropertyKey"));
var React = _interopRequireWildcard(require("react"));
var _useGridApiMethod = require("../../utils/useGridApiMethod");
/**
* Implement the Pipeline Pattern
*
* More information and detailed example in (TODO add link to technical doc when ready)
*
* Some plugins contains custom logic to enrich data provided by other plugins or components.
* For instance, the row grouping plugin needs to add / remove the grouping columns when the grid columns are updated.
*
* =====================================================================================================================
*
* The plugin containing the custom logic must use:
*
* - `useGridRegisterPipeProcessor` to register their processor.
*
* - `apiRef.current.requestPipeProcessorsApplication` to imperatively re-apply a group.
* This method should be used in last resort.
* Most of the time, the application should be triggered by an update on the deps of the processor.
*
* =====================================================================================================================
*
* The plugin or component that needs to enrich its data must use:
*
* - `apiRef.current.unstable_applyPipeProcessors` to run in chain all the processors of a given group.
*
* - `useGridRegisterPipeApplier` to re-apply the whole pipe when requested.
* The applier will be called when:
* * a processor is registered.
* * `apiRef.current.requestPipeProcessorsApplication` is called for the given group.
*/
const useGridPipeProcessing = apiRef => {
const cache = React.useRef({});
const isRunning = React.useRef(false);
const runAppliers = React.useCallback(groupCache => {
if (isRunning.current || !groupCache) {
return;
}
isRunning.current = true;
Object.values(groupCache.appliers).forEach(callback => {
callback();
});
isRunning.current = false;
}, []);
const registerPipeProcessor = React.useCallback((group, id, processor) => {
if (!cache.current[group]) {
cache.current[group] = {
processors: new Map(),
processorsAsArray: [],
appliers: {},
processorsUpdated: false
};
}
const groupCache = cache.current[group];
const oldProcessor = groupCache.processors.get(id);
if (oldProcessor !== processor) {
groupCache.processors.set(id, processor);
groupCache.processorsAsArray = Array.from(cache.current[group].processors.values()).filter(processorValue => processorValue !== null);
groupCache.processorsUpdated = true;
}
return () => {
cache.current[group].processors.set(id, null);
cache.current[group].processorsAsArray = Array.from(cache.current[group].processors.values()).filter(processorValue => processorValue !== null);
};
}, []);
const registerPipeApplier = React.useCallback((group, id, applier) => {
if (!cache.current[group]) {
cache.current[group] = {
processors: new Map(),
processorsAsArray: [],
appliers: {},
processorsUpdated: false
};
}
cache.current[group].appliers[id] = applier;
return () => {
const _appliers = cache.current[group].appliers,
otherAppliers = (0, _objectWithoutPropertiesLoose2.default)(_appliers, [id].map(_toPropertyKey2.default));
cache.current[group].appliers = otherAppliers;
};
}, []);
const requestPipeProcessorsApplication = React.useCallback(group => {
runAppliers(cache.current[group]);
}, [runAppliers]);
const runAppliersForPendingProcessors = React.useCallback(() => {
for (const group in cache.current) {
if (!Object.prototype.hasOwnProperty.call(cache.current, group)) {
continue;
}
const groupCache = cache.current[group];
if (groupCache.processorsUpdated) {
groupCache.processorsUpdated = false;
runAppliers(groupCache);
}
}
}, [runAppliers]);
const applyPipeProcessors = React.useCallback((...args) => {
const [group, value, context] = args;
if (!cache.current[group]) {
return value;
}
const processors = cache.current[group].processorsAsArray;
let result = value;
for (let i = 0; i < processors.length; i += 1) {
result = processors[i](result, context);
}
return result;
}, []);
const preProcessingPrivateApi = {
registerPipeProcessor,
registerPipeApplier,
requestPipeProcessorsApplication,
runAppliersForPendingProcessors
};
const preProcessingPublicApi = {
unstable_applyPipeProcessors: applyPipeProcessors
};
(0, _useGridApiMethod.useGridApiMethod)(apiRef, preProcessingPrivateApi, 'private');
(0, _useGridApiMethod.useGridApiMethod)(apiRef, preProcessingPublicApi, 'public');
};
exports.useGridPipeProcessing = useGridPipeProcessing;
@@ -0,0 +1,124 @@
'use client';
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _toPropertyKey from "@babel/runtime/helpers/esm/toPropertyKey";
import * as React from 'react';
import { useGridApiMethod } from "../../utils/useGridApiMethod.mjs";
/**
* Implement the Pipeline Pattern
*
* More information and detailed example in (TODO add link to technical doc when ready)
*
* Some plugins contains custom logic to enrich data provided by other plugins or components.
* For instance, the row grouping plugin needs to add / remove the grouping columns when the grid columns are updated.
*
* =====================================================================================================================
*
* The plugin containing the custom logic must use:
*
* - `useGridRegisterPipeProcessor` to register their processor.
*
* - `apiRef.current.requestPipeProcessorsApplication` to imperatively re-apply a group.
* This method should be used in last resort.
* Most of the time, the application should be triggered by an update on the deps of the processor.
*
* =====================================================================================================================
*
* The plugin or component that needs to enrich its data must use:
*
* - `apiRef.current.unstable_applyPipeProcessors` to run in chain all the processors of a given group.
*
* - `useGridRegisterPipeApplier` to re-apply the whole pipe when requested.
* The applier will be called when:
* * a processor is registered.
* * `apiRef.current.requestPipeProcessorsApplication` is called for the given group.
*/
export const useGridPipeProcessing = apiRef => {
const cache = React.useRef({});
const isRunning = React.useRef(false);
const runAppliers = React.useCallback(groupCache => {
if (isRunning.current || !groupCache) {
return;
}
isRunning.current = true;
Object.values(groupCache.appliers).forEach(callback => {
callback();
});
isRunning.current = false;
}, []);
const registerPipeProcessor = React.useCallback((group, id, processor) => {
if (!cache.current[group]) {
cache.current[group] = {
processors: new Map(),
processorsAsArray: [],
appliers: {},
processorsUpdated: false
};
}
const groupCache = cache.current[group];
const oldProcessor = groupCache.processors.get(id);
if (oldProcessor !== processor) {
groupCache.processors.set(id, processor);
groupCache.processorsAsArray = Array.from(cache.current[group].processors.values()).filter(processorValue => processorValue !== null);
groupCache.processorsUpdated = true;
}
return () => {
cache.current[group].processors.set(id, null);
cache.current[group].processorsAsArray = Array.from(cache.current[group].processors.values()).filter(processorValue => processorValue !== null);
};
}, []);
const registerPipeApplier = React.useCallback((group, id, applier) => {
if (!cache.current[group]) {
cache.current[group] = {
processors: new Map(),
processorsAsArray: [],
appliers: {},
processorsUpdated: false
};
}
cache.current[group].appliers[id] = applier;
return () => {
const _appliers = cache.current[group].appliers,
otherAppliers = _objectWithoutPropertiesLoose(_appliers, [id].map(_toPropertyKey));
cache.current[group].appliers = otherAppliers;
};
}, []);
const requestPipeProcessorsApplication = React.useCallback(group => {
runAppliers(cache.current[group]);
}, [runAppliers]);
const runAppliersForPendingProcessors = React.useCallback(() => {
for (const group in cache.current) {
if (!Object.prototype.hasOwnProperty.call(cache.current, group)) {
continue;
}
const groupCache = cache.current[group];
if (groupCache.processorsUpdated) {
groupCache.processorsUpdated = false;
runAppliers(groupCache);
}
}
}, [runAppliers]);
const applyPipeProcessors = React.useCallback((...args) => {
const [group, value, context] = args;
if (!cache.current[group]) {
return value;
}
const processors = cache.current[group].processorsAsArray;
let result = value;
for (let i = 0; i < processors.length; i += 1) {
result = processors[i](result, context);
}
return result;
}, []);
const preProcessingPrivateApi = {
registerPipeProcessor,
registerPipeApplier,
requestPipeProcessorsApplication,
runAppliersForPendingProcessors
};
const preProcessingPublicApi = {
unstable_applyPipeProcessors: applyPipeProcessors
};
useGridApiMethod(apiRef, preProcessingPrivateApi, 'private');
useGridApiMethod(apiRef, preProcessingPublicApi, 'public');
};
@@ -0,0 +1,4 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../../models/api/gridApiCommon.mjs";
import type { GridPipeProcessorGroup } from "./gridPipeProcessingApi.mjs";
export declare const useGridRegisterPipeApplier: <PrivateApi extends GridPrivateApiCommon, G extends GridPipeProcessorGroup>(apiRef: RefObject<PrivateApi>, group: G, callback: () => void) => void;
@@ -0,0 +1,4 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../../models/api/gridApiCommon.js";
import type { GridPipeProcessorGroup } from "./gridPipeProcessingApi.js";
export declare const useGridRegisterPipeApplier: <PrivateApi extends GridPrivateApiCommon, G extends GridPipeProcessorGroup>(apiRef: RefObject<PrivateApi>, group: G, callback: () => void) => void;
@@ -0,0 +1,35 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridRegisterPipeApplier = void 0;
var React = _interopRequireWildcard(require("react"));
var _useFirstRender = require("../../utils/useFirstRender");
const useGridRegisterPipeApplier = (apiRef, group, callback) => {
const cleanup = React.useRef(null);
const id = React.useRef(`mui-${Math.round(Math.random() * 1e9)}`);
const registerPreProcessor = React.useCallback(() => {
cleanup.current = apiRef.current.registerPipeApplier(group, id.current, callback);
}, [apiRef, callback, group]);
(0, _useFirstRender.useFirstRender)(() => {
registerPreProcessor();
});
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
} else {
registerPreProcessor();
}
return () => {
if (cleanup.current) {
cleanup.current();
cleanup.current = null;
}
};
}, [registerPreProcessor]);
};
exports.useGridRegisterPipeApplier = useGridRegisterPipeApplier;
@@ -0,0 +1,28 @@
'use client';
import * as React from 'react';
import { useFirstRender } from "../../utils/useFirstRender.mjs";
export const useGridRegisterPipeApplier = (apiRef, group, callback) => {
const cleanup = React.useRef(null);
const id = React.useRef(`mui-${Math.round(Math.random() * 1e9)}`);
const registerPreProcessor = React.useCallback(() => {
cleanup.current = apiRef.current.registerPipeApplier(group, id.current, callback);
}, [apiRef, callback, group]);
useFirstRender(() => {
registerPreProcessor();
});
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
} else {
registerPreProcessor();
}
return () => {
if (cleanup.current) {
cleanup.current();
cleanup.current = null;
}
};
}, [registerPreProcessor]);
};
@@ -0,0 +1,4 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../../models/api/gridApiCommon.mjs";
import type { GridPipeProcessorGroup, GridPipeProcessor } from "./gridPipeProcessingApi.mjs";
export declare const useGridRegisterPipeProcessor: <PrivateApi extends GridPrivateApiCommon, G extends GridPipeProcessorGroup>(apiRef: RefObject<PrivateApi>, group: G, callback: GridPipeProcessor<G>, enabled?: boolean) => void;
@@ -0,0 +1,4 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../../models/api/gridApiCommon.js";
import type { GridPipeProcessorGroup, GridPipeProcessor } from "./gridPipeProcessingApi.js";
export declare const useGridRegisterPipeProcessor: <PrivateApi extends GridPrivateApiCommon, G extends GridPipeProcessorGroup>(apiRef: RefObject<PrivateApi>, group: G, callback: GridPipeProcessor<G>, enabled?: boolean) => void;
@@ -0,0 +1,37 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridRegisterPipeProcessor = void 0;
var React = _interopRequireWildcard(require("react"));
var _useFirstRender = require("../../utils/useFirstRender");
const useGridRegisterPipeProcessor = (apiRef, group, callback, enabled = true) => {
const cleanup = React.useRef(null);
const id = React.useRef(`mui-${Math.round(Math.random() * 1e9)}`);
const registerPreProcessor = React.useCallback(() => {
cleanup.current = apiRef.current.registerPipeProcessor(group, id.current, callback);
}, [apiRef, callback, group]);
(0, _useFirstRender.useFirstRender)(() => {
if (enabled) {
registerPreProcessor();
}
});
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
} else if (enabled) {
registerPreProcessor();
}
return () => {
if (cleanup.current) {
cleanup.current();
cleanup.current = null;
}
};
}, [registerPreProcessor, enabled]);
};
exports.useGridRegisterPipeProcessor = useGridRegisterPipeProcessor;
@@ -0,0 +1,30 @@
'use client';
import * as React from 'react';
import { useFirstRender } from "../../utils/useFirstRender.mjs";
export const useGridRegisterPipeProcessor = (apiRef, group, callback, enabled = true) => {
const cleanup = React.useRef(null);
const id = React.useRef(`mui-${Math.round(Math.random() * 1e9)}`);
const registerPreProcessor = React.useCallback(() => {
cleanup.current = apiRef.current.registerPipeProcessor(group, id.current, callback);
}, [apiRef, callback, group]);
useFirstRender(() => {
if (enabled) {
registerPreProcessor();
}
});
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
} else if (enabled) {
registerPreProcessor();
}
return () => {
if (cleanup.current) {
cleanup.current();
cleanup.current = null;
}
};
}, [registerPreProcessor, enabled]);
};
@@ -0,0 +1,97 @@
import type { GridRowTreeCreationParams, GridRowTreeCreationValue, GridRowsState } from "../../features/rows/gridRowsInterfaces.mjs";
import type { GridFilteringMethodParams, GridFilteringMethodValue, GridFilterState, GridVisibleRowsLookupState } from "../../features/filter/gridFilterState.mjs";
import type { GridSortingMethodParams, GridSortingMethodValue } from "../../features/sorting/gridSortingState.mjs";
import type { GridGetRowsParams, GridGetRowsResponse, GridGetRowsOptions } from "../../../models/gridDataSource.mjs";
import type { GridRowId } from "../../../models/gridRows.mjs";
export type GridStrategyProcessorName = keyof GridStrategyProcessingLookup;
export declare enum GridStrategyGroup {
DataSource = "dataSource",
RowTree = "rowTree",
}
export type GridStrategyGroupValue = `${GridStrategyGroup}`;
export interface GridStrategyProcessingLookup {
dataSourceRootRowsUpdate: {
group: GridStrategyGroup.DataSource;
params: {
response: GridGetRowsResponse;
fetchParams: GridGetRowsParams;
options: GridGetRowsOptions;
} | {
error: Error;
fetchParams: GridGetRowsParams;
options: GridGetRowsOptions;
};
value: void;
};
dataSourceNestedRowsUpdate: {
group: GridStrategyGroup.DataSource;
params: {
parentId: GridRowId;
path: string[];
response: GridGetRowsResponse;
fetchParams: GridGetRowsParams;
} | {
parentId: GridRowId;
path: string[];
error: Error;
fetchParams: GridGetRowsParams;
};
value: void;
};
rowTreeCreation: {
group: GridStrategyGroup.RowTree;
params: GridRowTreeCreationParams;
value: GridRowTreeCreationValue;
};
filtering: {
group: GridStrategyGroup.RowTree;
params: GridFilteringMethodParams;
value: GridFilteringMethodValue;
};
sorting: {
group: GridStrategyGroup.RowTree;
params: GridSortingMethodParams;
value: GridSortingMethodValue;
};
visibleRowsLookupCreation: {
group: GridStrategyGroup.RowTree;
params: {
tree: GridRowsState['tree'];
filteredRowsLookup: GridFilterState['filteredRowsLookup'];
};
value: GridVisibleRowsLookupState;
};
}
export type GridStrategyProcessor<P extends GridStrategyProcessorName> = (params: GridStrategyProcessingLookup[P]['params']) => GridStrategyProcessingLookup[P]['value'];
export interface GridStrategyProcessingApi {
/**
* Registers a strategy processor.
* If the strategy is active, it emits an event to notify the agents to re-apply the processor.
* @template P
* @param {string} strategyName The name of the strategy on which this processor should be applied.
* @param {GridStrategyProcessorName} processorName The name of the processor.
* @param {GridStrategyProcessor<P>} processor The processor to register.
* @returns {() => void} A function to unregister the processor.
*/
registerStrategyProcessor: <P extends GridStrategyProcessorName>(strategyName: string, processorName: P, processor: GridStrategyProcessor<P>) => () => void;
/**
* Set a callback to know if a strategy is available.
* @param {GridStrategyGroupValue} strategyGroup The group for which we set strategy availability.
* @param {string} strategyName The name of the strategy.
* @param {boolean} callback A callback to know if this strategy is available.
*/
setStrategyAvailability: (strategyGroup: GridStrategyGroupValue, strategyName: string, callback: () => boolean) => void;
/**
* Returns the name of the active strategy of a given strategy group
* @param {GridStrategyGroupValue} strategyGroup The group from which we want the active strategy.
* @returns {string} The name of the active strategy.
*/
getActiveStrategy: (strategyGroup: GridStrategyGroupValue) => string;
/**
* Run the processor registered for the active strategy.
* @param {GridStrategyProcessorName} processorName The name of the processor to run.
* @param {GridStrategyProcessingLookup[P]['params']} params Additional params to pass to the processor.
* @returns {GridStrategyProcessingLookup[P]['value']} The value returned by the processor.
*/
applyStrategyProcessor: <P extends GridStrategyProcessorName>(processorName: P, params: GridStrategyProcessingLookup[P]['params']) => GridStrategyProcessingLookup[P]['value'];
}
@@ -0,0 +1,97 @@
import type { GridRowTreeCreationParams, GridRowTreeCreationValue, GridRowsState } from "../../features/rows/gridRowsInterfaces.js";
import type { GridFilteringMethodParams, GridFilteringMethodValue, GridFilterState, GridVisibleRowsLookupState } from "../../features/filter/gridFilterState.js";
import type { GridSortingMethodParams, GridSortingMethodValue } from "../../features/sorting/gridSortingState.js";
import type { GridGetRowsParams, GridGetRowsResponse, GridGetRowsOptions } from "../../../models/gridDataSource.js";
import type { GridRowId } from "../../../models/gridRows.js";
export type GridStrategyProcessorName = keyof GridStrategyProcessingLookup;
export declare enum GridStrategyGroup {
DataSource = "dataSource",
RowTree = "rowTree",
}
export type GridStrategyGroupValue = `${GridStrategyGroup}`;
export interface GridStrategyProcessingLookup {
dataSourceRootRowsUpdate: {
group: GridStrategyGroup.DataSource;
params: {
response: GridGetRowsResponse;
fetchParams: GridGetRowsParams;
options: GridGetRowsOptions;
} | {
error: Error;
fetchParams: GridGetRowsParams;
options: GridGetRowsOptions;
};
value: void;
};
dataSourceNestedRowsUpdate: {
group: GridStrategyGroup.DataSource;
params: {
parentId: GridRowId;
path: string[];
response: GridGetRowsResponse;
fetchParams: GridGetRowsParams;
} | {
parentId: GridRowId;
path: string[];
error: Error;
fetchParams: GridGetRowsParams;
};
value: void;
};
rowTreeCreation: {
group: GridStrategyGroup.RowTree;
params: GridRowTreeCreationParams;
value: GridRowTreeCreationValue;
};
filtering: {
group: GridStrategyGroup.RowTree;
params: GridFilteringMethodParams;
value: GridFilteringMethodValue;
};
sorting: {
group: GridStrategyGroup.RowTree;
params: GridSortingMethodParams;
value: GridSortingMethodValue;
};
visibleRowsLookupCreation: {
group: GridStrategyGroup.RowTree;
params: {
tree: GridRowsState['tree'];
filteredRowsLookup: GridFilterState['filteredRowsLookup'];
};
value: GridVisibleRowsLookupState;
};
}
export type GridStrategyProcessor<P extends GridStrategyProcessorName> = (params: GridStrategyProcessingLookup[P]['params']) => GridStrategyProcessingLookup[P]['value'];
export interface GridStrategyProcessingApi {
/**
* Registers a strategy processor.
* If the strategy is active, it emits an event to notify the agents to re-apply the processor.
* @template P
* @param {string} strategyName The name of the strategy on which this processor should be applied.
* @param {GridStrategyProcessorName} processorName The name of the processor.
* @param {GridStrategyProcessor<P>} processor The processor to register.
* @returns {() => void} A function to unregister the processor.
*/
registerStrategyProcessor: <P extends GridStrategyProcessorName>(strategyName: string, processorName: P, processor: GridStrategyProcessor<P>) => () => void;
/**
* Set a callback to know if a strategy is available.
* @param {GridStrategyGroupValue} strategyGroup The group for which we set strategy availability.
* @param {string} strategyName The name of the strategy.
* @param {boolean} callback A callback to know if this strategy is available.
*/
setStrategyAvailability: (strategyGroup: GridStrategyGroupValue, strategyName: string, callback: () => boolean) => void;
/**
* Returns the name of the active strategy of a given strategy group
* @param {GridStrategyGroupValue} strategyGroup The group from which we want the active strategy.
* @returns {string} The name of the active strategy.
*/
getActiveStrategy: (strategyGroup: GridStrategyGroupValue) => string;
/**
* Run the processor registered for the active strategy.
* @param {GridStrategyProcessorName} processorName The name of the processor to run.
* @param {GridStrategyProcessingLookup[P]['params']} params Additional params to pass to the processor.
* @returns {GridStrategyProcessingLookup[P]['value']} The value returned by the processor.
*/
applyStrategyProcessor: <P extends GridStrategyProcessorName>(processorName: P, params: GridStrategyProcessingLookup[P]['params']) => GridStrategyProcessingLookup[P]['value'];
}
@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GridStrategyGroup = void 0;
let GridStrategyGroup = exports.GridStrategyGroup = /*#__PURE__*/function (GridStrategyGroup) {
GridStrategyGroup["DataSource"] = "dataSource";
GridStrategyGroup["RowTree"] = "rowTree";
return GridStrategyGroup;
}({});
@@ -0,0 +1,5 @@
export let GridStrategyGroup = /*#__PURE__*/function (GridStrategyGroup) {
GridStrategyGroup["DataSource"] = "dataSource";
GridStrategyGroup["RowTree"] = "rowTree";
return GridStrategyGroup;
}({});
@@ -0,0 +1,3 @@
export * from "./gridStrategyProcessingApi.mjs";
export * from "./useGridRegisterStrategyProcessor.mjs";
export * from "./useGridStrategyProcessing.mjs";
@@ -0,0 +1,3 @@
export * from "./gridStrategyProcessingApi.js";
export * from "./useGridRegisterStrategyProcessor.js";
export * from "./useGridStrategyProcessing.js";
@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _gridStrategyProcessingApi = require("./gridStrategyProcessingApi");
Object.keys(_gridStrategyProcessingApi).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _gridStrategyProcessingApi[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _gridStrategyProcessingApi[key];
}
});
});
var _useGridRegisterStrategyProcessor = require("./useGridRegisterStrategyProcessor");
Object.keys(_useGridRegisterStrategyProcessor).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _useGridRegisterStrategyProcessor[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _useGridRegisterStrategyProcessor[key];
}
});
});
var _useGridStrategyProcessing = require("./useGridStrategyProcessing");
Object.keys(_useGridStrategyProcessing).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _useGridStrategyProcessing[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _useGridStrategyProcessing[key];
}
});
});
@@ -0,0 +1,3 @@
export * from "./gridStrategyProcessingApi.mjs";
export * from "./useGridRegisterStrategyProcessor.mjs";
export * from "./useGridStrategyProcessing.mjs";
@@ -0,0 +1,4 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../../models/api/gridApiCommon.mjs";
import type { GridStrategyProcessorName, GridStrategyProcessor } from "./gridStrategyProcessingApi.mjs";
export declare const useGridRegisterStrategyProcessor: <Api extends GridPrivateApiCommon, G extends GridStrategyProcessorName>(apiRef: RefObject<Api>, strategyName: string, group: G, processor: GridStrategyProcessor<G>) => void;
@@ -0,0 +1,4 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../../models/api/gridApiCommon.js";
import type { GridStrategyProcessorName, GridStrategyProcessor } from "./gridStrategyProcessingApi.js";
export declare const useGridRegisterStrategyProcessor: <Api extends GridPrivateApiCommon, G extends GridStrategyProcessorName>(apiRef: RefObject<Api>, strategyName: string, group: G, processor: GridStrategyProcessor<G>) => void;
@@ -0,0 +1,33 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridRegisterStrategyProcessor = void 0;
var React = _interopRequireWildcard(require("react"));
var _useFirstRender = require("../../utils/useFirstRender");
const useGridRegisterStrategyProcessor = (apiRef, strategyName, group, processor) => {
const registerPreProcessor = React.useCallback(() => {
// NOTE: the unregister fn is intentionally discarded. Unlike pipe processors
// (which are additive), a strategy processor is required for as long as its
// strategy is active — `applyStrategyProcessor` throws if the active strategy's
// processor is missing — so it must outlive the registering component. The cache
// keeps a single entry per (processor, strategy) and is reclaimed with the grid
// api, so nothing leaks; `void` documents the deliberate discard.
void apiRef.current.registerStrategyProcessor(strategyName, group, processor);
}, [apiRef, processor, group, strategyName]);
(0, _useFirstRender.useFirstRender)(() => {
registerPreProcessor();
});
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
} else {
registerPreProcessor();
}
}, [registerPreProcessor]);
};
exports.useGridRegisterStrategyProcessor = useGridRegisterStrategyProcessor;
@@ -0,0 +1,26 @@
'use client';
import * as React from 'react';
import { useFirstRender } from "../../utils/useFirstRender.mjs";
export const useGridRegisterStrategyProcessor = (apiRef, strategyName, group, processor) => {
const registerPreProcessor = React.useCallback(() => {
// NOTE: the unregister fn is intentionally discarded. Unlike pipe processors
// (which are additive), a strategy processor is required for as long as its
// strategy is active — `applyStrategyProcessor` throws if the active strategy's
// processor is missing — so it must outlive the registering component. The cache
// keeps a single entry per (processor, strategy) and is reclaimed with the grid
// api, so nothing leaks; `void` documents the deliberate discard.
void apiRef.current.registerStrategyProcessor(strategyName, group, processor);
}, [apiRef, processor, group, strategyName]);
useFirstRender(() => {
registerPreProcessor();
});
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
} else {
registerPreProcessor();
}
}, [registerPreProcessor]);
};
@@ -0,0 +1,41 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../../models/api/gridApiCommon.mjs";
export declare const GRID_DEFAULT_STRATEGY = "none";
/**
* Implements a variant of the Strategy Pattern (see https://en.wikipedia.org/wiki/Strategy_pattern)
*
* More information and detailed example in (TODO add link to technical doc when ready)
*
* Some plugins contains custom logic that must only be applied if the right strategy is active.
* For instance, the row grouping plugin has a custom filtering algorithm.
* This algorithm must be applied by the filtering plugin if the row grouping is the current way of grouping rows,
* but not if the tree data is the current way of grouping rows.
*
* =====================================================================================================================
*
* The plugin containing the custom logic must use:
*
* - `useGridRegisterStrategyProcessor` to register their processor.
* When the processor of the active strategy changes, it will fire `"activeStrategyProcessorChange"` to re-apply the processor.
*
* - `apiRef.current.setStrategyAvailability` to tell if their strategy can be used.
*
* =====================================================================================================================
*
* The plugin or component that needs to apply the custom logic of the current strategy must use:
*
* - `apiRef.current.applyStrategyProcessor` to run the processor of the active strategy for a given processor name.
*
* - the "strategyAvailabilityChange" event to update something when the active strategy changes.
* Warning: Be careful not to apply the processor several times.
* For instance "rowsSet" is fired by `useGridRows` whenever the active strategy changes.
* So listening to both would most likely run your logic twice.
*
* - The "activeStrategyProcessorChange" event to update something when the processor of the active strategy changes.
*
* =====================================================================================================================
*
* Each processor name is part of a strategy group which can only have one active strategy at the time.
* There are two active groups named `rowTree` and `dataSource`.
*/
export declare const useGridStrategyProcessing: (apiRef: RefObject<GridPrivateApiCommon>) => void;
@@ -0,0 +1,41 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../../models/api/gridApiCommon.js";
export declare const GRID_DEFAULT_STRATEGY = "none";
/**
* Implements a variant of the Strategy Pattern (see https://en.wikipedia.org/wiki/Strategy_pattern)
*
* More information and detailed example in (TODO add link to technical doc when ready)
*
* Some plugins contains custom logic that must only be applied if the right strategy is active.
* For instance, the row grouping plugin has a custom filtering algorithm.
* This algorithm must be applied by the filtering plugin if the row grouping is the current way of grouping rows,
* but not if the tree data is the current way of grouping rows.
*
* =====================================================================================================================
*
* The plugin containing the custom logic must use:
*
* - `useGridRegisterStrategyProcessor` to register their processor.
* When the processor of the active strategy changes, it will fire `"activeStrategyProcessorChange"` to re-apply the processor.
*
* - `apiRef.current.setStrategyAvailability` to tell if their strategy can be used.
*
* =====================================================================================================================
*
* The plugin or component that needs to apply the custom logic of the current strategy must use:
*
* - `apiRef.current.applyStrategyProcessor` to run the processor of the active strategy for a given processor name.
*
* - the "strategyAvailabilityChange" event to update something when the active strategy changes.
* Warning: Be careful not to apply the processor several times.
* For instance "rowsSet" is fired by `useGridRows` whenever the active strategy changes.
* So listening to both would most likely run your logic twice.
*
* - The "activeStrategyProcessorChange" event to update something when the processor of the active strategy changes.
*
* =====================================================================================================================
*
* Each processor name is part of a strategy group which can only have one active strategy at the time.
* There are two active groups named `rowTree` and `dataSource`.
*/
export declare const useGridStrategyProcessing: (apiRef: RefObject<GridPrivateApiCommon>) => void;
@@ -0,0 +1,122 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridStrategyProcessing = exports.GRID_DEFAULT_STRATEGY = void 0;
var _formatErrorMessage2 = _interopRequireDefault(require("@mui/x-internals/formatErrorMessage"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _toPropertyKey2 = _interopRequireDefault(require("@babel/runtime/helpers/toPropertyKey"));
var React = _interopRequireWildcard(require("react"));
var _gridStrategyProcessingApi = require("./gridStrategyProcessingApi");
var _useGridApiMethod = require("../../utils/useGridApiMethod");
const GRID_DEFAULT_STRATEGY = exports.GRID_DEFAULT_STRATEGY = 'none';
const GRID_STRATEGIES_PROCESSORS = {
dataSourceRootRowsUpdate: _gridStrategyProcessingApi.GridStrategyGroup.DataSource,
dataSourceNestedRowsUpdate: _gridStrategyProcessingApi.GridStrategyGroup.DataSource,
rowTreeCreation: _gridStrategyProcessingApi.GridStrategyGroup.RowTree,
filtering: _gridStrategyProcessingApi.GridStrategyGroup.RowTree,
sorting: _gridStrategyProcessingApi.GridStrategyGroup.RowTree,
visibleRowsLookupCreation: _gridStrategyProcessingApi.GridStrategyGroup.RowTree
};
/**
* Implements a variant of the Strategy Pattern (see https://en.wikipedia.org/wiki/Strategy_pattern)
*
* More information and detailed example in (TODO add link to technical doc when ready)
*
* Some plugins contains custom logic that must only be applied if the right strategy is active.
* For instance, the row grouping plugin has a custom filtering algorithm.
* This algorithm must be applied by the filtering plugin if the row grouping is the current way of grouping rows,
* but not if the tree data is the current way of grouping rows.
*
* =====================================================================================================================
*
* The plugin containing the custom logic must use:
*
* - `useGridRegisterStrategyProcessor` to register their processor.
* When the processor of the active strategy changes, it will fire `"activeStrategyProcessorChange"` to re-apply the processor.
*
* - `apiRef.current.setStrategyAvailability` to tell if their strategy can be used.
*
* =====================================================================================================================
*
* The plugin or component that needs to apply the custom logic of the current strategy must use:
*
* - `apiRef.current.applyStrategyProcessor` to run the processor of the active strategy for a given processor name.
*
* - the "strategyAvailabilityChange" event to update something when the active strategy changes.
* Warning: Be careful not to apply the processor several times.
* For instance "rowsSet" is fired by `useGridRows` whenever the active strategy changes.
* So listening to both would most likely run your logic twice.
*
* - The "activeStrategyProcessorChange" event to update something when the processor of the active strategy changes.
*
* =====================================================================================================================
*
* Each processor name is part of a strategy group which can only have one active strategy at the time.
* There are two active groups named `rowTree` and `dataSource`.
*/
const useGridStrategyProcessing = apiRef => {
const availableStrategies = React.useRef(new Map());
const strategiesCache = React.useRef({});
const registerStrategyProcessor = React.useCallback((strategyName, processorName, processor) => {
const cleanup = () => {
const _ref = strategiesCache.current[processorName],
otherProcessors = (0, _objectWithoutPropertiesLoose2.default)(_ref, [strategyName].map(_toPropertyKey2.default));
strategiesCache.current[processorName] = otherProcessors;
};
if (!strategiesCache.current[processorName]) {
strategiesCache.current[processorName] = {};
}
const groupPreProcessors = strategiesCache.current[processorName];
const previousProcessor = groupPreProcessors[strategyName];
groupPreProcessors[strategyName] = processor;
if (!previousProcessor || previousProcessor === processor) {
return cleanup;
}
if (strategyName === apiRef.current.getActiveStrategy(GRID_STRATEGIES_PROCESSORS[processorName])) {
apiRef.current.publishEvent('activeStrategyProcessorChange', processorName);
}
return cleanup;
}, [apiRef]);
const applyStrategyProcessor = React.useCallback((processorName, params) => {
const activeStrategy = apiRef.current.getActiveStrategy(GRID_STRATEGIES_PROCESSORS[processorName]);
if (activeStrategy == null) {
throw new Error(process.env.NODE_ENV !== "production" ? "MUI X: Can't apply a strategy processor before defining an active strategy" : (0, _formatErrorMessage2.default)(72));
}
const groupCache = strategiesCache.current[processorName];
if (!groupCache || !groupCache[activeStrategy]) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No processor found for processor "${processorName}" on strategy "${activeStrategy}"` : (0, _formatErrorMessage2.default)(73, processorName, activeStrategy));
}
const processor = groupCache[activeStrategy];
return processor(params);
}, [apiRef]);
const getActiveStrategy = React.useCallback(strategyGroup => {
const strategyEntries = Array.from(availableStrategies.current.entries());
const availableStrategyEntry = strategyEntries.find(([, strategy]) => {
if (strategy.group !== strategyGroup) {
return false;
}
return strategy.isAvailable();
});
return availableStrategyEntry?.[0] ?? GRID_DEFAULT_STRATEGY;
}, []);
const setStrategyAvailability = React.useCallback((strategyGroup, strategyName, isAvailable) => {
availableStrategies.current.set(strategyName, {
group: strategyGroup,
isAvailable
});
apiRef.current.publishEvent('strategyAvailabilityChange');
}, [apiRef]);
const strategyProcessingApi = {
registerStrategyProcessor,
applyStrategyProcessor,
getActiveStrategy,
setStrategyAvailability
};
(0, _useGridApiMethod.useGridApiMethod)(apiRef, strategyProcessingApi, 'private');
};
exports.useGridStrategyProcessing = useGridStrategyProcessing;
@@ -0,0 +1,114 @@
'use client';
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _toPropertyKey from "@babel/runtime/helpers/esm/toPropertyKey";
import * as React from 'react';
import { GridStrategyGroup } from "./gridStrategyProcessingApi.mjs";
import { useGridApiMethod } from "../../utils/useGridApiMethod.mjs";
export const GRID_DEFAULT_STRATEGY = 'none';
const GRID_STRATEGIES_PROCESSORS = {
dataSourceRootRowsUpdate: GridStrategyGroup.DataSource,
dataSourceNestedRowsUpdate: GridStrategyGroup.DataSource,
rowTreeCreation: GridStrategyGroup.RowTree,
filtering: GridStrategyGroup.RowTree,
sorting: GridStrategyGroup.RowTree,
visibleRowsLookupCreation: GridStrategyGroup.RowTree
};
/**
* Implements a variant of the Strategy Pattern (see https://en.wikipedia.org/wiki/Strategy_pattern)
*
* More information and detailed example in (TODO add link to technical doc when ready)
*
* Some plugins contains custom logic that must only be applied if the right strategy is active.
* For instance, the row grouping plugin has a custom filtering algorithm.
* This algorithm must be applied by the filtering plugin if the row grouping is the current way of grouping rows,
* but not if the tree data is the current way of grouping rows.
*
* =====================================================================================================================
*
* The plugin containing the custom logic must use:
*
* - `useGridRegisterStrategyProcessor` to register their processor.
* When the processor of the active strategy changes, it will fire `"activeStrategyProcessorChange"` to re-apply the processor.
*
* - `apiRef.current.setStrategyAvailability` to tell if their strategy can be used.
*
* =====================================================================================================================
*
* The plugin or component that needs to apply the custom logic of the current strategy must use:
*
* - `apiRef.current.applyStrategyProcessor` to run the processor of the active strategy for a given processor name.
*
* - the "strategyAvailabilityChange" event to update something when the active strategy changes.
* Warning: Be careful not to apply the processor several times.
* For instance "rowsSet" is fired by `useGridRows` whenever the active strategy changes.
* So listening to both would most likely run your logic twice.
*
* - The "activeStrategyProcessorChange" event to update something when the processor of the active strategy changes.
*
* =====================================================================================================================
*
* Each processor name is part of a strategy group which can only have one active strategy at the time.
* There are two active groups named `rowTree` and `dataSource`.
*/
export const useGridStrategyProcessing = apiRef => {
const availableStrategies = React.useRef(new Map());
const strategiesCache = React.useRef({});
const registerStrategyProcessor = React.useCallback((strategyName, processorName, processor) => {
const cleanup = () => {
const _ref = strategiesCache.current[processorName],
otherProcessors = _objectWithoutPropertiesLoose(_ref, [strategyName].map(_toPropertyKey));
strategiesCache.current[processorName] = otherProcessors;
};
if (!strategiesCache.current[processorName]) {
strategiesCache.current[processorName] = {};
}
const groupPreProcessors = strategiesCache.current[processorName];
const previousProcessor = groupPreProcessors[strategyName];
groupPreProcessors[strategyName] = processor;
if (!previousProcessor || previousProcessor === processor) {
return cleanup;
}
if (strategyName === apiRef.current.getActiveStrategy(GRID_STRATEGIES_PROCESSORS[processorName])) {
apiRef.current.publishEvent('activeStrategyProcessorChange', processorName);
}
return cleanup;
}, [apiRef]);
const applyStrategyProcessor = React.useCallback((processorName, params) => {
const activeStrategy = apiRef.current.getActiveStrategy(GRID_STRATEGIES_PROCESSORS[processorName]);
if (activeStrategy == null) {
throw new Error(process.env.NODE_ENV !== "production" ? "MUI X: Can't apply a strategy processor before defining an active strategy" : _formatErrorMessage(72));
}
const groupCache = strategiesCache.current[processorName];
if (!groupCache || !groupCache[activeStrategy]) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No processor found for processor "${processorName}" on strategy "${activeStrategy}"` : _formatErrorMessage(73, processorName, activeStrategy));
}
const processor = groupCache[activeStrategy];
return processor(params);
}, [apiRef]);
const getActiveStrategy = React.useCallback(strategyGroup => {
const strategyEntries = Array.from(availableStrategies.current.entries());
const availableStrategyEntry = strategyEntries.find(([, strategy]) => {
if (strategy.group !== strategyGroup) {
return false;
}
return strategy.isAvailable();
});
return availableStrategyEntry?.[0] ?? GRID_DEFAULT_STRATEGY;
}, []);
const setStrategyAvailability = React.useCallback((strategyGroup, strategyName, isAvailable) => {
availableStrategies.current.set(strategyName, {
group: strategyGroup,
isAvailable
});
apiRef.current.publishEvent('strategyAvailabilityChange');
}, [apiRef]);
const strategyProcessingApi = {
registerStrategyProcessor,
applyStrategyProcessor,
getActiveStrategy,
setStrategyAvailability
};
useGridApiMethod(apiRef, strategyProcessingApi, 'private');
};
@@ -0,0 +1,5 @@
import type { RefObject } from '@mui/x-internals/types';
import type { DataGridProcessedProps } from "../../models/props/DataGridProps.mjs";
import type { GridApiCommon, GridPrivateApiCommon } from "../../models/api/gridApiCommon.mjs";
export declare function unwrapPrivateAPI<PrivateApi extends GridPrivateApiCommon, Api extends GridApiCommon>(publicApi: Api): PrivateApi;
export declare function useGridApiInitialization<PrivateApi extends GridPrivateApiCommon, Api extends GridApiCommon>(inputApiRef: RefObject<Api | null> | undefined, props: Pick<DataGridProcessedProps, 'signature'>): RefObject<PrivateApi>;
@@ -0,0 +1,5 @@
import type { RefObject } from '@mui/x-internals/types';
import type { DataGridProcessedProps } from "../../models/props/DataGridProps.js";
import type { GridApiCommon, GridPrivateApiCommon } from "../../models/api/gridApiCommon.js";
export declare function unwrapPrivateAPI<PrivateApi extends GridPrivateApiCommon, Api extends GridApiCommon>(publicApi: Api): PrivateApi;
export declare function useGridApiInitialization<PrivateApi extends GridPrivateApiCommon, Api extends GridApiCommon>(inputApiRef: RefObject<Api | null> | undefined, props: Pick<DataGridProcessedProps, 'signature'>): RefObject<PrivateApi>;
@@ -0,0 +1,121 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.unwrapPrivateAPI = unwrapPrivateAPI;
exports.useGridApiInitialization = useGridApiInitialization;
var React = _interopRequireWildcard(require("react"));
var _EventManager = require("@mui/x-internals/EventManager");
var _store = require("@mui/x-internals/store");
var _useGridApiMethod = require("../utils/useGridApiMethod");
var _signature = require("../../constants/signature");
const SYMBOL_API_PRIVATE = Symbol('mui.api_private');
const isSyntheticEvent = event => {
return event.isPropagationStopped !== undefined;
};
function unwrapPrivateAPI(publicApi) {
return publicApi[SYMBOL_API_PRIVATE];
}
let globalId = 0;
function createPrivateAPI(publicApiRef) {
const existingPrivateApi = publicApiRef.current?.[SYMBOL_API_PRIVATE];
if (existingPrivateApi) {
return existingPrivateApi;
}
const state = {};
const privateApi = {
state,
store: _store.Store.create(state),
instanceId: {
id: globalId
}
};
globalId += 1;
privateApi.getPublicApi = () => publicApiRef.current;
privateApi.register = (visibility, methods) => {
Object.keys(methods).forEach(methodName => {
const method = methods[methodName];
const currentPrivateMethod = privateApi[methodName];
if (currentPrivateMethod?.spying === true) {
currentPrivateMethod.target = method;
} else {
privateApi[methodName] = method;
}
if (visibility === 'public') {
const publicApi = publicApiRef.current;
const currentPublicMethod = publicApi[methodName];
if (currentPublicMethod?.spying === true) {
currentPublicMethod.target = method;
} else {
publicApi[methodName] = method;
}
}
});
};
privateApi.register('private', {
caches: {},
eventManager: new _EventManager.EventManager()
});
return privateApi;
}
function createPublicAPI(privateApiRef) {
const publicApi = {
get state() {
return privateApiRef.current.state;
},
get store() {
return privateApiRef.current.store;
},
get instanceId() {
return privateApiRef.current.instanceId;
},
[SYMBOL_API_PRIVATE]: privateApiRef.current
};
return publicApi;
}
function useGridApiInitialization(inputApiRef, props) {
const publicApiRef = React.useRef(null);
const privateApiRef = React.useRef(null);
if (!privateApiRef.current) {
privateApiRef.current = createPrivateAPI(publicApiRef);
}
if (!publicApiRef.current) {
publicApiRef.current = createPublicAPI(privateApiRef);
}
const publishEvent = React.useCallback((...args) => {
const [name, params, event = {}] = args;
event.defaultMuiPrevented = false;
if (isSyntheticEvent(event) && event.isPropagationStopped()) {
return;
}
const details = props.signature === _signature.GridSignature.DataGridPro || props.signature === _signature.GridSignature.DataGridPremium ? {
api: privateApiRef.current.getPublicApi()
} : {};
privateApiRef.current.eventManager.emit(name, params, event, details);
}, [privateApiRef, props.signature]);
const subscribeEvent = React.useCallback((event, handler, options) => {
privateApiRef.current.eventManager.on(event, handler, options);
const api = privateApiRef.current;
return () => {
api.eventManager.removeListener(event, handler);
};
}, [privateApiRef]);
(0, _useGridApiMethod.useGridApiMethod)(privateApiRef, {
subscribeEvent,
publishEvent
}, 'public');
if (inputApiRef && !inputApiRef.current?.state) {
inputApiRef.current = publicApiRef.current;
}
React.useImperativeHandle(inputApiRef, () => publicApiRef.current, [publicApiRef]);
React.useEffect(() => {
const api = privateApiRef.current;
return () => {
api.publishEvent('unmount');
};
}, [privateApiRef]);
return privateApiRef;
}
@@ -0,0 +1,114 @@
'use client';
import * as React from 'react';
import { EventManager } from '@mui/x-internals/EventManager';
import { Store } from '@mui/x-internals/store';
import { useGridApiMethod } from "../utils/useGridApiMethod.mjs";
import { GridSignature } from "../../constants/signature.mjs";
const SYMBOL_API_PRIVATE = Symbol('mui.api_private');
const isSyntheticEvent = event => {
return event.isPropagationStopped !== undefined;
};
export function unwrapPrivateAPI(publicApi) {
return publicApi[SYMBOL_API_PRIVATE];
}
let globalId = 0;
function createPrivateAPI(publicApiRef) {
const existingPrivateApi = publicApiRef.current?.[SYMBOL_API_PRIVATE];
if (existingPrivateApi) {
return existingPrivateApi;
}
const state = {};
const privateApi = {
state,
store: Store.create(state),
instanceId: {
id: globalId
}
};
globalId += 1;
privateApi.getPublicApi = () => publicApiRef.current;
privateApi.register = (visibility, methods) => {
Object.keys(methods).forEach(methodName => {
const method = methods[methodName];
const currentPrivateMethod = privateApi[methodName];
if (currentPrivateMethod?.spying === true) {
currentPrivateMethod.target = method;
} else {
privateApi[methodName] = method;
}
if (visibility === 'public') {
const publicApi = publicApiRef.current;
const currentPublicMethod = publicApi[methodName];
if (currentPublicMethod?.spying === true) {
currentPublicMethod.target = method;
} else {
publicApi[methodName] = method;
}
}
});
};
privateApi.register('private', {
caches: {},
eventManager: new EventManager()
});
return privateApi;
}
function createPublicAPI(privateApiRef) {
const publicApi = {
get state() {
return privateApiRef.current.state;
},
get store() {
return privateApiRef.current.store;
},
get instanceId() {
return privateApiRef.current.instanceId;
},
[SYMBOL_API_PRIVATE]: privateApiRef.current
};
return publicApi;
}
export function useGridApiInitialization(inputApiRef, props) {
const publicApiRef = React.useRef(null);
const privateApiRef = React.useRef(null);
if (!privateApiRef.current) {
privateApiRef.current = createPrivateAPI(publicApiRef);
}
if (!publicApiRef.current) {
publicApiRef.current = createPublicAPI(privateApiRef);
}
const publishEvent = React.useCallback((...args) => {
const [name, params, event = {}] = args;
event.defaultMuiPrevented = false;
if (isSyntheticEvent(event) && event.isPropagationStopped()) {
return;
}
const details = props.signature === GridSignature.DataGridPro || props.signature === GridSignature.DataGridPremium ? {
api: privateApiRef.current.getPublicApi()
} : {};
privateApiRef.current.eventManager.emit(name, params, event, details);
}, [privateApiRef, props.signature]);
const subscribeEvent = React.useCallback((event, handler, options) => {
privateApiRef.current.eventManager.on(event, handler, options);
const api = privateApiRef.current;
return () => {
api.eventManager.removeListener(event, handler);
};
}, [privateApiRef]);
useGridApiMethod(privateApiRef, {
subscribeEvent,
publishEvent
}, 'public');
if (inputApiRef && !inputApiRef.current?.state) {
inputApiRef.current = publicApiRef.current;
}
React.useImperativeHandle(inputApiRef, () => publicApiRef.current, [publicApiRef]);
React.useEffect(() => {
const api = privateApiRef.current;
return () => {
api.publishEvent('unmount');
};
}, [privateApiRef]);
return privateApiRef;
}
@@ -0,0 +1,7 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.mjs";
import type { DataGridProcessedProps } from "../../models/props/DataGridProps.mjs";
/**
* Initialize the technical pieces of the DataGrid (logger, state, ...) that any DataGrid implementation needs
*/
export declare const useGridInitialization: <PrivateApi extends GridPrivateApiCommon>(privateApiRef: RefObject<PrivateApi>, props: DataGridProcessedProps) => void;
@@ -0,0 +1,7 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.js";
import type { DataGridProcessedProps } from "../../models/props/DataGridProps.js";
/**
* Initialize the technical pieces of the DataGrid (logger, state, ...) that any DataGrid implementation needs
*/
export declare const useGridInitialization: <PrivateApi extends GridPrivateApiCommon>(privateApiRef: RefObject<PrivateApi>, props: DataGridProcessedProps) => void;
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridInitialization = void 0;
var _useGridRefs = require("./useGridRefs");
var _useGridIsRtl = require("./useGridIsRtl");
var _useGridLoggerFactory = require("./useGridLoggerFactory");
var _useGridLocaleText = require("./useGridLocaleText");
var _pipeProcessing = require("./pipeProcessing");
var _strategyProcessing = require("./strategyProcessing");
var _useGridStateInitialization = require("./useGridStateInitialization");
var _useGridProps = require("./useGridProps");
/**
* Initialize the technical pieces of the DataGrid (logger, state, ...) that any DataGrid implementation needs
*/
const useGridInitialization = (privateApiRef, props) => {
(0, _useGridRefs.useGridRefs)(privateApiRef);
(0, _useGridProps.useGridProps)(privateApiRef, props);
(0, _useGridIsRtl.useGridIsRtl)(privateApiRef);
(0, _useGridLoggerFactory.useGridLoggerFactory)(privateApiRef, props);
(0, _useGridStateInitialization.useGridStateInitialization)(privateApiRef);
(0, _pipeProcessing.useGridPipeProcessing)(privateApiRef);
(0, _strategyProcessing.useGridStrategyProcessing)(privateApiRef);
(0, _useGridLocaleText.useGridLocaleText)(privateApiRef, props);
privateApiRef.current.register('private', {
rootProps: props
});
};
exports.useGridInitialization = useGridInitialization;
@@ -0,0 +1,25 @@
import { useGridRefs } from "./useGridRefs.mjs";
import { useGridIsRtl } from "./useGridIsRtl.mjs";
import { useGridLoggerFactory } from "./useGridLoggerFactory.mjs";
import { useGridLocaleText } from "./useGridLocaleText.mjs";
import { useGridPipeProcessing } from "./pipeProcessing/index.mjs";
import { useGridStrategyProcessing } from "./strategyProcessing/index.mjs";
import { useGridStateInitialization } from "./useGridStateInitialization.mjs";
import { useGridProps } from "./useGridProps.mjs";
/**
* Initialize the technical pieces of the DataGrid (logger, state, ...) that any DataGrid implementation needs
*/
export const useGridInitialization = (privateApiRef, props) => {
useGridRefs(privateApiRef);
useGridProps(privateApiRef, props);
useGridIsRtl(privateApiRef);
useGridLoggerFactory(privateApiRef, props);
useGridStateInitialization(privateApiRef);
useGridPipeProcessing(privateApiRef);
useGridStrategyProcessing(privateApiRef);
useGridLocaleText(privateApiRef, props);
privateApiRef.current.register('private', {
rootProps: props
});
};
+3
View File
@@ -0,0 +1,3 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.mjs";
export declare const useGridIsRtl: (apiRef: RefObject<GridPrivateApiCommon>) => void;
+3
View File
@@ -0,0 +1,3 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.js";
export declare const useGridIsRtl: (apiRef: RefObject<GridPrivateApiCommon>) => void;
+29
View File
@@ -0,0 +1,29 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridIsRtl = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _RtlProvider = require("@mui/system/RtlProvider");
const useGridIsRtl = apiRef => {
const isRtl = (0, _RtlProvider.useRtl)();
if (apiRef.current.state.isRtl === undefined) {
apiRef.current.state.isRtl = isRtl;
}
const isFirstEffect = React.useRef(true);
React.useEffect(() => {
if (isFirstEffect.current) {
isFirstEffect.current = false;
} else {
apiRef.current.setState(state => (0, _extends2.default)({}, state, {
isRtl
}));
}
}, [apiRef, isRtl]);
};
exports.useGridIsRtl = useGridIsRtl;
+21
View File
@@ -0,0 +1,21 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import { useRtl } from '@mui/system/RtlProvider';
export const useGridIsRtl = apiRef => {
const isRtl = useRtl();
if (apiRef.current.state.isRtl === undefined) {
apiRef.current.state.isRtl = isRtl;
}
const isFirstEffect = React.useRef(true);
React.useEffect(() => {
if (isFirstEffect.current) {
isFirstEffect.current = false;
} else {
apiRef.current.setState(state => _extends({}, state, {
isRtl
}));
}
}, [apiRef, isRtl]);
};
@@ -0,0 +1,4 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.mjs";
import type { DataGridProcessedProps } from "../../models/props/DataGridProps.mjs";
export declare const useGridLocaleText: (apiRef: RefObject<GridPrivateApiCommon>, props: Pick<DataGridProcessedProps, 'localeText'>) => void;
@@ -0,0 +1,4 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.js";
import type { DataGridProcessedProps } from "../../models/props/DataGridProps.js";
export declare const useGridLocaleText: (apiRef: RefObject<GridPrivateApiCommon>, props: Pick<DataGridProcessedProps, 'localeText'>) => void;
+22
View File
@@ -0,0 +1,22 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridLocaleText = void 0;
var _formatErrorMessage2 = _interopRequireDefault(require("@mui/x-internals/formatErrorMessage"));
var React = _interopRequireWildcard(require("react"));
const useGridLocaleText = (apiRef, props) => {
const getLocaleText = React.useCallback(key => {
if (props.localeText[key] == null) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: Missing translation for key ${key}.` : (0, _formatErrorMessage2.default)(64, key));
}
return props.localeText[key];
}, [props.localeText]);
apiRef.current.register('public', {
getLocaleText
});
};
exports.useGridLocaleText = useGridLocaleText;
+13
View File
@@ -0,0 +1,13 @@
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import * as React from 'react';
export const useGridLocaleText = (apiRef, props) => {
const getLocaleText = React.useCallback(key => {
if (props.localeText[key] == null) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: Missing translation for key ${key}.` : _formatErrorMessage(64, key));
}
return props.localeText[key];
}, [props.localeText]);
apiRef.current.register('public', {
getLocaleText
});
};
@@ -0,0 +1,4 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.mjs";
import type { DataGridProcessedProps } from "../../models/props/DataGridProps.mjs";
export declare const useGridLoggerFactory: (apiRef: RefObject<GridPrivateApiCommon>, props: Pick<DataGridProcessedProps, 'logger' | 'logLevel'>) => void;
@@ -0,0 +1,4 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.js";
import type { DataGridProcessedProps } from "../../models/props/DataGridProps.js";
export declare const useGridLoggerFactory: (apiRef: RefObject<GridPrivateApiCommon>, props: Pick<DataGridProcessedProps, 'logger' | 'logLevel'>) => void;
@@ -0,0 +1,54 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridLoggerFactory = void 0;
var _formatErrorMessage2 = _interopRequireDefault(require("@mui/x-internals/formatErrorMessage"));
var React = _interopRequireWildcard(require("react"));
var _utils = require("../../utils/utils");
var _utils2 = require("../utils");
const forceDebug = (0, _utils.localStorageAvailable)() && window.localStorage.getItem('DEBUG') != null;
const noop = () => {};
const noopLogger = {
debug: noop,
info: noop,
warn: noop,
error: noop
};
const LOG_LEVELS = ['debug', 'info', 'warn', 'error'];
function getAppender(name, logLevel, appender = console) {
const minLogLevelIdx = LOG_LEVELS.indexOf(logLevel);
if (minLogLevelIdx === -1) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: Log level ${logLevel} not recognized.` : (0, _formatErrorMessage2.default)(65, logLevel));
}
const logger = LOG_LEVELS.reduce((loggerObj, method, idx) => {
if (idx >= minLogLevelIdx) {
loggerObj[method] = (...args) => {
const [message, ...other] = args;
appender[method](`MUI X: ${name} - ${message}`, ...other);
};
} else {
loggerObj[method] = noop;
}
return loggerObj;
}, {});
return logger;
}
const useGridLoggerFactory = (apiRef, props) => {
const getLogger = React.useCallback(name => {
if (forceDebug) {
return getAppender(name, 'debug', props.logger);
}
if (!props.logLevel) {
return noopLogger;
}
return getAppender(name, props.logLevel.toString(), props.logger);
}, [props.logLevel, props.logger]);
(0, _utils2.useGridApiMethod)(apiRef, {
getLogger
}, 'private');
};
exports.useGridLoggerFactory = useGridLoggerFactory;
@@ -0,0 +1,45 @@
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import * as React from 'react';
import { localStorageAvailable } from "../../utils/utils.mjs";
import { useGridApiMethod } from "../utils/index.mjs";
const forceDebug = localStorageAvailable() && window.localStorage.getItem('DEBUG') != null;
const noop = () => {};
const noopLogger = {
debug: noop,
info: noop,
warn: noop,
error: noop
};
const LOG_LEVELS = ['debug', 'info', 'warn', 'error'];
function getAppender(name, logLevel, appender = console) {
const minLogLevelIdx = LOG_LEVELS.indexOf(logLevel);
if (minLogLevelIdx === -1) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: Log level ${logLevel} not recognized.` : _formatErrorMessage(65, logLevel));
}
const logger = LOG_LEVELS.reduce((loggerObj, method, idx) => {
if (idx >= minLogLevelIdx) {
loggerObj[method] = (...args) => {
const [message, ...other] = args;
appender[method](`MUI X: ${name} - ${message}`, ...other);
};
} else {
loggerObj[method] = noop;
}
return loggerObj;
}, {});
return logger;
}
export const useGridLoggerFactory = (apiRef, props) => {
const getLogger = React.useCallback(name => {
if (forceDebug) {
return getAppender(name, 'debug', props.logger);
}
if (!props.logLevel) {
return noopLogger;
}
return getAppender(name, props.logLevel.toString(), props.logger);
}, [props.logLevel, props.logger]);
useGridApiMethod(apiRef, {
getLogger
}, 'private');
};
+6
View File
@@ -0,0 +1,6 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.mjs";
import type { GridStateProps } from "../../models/gridStateCommunity.mjs";
import type { GridStateInitializer } from "../utils/useGridInitializeState.mjs";
export declare const propsStateInitializer: GridStateInitializer<GridStateProps>;
export declare const useGridProps: <PrivateApi extends GridPrivateApiCommon>(apiRef: RefObject<PrivateApi>, props: GridStateProps) => void;
+6
View File
@@ -0,0 +1,6 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.js";
import type { GridStateProps } from "../../models/gridStateCommunity.js";
import type { GridStateInitializer } from "../utils/useGridInitializeState.js";
export declare const propsStateInitializer: GridStateInitializer<GridStateProps>;
export declare const useGridProps: <PrivateApi extends GridPrivateApiCommon>(apiRef: RefObject<PrivateApi>, props: GridStateProps) => void;
+44
View File
@@ -0,0 +1,44 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridProps = exports.propsStateInitializer = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
const propsStateInitializer = (state, props) => {
return (0, _extends2.default)({}, state, {
props: {
listView: props.listView,
getRowId: props.getRowId,
isCellEditable: props.isCellEditable,
isRowSelectable: props.isRowSelectable,
dataSource: props.dataSource,
signature: props.signature
}
});
};
exports.propsStateInitializer = propsStateInitializer;
const useGridProps = (apiRef, props) => {
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}
apiRef.current.setState(state => (0, _extends2.default)({}, state, {
props: {
listView: props.listView,
getRowId: props.getRowId,
isCellEditable: props.isCellEditable,
isRowSelectable: props.isRowSelectable,
dataSource: props.dataSource,
signature: props.signature
}
}));
}, [apiRef, props.listView, props.getRowId, props.isCellEditable, props.isRowSelectable, props.dataSource, props.signature]);
};
exports.useGridProps = useGridProps;
+35
View File
@@ -0,0 +1,35 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
export const propsStateInitializer = (state, props) => {
return _extends({}, state, {
props: {
listView: props.listView,
getRowId: props.getRowId,
isCellEditable: props.isCellEditable,
isRowSelectable: props.isRowSelectable,
dataSource: props.dataSource,
signature: props.signature
}
});
};
export const useGridProps = (apiRef, props) => {
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}
apiRef.current.setState(state => _extends({}, state, {
props: {
listView: props.listView,
getRowId: props.getRowId,
isCellEditable: props.isCellEditable,
isRowSelectable: props.isRowSelectable,
dataSource: props.dataSource,
signature: props.signature
}
}));
}, [apiRef, props.listView, props.getRowId, props.isCellEditable, props.isRowSelectable, props.dataSource, props.signature]);
};
+3
View File
@@ -0,0 +1,3 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.mjs";
export declare const useGridRefs: <PrivateApi extends GridPrivateApiCommon>(apiRef: RefObject<PrivateApi>) => void;
+3
View File
@@ -0,0 +1,3 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.js";
export declare const useGridRefs: <PrivateApi extends GridPrivateApiCommon>(apiRef: RefObject<PrivateApi>) => void;
+28
View File
@@ -0,0 +1,28 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridRefs = void 0;
var React = _interopRequireWildcard(require("react"));
const useGridRefs = apiRef => {
const rootElementRef = React.useRef(null);
const mainElementRef = React.useRef(null);
const virtualScrollerRef = React.useRef(null);
const virtualScrollbarVerticalRef = React.useRef(null);
const virtualScrollbarHorizontalRef = React.useRef(null);
const columnHeadersContainerRef = React.useRef(null);
apiRef.current.register('public', {
rootElementRef
});
apiRef.current.register('private', {
mainElementRef,
virtualScrollerRef,
virtualScrollbarVerticalRef,
virtualScrollbarHorizontalRef,
columnHeadersContainerRef
});
};
exports.useGridRefs = useGridRefs;
+21
View File
@@ -0,0 +1,21 @@
'use client';
import * as React from 'react';
export const useGridRefs = apiRef => {
const rootElementRef = React.useRef(null);
const mainElementRef = React.useRef(null);
const virtualScrollerRef = React.useRef(null);
const virtualScrollbarVerticalRef = React.useRef(null);
const virtualScrollbarHorizontalRef = React.useRef(null);
const columnHeadersContainerRef = React.useRef(null);
apiRef.current.register('public', {
rootElementRef
});
apiRef.current.register('private', {
mainElementRef,
virtualScrollerRef,
virtualScrollbarVerticalRef,
virtualScrollbarHorizontalRef,
columnHeadersContainerRef
});
};
@@ -0,0 +1,3 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.mjs";
export declare const useGridStateInitialization: <PrivateApi extends GridPrivateApiCommon>(apiRef: RefObject<PrivateApi>) => void;
@@ -0,0 +1,3 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommon } from "../../models/api/gridApiCommon.js";
export declare const useGridStateInitialization: <PrivateApi extends GridPrivateApiCommon>(apiRef: RefObject<PrivateApi>) => void;
@@ -0,0 +1,106 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridStateInitialization = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _formatErrorMessage2 = _interopRequireDefault(require("@mui/x-internals/formatErrorMessage"));
var React = _interopRequireWildcard(require("react"));
var _utils = require("../utils");
var _utils2 = require("../../utils/utils");
const useGridStateInitialization = apiRef => {
const controlStateMapRef = React.useRef({});
const registerControlState = React.useCallback(controlStateItem => {
controlStateMapRef.current[controlStateItem.stateId] = controlStateItem;
}, []);
const setState = React.useCallback((state, reason) => {
let newState;
if ((0, _utils2.isFunction)(state)) {
newState = state(apiRef.current.state);
} else {
newState = state;
}
if (apiRef.current.state === newState) {
return false;
}
const apiRefWithNewState = {
current: {
state: newState
}
};
let ignoreSetState = false;
// Apply the control state constraints
const updatedControlStateIds = [];
Object.keys(controlStateMapRef.current).forEach(stateId => {
const controlState = controlStateMapRef.current[stateId];
const oldSubState = controlState.stateSelector(apiRef);
const newSubState = controlState.stateSelector(apiRefWithNewState);
if (newSubState === oldSubState) {
return;
}
updatedControlStateIds.push({
stateId: controlState.stateId,
hasPropChanged: newSubState !== controlState.propModel
});
// The state is controlled, the prop should always win
if (controlState.propModel !== undefined && newSubState !== controlState.propModel) {
ignoreSetState = true;
}
});
if (updatedControlStateIds.length > 1) {
// Each hook modify its own state, and it should not leak
// Events are here to forward to other hooks and apply changes.
// You are trying to update several states in a no isolated way.
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: You're not allowed to update several sub-state in one transaction. You already updated ${updatedControlStateIds[0].stateId}, therefore, you're not allowed to update ${updatedControlStateIds.map(el => el.stateId).join(', ')} in the same transaction.` : (0, _formatErrorMessage2.default)(66, updatedControlStateIds[0].stateId, updatedControlStateIds.map(el => el.stateId).join(', ')));
}
if (!ignoreSetState) {
// We always assign it as we mutate rows for perf reason.
apiRef.current.state = newState;
apiRef.current.publishEvent('stateChange', newState);
apiRef.current.store.update(newState);
}
if (updatedControlStateIds.length === 1) {
const {
stateId,
hasPropChanged
} = updatedControlStateIds[0];
const controlState = controlStateMapRef.current[stateId];
const model = controlState.stateSelector(apiRefWithNewState);
if (controlState.propOnChange && hasPropChanged) {
controlState.propOnChange(model, {
reason,
api: apiRef.current
});
}
if (!ignoreSetState) {
apiRef.current.publishEvent(controlState.changeEvent, model, {
reason
});
}
}
return !ignoreSetState;
}, [apiRef]);
const updateControlState = React.useCallback((key, state, reason) => {
return apiRef.current.setState(previousState => {
return (0, _extends2.default)({}, previousState, {
[key]: state(previousState[key])
});
}, reason);
}, [apiRef]);
const publicStateApi = {
setState
};
const privateStateApi = {
updateControlState,
registerControlState
};
(0, _utils.useGridApiMethod)(apiRef, publicStateApi, 'public');
(0, _utils.useGridApiMethod)(apiRef, privateStateApi, 'private');
};
exports.useGridStateInitialization = useGridStateInitialization;
@@ -0,0 +1,98 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import * as React from 'react';
import { useGridApiMethod } from "../utils/index.mjs";
import { isFunction } from "../../utils/utils.mjs";
export const useGridStateInitialization = apiRef => {
const controlStateMapRef = React.useRef({});
const registerControlState = React.useCallback(controlStateItem => {
controlStateMapRef.current[controlStateItem.stateId] = controlStateItem;
}, []);
const setState = React.useCallback((state, reason) => {
let newState;
if (isFunction(state)) {
newState = state(apiRef.current.state);
} else {
newState = state;
}
if (apiRef.current.state === newState) {
return false;
}
const apiRefWithNewState = {
current: {
state: newState
}
};
let ignoreSetState = false;
// Apply the control state constraints
const updatedControlStateIds = [];
Object.keys(controlStateMapRef.current).forEach(stateId => {
const controlState = controlStateMapRef.current[stateId];
const oldSubState = controlState.stateSelector(apiRef);
const newSubState = controlState.stateSelector(apiRefWithNewState);
if (newSubState === oldSubState) {
return;
}
updatedControlStateIds.push({
stateId: controlState.stateId,
hasPropChanged: newSubState !== controlState.propModel
});
// The state is controlled, the prop should always win
if (controlState.propModel !== undefined && newSubState !== controlState.propModel) {
ignoreSetState = true;
}
});
if (updatedControlStateIds.length > 1) {
// Each hook modify its own state, and it should not leak
// Events are here to forward to other hooks and apply changes.
// You are trying to update several states in a no isolated way.
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: You're not allowed to update several sub-state in one transaction. You already updated ${updatedControlStateIds[0].stateId}, therefore, you're not allowed to update ${updatedControlStateIds.map(el => el.stateId).join(', ')} in the same transaction.` : _formatErrorMessage(66, updatedControlStateIds[0].stateId, updatedControlStateIds.map(el => el.stateId).join(', ')));
}
if (!ignoreSetState) {
// We always assign it as we mutate rows for perf reason.
apiRef.current.state = newState;
apiRef.current.publishEvent('stateChange', newState);
apiRef.current.store.update(newState);
}
if (updatedControlStateIds.length === 1) {
const {
stateId,
hasPropChanged
} = updatedControlStateIds[0];
const controlState = controlStateMapRef.current[stateId];
const model = controlState.stateSelector(apiRefWithNewState);
if (controlState.propOnChange && hasPropChanged) {
controlState.propOnChange(model, {
reason,
api: apiRef.current
});
}
if (!ignoreSetState) {
apiRef.current.publishEvent(controlState.changeEvent, model, {
reason
});
}
}
return !ignoreSetState;
}, [apiRef]);
const updateControlState = React.useCallback((key, state, reason) => {
return apiRef.current.setState(previousState => {
return _extends({}, previousState, {
[key]: state(previousState[key])
});
}, reason);
}, [apiRef]);
const publicStateApi = {
setState
};
const privateStateApi = {
updateControlState,
registerControlState
};
useGridApiMethod(apiRef, publicStateApi, 'public');
useGridApiMethod(apiRef, privateStateApi, 'private');
};
@@ -0,0 +1,39 @@
import * as React from 'react';
import { Dimensions, LayoutDataGrid, Virtualization } from '@mui/x-virtualizer';
/**
* Virtualizer setup
*/
export declare function useGridVirtualizer(): {
store: import("@mui/x-internals/store").Store<Dimensions.State & Virtualization.State<LayoutDataGrid> & import("@mui/x-virtualizer").Colspan.State & import("@mui/x-virtualizer").Rowspan.State>;
api: {
updateDimensions: (firstUpdate?: boolean) => void;
debouncedUpdateDimensions: (((firstUpdate?: boolean) => void) & import("@mui/x-internals/throttle").Cancelable) | undefined;
rowsMeta: {
getRowHeight: (rowId: import("@mui/x-virtualizer").RowId) => any;
setLastMeasuredRowIndex: (index: number) => void;
storeRowHeightMeasurement: (id: import("@mui/x-virtualizer").RowId, height: number) => void;
hydrateRowsMeta: () => void;
observeRowHeight: (element: Element, rowId: import("@mui/x-virtualizer").RowId) => () => void | undefined;
rowHasAutoHeight: (id: import("@mui/x-virtualizer").RowId) => any;
getRowHeightEntry: (rowId: import("@mui/x-virtualizer").RowId) => any;
getLastMeasuredRowIndex: () => number;
resetRowHeights: () => void;
};
} & {
getCellColSpanInfo: (rowId: import("@mui/x-virtualizer").RowId, columnIndex: import("@mui/x-internals/types").integer) => import("@mui/x-virtualizer").CellColSpanInfo;
calculateColSpan: (rowId: import("@mui/x-virtualizer").RowId, minFirstColumn: import("@mui/x-internals/types").integer, maxLastColumn: import("@mui/x-internals/types").integer, columns: import("@mui/x-virtualizer").ColumnWithWidth[]) => void;
getHiddenCellsOrigin: () => Record<import("@mui/x-virtualizer").RowId, Record<number, number>>;
getters: any;
setPanels: React.Dispatch<React.SetStateAction<Readonly<Map<any, React.ReactNode>>>>;
forceUpdateRenderContext: () => void;
scheduleUpdateRenderContext: () => void;
} & {
resetColSpan: () => void;
getCellColSpanInfo: (rowId: import("@mui/x-virtualizer").RowId, columnIndex: import("@mui/x-internals/types").integer) => import("@mui/x-virtualizer").CellColSpanInfo | undefined;
calculateColSpan: (rowId: import("@mui/x-virtualizer").RowId, minFirstColumn: import("@mui/x-internals/types").integer, maxLastColumn: import("@mui/x-internals/types").integer, columns: import("@mui/x-virtualizer").ColumnWithWidth[]) => void;
} & {
getHiddenCellsOrigin: () => Record<number, Record<number, number>>;
} & {
getViewportPageSize: () => number;
};
};
@@ -0,0 +1,39 @@
import * as React from 'react';
import { Dimensions, LayoutDataGrid, Virtualization } from '@mui/x-virtualizer';
/**
* Virtualizer setup
*/
export declare function useGridVirtualizer(): {
store: import("@mui/x-internals/store").Store<Dimensions.State & Virtualization.State<LayoutDataGrid> & import("@mui/x-virtualizer").Colspan.State & import("@mui/x-virtualizer").Rowspan.State>;
api: {
updateDimensions: (firstUpdate?: boolean) => void;
debouncedUpdateDimensions: (((firstUpdate?: boolean) => void) & import("@mui/x-internals/throttle").Cancelable) | undefined;
rowsMeta: {
getRowHeight: (rowId: import("@mui/x-virtualizer").RowId) => any;
setLastMeasuredRowIndex: (index: number) => void;
storeRowHeightMeasurement: (id: import("@mui/x-virtualizer").RowId, height: number) => void;
hydrateRowsMeta: () => void;
observeRowHeight: (element: Element, rowId: import("@mui/x-virtualizer").RowId) => () => void | undefined;
rowHasAutoHeight: (id: import("@mui/x-virtualizer").RowId) => any;
getRowHeightEntry: (rowId: import("@mui/x-virtualizer").RowId) => any;
getLastMeasuredRowIndex: () => number;
resetRowHeights: () => void;
};
} & {
getCellColSpanInfo: (rowId: import("@mui/x-virtualizer").RowId, columnIndex: import("@mui/x-internals/types").integer) => import("@mui/x-virtualizer").CellColSpanInfo;
calculateColSpan: (rowId: import("@mui/x-virtualizer").RowId, minFirstColumn: import("@mui/x-internals/types").integer, maxLastColumn: import("@mui/x-internals/types").integer, columns: import("@mui/x-virtualizer").ColumnWithWidth[]) => void;
getHiddenCellsOrigin: () => Record<import("@mui/x-virtualizer").RowId, Record<number, number>>;
getters: any;
setPanels: React.Dispatch<React.SetStateAction<Readonly<Map<any, React.ReactNode>>>>;
forceUpdateRenderContext: () => void;
scheduleUpdateRenderContext: () => void;
} & {
resetColSpan: () => void;
getCellColSpanInfo: (rowId: import("@mui/x-virtualizer").RowId, columnIndex: import("@mui/x-internals/types").integer) => import("@mui/x-virtualizer").CellColSpanInfo | undefined;
calculateColSpan: (rowId: import("@mui/x-virtualizer").RowId, minFirstColumn: import("@mui/x-internals/types").integer, maxLastColumn: import("@mui/x-internals/types").integer, columns: import("@mui/x-virtualizer").ColumnWithWidth[]) => void;
} & {
getHiddenCellsOrigin: () => Record<number, Record<number, number>>;
} & {
getViewportPageSize: () => number;
};
};
+274
View File
@@ -0,0 +1,274 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridVirtualizer = useGridVirtualizer;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _useLazyRef = _interopRequireDefault(require("@mui/utils/useLazyRef"));
var _useEventCallback = _interopRequireDefault(require("@mui/utils/useEventCallback"));
var _RtlProvider = require("@mui/system/RtlProvider");
var _math = require("@mui/x-internals/math");
var _lruMemoize = require("@mui/x-internals/lruMemoize");
var _store = require("@mui/x-internals/store");
var _xVirtualizer = require("@mui/x-virtualizer");
var _useFirstRender = require("../utils/useFirstRender");
var _createSelector = require("../../utils/createSelector");
var _useGridSelector = require("../utils/useGridSelector");
var _gridDimensionsSelectors = require("../features/dimensions/gridDimensionsSelectors");
var _density = require("../features/density");
var _gridColumnsSelector = require("../features/columns/gridColumnsSelector");
var _gridRowsSelector = require("../features/rows/gridRowsSelector");
var _useGridVisibleRows = require("../utils/useGridVisibleRows");
var _pagination = require("../features/pagination");
var _gridFocusedVirtualCellSelector = require("../features/virtualization/gridFocusedVirtualCellSelector");
var _rowSelection = require("../features/rowSelection");
var _dataGridPropsDefaultValues = require("../../constants/dataGridPropsDefaultValues");
var _gridRowsUtils = require("../features/rows/gridRowsUtils");
var _gridColumnsUtils = require("../features/columns/gridColumnsUtils");
var _useGridOverlays = require("../features/overlays/useGridOverlays");
var _useGridRootProps = require("../utils/useGridRootProps");
var _useGridPrivateApiContext = require("../utils/useGridPrivateApiContext");
var _useGridRowsMeta = require("../features/rows/useGridRowsMeta");
var _utils = require("../../utils/utils");
var _jsxRuntime = require("react/jsx-runtime");
const columnsTotalWidthSelector = (0, _createSelector.createSelector)(_gridColumnsSelector.gridVisibleColumnDefinitionsSelector, _gridColumnsSelector.gridColumnPositionsSelector, (visibleColumns, positions) => {
const colCount = visibleColumns.length;
if (colCount === 0) {
return 0;
}
return (0, _math.roundToDecimalPlaces)(positions[colCount - 1] + visibleColumns[colCount - 1].computedWidth, 1);
});
/** Translates virtualizer state to grid state */
const addGridDimensionsCreator = () => (0, _lruMemoize.lruMemoize)((dimensions, headerHeight, groupHeaderHeight, headerFilterHeight, headersTotalHeight) => {
return (0, _extends2.default)({}, dimensions, {
headerHeight,
groupHeaderHeight,
headerFilterHeight,
headersTotalHeight
});
}, {
maxSize: 1
});
/**
* Virtualizer setup
*/
function useGridVirtualizer() {
const isRtl = (0, _RtlProvider.useRtl)();
const rootProps = (0, _useGridRootProps.useGridRootProps)();
const apiRef = (0, _useGridPrivateApiContext.useGridPrivateApiContext)();
const {
listView
} = rootProps;
const visibleColumns = (0, _useGridSelector.useGridSelector)(apiRef, _gridColumnsSelector.gridVisibleColumnDefinitionsSelector);
const pinnedRows = (0, _useGridSelector.useGridSelector)(apiRef, _gridRowsSelector.gridPinnedRowsSelector);
const pinnedColumns = (0, _gridColumnsSelector.gridVisiblePinnedColumnDefinitionsSelector)(apiRef);
const rowSelectionManager = (0, _useGridSelector.useGridSelector)(apiRef, _rowSelection.gridRowSelectionManagerSelector);
const isRowSelected = React.useCallback(id => rowSelectionManager.has(id) && apiRef.current.isRowSelectable(id), [rowSelectionManager, apiRef]);
const currentPage = (0, _useGridVisibleRows.useGridVisibleRows)(apiRef);
const hasColSpan = (0, _useGridSelector.useGridSelector)(apiRef, _gridColumnsSelector.gridHasColSpanSelector);
const verticalScrollbarWidth = (0, _useGridSelector.useGridSelector)(apiRef, _gridDimensionsSelectors.gridVerticalScrollbarWidthSelector);
const hasFiller = (0, _useGridSelector.useGridSelector)(apiRef, _gridDimensionsSelectors.gridHasFillerSelector);
const {
autoHeight
} = rootProps;
const scrollReset = listView;
// <DIMENSIONS>
const density = (0, _useGridSelector.useGridSelector)(apiRef, _density.gridDensityFactorSelector);
const baseRowHeight = (0, _gridRowsUtils.getValidRowHeight)(rootProps.rowHeight, _dataGridPropsDefaultValues.DATA_GRID_PROPS_DEFAULT_VALUES.rowHeight, _gridRowsUtils.rowHeightWarning);
const rowHeight = Math.floor(baseRowHeight * density);
const headerHeight = Math.floor(rootProps.columnHeaderHeight * density);
const groupHeaderHeight = Math.floor((rootProps.columnGroupHeaderHeight ?? rootProps.columnHeaderHeight) * density);
const headerFilterHeight = Math.floor((rootProps.headerFilterHeight ?? rootProps.columnHeaderHeight) * density);
const columnsTotalWidth = (0, _useGridSelector.useGridSelector)(apiRef, columnsTotalWidthSelector);
const headersTotalHeight = (0, _gridColumnsUtils.getTotalHeaderHeight)(apiRef, rootProps);
const leftPinnedWidth = pinnedColumns.left.reduce((w, col) => w + col.computedWidth, 0);
const rightPinnedWidth = pinnedColumns.right.reduce((w, col) => w + col.computedWidth, 0);
const overlayState = (0, _useGridOverlays.useGridOverlays)(apiRef, rootProps);
const dimensionsParams = {
rowHeight,
headerHeight,
columnsTotalWidth,
leftPinnedWidth,
rightPinnedWidth,
topPinnedHeight: headersTotalHeight,
bottomPinnedHeight: 0,
autoHeight,
minimalContentHeight: _gridRowsUtils.minimalContentHeight,
scrollbarSize: rootProps.scrollbarSize
};
const addGridDimensions = (0, _useLazyRef.default)(addGridDimensionsCreator).current;
// </DIMENSIONS>
// <ROWS_META>
const dataRowCount = (0, _useGridSelector.useGridSelector)(apiRef, _gridRowsSelector.gridRowCountSelector);
const pagination = (0, _useGridSelector.useGridSelector)(apiRef, _pagination.gridPaginationSelector);
const rowCount = Math.min(pagination.enabled ? pagination.paginationModel.pageSize : dataRowCount, dataRowCount);
const {
getRowHeight,
getEstimatedRowHeight,
getRowSpacing
} = rootProps;
// </ROWS_META>
const RowSlot = rootProps.slots.row;
const rowSlotProps = rootProps.slotProps?.row;
const focusedVirtualCell = (0, _useGridSelector.useGridSelector)(apiRef, _gridFocusedVirtualCellSelector.gridFocusedVirtualCellSelector);
// We need it to trigger a new render, but rowsMeta needs access to the latest value, hence we cannot pass it to the focusedVirtualCell callback in the virtualizer params
(0, _utils.eslintUseValue)(focusedVirtualCell);
const layout = (0, _useLazyRef.default)(() => new _xVirtualizer.LayoutDataGrid({
container: apiRef.current.mainElementRef,
scroller: apiRef.current.virtualScrollerRef,
scrollbarVertical: apiRef.current.virtualScrollbarVerticalRef,
scrollbarHorizontal: apiRef.current.virtualScrollbarHorizontalRef
})).current;
const virtualizer = (0, _xVirtualizer.useVirtualizer)({
layout,
dimensions: dimensionsParams,
virtualization: {
layoutMode: rootProps.experimentalFeatures?.virtualizerLayoutMode ?? 'uncontrolled',
isRtl,
rowBufferPx: rootProps.rowBufferPx,
columnBufferPx: rootProps.columnBufferPx
},
colspan: {
enabled: hasColSpan,
getColspan: React.useCallback((rowId, column) => {
if (typeof column.colSpan === 'function') {
const row = apiRef.current.getRow(rowId);
const value = apiRef.current.getRowValue(row, column);
return column.colSpan(value, row, column, apiRef) ?? 0;
}
return column.colSpan ?? 1;
}, [apiRef])
},
initialState: {
scroll: rootProps.initialState?.scroll,
rowSpanning: apiRef.current.state.rowSpanning,
virtualization: apiRef.current.state.virtualization
},
rows: currentPage.rows,
range: currentPage.range,
rowCount,
columns: visibleColumns,
pinnedRows,
pinnedColumns,
disableHorizontalScroll: listView,
disableVerticalScroll: overlayState.overlayType === 'noColumnsOverlay' || overlayState.loadingOverlayVariant === 'skeleton',
getRowHeight: React.useMemo(() => {
if (!getRowHeight) {
return undefined;
}
return rowEntry => getRowHeight((0, _extends2.default)({}, rowEntry, {
densityFactor: density
}));
}, [getRowHeight, density]),
getEstimatedRowHeight: React.useMemo(() => getEstimatedRowHeight ? rowEntry => getEstimatedRowHeight((0, _extends2.default)({}, rowEntry, {
densityFactor: density
})) : undefined, [getEstimatedRowHeight, density]),
getRowSpacing: React.useMemo(() => getRowSpacing ? rowEntry => {
const indexRelativeToCurrentPage = currentPage.rowIdToIndexMap.get(rowEntry.id) ?? -1;
const visibility = {
isFirstVisible: indexRelativeToCurrentPage === 0,
isLastVisible: indexRelativeToCurrentPage === currentPage.rows.length - 1,
indexRelativeToCurrentPage
};
return getRowSpacing((0, _extends2.default)({}, rowEntry, visibility, {
indexRelativeToCurrentPage: apiRef.current.getRowIndexRelativeToVisibleRows(rowEntry.id)
}));
} : undefined, [apiRef, getRowSpacing, currentPage.rows, currentPage.rowIdToIndexMap]),
applyRowHeight: (0, _useEventCallback.default)((entry, row) => apiRef.current.unstable_applyPipeProcessors('rowHeight', entry, row)),
virtualizeColumnsWithAutoRowHeight: rootProps.virtualizeColumnsWithAutoRowHeight,
focusedVirtualCell: (0, _useEventCallback.default)(() => (0, _gridFocusedVirtualCellSelector.gridFocusedVirtualCellSelector)(apiRef)),
resizeThrottleMs: rootProps.resizeThrottleMs,
onResize: (0, _useEventCallback.default)(size => apiRef.current.publishEvent('resize', size)),
onWheel: (0, _useEventCallback.default)(event => {
apiRef.current.publishEvent('virtualScrollerWheel', {}, event);
}),
onTouchMove: (0, _useEventCallback.default)(event => {
apiRef.current.publishEvent('virtualScrollerTouchMove', {}, event);
}),
onRenderContextChange: (0, _useEventCallback.default)(nextRenderContext => {
apiRef.current.publishEvent('renderedRowsIntervalChange', nextRenderContext);
}),
onScrollChange: React.useCallback((scrollPosition, nextRenderContext) => {
apiRef.current.publishEvent('scrollPositionChange', {
top: scrollPosition.top,
left: scrollPosition.left,
renderContext: nextRenderContext
});
}, [apiRef]),
scrollReset,
renderRow: React.useCallback(params => /*#__PURE__*/(0, _jsxRuntime.jsx)(RowSlot, (0, _extends2.default)({
row: params.model,
rowId: params.id,
index: params.rowIndex,
selected: isRowSelected(params.id),
offsetLeft: params.offsetLeft,
columnsTotalWidth: columnsTotalWidth,
rowHeight: params.baseRowHeight,
pinnedColumns: pinnedColumns,
visibleColumns: visibleColumns,
firstColumnIndex: params.firstColumnIndex,
lastColumnIndex: params.lastColumnIndex,
focusedColumnIndex: params.focusedColumnIndex,
isFirstVisible: params.isFirstVisible,
isLastVisible: params.isLastVisible,
isNotVisible: params.isVirtualFocusRow,
showBottomBorder: params.showBottomBorder,
scrollbarWidth: verticalScrollbarWidth,
gridHasFiller: hasFiller
}, rowSlotProps), params.id), [columnsTotalWidth, hasFiller, isRowSelected, pinnedColumns, RowSlot, rowSlotProps, verticalScrollbarWidth, visibleColumns]),
renderInfiniteLoadingTrigger: React.useCallback(id => apiRef.current.getInfiniteLoadingTriggerElement?.({
lastRowId: id
}), [apiRef])
});
// HACK: Keep the grid's store in sync with the virtualizer store. We set up the
// subscription in the render phase rather than in an effect because other grid
// initialization code runs between those two moments.
//
// TODO(v9): Remove this
(0, _useFirstRender.useFirstRender)(() => {
apiRef.current.store.state.dimensions = addGridDimensions(virtualizer.store.state.dimensions, headerHeight, groupHeaderHeight, headerFilterHeight, headersTotalHeight);
apiRef.current.store.state.rowsMeta = virtualizer.store.state.rowsMeta;
apiRef.current.store.state.virtualization = virtualizer.store.state.virtualization;
});
(0, _store.useStoreEffect)(virtualizer.store, _xVirtualizer.Dimensions.selectors.dimensions, (_, dimensions) => {
if (!dimensions.isReady) {
return;
}
apiRef.current.setState(gridState => (0, _extends2.default)({}, gridState, {
dimensions: addGridDimensions(dimensions, headerHeight, groupHeaderHeight, headerFilterHeight, headersTotalHeight)
}));
});
(0, _store.useStoreEffect)(virtualizer.store, _xVirtualizer.Dimensions.selectors.rowsMeta, (_, rowsMeta) => {
if (rowsMeta !== apiRef.current.state.rowsMeta) {
apiRef.current.setState(gridState => (0, _extends2.default)({}, gridState, {
rowsMeta
}));
}
});
(0, _store.useStoreEffect)(virtualizer.store, _xVirtualizer.Virtualization.selectors.store, (_, virtualization) => {
if (virtualization.renderContext === _xVirtualizer.EMPTY_RENDER_CONTEXT) {
return;
}
if (virtualization !== apiRef.current.state.virtualization) {
apiRef.current.setState(gridState => (0, _extends2.default)({}, gridState, {
virtualization
}));
}
});
apiRef.current.register('private', {
virtualizer
});
(0, _useGridRowsMeta.useGridRowsMeta)(apiRef, rootProps);
return virtualizer;
}
+266
View File
@@ -0,0 +1,266 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import useLazyRef from '@mui/utils/useLazyRef';
import useEventCallback from '@mui/utils/useEventCallback';
import { useRtl } from '@mui/system/RtlProvider';
import { roundToDecimalPlaces } from '@mui/x-internals/math';
import { lruMemoize } from '@mui/x-internals/lruMemoize';
import { useStoreEffect } from '@mui/x-internals/store';
import { useVirtualizer, Dimensions, LayoutDataGrid, Virtualization, EMPTY_RENDER_CONTEXT } from '@mui/x-virtualizer';
import { useFirstRender } from "../utils/useFirstRender.mjs";
import { createSelector } from "../../utils/createSelector.mjs";
import { useGridSelector } from "../utils/useGridSelector.mjs";
import { gridHasFillerSelector, gridVerticalScrollbarWidthSelector } from "../features/dimensions/gridDimensionsSelectors.mjs";
import { gridDensityFactorSelector } from "../features/density/index.mjs";
import { gridVisibleColumnDefinitionsSelector, gridVisiblePinnedColumnDefinitionsSelector, gridColumnPositionsSelector, gridHasColSpanSelector } from "../features/columns/gridColumnsSelector.mjs";
import { gridPinnedRowsSelector, gridRowCountSelector } from "../features/rows/gridRowsSelector.mjs";
import { useGridVisibleRows } from "../utils/useGridVisibleRows.mjs";
import { gridPaginationSelector } from "../features/pagination/index.mjs";
import { gridFocusedVirtualCellSelector } from "../features/virtualization/gridFocusedVirtualCellSelector.mjs";
import { gridRowSelectionManagerSelector } from "../features/rowSelection/index.mjs";
import { DATA_GRID_PROPS_DEFAULT_VALUES } from "../../constants/dataGridPropsDefaultValues.mjs";
import { getValidRowHeight, minimalContentHeight, rowHeightWarning } from "../features/rows/gridRowsUtils.mjs";
import { getTotalHeaderHeight } from "../features/columns/gridColumnsUtils.mjs";
import { useGridOverlays } from "../features/overlays/useGridOverlays.mjs";
import { useGridRootProps } from "../utils/useGridRootProps.mjs";
import { useGridPrivateApiContext } from "../utils/useGridPrivateApiContext.mjs";
import { useGridRowsMeta } from "../features/rows/useGridRowsMeta.mjs";
import { eslintUseValue } from "../../utils/utils.mjs";
import { jsx as _jsx } from "react/jsx-runtime";
const columnsTotalWidthSelector = createSelector(gridVisibleColumnDefinitionsSelector, gridColumnPositionsSelector, (visibleColumns, positions) => {
const colCount = visibleColumns.length;
if (colCount === 0) {
return 0;
}
return roundToDecimalPlaces(positions[colCount - 1] + visibleColumns[colCount - 1].computedWidth, 1);
});
/** Translates virtualizer state to grid state */
const addGridDimensionsCreator = () => lruMemoize((dimensions, headerHeight, groupHeaderHeight, headerFilterHeight, headersTotalHeight) => {
return _extends({}, dimensions, {
headerHeight,
groupHeaderHeight,
headerFilterHeight,
headersTotalHeight
});
}, {
maxSize: 1
});
/**
* Virtualizer setup
*/
export function useGridVirtualizer() {
const isRtl = useRtl();
const rootProps = useGridRootProps();
const apiRef = useGridPrivateApiContext();
const {
listView
} = rootProps;
const visibleColumns = useGridSelector(apiRef, gridVisibleColumnDefinitionsSelector);
const pinnedRows = useGridSelector(apiRef, gridPinnedRowsSelector);
const pinnedColumns = gridVisiblePinnedColumnDefinitionsSelector(apiRef);
const rowSelectionManager = useGridSelector(apiRef, gridRowSelectionManagerSelector);
const isRowSelected = React.useCallback(id => rowSelectionManager.has(id) && apiRef.current.isRowSelectable(id), [rowSelectionManager, apiRef]);
const currentPage = useGridVisibleRows(apiRef);
const hasColSpan = useGridSelector(apiRef, gridHasColSpanSelector);
const verticalScrollbarWidth = useGridSelector(apiRef, gridVerticalScrollbarWidthSelector);
const hasFiller = useGridSelector(apiRef, gridHasFillerSelector);
const {
autoHeight
} = rootProps;
const scrollReset = listView;
// <DIMENSIONS>
const density = useGridSelector(apiRef, gridDensityFactorSelector);
const baseRowHeight = getValidRowHeight(rootProps.rowHeight, DATA_GRID_PROPS_DEFAULT_VALUES.rowHeight, rowHeightWarning);
const rowHeight = Math.floor(baseRowHeight * density);
const headerHeight = Math.floor(rootProps.columnHeaderHeight * density);
const groupHeaderHeight = Math.floor((rootProps.columnGroupHeaderHeight ?? rootProps.columnHeaderHeight) * density);
const headerFilterHeight = Math.floor((rootProps.headerFilterHeight ?? rootProps.columnHeaderHeight) * density);
const columnsTotalWidth = useGridSelector(apiRef, columnsTotalWidthSelector);
const headersTotalHeight = getTotalHeaderHeight(apiRef, rootProps);
const leftPinnedWidth = pinnedColumns.left.reduce((w, col) => w + col.computedWidth, 0);
const rightPinnedWidth = pinnedColumns.right.reduce((w, col) => w + col.computedWidth, 0);
const overlayState = useGridOverlays(apiRef, rootProps);
const dimensionsParams = {
rowHeight,
headerHeight,
columnsTotalWidth,
leftPinnedWidth,
rightPinnedWidth,
topPinnedHeight: headersTotalHeight,
bottomPinnedHeight: 0,
autoHeight,
minimalContentHeight,
scrollbarSize: rootProps.scrollbarSize
};
const addGridDimensions = useLazyRef(addGridDimensionsCreator).current;
// </DIMENSIONS>
// <ROWS_META>
const dataRowCount = useGridSelector(apiRef, gridRowCountSelector);
const pagination = useGridSelector(apiRef, gridPaginationSelector);
const rowCount = Math.min(pagination.enabled ? pagination.paginationModel.pageSize : dataRowCount, dataRowCount);
const {
getRowHeight,
getEstimatedRowHeight,
getRowSpacing
} = rootProps;
// </ROWS_META>
const RowSlot = rootProps.slots.row;
const rowSlotProps = rootProps.slotProps?.row;
const focusedVirtualCell = useGridSelector(apiRef, gridFocusedVirtualCellSelector);
// We need it to trigger a new render, but rowsMeta needs access to the latest value, hence we cannot pass it to the focusedVirtualCell callback in the virtualizer params
eslintUseValue(focusedVirtualCell);
const layout = useLazyRef(() => new LayoutDataGrid({
container: apiRef.current.mainElementRef,
scroller: apiRef.current.virtualScrollerRef,
scrollbarVertical: apiRef.current.virtualScrollbarVerticalRef,
scrollbarHorizontal: apiRef.current.virtualScrollbarHorizontalRef
})).current;
const virtualizer = useVirtualizer({
layout,
dimensions: dimensionsParams,
virtualization: {
layoutMode: rootProps.experimentalFeatures?.virtualizerLayoutMode ?? 'uncontrolled',
isRtl,
rowBufferPx: rootProps.rowBufferPx,
columnBufferPx: rootProps.columnBufferPx
},
colspan: {
enabled: hasColSpan,
getColspan: React.useCallback((rowId, column) => {
if (typeof column.colSpan === 'function') {
const row = apiRef.current.getRow(rowId);
const value = apiRef.current.getRowValue(row, column);
return column.colSpan(value, row, column, apiRef) ?? 0;
}
return column.colSpan ?? 1;
}, [apiRef])
},
initialState: {
scroll: rootProps.initialState?.scroll,
rowSpanning: apiRef.current.state.rowSpanning,
virtualization: apiRef.current.state.virtualization
},
rows: currentPage.rows,
range: currentPage.range,
rowCount,
columns: visibleColumns,
pinnedRows,
pinnedColumns,
disableHorizontalScroll: listView,
disableVerticalScroll: overlayState.overlayType === 'noColumnsOverlay' || overlayState.loadingOverlayVariant === 'skeleton',
getRowHeight: React.useMemo(() => {
if (!getRowHeight) {
return undefined;
}
return rowEntry => getRowHeight(_extends({}, rowEntry, {
densityFactor: density
}));
}, [getRowHeight, density]),
getEstimatedRowHeight: React.useMemo(() => getEstimatedRowHeight ? rowEntry => getEstimatedRowHeight(_extends({}, rowEntry, {
densityFactor: density
})) : undefined, [getEstimatedRowHeight, density]),
getRowSpacing: React.useMemo(() => getRowSpacing ? rowEntry => {
const indexRelativeToCurrentPage = currentPage.rowIdToIndexMap.get(rowEntry.id) ?? -1;
const visibility = {
isFirstVisible: indexRelativeToCurrentPage === 0,
isLastVisible: indexRelativeToCurrentPage === currentPage.rows.length - 1,
indexRelativeToCurrentPage
};
return getRowSpacing(_extends({}, rowEntry, visibility, {
indexRelativeToCurrentPage: apiRef.current.getRowIndexRelativeToVisibleRows(rowEntry.id)
}));
} : undefined, [apiRef, getRowSpacing, currentPage.rows, currentPage.rowIdToIndexMap]),
applyRowHeight: useEventCallback((entry, row) => apiRef.current.unstable_applyPipeProcessors('rowHeight', entry, row)),
virtualizeColumnsWithAutoRowHeight: rootProps.virtualizeColumnsWithAutoRowHeight,
focusedVirtualCell: useEventCallback(() => gridFocusedVirtualCellSelector(apiRef)),
resizeThrottleMs: rootProps.resizeThrottleMs,
onResize: useEventCallback(size => apiRef.current.publishEvent('resize', size)),
onWheel: useEventCallback(event => {
apiRef.current.publishEvent('virtualScrollerWheel', {}, event);
}),
onTouchMove: useEventCallback(event => {
apiRef.current.publishEvent('virtualScrollerTouchMove', {}, event);
}),
onRenderContextChange: useEventCallback(nextRenderContext => {
apiRef.current.publishEvent('renderedRowsIntervalChange', nextRenderContext);
}),
onScrollChange: React.useCallback((scrollPosition, nextRenderContext) => {
apiRef.current.publishEvent('scrollPositionChange', {
top: scrollPosition.top,
left: scrollPosition.left,
renderContext: nextRenderContext
});
}, [apiRef]),
scrollReset,
renderRow: React.useCallback(params => /*#__PURE__*/_jsx(RowSlot, _extends({
row: params.model,
rowId: params.id,
index: params.rowIndex,
selected: isRowSelected(params.id),
offsetLeft: params.offsetLeft,
columnsTotalWidth: columnsTotalWidth,
rowHeight: params.baseRowHeight,
pinnedColumns: pinnedColumns,
visibleColumns: visibleColumns,
firstColumnIndex: params.firstColumnIndex,
lastColumnIndex: params.lastColumnIndex,
focusedColumnIndex: params.focusedColumnIndex,
isFirstVisible: params.isFirstVisible,
isLastVisible: params.isLastVisible,
isNotVisible: params.isVirtualFocusRow,
showBottomBorder: params.showBottomBorder,
scrollbarWidth: verticalScrollbarWidth,
gridHasFiller: hasFiller
}, rowSlotProps), params.id), [columnsTotalWidth, hasFiller, isRowSelected, pinnedColumns, RowSlot, rowSlotProps, verticalScrollbarWidth, visibleColumns]),
renderInfiniteLoadingTrigger: React.useCallback(id => apiRef.current.getInfiniteLoadingTriggerElement?.({
lastRowId: id
}), [apiRef])
});
// HACK: Keep the grid's store in sync with the virtualizer store. We set up the
// subscription in the render phase rather than in an effect because other grid
// initialization code runs between those two moments.
//
// TODO(v9): Remove this
useFirstRender(() => {
apiRef.current.store.state.dimensions = addGridDimensions(virtualizer.store.state.dimensions, headerHeight, groupHeaderHeight, headerFilterHeight, headersTotalHeight);
apiRef.current.store.state.rowsMeta = virtualizer.store.state.rowsMeta;
apiRef.current.store.state.virtualization = virtualizer.store.state.virtualization;
});
useStoreEffect(virtualizer.store, Dimensions.selectors.dimensions, (_, dimensions) => {
if (!dimensions.isReady) {
return;
}
apiRef.current.setState(gridState => _extends({}, gridState, {
dimensions: addGridDimensions(dimensions, headerHeight, groupHeaderHeight, headerFilterHeight, headersTotalHeight)
}));
});
useStoreEffect(virtualizer.store, Dimensions.selectors.rowsMeta, (_, rowsMeta) => {
if (rowsMeta !== apiRef.current.state.rowsMeta) {
apiRef.current.setState(gridState => _extends({}, gridState, {
rowsMeta
}));
}
});
useStoreEffect(virtualizer.store, Virtualization.selectors.store, (_, virtualization) => {
if (virtualization.renderContext === EMPTY_RENDER_CONTEXT) {
return;
}
if (virtualization !== apiRef.current.state.virtualization) {
apiRef.current.setState(gridState => _extends({}, gridState, {
virtualization
}));
}
});
apiRef.current.register('private', {
virtualizer
});
useGridRowsMeta(apiRef, rootProps);
return virtualizer;
}
@@ -0,0 +1,8 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.mjs";
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.mjs";
/**
* @requires useGridCsvExport (method)
* @requires useGridSelection (method)
*/
export declare const useGridClipboard: (apiRef: RefObject<GridPrivateApiCommunity>, props: Pick<DataGridProcessedProps, 'ignoreValueFormatterDuringExport' | 'onClipboardCopy' | 'clipboardCopyCellDelimiter'>) => void;
@@ -0,0 +1,8 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.js";
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.js";
/**
* @requires useGridCsvExport (method)
* @requires useGridSelection (method)
*/
export declare const useGridClipboard: (apiRef: RefObject<GridPrivateApiCommunity>, props: Pick<DataGridProcessedProps, 'ignoreValueFormatterDuringExport' | 'onClipboardCopy' | 'clipboardCopyCellDelimiter'>) => void;
@@ -0,0 +1,105 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridClipboard = void 0;
var React = _interopRequireWildcard(require("react"));
var _utils = require("../../utils");
var _gridFocusStateSelector = require("../focus/gridFocusStateSelector");
var _csvSerializer = require("../export/serializers/csvSerializer");
var _keyboardUtils = require("../../../utils/keyboardUtils");
var _rowSelection = require("../rowSelection");
function writeToClipboardPolyfill(data) {
const span = document.createElement('span');
span.style.whiteSpace = 'pre';
span.style.userSelect = 'all';
span.style.opacity = '0px';
span.textContent = data;
document.body.appendChild(span);
const range = document.createRange();
range.selectNode(span);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
try {
document.execCommand('copy');
} finally {
document.body.removeChild(span);
}
}
function copyToClipboard(data) {
if (navigator.clipboard) {
navigator.clipboard.writeText(data).catch(() => {
writeToClipboardPolyfill(data);
});
} else {
writeToClipboardPolyfill(data);
}
}
function hasNativeSelection(element) {
// When getSelection is called on an <iframe> that is not displayed Firefox will return null.
if (window.getSelection()?.toString()) {
return true;
}
// window.getSelection() returns an empty string in Firefox for selections inside a form element.
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=85686.
// Instead, we can use element.selectionStart that is only defined on form elements.
if (element && (element.selectionEnd || 0) - (element.selectionStart || 0) > 0) {
return true;
}
return false;
}
/**
* @requires useGridCsvExport (method)
* @requires useGridSelection (method)
*/
const useGridClipboard = (apiRef, props) => {
const ignoreValueFormatterProp = props.ignoreValueFormatterDuringExport;
const ignoreValueFormatter = (typeof ignoreValueFormatterProp === 'object' ? ignoreValueFormatterProp?.clipboardExport : ignoreValueFormatterProp) || false;
const clipboardCopyCellDelimiter = props.clipboardCopyCellDelimiter;
const handleCopy = React.useCallback(event => {
if (!(0, _keyboardUtils.isCopyShortcut)(event)) {
return;
}
// Do nothing if there's a native selection
if (hasNativeSelection(event.target)) {
return;
}
let textToCopy = '';
const selectedRowsCount = (0, _rowSelection.gridRowSelectionCountSelector)(apiRef);
if (selectedRowsCount > 0) {
textToCopy = apiRef.current.getDataAsCsv({
includeHeaders: false,
delimiter: clipboardCopyCellDelimiter,
shouldAppendQuotes: false,
escapeFormulas: false
});
} else {
const focusedCell = (0, _gridFocusStateSelector.gridFocusCellSelector)(apiRef);
if (focusedCell) {
const cellParams = apiRef.current.getCellParams(focusedCell.id, focusedCell.field);
textToCopy = (0, _csvSerializer.serializeCellValue)(cellParams, {
csvOptions: {
delimiter: clipboardCopyCellDelimiter,
shouldAppendQuotes: false,
escapeFormulas: false
},
ignoreValueFormatter
});
}
}
textToCopy = apiRef.current.unstable_applyPipeProcessors('clipboardCopy', textToCopy);
if (textToCopy) {
copyToClipboard(textToCopy);
apiRef.current.publishEvent('clipboardCopy', textToCopy);
}
}, [apiRef, ignoreValueFormatter, clipboardCopyCellDelimiter]);
(0, _utils.useGridNativeEventListener)(apiRef, () => apiRef.current.rootElementRef.current, 'keydown', handleCopy);
(0, _utils.useGridEventPriority)(apiRef, 'clipboardCopy', props.onClipboardCopy);
};
exports.useGridClipboard = useGridClipboard;
@@ -0,0 +1,97 @@
import * as React from 'react';
import { useGridEventPriority, useGridNativeEventListener } from "../../utils/index.mjs";
import { gridFocusCellSelector } from "../focus/gridFocusStateSelector.mjs";
import { serializeCellValue } from "../export/serializers/csvSerializer.mjs";
import { isCopyShortcut } from "../../../utils/keyboardUtils.mjs";
import { gridRowSelectionCountSelector } from "../rowSelection/index.mjs";
function writeToClipboardPolyfill(data) {
const span = document.createElement('span');
span.style.whiteSpace = 'pre';
span.style.userSelect = 'all';
span.style.opacity = '0px';
span.textContent = data;
document.body.appendChild(span);
const range = document.createRange();
range.selectNode(span);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
try {
document.execCommand('copy');
} finally {
document.body.removeChild(span);
}
}
function copyToClipboard(data) {
if (navigator.clipboard) {
navigator.clipboard.writeText(data).catch(() => {
writeToClipboardPolyfill(data);
});
} else {
writeToClipboardPolyfill(data);
}
}
function hasNativeSelection(element) {
// When getSelection is called on an <iframe> that is not displayed Firefox will return null.
if (window.getSelection()?.toString()) {
return true;
}
// window.getSelection() returns an empty string in Firefox for selections inside a form element.
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=85686.
// Instead, we can use element.selectionStart that is only defined on form elements.
if (element && (element.selectionEnd || 0) - (element.selectionStart || 0) > 0) {
return true;
}
return false;
}
/**
* @requires useGridCsvExport (method)
* @requires useGridSelection (method)
*/
export const useGridClipboard = (apiRef, props) => {
const ignoreValueFormatterProp = props.ignoreValueFormatterDuringExport;
const ignoreValueFormatter = (typeof ignoreValueFormatterProp === 'object' ? ignoreValueFormatterProp?.clipboardExport : ignoreValueFormatterProp) || false;
const clipboardCopyCellDelimiter = props.clipboardCopyCellDelimiter;
const handleCopy = React.useCallback(event => {
if (!isCopyShortcut(event)) {
return;
}
// Do nothing if there's a native selection
if (hasNativeSelection(event.target)) {
return;
}
let textToCopy = '';
const selectedRowsCount = gridRowSelectionCountSelector(apiRef);
if (selectedRowsCount > 0) {
textToCopy = apiRef.current.getDataAsCsv({
includeHeaders: false,
delimiter: clipboardCopyCellDelimiter,
shouldAppendQuotes: false,
escapeFormulas: false
});
} else {
const focusedCell = gridFocusCellSelector(apiRef);
if (focusedCell) {
const cellParams = apiRef.current.getCellParams(focusedCell.id, focusedCell.field);
textToCopy = serializeCellValue(cellParams, {
csvOptions: {
delimiter: clipboardCopyCellDelimiter,
shouldAppendQuotes: false,
escapeFormulas: false
},
ignoreValueFormatter
});
}
}
textToCopy = apiRef.current.unstable_applyPipeProcessors('clipboardCopy', textToCopy);
if (textToCopy) {
copyToClipboard(textToCopy);
apiRef.current.publishEvent('clipboardCopy', textToCopy);
}
}, [apiRef, ignoreValueFormatter, clipboardCopyCellDelimiter]);
useGridNativeEventListener(apiRef, () => apiRef.current.rootElementRef.current, 'keydown', handleCopy);
useGridEventPriority(apiRef, 'clipboardCopy', props.onClipboardCopy);
};
@@ -0,0 +1,19 @@
import type { GridColumnGroup, GridColumnGroupingModel } from "../../../models/gridColumnGrouping.mjs";
export type GridColumnGroupLookup = {
[groupId: string]: Omit<GridColumnGroup, 'children'>;
};
export type GridGroupingStructure = {
groupId: null | string;
columnFields: string[];
};
export interface GridColumnsGroupingState {
lookup: GridColumnGroupLookup;
headerStructure: GridGroupingStructure[][];
unwrappedGroupingModel: {
[columnField: string]: GridColumnGroup['groupId'][];
};
maxDepth: number;
}
export interface GridColumnGroupingInternalCache {
lastColumnGroupingModel?: GridColumnGroupingModel;
}
@@ -0,0 +1,19 @@
import type { GridColumnGroup, GridColumnGroupingModel } from "../../../models/gridColumnGrouping.js";
export type GridColumnGroupLookup = {
[groupId: string]: Omit<GridColumnGroup, 'children'>;
};
export type GridGroupingStructure = {
groupId: null | string;
columnFields: string[];
};
export interface GridColumnsGroupingState {
lookup: GridColumnGroupLookup;
headerStructure: GridGroupingStructure[][];
unwrappedGroupingModel: {
[columnField: string]: GridColumnGroup['groupId'][];
};
maxDepth: number;
}
export interface GridColumnGroupingInternalCache {
lastColumnGroupingModel?: GridColumnGroupingModel;
}
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,20 @@
import type { GridStateCommunity } from "../../../models/gridStateCommunity.mjs";
/**
* @category ColumnGrouping
* @ignore - do not document.
*/
export declare const gridColumnGroupingSelector: import("@mui/x-data-grid").OutputSelector<GridStateCommunity, unknown, import("@mui/x-data-grid").GridColumnsGroupingState>;
export declare const gridColumnGroupsUnwrappedModelSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => {
[columnField: string]: string[];
};
export declare const gridColumnGroupsLookupSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("./gridColumnGroupsInterfaces.mjs").GridColumnGroupLookup;
export declare const gridColumnGroupsHeaderStructureSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("./gridColumnGroupsInterfaces.mjs").GridGroupingStructure[][];
export declare const gridColumnGroupsHeaderMaxDepthSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => number;
@@ -0,0 +1,20 @@
import type { GridStateCommunity } from "../../../models/gridStateCommunity.js";
/**
* @category ColumnGrouping
* @ignore - do not document.
*/
export declare const gridColumnGroupingSelector: import("@mui/x-data-grid").OutputSelector<GridStateCommunity, unknown, import("@mui/x-data-grid").GridColumnsGroupingState>;
export declare const gridColumnGroupsUnwrappedModelSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => {
[columnField: string]: string[];
};
export declare const gridColumnGroupsLookupSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("./gridColumnGroupsInterfaces.js").GridColumnGroupLookup;
export declare const gridColumnGroupsHeaderStructureSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("./gridColumnGroupsInterfaces.js").GridGroupingStructure[][];
export declare const gridColumnGroupsHeaderMaxDepthSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => number;
@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.gridColumnGroupsUnwrappedModelSelector = exports.gridColumnGroupsLookupSelector = exports.gridColumnGroupsHeaderStructureSelector = exports.gridColumnGroupsHeaderMaxDepthSelector = exports.gridColumnGroupingSelector = void 0;
var _createSelector = require("../../../utils/createSelector");
/**
* @category ColumnGrouping
* @ignore - do not document.
*/
const gridColumnGroupingSelector = exports.gridColumnGroupingSelector = (0, _createSelector.createRootSelector)(state => state.columnGrouping);
const gridColumnGroupsUnwrappedModelSelector = exports.gridColumnGroupsUnwrappedModelSelector = (0, _createSelector.createSelectorMemoized)(gridColumnGroupingSelector, columnGrouping => columnGrouping?.unwrappedGroupingModel ?? {});
const gridColumnGroupsLookupSelector = exports.gridColumnGroupsLookupSelector = (0, _createSelector.createSelectorMemoized)(gridColumnGroupingSelector, columnGrouping => columnGrouping?.lookup ?? {});
const gridColumnGroupsHeaderStructureSelector = exports.gridColumnGroupsHeaderStructureSelector = (0, _createSelector.createSelectorMemoized)(gridColumnGroupingSelector, columnGrouping => columnGrouping?.headerStructure ?? []);
const gridColumnGroupsHeaderMaxDepthSelector = exports.gridColumnGroupsHeaderMaxDepthSelector = (0, _createSelector.createSelector)(gridColumnGroupingSelector, columnGrouping => columnGrouping?.maxDepth ?? 0);
@@ -0,0 +1,10 @@
import { createSelector, createRootSelector, createSelectorMemoized } from "../../../utils/createSelector.mjs";
/**
* @category ColumnGrouping
* @ignore - do not document.
*/
export const gridColumnGroupingSelector = createRootSelector(state => state.columnGrouping);
export const gridColumnGroupsUnwrappedModelSelector = createSelectorMemoized(gridColumnGroupingSelector, columnGrouping => columnGrouping?.unwrappedGroupingModel ?? {});
export const gridColumnGroupsLookupSelector = createSelectorMemoized(gridColumnGroupingSelector, columnGrouping => columnGrouping?.lookup ?? {});
export const gridColumnGroupsHeaderStructureSelector = createSelectorMemoized(gridColumnGroupingSelector, columnGrouping => columnGrouping?.headerStructure ?? []);
export const gridColumnGroupsHeaderMaxDepthSelector = createSelector(gridColumnGroupingSelector, columnGrouping => columnGrouping?.maxDepth ?? 0);
@@ -0,0 +1,19 @@
import type { GridColumnGroupingModel, GridColumnNode, GridColumnGroup } from "../../../models/gridColumnGrouping.mjs";
import type { GridColDef } from "../../../models/colDef/index.mjs";
import type { GridColumnGroupLookup, GridGroupingStructure } from "./gridColumnGroupsInterfaces.mjs";
type UnwrappedGroupingModel = {
[key: GridColDef['field']]: GridColumnGroup['groupId'][];
};
export declare const createGroupLookup: (columnGroupingModel: GridColumnNode[]) => GridColumnGroupLookup;
/**
* This is a function that provide for each column the array of its parents.
* Parents are ordered from the root to the leaf.
* @param columnGroupingModel The model such as provided in DataGrid props
* @returns An object `{[field]: groupIds}` where `groupIds` is the parents of the column `field`
*/
export declare const unwrapGroupingColumnModel: (columnGroupingModel?: GridColumnGroupingModel) => UnwrappedGroupingModel;
export declare const getColumnGroupsHeaderStructure: (orderedColumns: string[], unwrappedGroupingModel: UnwrappedGroupingModel, pinnedFields: {
right?: string[];
left?: string[];
}) => GridGroupingStructure[][];
export {};
@@ -0,0 +1,19 @@
import type { GridColumnGroupingModel, GridColumnNode, GridColumnGroup } from "../../../models/gridColumnGrouping.js";
import type { GridColDef } from "../../../models/colDef/index.js";
import type { GridColumnGroupLookup, GridGroupingStructure } from "./gridColumnGroupsInterfaces.js";
type UnwrappedGroupingModel = {
[key: GridColDef['field']]: GridColumnGroup['groupId'][];
};
export declare const createGroupLookup: (columnGroupingModel: GridColumnNode[]) => GridColumnGroupLookup;
/**
* This is a function that provide for each column the array of its parents.
* Parents are ordered from the root to the leaf.
* @param columnGroupingModel The model such as provided in DataGrid props
* @returns An object `{[field]: groupIds}` where `groupIds` is the parents of the column `field`
*/
export declare const unwrapGroupingColumnModel: (columnGroupingModel?: GridColumnGroupingModel) => UnwrappedGroupingModel;
export declare const getColumnGroupsHeaderStructure: (orderedColumns: string[], unwrappedGroupingModel: UnwrappedGroupingModel, pinnedFields: {
right?: string[];
left?: string[];
}) => GridGroupingStructure[][];
export {};
@@ -0,0 +1,130 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.unwrapGroupingColumnModel = exports.getColumnGroupsHeaderStructure = exports.createGroupLookup = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _formatErrorMessage2 = _interopRequireDefault(require("@mui/x-internals/formatErrorMessage"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _gridColumnGrouping = require("../../../models/gridColumnGrouping");
const _excluded = ["groupId", "children"];
const createGroupLookup = columnGroupingModel => {
const groupLookup = {};
for (let i = 0; i < columnGroupingModel.length; i += 1) {
const node = columnGroupingModel[i];
if ((0, _gridColumnGrouping.isLeaf)(node)) {
continue;
}
const {
groupId,
children
} = node,
other = (0, _objectWithoutPropertiesLoose2.default)(node, _excluded);
if (!groupId) {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X Data Grid: An element of the columnGroupingModel is missing both `field` and `groupId`. ' + 'Each column group must have a groupId to identify it. ' + 'Add a groupId to the column group definition.' : (0, _formatErrorMessage2.default)(74));
}
if (process.env.NODE_ENV !== 'production' && !children) {
console.warn(`MUI X: group groupId=${groupId} has no children.`);
}
const groupParam = (0, _extends2.default)({}, other, {
groupId
});
const subTreeLookup = createGroupLookup(children);
if (subTreeLookup[groupId] !== undefined || groupLookup[groupId] !== undefined) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X Data Grid: The groupId "${groupId}" is used multiple times in the columnGroupingModel. ` + 'Each groupId must be unique within the column grouping model. ' + 'Use unique groupId values for each column group.' : (0, _formatErrorMessage2.default)(75, groupId));
}
Object.assign(groupLookup, subTreeLookup);
groupLookup[groupId] = groupParam;
}
return groupLookup;
};
// This is the recurrence function that help writing `unwrapGroupingColumnModel()`
exports.createGroupLookup = createGroupLookup;
const recurrentUnwrapGroupingColumnModel = (columnGroupNode, parents, unwrappedGroupingModelToComplete) => {
if ((0, _gridColumnGrouping.isLeaf)(columnGroupNode)) {
if (unwrappedGroupingModelToComplete[columnGroupNode.field] !== undefined) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X Data Grid: The field "${columnGroupNode.field}" appears multiple times in the columnGroupingModel. ` + `It is found in both: "${unwrappedGroupingModelToComplete[columnGroupNode.field].join(' > ')}" and "${parents.join(' > ')}". ` + 'Each field should only appear once in the grouping model.' : (0, _formatErrorMessage2.default)(76, columnGroupNode.field, unwrappedGroupingModelToComplete[columnGroupNode.field].join(' > '), parents.join(' > ')));
}
unwrappedGroupingModelToComplete[columnGroupNode.field] = parents;
return;
}
const {
groupId,
children
} = columnGroupNode;
children.forEach(child => {
recurrentUnwrapGroupingColumnModel(child, [...parents, groupId], unwrappedGroupingModelToComplete);
});
};
/**
* This is a function that provide for each column the array of its parents.
* Parents are ordered from the root to the leaf.
* @param columnGroupingModel The model such as provided in DataGrid props
* @returns An object `{[field]: groupIds}` where `groupIds` is the parents of the column `field`
*/
const unwrapGroupingColumnModel = columnGroupingModel => {
if (!columnGroupingModel) {
return {};
}
const unwrappedSubTree = {};
columnGroupingModel.forEach(columnGroupNode => {
recurrentUnwrapGroupingColumnModel(columnGroupNode, [], unwrappedSubTree);
});
return unwrappedSubTree;
};
exports.unwrapGroupingColumnModel = unwrapGroupingColumnModel;
const getColumnGroupsHeaderStructure = (orderedColumns, unwrappedGroupingModel, pinnedFields) => {
const getParents = field => unwrappedGroupingModel[field] ?? [];
const groupingHeaderStructure = [];
const maxDepth = Math.max(0, ...orderedColumns.map(field => getParents(field).length));
const haveSameParents = (field1, field2, depth) => {
const a = getParents(field1);
const b = getParents(field2);
for (let i = 0; i <= depth; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
};
const haveDifferentContainers = (field1, field2) => {
const left = pinnedFields?.left;
const right = pinnedFields?.right;
const inLeft1 = !!left?.includes(field1);
const inLeft2 = !!left?.includes(field2);
const inRight1 = !!right?.includes(field1);
const inRight2 = !!right?.includes(field2);
return inLeft1 !== inLeft2 || inRight1 !== inRight2;
};
for (let depth = 0; depth < maxDepth; depth += 1) {
const depthStructure = [];
for (let i = 0; i < orderedColumns.length; i += 1) {
const field = orderedColumns[i];
const groupId = getParents(field)[depth] ?? null;
if (depthStructure.length === 0) {
depthStructure.push({
columnFields: [field],
groupId
});
continue;
}
const lastGroup = depthStructure[depthStructure.length - 1];
const prevField = lastGroup.columnFields[lastGroup.columnFields.length - 1];
if (lastGroup.groupId !== groupId || !haveSameParents(prevField, field, depth) || haveDifferentContainers(prevField, field)) {
depthStructure.push({
columnFields: [field],
groupId
});
} else {
lastGroup.columnFields.push(field);
}
}
groupingHeaderStructure.push(depthStructure);
}
return groupingHeaderStructure;
};
exports.getColumnGroupsHeaderStructure = getColumnGroupsHeaderStructure;
@@ -0,0 +1,120 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["groupId", "children"];
import { isLeaf } from "../../../models/gridColumnGrouping.mjs";
export const createGroupLookup = columnGroupingModel => {
const groupLookup = {};
for (let i = 0; i < columnGroupingModel.length; i += 1) {
const node = columnGroupingModel[i];
if (isLeaf(node)) {
continue;
}
const {
groupId,
children
} = node,
other = _objectWithoutPropertiesLoose(node, _excluded);
if (!groupId) {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X Data Grid: An element of the columnGroupingModel is missing both `field` and `groupId`. ' + 'Each column group must have a groupId to identify it. ' + 'Add a groupId to the column group definition.' : _formatErrorMessage(74));
}
if (process.env.NODE_ENV !== 'production' && !children) {
console.warn(`MUI X: group groupId=${groupId} has no children.`);
}
const groupParam = _extends({}, other, {
groupId
});
const subTreeLookup = createGroupLookup(children);
if (subTreeLookup[groupId] !== undefined || groupLookup[groupId] !== undefined) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X Data Grid: The groupId "${groupId}" is used multiple times in the columnGroupingModel. ` + 'Each groupId must be unique within the column grouping model. ' + 'Use unique groupId values for each column group.' : _formatErrorMessage(75, groupId));
}
Object.assign(groupLookup, subTreeLookup);
groupLookup[groupId] = groupParam;
}
return groupLookup;
};
// This is the recurrence function that help writing `unwrapGroupingColumnModel()`
const recurrentUnwrapGroupingColumnModel = (columnGroupNode, parents, unwrappedGroupingModelToComplete) => {
if (isLeaf(columnGroupNode)) {
if (unwrappedGroupingModelToComplete[columnGroupNode.field] !== undefined) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X Data Grid: The field "${columnGroupNode.field}" appears multiple times in the columnGroupingModel. ` + `It is found in both: "${unwrappedGroupingModelToComplete[columnGroupNode.field].join(' > ')}" and "${parents.join(' > ')}". ` + 'Each field should only appear once in the grouping model.' : _formatErrorMessage(76, columnGroupNode.field, unwrappedGroupingModelToComplete[columnGroupNode.field].join(' > '), parents.join(' > ')));
}
unwrappedGroupingModelToComplete[columnGroupNode.field] = parents;
return;
}
const {
groupId,
children
} = columnGroupNode;
children.forEach(child => {
recurrentUnwrapGroupingColumnModel(child, [...parents, groupId], unwrappedGroupingModelToComplete);
});
};
/**
* This is a function that provide for each column the array of its parents.
* Parents are ordered from the root to the leaf.
* @param columnGroupingModel The model such as provided in DataGrid props
* @returns An object `{[field]: groupIds}` where `groupIds` is the parents of the column `field`
*/
export const unwrapGroupingColumnModel = columnGroupingModel => {
if (!columnGroupingModel) {
return {};
}
const unwrappedSubTree = {};
columnGroupingModel.forEach(columnGroupNode => {
recurrentUnwrapGroupingColumnModel(columnGroupNode, [], unwrappedSubTree);
});
return unwrappedSubTree;
};
export const getColumnGroupsHeaderStructure = (orderedColumns, unwrappedGroupingModel, pinnedFields) => {
const getParents = field => unwrappedGroupingModel[field] ?? [];
const groupingHeaderStructure = [];
const maxDepth = Math.max(0, ...orderedColumns.map(field => getParents(field).length));
const haveSameParents = (field1, field2, depth) => {
const a = getParents(field1);
const b = getParents(field2);
for (let i = 0; i <= depth; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
};
const haveDifferentContainers = (field1, field2) => {
const left = pinnedFields?.left;
const right = pinnedFields?.right;
const inLeft1 = !!left?.includes(field1);
const inLeft2 = !!left?.includes(field2);
const inRight1 = !!right?.includes(field1);
const inRight2 = !!right?.includes(field2);
return inLeft1 !== inLeft2 || inRight1 !== inRight2;
};
for (let depth = 0; depth < maxDepth; depth += 1) {
const depthStructure = [];
for (let i = 0; i < orderedColumns.length; i += 1) {
const field = orderedColumns[i];
const groupId = getParents(field)[depth] ?? null;
if (depthStructure.length === 0) {
depthStructure.push({
columnFields: [field],
groupId
});
continue;
}
const lastGroup = depthStructure[depthStructure.length - 1];
const prevField = lastGroup.columnFields[lastGroup.columnFields.length - 1];
if (lastGroup.groupId !== groupId || !haveSameParents(prevField, field, depth) || haveDifferentContainers(prevField, field)) {
depthStructure.push({
columnFields: [field],
groupId
});
} else {
lastGroup.columnFields.push(field);
}
}
groupingHeaderStructure.push(depthStructure);
}
return groupingHeaderStructure;
};
@@ -0,0 +1,2 @@
export * from "./gridColumnGroupsSelector.mjs";
export type { GridColumnsGroupingState } from "./gridColumnGroupsInterfaces.mjs";
@@ -0,0 +1,2 @@
export * from "./gridColumnGroupsSelector.js";
export type { GridColumnsGroupingState } from "./gridColumnGroupsInterfaces.js";
@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _gridColumnGroupsSelector = require("./gridColumnGroupsSelector");
Object.keys(_gridColumnGroupsSelector).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _gridColumnGroupsSelector[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _gridColumnGroupsSelector[key];
}
});
});
@@ -0,0 +1,2 @@
export * from "./gridColumnGroupsSelector.mjs";
export {};

Some files were not shown because too many files have changed in this diff Show More