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,9 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridRenderContext } from "../../../models/index.mjs";
import type { GridValidRowModel } from "../../../models/gridRows.mjs";
import type { GridColDef } from "../../../models/colDef/index.mjs";
import type { GridApiCommunity } from "../../../models/api/gridApiCommunity.mjs";
import type { RowRange } from "./useGridRowSpanning.mjs";
export declare function getUnprocessedRange(testRange: RowRange, processedRange: RowRange): RowRange | null;
export declare function isRowContextInitialized(renderContext: GridRenderContext): boolean;
export declare const getCellValue: (row: GridValidRowModel, colDef: GridColDef | undefined, apiRef: RefObject<GridApiCommunity>) => any;
@@ -0,0 +1,9 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridRenderContext } from "../../../models/index.js";
import type { GridValidRowModel } from "../../../models/gridRows.js";
import type { GridColDef } from "../../../models/colDef/index.js";
import type { GridApiCommunity } from "../../../models/api/gridApiCommunity.js";
import type { RowRange } from "./useGridRowSpanning.js";
export declare function getUnprocessedRange(testRange: RowRange, processedRange: RowRange): RowRange | null;
export declare function isRowContextInitialized(renderContext: GridRenderContext): boolean;
export declare const getCellValue: (row: GridValidRowModel, colDef: GridColDef | undefined, apiRef: RefObject<GridApiCommunity>) => any;
@@ -0,0 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getCellValue = void 0;
exports.getUnprocessedRange = getUnprocessedRange;
exports.isRowContextInitialized = isRowContextInitialized;
var _gridRowsUtils = require("./gridRowsUtils");
function getUnprocessedRange(testRange, processedRange) {
if (testRange.firstRowIndex >= processedRange.firstRowIndex && testRange.lastRowIndex <= processedRange.lastRowIndex) {
return null;
}
// Overflowing at the end
// Example: testRange={ firstRowIndex: 10, lastRowIndex: 20 }, processedRange={ firstRowIndex: 0, lastRowIndex: 15 }
// Unprocessed Range={ firstRowIndex: 16, lastRowIndex: 20 }
if (testRange.firstRowIndex >= processedRange.firstRowIndex && testRange.lastRowIndex > processedRange.lastRowIndex) {
return {
firstRowIndex: processedRange.lastRowIndex,
lastRowIndex: testRange.lastRowIndex
};
}
// Overflowing at the beginning
// Example: testRange={ firstRowIndex: 0, lastRowIndex: 20 }, processedRange={ firstRowIndex: 16, lastRowIndex: 30 }
// Unprocessed Range={ firstRowIndex: 0, lastRowIndex: 15 }
if (testRange.firstRowIndex < processedRange.firstRowIndex && testRange.lastRowIndex <= processedRange.lastRowIndex) {
return {
firstRowIndex: testRange.firstRowIndex,
lastRowIndex: processedRange.firstRowIndex - 1
};
}
// TODO: Should return two ranges handle overflowing at both ends ?
return testRange;
}
function isRowContextInitialized(renderContext) {
return renderContext.firstRowIndex !== 0 || renderContext.lastRowIndex !== 0;
}
const getCellValue = (row, colDef, apiRef) => {
if (!row || !colDef) {
return null;
}
const cellValue = row[colDef.field];
if (colDef.rowSpanValueGetter) {
return colDef.rowSpanValueGetter(cellValue, row, colDef, apiRef);
}
// This util is also called during the state initialization
// Use util method directly instead of calling apiRef.current.getRowValue
return (0, _gridRowsUtils.getRowValue)(row, colDef, apiRef);
};
exports.getCellValue = getCellValue;
@@ -0,0 +1,42 @@
import { getRowValue } from "./gridRowsUtils.mjs";
export function getUnprocessedRange(testRange, processedRange) {
if (testRange.firstRowIndex >= processedRange.firstRowIndex && testRange.lastRowIndex <= processedRange.lastRowIndex) {
return null;
}
// Overflowing at the end
// Example: testRange={ firstRowIndex: 10, lastRowIndex: 20 }, processedRange={ firstRowIndex: 0, lastRowIndex: 15 }
// Unprocessed Range={ firstRowIndex: 16, lastRowIndex: 20 }
if (testRange.firstRowIndex >= processedRange.firstRowIndex && testRange.lastRowIndex > processedRange.lastRowIndex) {
return {
firstRowIndex: processedRange.lastRowIndex,
lastRowIndex: testRange.lastRowIndex
};
}
// Overflowing at the beginning
// Example: testRange={ firstRowIndex: 0, lastRowIndex: 20 }, processedRange={ firstRowIndex: 16, lastRowIndex: 30 }
// Unprocessed Range={ firstRowIndex: 0, lastRowIndex: 15 }
if (testRange.firstRowIndex < processedRange.firstRowIndex && testRange.lastRowIndex <= processedRange.lastRowIndex) {
return {
firstRowIndex: testRange.firstRowIndex,
lastRowIndex: processedRange.firstRowIndex - 1
};
}
// TODO: Should return two ranges handle overflowing at both ends ?
return testRange;
}
export function isRowContextInitialized(renderContext) {
return renderContext.firstRowIndex !== 0 || renderContext.lastRowIndex !== 0;
}
export const getCellValue = (row, colDef, apiRef) => {
if (!row || !colDef) {
return null;
}
const cellValue = row[colDef.field];
if (colDef.rowSpanValueGetter) {
return colDef.rowSpanValueGetter(cellValue, row, colDef, apiRef);
}
// This util is also called during the state initialization
// Use util method directly instead of calling apiRef.current.getRowValue
return getRowValue(row, colDef, apiRef);
};
@@ -0,0 +1,98 @@
import type { GridRowEntry, GridRowId, GridRowTreeConfig, GridValidRowModel } from "../../../models/gridRows.mjs";
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.mjs";
export interface GridRowsInternalCache {
/**
* The rows as they were the last time all the rows have been updated at once
* It is used to avoid processing several time the same set of rows
*/
rowsBeforePartialUpdates: DataGridProcessedProps['rows'];
/**
* The value of the `loading` prop since the last time that the rows state was updated.
*/
loadingPropBeforePartialUpdates: DataGridProcessedProps['loading'];
/**
* The value of the `rowCount` prop since the last time that the rows state was updated.
*/
rowCountPropBeforePartialUpdates: DataGridProcessedProps['rowCount'];
/**
* Lookup containing the latest model at all time (even those not stored in the state yet).
*/
dataRowIdToModelLookup: GridRowIdToModelLookup;
/**
* List of updates (partial or full) applied since the last time the state was synced with the cache.
* It is used to build the tree.
* If the update is a full update, we rebuild the tree from scratch.
* If the update is a partial update, we only modify the impacted nodes.
*/
updates: GridRowsPartialUpdates | GridRowsFullUpdate;
}
export interface GridRowsState {
/**
* Name of the algorithm used to group the rows
* It is useful to decide which filtering / sorting algorithm to apply, to avoid applying tree-data filtering on a grouping-by-column dataset for instance.
*/
groupingName: string;
tree: GridRowTreeConfig;
/**
* Amount of nodes at each depth (including auto-generated ones)
*/
treeDepths: GridTreeDepths;
dataRowIds: GridRowId[];
/**
* The loading status of the rows.
*/
loading?: boolean;
/**
* Amount of data rows provided to the grid.
* Includes the filtered and collapsed rows.
* Does not include the auto-generated rows (auto generated groups and footers).
*/
totalRowCount: number;
/**
* Amount of top level rows.
* Includes the filtered rows and the auto-generated root footer if any.
* Does not include the rows of depth > 0 (rows inside a group).
*/
totalTopLevelRowCount: number;
dataRowIdToModelLookup: GridRowIdToModelLookup;
additionalRowGroups?: {
pinnedRows?: GridPinnedRowsState;
};
/**
* Contains some values of type `GridRowId` that have been requested to be fetched
* either by `defaultGroupingExpansionDepth` or `isGroupExpandedByDefault` props.
* Applicable with server-side grouped data and `dataSource` only.
*/
groupsToFetch?: GridRowId[];
}
export interface GridRowTreeCreationParams {
previousTree: GridRowTreeConfig | null;
previousTreeDepths: GridTreeDepths | null;
updates: GridRowsPartialUpdates | GridRowsFullUpdate;
dataRowIdToModelLookup: GridRowIdToModelLookup;
previousGroupsToFetch?: GridRowId[];
}
export type GridRowTreeCreationValue = Pick<GridRowsState, 'groupingName' | 'tree' | 'treeDepths' | 'dataRowIds' | 'groupsToFetch'>;
export type GridHydrateRowsValue = Pick<GridRowsState, 'tree' | 'treeDepths' | 'dataRowIds' | 'dataRowIdToModelLookup' | 'additionalRowGroups'>;
export type GridRowsPartialUpdateAction = 'insert' | 'modify' | 'remove';
export type GridRowIdToModelLookup<R extends GridValidRowModel = GridValidRowModel> = Record<string, R>;
export type GridTreeDepths = {
[depth: number]: number;
};
export interface GridRowsFullUpdate {
type: 'full';
rows: GridRowId[];
}
export interface GridRowsPartialUpdates {
type: 'partial';
actions: { [action in GridRowsPartialUpdateAction]: GridRowId[] };
idToActionLookup: {
[id: GridRowId]: GridRowsPartialUpdateAction | undefined;
};
groupKeys?: string[];
}
export interface GridPinnedRowsState {
top?: GridRowEntry[];
bottom?: GridRowEntry[];
}
export type GridPinnedRowsPosition = keyof GridPinnedRowsState;
@@ -0,0 +1,98 @@
import type { GridRowEntry, GridRowId, GridRowTreeConfig, GridValidRowModel } from "../../../models/gridRows.js";
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.js";
export interface GridRowsInternalCache {
/**
* The rows as they were the last time all the rows have been updated at once
* It is used to avoid processing several time the same set of rows
*/
rowsBeforePartialUpdates: DataGridProcessedProps['rows'];
/**
* The value of the `loading` prop since the last time that the rows state was updated.
*/
loadingPropBeforePartialUpdates: DataGridProcessedProps['loading'];
/**
* The value of the `rowCount` prop since the last time that the rows state was updated.
*/
rowCountPropBeforePartialUpdates: DataGridProcessedProps['rowCount'];
/**
* Lookup containing the latest model at all time (even those not stored in the state yet).
*/
dataRowIdToModelLookup: GridRowIdToModelLookup;
/**
* List of updates (partial or full) applied since the last time the state was synced with the cache.
* It is used to build the tree.
* If the update is a full update, we rebuild the tree from scratch.
* If the update is a partial update, we only modify the impacted nodes.
*/
updates: GridRowsPartialUpdates | GridRowsFullUpdate;
}
export interface GridRowsState {
/**
* Name of the algorithm used to group the rows
* It is useful to decide which filtering / sorting algorithm to apply, to avoid applying tree-data filtering on a grouping-by-column dataset for instance.
*/
groupingName: string;
tree: GridRowTreeConfig;
/**
* Amount of nodes at each depth (including auto-generated ones)
*/
treeDepths: GridTreeDepths;
dataRowIds: GridRowId[];
/**
* The loading status of the rows.
*/
loading?: boolean;
/**
* Amount of data rows provided to the grid.
* Includes the filtered and collapsed rows.
* Does not include the auto-generated rows (auto generated groups and footers).
*/
totalRowCount: number;
/**
* Amount of top level rows.
* Includes the filtered rows and the auto-generated root footer if any.
* Does not include the rows of depth > 0 (rows inside a group).
*/
totalTopLevelRowCount: number;
dataRowIdToModelLookup: GridRowIdToModelLookup;
additionalRowGroups?: {
pinnedRows?: GridPinnedRowsState;
};
/**
* Contains some values of type `GridRowId` that have been requested to be fetched
* either by `defaultGroupingExpansionDepth` or `isGroupExpandedByDefault` props.
* Applicable with server-side grouped data and `dataSource` only.
*/
groupsToFetch?: GridRowId[];
}
export interface GridRowTreeCreationParams {
previousTree: GridRowTreeConfig | null;
previousTreeDepths: GridTreeDepths | null;
updates: GridRowsPartialUpdates | GridRowsFullUpdate;
dataRowIdToModelLookup: GridRowIdToModelLookup;
previousGroupsToFetch?: GridRowId[];
}
export type GridRowTreeCreationValue = Pick<GridRowsState, 'groupingName' | 'tree' | 'treeDepths' | 'dataRowIds' | 'groupsToFetch'>;
export type GridHydrateRowsValue = Pick<GridRowsState, 'tree' | 'treeDepths' | 'dataRowIds' | 'dataRowIdToModelLookup' | 'additionalRowGroups'>;
export type GridRowsPartialUpdateAction = 'insert' | 'modify' | 'remove';
export type GridRowIdToModelLookup<R extends GridValidRowModel = GridValidRowModel> = Record<string, R>;
export type GridTreeDepths = {
[depth: number]: number;
};
export interface GridRowsFullUpdate {
type: 'full';
rows: GridRowId[];
}
export interface GridRowsPartialUpdates {
type: 'partial';
actions: { [action in GridRowsPartialUpdateAction]: GridRowId[] };
idToActionLookup: {
[id: GridRowId]: GridRowsPartialUpdateAction | undefined;
};
groupKeys?: string[];
}
export interface GridPinnedRowsState {
top?: GridRowEntry[];
bottom?: GridRowEntry[];
}
export type GridPinnedRowsPosition = keyof GridPinnedRowsState;
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,10 @@
import type { HeightEntry } from '@mui/x-virtualizer/models';
import type { GridRowId } from "../../../models/gridRows.mjs";
export type { HeightEntry } from '@mui/x-virtualizer/models';
export type HeightCache = Map<GridRowId, HeightEntry>;
export interface GridRowsMetaInternalCache {
/**
* Map of height cache entries.
*/
heights: HeightCache;
}
@@ -0,0 +1,10 @@
import type { HeightEntry } from '@mui/x-virtualizer/models';
import type { GridRowId } from "../../../models/gridRows.js";
export type { HeightEntry } from '@mui/x-virtualizer/models';
export type HeightCache = Map<GridRowId, HeightEntry>;
export interface GridRowsMetaInternalCache {
/**
* Map of height cache entries.
*/
heights: HeightCache;
}
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,2 @@
import type { GridStateCommunity } from "../../../models/gridStateCommunity.mjs";
export declare const gridRowsMetaSelector: import("@mui/x-data-grid").OutputSelector<GridStateCommunity, unknown, import("@mui/x-data-grid").GridRowsMetaState>;
@@ -0,0 +1,2 @@
import type { GridStateCommunity } from "../../../models/gridStateCommunity.js";
export declare const gridRowsMetaSelector: import("@mui/x-data-grid").OutputSelector<GridStateCommunity, unknown, import("@mui/x-data-grid").GridRowsMetaState>;
@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.gridRowsMetaSelector = void 0;
var _createSelector = require("../../../utils/createSelector");
const gridRowsMetaSelector = exports.gridRowsMetaSelector = (0, _createSelector.createRootSelector)(state => state.rowsMeta);
@@ -0,0 +1,2 @@
import { createRootSelector } from "../../../utils/createSelector.mjs";
export const gridRowsMetaSelector = createRootSelector(state => state.rowsMeta);
@@ -0,0 +1,5 @@
import type { RowsMetaState } from '@mui/x-virtualizer/models';
/**
* The grid rows total height and row positions.
*/
export interface GridRowsMetaState extends RowsMetaState {}
@@ -0,0 +1,5 @@
import type { RowsMetaState } from '@mui/x-virtualizer/models';
/**
* The grid rows total height and row positions.
*/
export interface GridRowsMetaState extends RowsMetaState {}
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,80 @@
import type { GridRowId } from "../../../models/gridRows.mjs";
import type { GridStateCommunity } from "../../../models/gridStateCommunity.mjs";
export declare const gridRowsStateSelector: import("@mui/x-data-grid").OutputSelector<GridStateCommunity, unknown, import("@mui/x-data-grid").GridRowsState>;
export declare const gridRowCountSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => number;
export declare const gridRowsLoadingSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => boolean | undefined;
export declare const gridTopLevelRowCountSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => number;
export declare const gridRowsLookupSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("@mui/x-data-grid").GridRowIdToModelLookup<import("@mui/x-data-grid").GridValidRowModel>;
/**
* @category Rows
*/
export declare const gridRowSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>, id: GridRowId) => import("@mui/x-data-grid").GridValidRowModel;
export declare const gridRowTreeSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("@mui/x-data-grid").GridRowTreeConfig;
/**
* @category Rows
*/
export declare const gridRowNodeSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>, rowId: GridRowId) => import("@mui/x-data-grid").GridTreeNode;
export declare const gridRowGroupsToFetchSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => GridRowId[] | undefined;
export declare const gridRowGroupingNameSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => string;
export declare const gridRowTreeDepthsSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("./gridRowsInterfaces.mjs").GridTreeDepths;
export declare const gridRowMaximumTreeDepthSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => number;
/**
* @category Rows
*/
export declare const gridDataRowIdsSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => GridRowId[];
export declare const gridDataRowsSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("@mui/x-data-grid").GridValidRowModel[];
/**
* @ignore - do not document.
*/
export declare const gridAdditionalRowGroupsSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => {
pinnedRows?: import("./gridRowsInterfaces.mjs").GridPinnedRowsState;
} | undefined;
/**
* @ignore - do not document.
*/
export declare const gridPinnedRowsSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => {
bottom: {
id: GridRowId;
model: import("@mui/x-data-grid").GridValidRowModel;
}[];
top: {
id: GridRowId;
model: import("@mui/x-data-grid").GridValidRowModel;
}[];
};
/**
* @ignore - do not document.
*/
export declare const gridPinnedRowsCountSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => number;
@@ -0,0 +1,80 @@
import type { GridRowId } from "../../../models/gridRows.js";
import type { GridStateCommunity } from "../../../models/gridStateCommunity.js";
export declare const gridRowsStateSelector: import("@mui/x-data-grid").OutputSelector<GridStateCommunity, unknown, import("@mui/x-data-grid").GridRowsState>;
export declare const gridRowCountSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => number;
export declare const gridRowsLoadingSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => boolean | undefined;
export declare const gridTopLevelRowCountSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => number;
export declare const gridRowsLookupSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("@mui/x-data-grid").GridRowIdToModelLookup<import("@mui/x-data-grid").GridValidRowModel>;
/**
* @category Rows
*/
export declare const gridRowSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>, id: GridRowId) => import("@mui/x-data-grid").GridValidRowModel;
export declare const gridRowTreeSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("@mui/x-data-grid").GridRowTreeConfig;
/**
* @category Rows
*/
export declare const gridRowNodeSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>, rowId: GridRowId) => import("@mui/x-data-grid").GridTreeNode;
export declare const gridRowGroupsToFetchSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => GridRowId[] | undefined;
export declare const gridRowGroupingNameSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => string;
export declare const gridRowTreeDepthsSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("./gridRowsInterfaces.js").GridTreeDepths;
export declare const gridRowMaximumTreeDepthSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => number;
/**
* @category Rows
*/
export declare const gridDataRowIdsSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => GridRowId[];
export declare const gridDataRowsSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => import("@mui/x-data-grid").GridValidRowModel[];
/**
* @ignore - do not document.
*/
export declare const gridAdditionalRowGroupsSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => {
pinnedRows?: import("./gridRowsInterfaces.js").GridPinnedRowsState;
} | undefined;
/**
* @ignore - do not document.
*/
export declare const gridPinnedRowsSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => {
bottom: {
id: GridRowId;
model: import("@mui/x-data-grid").GridValidRowModel;
}[];
top: {
id: GridRowId;
model: import("@mui/x-data-grid").GridValidRowModel;
}[];
};
/**
* @ignore - do not document.
*/
export declare const gridPinnedRowsCountSelector: (args_0: import("react").RefObject<{
state: GridStateCommunity;
} | null>) => number;
@@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.gridTopLevelRowCountSelector = exports.gridRowsStateSelector = exports.gridRowsLookupSelector = exports.gridRowsLoadingSelector = exports.gridRowTreeSelector = exports.gridRowTreeDepthsSelector = exports.gridRowSelector = exports.gridRowNodeSelector = exports.gridRowMaximumTreeDepthSelector = exports.gridRowGroupsToFetchSelector = exports.gridRowGroupingNameSelector = exports.gridRowCountSelector = exports.gridPinnedRowsSelector = exports.gridPinnedRowsCountSelector = exports.gridDataRowsSelector = exports.gridDataRowIdsSelector = exports.gridAdditionalRowGroupsSelector = void 0;
var _createSelector = require("../../../utils/createSelector");
const gridRowsStateSelector = exports.gridRowsStateSelector = (0, _createSelector.createRootSelector)(state => state.rows);
const gridRowCountSelector = exports.gridRowCountSelector = (0, _createSelector.createSelector)(gridRowsStateSelector, rows => rows.totalRowCount);
const gridRowsLoadingSelector = exports.gridRowsLoadingSelector = (0, _createSelector.createSelector)(gridRowsStateSelector, rows => rows.loading);
const gridTopLevelRowCountSelector = exports.gridTopLevelRowCountSelector = (0, _createSelector.createSelector)(gridRowsStateSelector, rows => rows.totalTopLevelRowCount);
// TODO rows v6: Rename
const gridRowsLookupSelector = exports.gridRowsLookupSelector = (0, _createSelector.createSelector)(gridRowsStateSelector, rows => rows.dataRowIdToModelLookup);
/**
* @category Rows
*/
const gridRowSelector = exports.gridRowSelector = (0, _createSelector.createSelector)(gridRowsLookupSelector, (rows, id) => rows[id]);
const gridRowTreeSelector = exports.gridRowTreeSelector = (0, _createSelector.createSelector)(gridRowsStateSelector, rows => rows.tree);
/**
* @category Rows
*/
const gridRowNodeSelector = exports.gridRowNodeSelector = (0, _createSelector.createSelector)(gridRowTreeSelector, (rowTree, rowId) => rowTree[rowId]);
const gridRowGroupsToFetchSelector = exports.gridRowGroupsToFetchSelector = (0, _createSelector.createSelector)(gridRowsStateSelector, rows => rows.groupsToFetch);
const gridRowGroupingNameSelector = exports.gridRowGroupingNameSelector = (0, _createSelector.createSelector)(gridRowsStateSelector, rows => rows.groupingName);
const gridRowTreeDepthsSelector = exports.gridRowTreeDepthsSelector = (0, _createSelector.createSelector)(gridRowsStateSelector, rows => rows.treeDepths);
const gridRowMaximumTreeDepthSelector = exports.gridRowMaximumTreeDepthSelector = (0, _createSelector.createSelectorMemoized)(gridRowsStateSelector, rows => {
const entries = Object.entries(rows.treeDepths);
if (entries.length === 0) {
return 1;
}
return (entries.filter(([, nodeCount]) => nodeCount > 0).map(([depth]) => Number(depth)).sort((a, b) => b - a)[0] ?? 0) + 1;
});
/**
* @category Rows
*/
const gridDataRowIdsSelector = exports.gridDataRowIdsSelector = (0, _createSelector.createSelector)(gridRowsStateSelector, rows => rows.dataRowIds);
const gridDataRowsSelector = exports.gridDataRowsSelector = (0, _createSelector.createSelectorMemoized)(gridDataRowIdsSelector, gridRowsLookupSelector, (dataRowIds, rowsLookup) => dataRowIds.reduce((acc, id) => {
if (!rowsLookup[id]) {
return acc;
}
acc.push(rowsLookup[id]);
return acc;
}, []));
/**
* @ignore - do not document.
*/
const gridAdditionalRowGroupsSelector = exports.gridAdditionalRowGroupsSelector = (0, _createSelector.createSelector)(gridRowsStateSelector, rows => rows?.additionalRowGroups);
/**
* @ignore - do not document.
*/
const gridPinnedRowsSelector = exports.gridPinnedRowsSelector = (0, _createSelector.createSelectorMemoized)(gridAdditionalRowGroupsSelector, additionalRowGroups => {
const rawPinnedRows = additionalRowGroups?.pinnedRows;
return {
bottom: rawPinnedRows?.bottom?.map(rowEntry => ({
id: rowEntry.id,
model: rowEntry.model ?? {}
})) ?? [],
top: rawPinnedRows?.top?.map(rowEntry => ({
id: rowEntry.id,
model: rowEntry.model ?? {}
})) ?? []
};
});
/**
* @ignore - do not document.
*/
const gridPinnedRowsCountSelector = exports.gridPinnedRowsCountSelector = (0, _createSelector.createSelector)(gridPinnedRowsSelector, pinnedRows => {
return (pinnedRows?.top?.length || 0) + (pinnedRows?.bottom?.length || 0);
});
@@ -0,0 +1,70 @@
import { createRootSelector, createSelector, createSelectorMemoized } from "../../../utils/createSelector.mjs";
export const gridRowsStateSelector = createRootSelector(state => state.rows);
export const gridRowCountSelector = createSelector(gridRowsStateSelector, rows => rows.totalRowCount);
export const gridRowsLoadingSelector = createSelector(gridRowsStateSelector, rows => rows.loading);
export const gridTopLevelRowCountSelector = createSelector(gridRowsStateSelector, rows => rows.totalTopLevelRowCount);
// TODO rows v6: Rename
export const gridRowsLookupSelector = createSelector(gridRowsStateSelector, rows => rows.dataRowIdToModelLookup);
/**
* @category Rows
*/
export const gridRowSelector = createSelector(gridRowsLookupSelector, (rows, id) => rows[id]);
export const gridRowTreeSelector = createSelector(gridRowsStateSelector, rows => rows.tree);
/**
* @category Rows
*/
export const gridRowNodeSelector = createSelector(gridRowTreeSelector, (rowTree, rowId) => rowTree[rowId]);
export const gridRowGroupsToFetchSelector = createSelector(gridRowsStateSelector, rows => rows.groupsToFetch);
export const gridRowGroupingNameSelector = createSelector(gridRowsStateSelector, rows => rows.groupingName);
export const gridRowTreeDepthsSelector = createSelector(gridRowsStateSelector, rows => rows.treeDepths);
export const gridRowMaximumTreeDepthSelector = createSelectorMemoized(gridRowsStateSelector, rows => {
const entries = Object.entries(rows.treeDepths);
if (entries.length === 0) {
return 1;
}
return (entries.filter(([, nodeCount]) => nodeCount > 0).map(([depth]) => Number(depth)).sort((a, b) => b - a)[0] ?? 0) + 1;
});
/**
* @category Rows
*/
export const gridDataRowIdsSelector = createSelector(gridRowsStateSelector, rows => rows.dataRowIds);
export const gridDataRowsSelector = createSelectorMemoized(gridDataRowIdsSelector, gridRowsLookupSelector, (dataRowIds, rowsLookup) => dataRowIds.reduce((acc, id) => {
if (!rowsLookup[id]) {
return acc;
}
acc.push(rowsLookup[id]);
return acc;
}, []));
/**
* @ignore - do not document.
*/
export const gridAdditionalRowGroupsSelector = createSelector(gridRowsStateSelector, rows => rows?.additionalRowGroups);
/**
* @ignore - do not document.
*/
export const gridPinnedRowsSelector = createSelectorMemoized(gridAdditionalRowGroupsSelector, additionalRowGroups => {
const rawPinnedRows = additionalRowGroups?.pinnedRows;
return {
bottom: rawPinnedRows?.bottom?.map(rowEntry => ({
id: rowEntry.id,
model: rowEntry.model ?? {}
})) ?? [],
top: rawPinnedRows?.top?.map(rowEntry => ({
id: rowEntry.id,
model: rowEntry.model ?? {}
})) ?? []
};
});
/**
* @ignore - do not document.
*/
export const gridPinnedRowsCountSelector = createSelector(gridPinnedRowsSelector, pinnedRows => {
return (pinnedRows?.top?.length || 0) + (pinnedRows?.bottom?.length || 0);
});
@@ -0,0 +1,60 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridAutoGeneratedGroupNode, GridAutoGeneratedPinnedRowNode, GridColDef, GridFooterNode, GridGroupNode, GridRowId, GridRowIdGetter, GridRowModel, GridRowModelUpdate, GridRowTreeConfig, GridSkeletonRowNode, GridTreeNode, GridValidRowModel } from "../../../models/index.mjs";
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.mjs";
import type { GridApiCommunity, GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.mjs";
import type { GridRowsInternalCache, GridRowsState, GridRowTreeCreationParams } from "./gridRowsInterfaces.mjs";
export declare const GRID_ROOT_GROUP_ID: GridRowId;
export declare const GRID_ID_AUTOGENERATED: unique symbol;
export declare const buildRootGroup: () => GridGroupNode;
/**
* A helper function to check if the id provided is valid.
* @param {GridRowId} id Id as [[GridRowId]].
* @param {GridRowModel | Partial<GridRowModel>} row Row as [[GridRowModel]].
* @param {string} detailErrorMessage A custom error message to display for invalid IDs
*/
export declare function checkGridRowIdIsValid(id: GridRowId, row: GridRowModel | Partial<GridRowModel>, detailErrorMessage?: string): void;
export declare const getRowIdFromRowModel: (rowModel: GridRowModel, getRowId?: GridRowIdGetter, detailErrorMessage?: string) => GridRowId;
export declare const getRowValue: (row: GridValidRowModel, colDef: GridColDef | undefined, apiRef: RefObject<GridApiCommunity>) => any;
export declare const createRowsInternalCache: ({
rows,
getRowId,
loading,
rowCount
}: Pick<DataGridProcessedProps, 'rows' | 'getRowId' | 'loading' | 'rowCount'>) => GridRowsInternalCache;
export declare const getTopLevelRowCount: ({
tree,
rowCountProp
}: {
tree: GridRowTreeConfig;
rowCountProp: DataGridProcessedProps['rowCount'];
}) => number;
export declare const getRowsStateFromCache: ({
apiRef,
rowCountProp,
loadingProp,
previousTree,
previousTreeDepths,
previousGroupsToFetch
}: Pick<GridRowTreeCreationParams, 'previousTree' | 'previousTreeDepths' | 'previousGroupsToFetch'> & {
apiRef: RefObject<GridPrivateApiCommunity>;
rowCountProp: number | undefined;
loadingProp: boolean | undefined;
}) => GridRowsState;
export declare const isAutogeneratedRow: (row: GridRowModel) => boolean;
export declare const isAutogeneratedRowNode: (rowNode: GridTreeNode) => rowNode is GridFooterNode | GridSkeletonRowNode | GridAutoGeneratedGroupNode | GridAutoGeneratedPinnedRowNode;
export declare const getTreeNodeDescendants: (tree: GridRowTreeConfig, parentId: GridRowId, skipAutoGeneratedRows: boolean, directChildrenOnly?: boolean) => GridRowId[];
export declare const updateCacheWithNewRows: ({
previousCache,
getRowId,
updates,
groupKeys
}: {
previousCache: GridRowsInternalCache;
getRowId: DataGridProcessedProps['getRowId'];
updates: GridRowModelUpdate[];
groupKeys?: string[];
}) => GridRowsInternalCache;
export declare const minimalContentHeight = "var(--DataGrid-overlayHeight, calc(var(--height) * 2))";
export declare function computeRowsUpdates(apiRef: RefObject<GridApiCommunity>, updates: GridRowModelUpdate[], getRowId: DataGridProcessedProps['getRowId']): GridRowModelUpdate[];
export declare const getValidRowHeight: (rowHeightProp: any, defaultRowHeight: number, warningMessage: string) => number;
export declare const rowHeightWarning: string;
@@ -0,0 +1,60 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridAutoGeneratedGroupNode, GridAutoGeneratedPinnedRowNode, GridColDef, GridFooterNode, GridGroupNode, GridRowId, GridRowIdGetter, GridRowModel, GridRowModelUpdate, GridRowTreeConfig, GridSkeletonRowNode, GridTreeNode, GridValidRowModel } from "../../../models/index.js";
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.js";
import type { GridApiCommunity, GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.js";
import type { GridRowsInternalCache, GridRowsState, GridRowTreeCreationParams } from "./gridRowsInterfaces.js";
export declare const GRID_ROOT_GROUP_ID: GridRowId;
export declare const GRID_ID_AUTOGENERATED: unique symbol;
export declare const buildRootGroup: () => GridGroupNode;
/**
* A helper function to check if the id provided is valid.
* @param {GridRowId} id Id as [[GridRowId]].
* @param {GridRowModel | Partial<GridRowModel>} row Row as [[GridRowModel]].
* @param {string} detailErrorMessage A custom error message to display for invalid IDs
*/
export declare function checkGridRowIdIsValid(id: GridRowId, row: GridRowModel | Partial<GridRowModel>, detailErrorMessage?: string): void;
export declare const getRowIdFromRowModel: (rowModel: GridRowModel, getRowId?: GridRowIdGetter, detailErrorMessage?: string) => GridRowId;
export declare const getRowValue: (row: GridValidRowModel, colDef: GridColDef | undefined, apiRef: RefObject<GridApiCommunity>) => any;
export declare const createRowsInternalCache: ({
rows,
getRowId,
loading,
rowCount
}: Pick<DataGridProcessedProps, 'rows' | 'getRowId' | 'loading' | 'rowCount'>) => GridRowsInternalCache;
export declare const getTopLevelRowCount: ({
tree,
rowCountProp
}: {
tree: GridRowTreeConfig;
rowCountProp: DataGridProcessedProps['rowCount'];
}) => number;
export declare const getRowsStateFromCache: ({
apiRef,
rowCountProp,
loadingProp,
previousTree,
previousTreeDepths,
previousGroupsToFetch
}: Pick<GridRowTreeCreationParams, 'previousTree' | 'previousTreeDepths' | 'previousGroupsToFetch'> & {
apiRef: RefObject<GridPrivateApiCommunity>;
rowCountProp: number | undefined;
loadingProp: boolean | undefined;
}) => GridRowsState;
export declare const isAutogeneratedRow: (row: GridRowModel) => boolean;
export declare const isAutogeneratedRowNode: (rowNode: GridTreeNode) => rowNode is GridFooterNode | GridSkeletonRowNode | GridAutoGeneratedGroupNode | GridAutoGeneratedPinnedRowNode;
export declare const getTreeNodeDescendants: (tree: GridRowTreeConfig, parentId: GridRowId, skipAutoGeneratedRows: boolean, directChildrenOnly?: boolean) => GridRowId[];
export declare const updateCacheWithNewRows: ({
previousCache,
getRowId,
updates,
groupKeys
}: {
previousCache: GridRowsInternalCache;
getRowId: DataGridProcessedProps['getRowId'];
updates: GridRowModelUpdate[];
groupKeys?: string[];
}) => GridRowsInternalCache;
export declare const minimalContentHeight = "var(--DataGrid-overlayHeight, calc(var(--height) * 2))";
export declare function computeRowsUpdates(apiRef: RefObject<GridApiCommunity>, updates: GridRowModelUpdate[], getRowId: DataGridProcessedProps['getRowId']): GridRowModelUpdate[];
export declare const getValidRowHeight: (rowHeightProp: any, defaultRowHeight: number, warningMessage: string) => number;
export declare const rowHeightWarning: string;
@@ -0,0 +1,349 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildRootGroup = exports.GRID_ROOT_GROUP_ID = exports.GRID_ID_AUTOGENERATED = void 0;
exports.checkGridRowIdIsValid = checkGridRowIdIsValid;
exports.computeRowsUpdates = computeRowsUpdates;
exports.updateCacheWithNewRows = exports.rowHeightWarning = exports.minimalContentHeight = exports.isAutogeneratedRowNode = exports.isAutogeneratedRow = exports.getValidRowHeight = exports.getTreeNodeDescendants = exports.getTopLevelRowCount = exports.getRowsStateFromCache = exports.getRowValue = exports.getRowIdFromRowModel = exports.createRowsInternalCache = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _formatErrorMessage2 = _interopRequireDefault(require("@mui/x-internals/formatErrorMessage"));
var _gridRowsSelector = require("./gridRowsSelector");
const GRID_ROOT_GROUP_ID = exports.GRID_ROOT_GROUP_ID = `auto-generated-group-node-root`;
const GRID_ID_AUTOGENERATED = exports.GRID_ID_AUTOGENERATED = Symbol('mui.id_autogenerated');
const buildRootGroup = () => ({
type: 'group',
id: GRID_ROOT_GROUP_ID,
depth: -1,
groupingField: null,
groupingKey: null,
isAutoGenerated: true,
children: [],
// Prototype-less so user-supplied grouping values like `'constructor'`
// or `'__proto__'` cannot collide with `Object.prototype` properties.
childrenFromPath: Object.create(null),
childrenExpanded: true,
parent: null
});
/**
* A helper function to check if the id provided is valid.
* @param {GridRowId} id Id as [[GridRowId]].
* @param {GridRowModel | Partial<GridRowModel>} row Row as [[GridRowModel]].
* @param {string} detailErrorMessage A custom error message to display for invalid IDs
*/
exports.buildRootGroup = buildRootGroup;
function checkGridRowIdIsValid(id, row, detailErrorMessage = 'A row was provided without id in the rows prop:') {
if (id == null) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: The Data Grid component requires all rows to have a unique \`id\` property.
Alternatively, you can use the \`getRowId\` prop to specify a custom id for each row.
${detailErrorMessage}
${JSON.stringify(row)}` : (0, _formatErrorMessage2.default)(85, detailErrorMessage, JSON.stringify(row)));
}
}
const getRowIdFromRowModel = (rowModel, getRowId, detailErrorMessage) => {
const id = getRowId ? getRowId(rowModel) : rowModel.id;
checkGridRowIdIsValid(id, rowModel, detailErrorMessage);
return id;
};
exports.getRowIdFromRowModel = getRowIdFromRowModel;
const getRowValue = (row, colDef, apiRef) => {
if (!colDef) {
return undefined;
}
if (!colDef.valueGetter) {
return row[colDef.field];
}
const value = row[colDef.field];
return colDef.valueGetter(value, row, colDef, apiRef);
};
exports.getRowValue = getRowValue;
const createRowsInternalCache = ({
rows,
getRowId,
loading,
rowCount
}) => {
const updates = {
type: 'full',
rows: []
};
const dataRowIdToModelLookup = {};
for (let i = 0; i < rows.length; i += 1) {
const model = rows[i];
const id = getRowIdFromRowModel(model, getRowId);
dataRowIdToModelLookup[id] = model;
updates.rows.push(id);
}
return {
rowsBeforePartialUpdates: rows,
loadingPropBeforePartialUpdates: loading,
rowCountPropBeforePartialUpdates: rowCount,
updates,
dataRowIdToModelLookup
};
};
exports.createRowsInternalCache = createRowsInternalCache;
const getTopLevelRowCount = ({
tree,
rowCountProp = 0
}) => {
const rootGroupNode = tree[GRID_ROOT_GROUP_ID];
return Math.max(rowCountProp, rootGroupNode.children.length + (rootGroupNode.footerId == null ? 0 : 1));
};
exports.getTopLevelRowCount = getTopLevelRowCount;
const getRowsStateFromCache = ({
apiRef,
rowCountProp = 0,
loadingProp,
previousTree,
previousTreeDepths,
previousGroupsToFetch
}) => {
const cache = apiRef.current.caches.rows;
// 1. Apply the "rowTreeCreation" family processing.
const {
tree: unProcessedTree,
treeDepths: unProcessedTreeDepths,
dataRowIds: unProcessedDataRowIds,
groupingName,
groupsToFetch = []
} = apiRef.current.applyStrategyProcessor('rowTreeCreation', {
previousTree,
previousTreeDepths,
updates: cache.updates,
dataRowIdToModelLookup: cache.dataRowIdToModelLookup,
previousGroupsToFetch
});
// 2. Apply the "hydrateRows" pipe-processing.
const groupingParamsWithHydrateRows = apiRef.current.unstable_applyPipeProcessors('hydrateRows', {
tree: unProcessedTree,
treeDepths: unProcessedTreeDepths,
dataRowIds: unProcessedDataRowIds,
dataRowIdToModelLookup: cache.dataRowIdToModelLookup
});
// 3. Reset the cache updates
apiRef.current.caches.rows.updates = {
type: 'partial',
actions: {
insert: [],
modify: [],
remove: []
},
idToActionLookup: {}
};
return (0, _extends2.default)({}, groupingParamsWithHydrateRows, {
totalRowCount: Math.max(rowCountProp, groupingParamsWithHydrateRows.dataRowIds.length),
totalTopLevelRowCount: getTopLevelRowCount({
tree: groupingParamsWithHydrateRows.tree,
rowCountProp
}),
groupingName,
loading: loadingProp,
groupsToFetch
});
};
exports.getRowsStateFromCache = getRowsStateFromCache;
const isAutogeneratedRow = row => GRID_ID_AUTOGENERATED in row;
exports.isAutogeneratedRow = isAutogeneratedRow;
const isAutogeneratedRowNode = rowNode => rowNode.type === 'skeletonRow' || rowNode.type === 'footer' || rowNode.type === 'group' && rowNode.isAutoGenerated || rowNode.type === 'pinnedRow' && rowNode.isAutoGenerated;
exports.isAutogeneratedRowNode = isAutogeneratedRowNode;
const getTreeNodeDescendants = (tree, parentId, skipAutoGeneratedRows, directChildrenOnly) => {
const node = tree[parentId];
if (node?.type !== 'group') {
return [];
}
const validDescendants = [];
for (let i = 0; i < node.children.length; i += 1) {
const child = node.children[i];
if (!skipAutoGeneratedRows || !isAutogeneratedRowNode(tree[child])) {
validDescendants.push(child);
}
if (directChildrenOnly) {
continue;
}
const childDescendants = getTreeNodeDescendants(tree, child, skipAutoGeneratedRows, directChildrenOnly);
for (let j = 0; j < childDescendants.length; j += 1) {
validDescendants.push(childDescendants[j]);
}
}
if (!skipAutoGeneratedRows && node.footerId != null) {
validDescendants.push(node.footerId);
}
return validDescendants;
};
exports.getTreeNodeDescendants = getTreeNodeDescendants;
const updateCacheWithNewRows = ({
previousCache,
getRowId,
updates,
groupKeys
}) => {
if (previousCache.updates.type === 'full') {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: Unable to prepare a partial update if a full update is not applied yet.' : (0, _formatErrorMessage2.default)(86));
}
// Remove duplicate updates.
// A server can batch updates, and send several updates for the same row in one fn call.
const uniqueUpdates = new Map();
updates.forEach(update => {
const id = getRowIdFromRowModel(update, getRowId, 'A row was provided without id when calling updateRows():');
if (uniqueUpdates.has(id)) {
uniqueUpdates.set(id, (0, _extends2.default)({}, uniqueUpdates.get(id), update));
} else {
uniqueUpdates.set(id, update);
}
});
const partialUpdates = {
type: 'partial',
actions: {
insert: [...(previousCache.updates.actions.insert ?? [])],
modify: [...(previousCache.updates.actions.modify ?? [])],
remove: [...(previousCache.updates.actions.remove ?? [])]
},
idToActionLookup: (0, _extends2.default)({}, previousCache.updates.idToActionLookup),
groupKeys
};
const dataRowIdToModelLookup = (0, _extends2.default)({}, previousCache.dataRowIdToModelLookup);
const alreadyAppliedActionsToRemove = {
insert: {},
modify: {},
remove: {}
};
// Depending on the action already applied to the data row,
// We might want drop the already-applied-update.
// For instance:
// - if you delete then insert, then you don't want to apply the deletion in the tree.
// - if you insert, then modify, then you just want to apply the insertion in the tree.
uniqueUpdates.forEach((partialRow, id) => {
const actionAlreadyAppliedToRow = partialUpdates.idToActionLookup[id];
// Action === "delete"
// eslint-disable-next-line no-underscore-dangle
if (partialRow._action === 'delete') {
// If the data row has been removed since the last state update,
// Then do nothing.
if (actionAlreadyAppliedToRow === 'remove' || !dataRowIdToModelLookup[id]) {
return;
}
// If the data row has been inserted / modified since the last state update,
// Then drop this "insert" / "modify" update.
if (actionAlreadyAppliedToRow != null) {
alreadyAppliedActionsToRemove[actionAlreadyAppliedToRow][id] = true;
}
// Remove the data row from the lookups and add it to the "delete" update.
partialUpdates.actions.remove.push(id);
delete dataRowIdToModelLookup[id];
return;
}
const oldRow = dataRowIdToModelLookup[id];
// Action === "modify"
if (oldRow) {
// If the data row has been removed since the last state update,
// Then drop this "remove" update and add it to the "modify" update instead.
if (actionAlreadyAppliedToRow === 'remove') {
alreadyAppliedActionsToRemove.remove[id] = true;
partialUpdates.actions.modify.push(id);
}
// If the date has not been inserted / modified since the last state update,
// Then add it to the "modify" update (if it has been inserted it should just remain "inserted").
else if (actionAlreadyAppliedToRow == null) {
partialUpdates.actions.modify.push(id);
}
// Update the data row lookups.
// Prototype-preservation rules:
// 1. If partialRow is a class instance (non-plain object), use its prototype — the
// caller is passing in a fully-constructed instance and owns the prototype chain.
// 2. If partialRow is a plain object (Object.prototype), prefer oldRow's prototype so
// that a partial-update object does not silently discard the existing row's class.
// 3. If both are plain objects the result is also a plain object (no-op).
//
// Note: private class fields (#field syntax) cannot be preserved through a spread-style
// merge because the brand check is tied to the original instance. Rows that rely on
// private fields must supply a fully-constructed instance as partialRow (rule 1 above)
// rather than a plain-object partial update.
const partialRowProto = Object.getPrototypeOf(partialRow);
const isPartialRowPlain = partialRowProto === Object.prototype || partialRowProto === null;
const proto = isPartialRowPlain ? Object.getPrototypeOf(oldRow) : partialRowProto;
const merged = Object.create(proto);
Object.assign(merged, oldRow, partialRow);
dataRowIdToModelLookup[id] = merged;
return;
}
// Action === "insert"
// If the data row has been removed since the last state update,
// Then drop the "remove" update and add it to the "insert" update instead.
if (actionAlreadyAppliedToRow === 'remove') {
alreadyAppliedActionsToRemove.remove[id] = true;
partialUpdates.actions.insert.push(id);
}
// If the data row has not been inserted since the last state update,
// Then add it to the "insert" update.
// `actionAlreadyAppliedToRow` can't be equal to "modify", otherwise we would have an `oldRow` above.
else if (actionAlreadyAppliedToRow == null) {
partialUpdates.actions.insert.push(id);
}
// Update the data row lookups.
dataRowIdToModelLookup[id] = partialRow;
});
const actionTypeWithActionsToRemove = Object.keys(alreadyAppliedActionsToRemove);
for (let i = 0; i < actionTypeWithActionsToRemove.length; i += 1) {
const actionType = actionTypeWithActionsToRemove[i];
const idsToRemove = alreadyAppliedActionsToRemove[actionType];
if (Object.keys(idsToRemove).length > 0) {
partialUpdates.actions[actionType] = partialUpdates.actions[actionType].filter(id => !idsToRemove[id]);
}
}
return {
dataRowIdToModelLookup,
updates: partialUpdates,
rowsBeforePartialUpdates: previousCache.rowsBeforePartialUpdates,
loadingPropBeforePartialUpdates: previousCache.loadingPropBeforePartialUpdates,
rowCountPropBeforePartialUpdates: previousCache.rowCountPropBeforePartialUpdates
};
};
exports.updateCacheWithNewRows = updateCacheWithNewRows;
const minimalContentHeight = exports.minimalContentHeight = 'var(--DataGrid-overlayHeight, calc(var(--height) * 2))';
function computeRowsUpdates(apiRef, updates, getRowId) {
const nonPinnedRowsUpdates = [];
updates.forEach(update => {
const id = getRowIdFromRowModel(update, getRowId, 'A row was provided without id when calling updateRows():');
const rowNode = (0, _gridRowsSelector.gridRowNodeSelector)(apiRef, id);
if (rowNode?.type === 'pinnedRow') {
// @ts-ignore because otherwise `release:build` doesn't work
const pinnedRowsCache = apiRef.current.caches.pinnedRows;
const prevModel = pinnedRowsCache.idLookup[id];
if (prevModel) {
pinnedRowsCache.idLookup[id] = (0, _extends2.default)({}, prevModel, update);
}
} else {
nonPinnedRowsUpdates.push(update);
}
});
return nonPinnedRowsUpdates;
}
let warnedOnceInvalidRowHeight = false;
const getValidRowHeight = (rowHeightProp, defaultRowHeight, warningMessage) => {
if (typeof rowHeightProp === 'number' && rowHeightProp > 0) {
return rowHeightProp;
}
if (process.env.NODE_ENV !== 'production' && !warnedOnceInvalidRowHeight && typeof rowHeightProp !== 'undefined' && rowHeightProp !== null) {
console.warn(warningMessage);
warnedOnceInvalidRowHeight = true;
}
return defaultRowHeight;
};
exports.getValidRowHeight = getValidRowHeight;
const rowHeightWarning = exports.rowHeightWarning = [`MUI X: The \`rowHeight\` prop should be a number greater than 0.`, `The default value will be used instead.`].join('\n');
@@ -0,0 +1,328 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import { gridRowNodeSelector } from "./gridRowsSelector.mjs";
export const GRID_ROOT_GROUP_ID = `auto-generated-group-node-root`;
export const GRID_ID_AUTOGENERATED = Symbol('mui.id_autogenerated');
export const buildRootGroup = () => ({
type: 'group',
id: GRID_ROOT_GROUP_ID,
depth: -1,
groupingField: null,
groupingKey: null,
isAutoGenerated: true,
children: [],
// Prototype-less so user-supplied grouping values like `'constructor'`
// or `'__proto__'` cannot collide with `Object.prototype` properties.
childrenFromPath: Object.create(null),
childrenExpanded: true,
parent: null
});
/**
* A helper function to check if the id provided is valid.
* @param {GridRowId} id Id as [[GridRowId]].
* @param {GridRowModel | Partial<GridRowModel>} row Row as [[GridRowModel]].
* @param {string} detailErrorMessage A custom error message to display for invalid IDs
*/
export function checkGridRowIdIsValid(id, row, detailErrorMessage = 'A row was provided without id in the rows prop:') {
if (id == null) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: The Data Grid component requires all rows to have a unique \`id\` property.
Alternatively, you can use the \`getRowId\` prop to specify a custom id for each row.
${detailErrorMessage}
${JSON.stringify(row)}` : _formatErrorMessage(85, detailErrorMessage, JSON.stringify(row)));
}
}
export const getRowIdFromRowModel = (rowModel, getRowId, detailErrorMessage) => {
const id = getRowId ? getRowId(rowModel) : rowModel.id;
checkGridRowIdIsValid(id, rowModel, detailErrorMessage);
return id;
};
export const getRowValue = (row, colDef, apiRef) => {
if (!colDef) {
return undefined;
}
if (!colDef.valueGetter) {
return row[colDef.field];
}
const value = row[colDef.field];
return colDef.valueGetter(value, row, colDef, apiRef);
};
export const createRowsInternalCache = ({
rows,
getRowId,
loading,
rowCount
}) => {
const updates = {
type: 'full',
rows: []
};
const dataRowIdToModelLookup = {};
for (let i = 0; i < rows.length; i += 1) {
const model = rows[i];
const id = getRowIdFromRowModel(model, getRowId);
dataRowIdToModelLookup[id] = model;
updates.rows.push(id);
}
return {
rowsBeforePartialUpdates: rows,
loadingPropBeforePartialUpdates: loading,
rowCountPropBeforePartialUpdates: rowCount,
updates,
dataRowIdToModelLookup
};
};
export const getTopLevelRowCount = ({
tree,
rowCountProp = 0
}) => {
const rootGroupNode = tree[GRID_ROOT_GROUP_ID];
return Math.max(rowCountProp, rootGroupNode.children.length + (rootGroupNode.footerId == null ? 0 : 1));
};
export const getRowsStateFromCache = ({
apiRef,
rowCountProp = 0,
loadingProp,
previousTree,
previousTreeDepths,
previousGroupsToFetch
}) => {
const cache = apiRef.current.caches.rows;
// 1. Apply the "rowTreeCreation" family processing.
const {
tree: unProcessedTree,
treeDepths: unProcessedTreeDepths,
dataRowIds: unProcessedDataRowIds,
groupingName,
groupsToFetch = []
} = apiRef.current.applyStrategyProcessor('rowTreeCreation', {
previousTree,
previousTreeDepths,
updates: cache.updates,
dataRowIdToModelLookup: cache.dataRowIdToModelLookup,
previousGroupsToFetch
});
// 2. Apply the "hydrateRows" pipe-processing.
const groupingParamsWithHydrateRows = apiRef.current.unstable_applyPipeProcessors('hydrateRows', {
tree: unProcessedTree,
treeDepths: unProcessedTreeDepths,
dataRowIds: unProcessedDataRowIds,
dataRowIdToModelLookup: cache.dataRowIdToModelLookup
});
// 3. Reset the cache updates
apiRef.current.caches.rows.updates = {
type: 'partial',
actions: {
insert: [],
modify: [],
remove: []
},
idToActionLookup: {}
};
return _extends({}, groupingParamsWithHydrateRows, {
totalRowCount: Math.max(rowCountProp, groupingParamsWithHydrateRows.dataRowIds.length),
totalTopLevelRowCount: getTopLevelRowCount({
tree: groupingParamsWithHydrateRows.tree,
rowCountProp
}),
groupingName,
loading: loadingProp,
groupsToFetch
});
};
export const isAutogeneratedRow = row => GRID_ID_AUTOGENERATED in row;
export const isAutogeneratedRowNode = rowNode => rowNode.type === 'skeletonRow' || rowNode.type === 'footer' || rowNode.type === 'group' && rowNode.isAutoGenerated || rowNode.type === 'pinnedRow' && rowNode.isAutoGenerated;
export const getTreeNodeDescendants = (tree, parentId, skipAutoGeneratedRows, directChildrenOnly) => {
const node = tree[parentId];
if (node?.type !== 'group') {
return [];
}
const validDescendants = [];
for (let i = 0; i < node.children.length; i += 1) {
const child = node.children[i];
if (!skipAutoGeneratedRows || !isAutogeneratedRowNode(tree[child])) {
validDescendants.push(child);
}
if (directChildrenOnly) {
continue;
}
const childDescendants = getTreeNodeDescendants(tree, child, skipAutoGeneratedRows, directChildrenOnly);
for (let j = 0; j < childDescendants.length; j += 1) {
validDescendants.push(childDescendants[j]);
}
}
if (!skipAutoGeneratedRows && node.footerId != null) {
validDescendants.push(node.footerId);
}
return validDescendants;
};
export const updateCacheWithNewRows = ({
previousCache,
getRowId,
updates,
groupKeys
}) => {
if (previousCache.updates.type === 'full') {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: Unable to prepare a partial update if a full update is not applied yet.' : _formatErrorMessage(86));
}
// Remove duplicate updates.
// A server can batch updates, and send several updates for the same row in one fn call.
const uniqueUpdates = new Map();
updates.forEach(update => {
const id = getRowIdFromRowModel(update, getRowId, 'A row was provided without id when calling updateRows():');
if (uniqueUpdates.has(id)) {
uniqueUpdates.set(id, _extends({}, uniqueUpdates.get(id), update));
} else {
uniqueUpdates.set(id, update);
}
});
const partialUpdates = {
type: 'partial',
actions: {
insert: [...(previousCache.updates.actions.insert ?? [])],
modify: [...(previousCache.updates.actions.modify ?? [])],
remove: [...(previousCache.updates.actions.remove ?? [])]
},
idToActionLookup: _extends({}, previousCache.updates.idToActionLookup),
groupKeys
};
const dataRowIdToModelLookup = _extends({}, previousCache.dataRowIdToModelLookup);
const alreadyAppliedActionsToRemove = {
insert: {},
modify: {},
remove: {}
};
// Depending on the action already applied to the data row,
// We might want drop the already-applied-update.
// For instance:
// - if you delete then insert, then you don't want to apply the deletion in the tree.
// - if you insert, then modify, then you just want to apply the insertion in the tree.
uniqueUpdates.forEach((partialRow, id) => {
const actionAlreadyAppliedToRow = partialUpdates.idToActionLookup[id];
// Action === "delete"
// eslint-disable-next-line no-underscore-dangle
if (partialRow._action === 'delete') {
// If the data row has been removed since the last state update,
// Then do nothing.
if (actionAlreadyAppliedToRow === 'remove' || !dataRowIdToModelLookup[id]) {
return;
}
// If the data row has been inserted / modified since the last state update,
// Then drop this "insert" / "modify" update.
if (actionAlreadyAppliedToRow != null) {
alreadyAppliedActionsToRemove[actionAlreadyAppliedToRow][id] = true;
}
// Remove the data row from the lookups and add it to the "delete" update.
partialUpdates.actions.remove.push(id);
delete dataRowIdToModelLookup[id];
return;
}
const oldRow = dataRowIdToModelLookup[id];
// Action === "modify"
if (oldRow) {
// If the data row has been removed since the last state update,
// Then drop this "remove" update and add it to the "modify" update instead.
if (actionAlreadyAppliedToRow === 'remove') {
alreadyAppliedActionsToRemove.remove[id] = true;
partialUpdates.actions.modify.push(id);
}
// If the date has not been inserted / modified since the last state update,
// Then add it to the "modify" update (if it has been inserted it should just remain "inserted").
else if (actionAlreadyAppliedToRow == null) {
partialUpdates.actions.modify.push(id);
}
// Update the data row lookups.
// Prototype-preservation rules:
// 1. If partialRow is a class instance (non-plain object), use its prototype — the
// caller is passing in a fully-constructed instance and owns the prototype chain.
// 2. If partialRow is a plain object (Object.prototype), prefer oldRow's prototype so
// that a partial-update object does not silently discard the existing row's class.
// 3. If both are plain objects the result is also a plain object (no-op).
//
// Note: private class fields (#field syntax) cannot be preserved through a spread-style
// merge because the brand check is tied to the original instance. Rows that rely on
// private fields must supply a fully-constructed instance as partialRow (rule 1 above)
// rather than a plain-object partial update.
const partialRowProto = Object.getPrototypeOf(partialRow);
const isPartialRowPlain = partialRowProto === Object.prototype || partialRowProto === null;
const proto = isPartialRowPlain ? Object.getPrototypeOf(oldRow) : partialRowProto;
const merged = Object.create(proto);
Object.assign(merged, oldRow, partialRow);
dataRowIdToModelLookup[id] = merged;
return;
}
// Action === "insert"
// If the data row has been removed since the last state update,
// Then drop the "remove" update and add it to the "insert" update instead.
if (actionAlreadyAppliedToRow === 'remove') {
alreadyAppliedActionsToRemove.remove[id] = true;
partialUpdates.actions.insert.push(id);
}
// If the data row has not been inserted since the last state update,
// Then add it to the "insert" update.
// `actionAlreadyAppliedToRow` can't be equal to "modify", otherwise we would have an `oldRow` above.
else if (actionAlreadyAppliedToRow == null) {
partialUpdates.actions.insert.push(id);
}
// Update the data row lookups.
dataRowIdToModelLookup[id] = partialRow;
});
const actionTypeWithActionsToRemove = Object.keys(alreadyAppliedActionsToRemove);
for (let i = 0; i < actionTypeWithActionsToRemove.length; i += 1) {
const actionType = actionTypeWithActionsToRemove[i];
const idsToRemove = alreadyAppliedActionsToRemove[actionType];
if (Object.keys(idsToRemove).length > 0) {
partialUpdates.actions[actionType] = partialUpdates.actions[actionType].filter(id => !idsToRemove[id]);
}
}
return {
dataRowIdToModelLookup,
updates: partialUpdates,
rowsBeforePartialUpdates: previousCache.rowsBeforePartialUpdates,
loadingPropBeforePartialUpdates: previousCache.loadingPropBeforePartialUpdates,
rowCountPropBeforePartialUpdates: previousCache.rowCountPropBeforePartialUpdates
};
};
export const minimalContentHeight = 'var(--DataGrid-overlayHeight, calc(var(--height) * 2))';
export function computeRowsUpdates(apiRef, updates, getRowId) {
const nonPinnedRowsUpdates = [];
updates.forEach(update => {
const id = getRowIdFromRowModel(update, getRowId, 'A row was provided without id when calling updateRows():');
const rowNode = gridRowNodeSelector(apiRef, id);
if (rowNode?.type === 'pinnedRow') {
// @ts-ignore because otherwise `release:build` doesn't work
const pinnedRowsCache = apiRef.current.caches.pinnedRows;
const prevModel = pinnedRowsCache.idLookup[id];
if (prevModel) {
pinnedRowsCache.idLookup[id] = _extends({}, prevModel, update);
}
} else {
nonPinnedRowsUpdates.push(update);
}
});
return nonPinnedRowsUpdates;
}
let warnedOnceInvalidRowHeight = false;
export const getValidRowHeight = (rowHeightProp, defaultRowHeight, warningMessage) => {
if (typeof rowHeightProp === 'number' && rowHeightProp > 0) {
return rowHeightProp;
}
if (process.env.NODE_ENV !== 'production' && !warnedOnceInvalidRowHeight && typeof rowHeightProp !== 'undefined' && rowHeightProp !== null) {
console.warn(warningMessage);
warnedOnceInvalidRowHeight = true;
}
return defaultRowHeight;
};
export const rowHeightWarning = [`MUI X: The \`rowHeight\` prop should be a number greater than 0.`, `The default value will be used instead.`].join('\n');
@@ -0,0 +1,5 @@
export * from "./gridRowsMetaSelector.mjs";
export * from "./gridRowsMetaState.mjs";
export { gridRowCountSelector, gridRowsLoadingSelector, gridTopLevelRowCountSelector, gridRowsLookupSelector, gridRowTreeSelector, gridRowGroupingNameSelector, gridRowTreeDepthsSelector, gridRowMaximumTreeDepthSelector, gridDataRowIdsSelector, gridRowNodeSelector, gridRowSelector } from "./gridRowsSelector.mjs";
export type { GridRowsState, GridRowIdToModelLookup } from "./gridRowsInterfaces.mjs";
export { GRID_ROOT_GROUP_ID, checkGridRowIdIsValid, isAutogeneratedRow } from "./gridRowsUtils.mjs";
+5
View File
@@ -0,0 +1,5 @@
export * from "./gridRowsMetaSelector.js";
export * from "./gridRowsMetaState.js";
export { gridRowCountSelector, gridRowsLoadingSelector, gridTopLevelRowCountSelector, gridRowsLookupSelector, gridRowTreeSelector, gridRowGroupingNameSelector, gridRowTreeDepthsSelector, gridRowMaximumTreeDepthSelector, gridDataRowIdsSelector, gridRowNodeSelector, gridRowSelector } from "./gridRowsSelector.js";
export type { GridRowsState, GridRowIdToModelLookup } from "./gridRowsInterfaces.js";
export { GRID_ROOT_GROUP_ID, checkGridRowIdIsValid, isAutogeneratedRow } from "./gridRowsUtils.js";
+131
View File
@@ -0,0 +1,131 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
gridRowCountSelector: true,
gridRowsLoadingSelector: true,
gridTopLevelRowCountSelector: true,
gridRowsLookupSelector: true,
gridRowTreeSelector: true,
gridRowGroupingNameSelector: true,
gridRowTreeDepthsSelector: true,
gridRowMaximumTreeDepthSelector: true,
gridDataRowIdsSelector: true,
gridRowNodeSelector: true,
gridRowSelector: true,
GRID_ROOT_GROUP_ID: true,
checkGridRowIdIsValid: true,
isAutogeneratedRow: true
};
Object.defineProperty(exports, "GRID_ROOT_GROUP_ID", {
enumerable: true,
get: function () {
return _gridRowsUtils.GRID_ROOT_GROUP_ID;
}
});
Object.defineProperty(exports, "checkGridRowIdIsValid", {
enumerable: true,
get: function () {
return _gridRowsUtils.checkGridRowIdIsValid;
}
});
Object.defineProperty(exports, "gridDataRowIdsSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridDataRowIdsSelector;
}
});
Object.defineProperty(exports, "gridRowCountSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridRowCountSelector;
}
});
Object.defineProperty(exports, "gridRowGroupingNameSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridRowGroupingNameSelector;
}
});
Object.defineProperty(exports, "gridRowMaximumTreeDepthSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridRowMaximumTreeDepthSelector;
}
});
Object.defineProperty(exports, "gridRowNodeSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridRowNodeSelector;
}
});
Object.defineProperty(exports, "gridRowSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridRowSelector;
}
});
Object.defineProperty(exports, "gridRowTreeDepthsSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridRowTreeDepthsSelector;
}
});
Object.defineProperty(exports, "gridRowTreeSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridRowTreeSelector;
}
});
Object.defineProperty(exports, "gridRowsLoadingSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridRowsLoadingSelector;
}
});
Object.defineProperty(exports, "gridRowsLookupSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridRowsLookupSelector;
}
});
Object.defineProperty(exports, "gridTopLevelRowCountSelector", {
enumerable: true,
get: function () {
return _gridRowsSelector.gridTopLevelRowCountSelector;
}
});
Object.defineProperty(exports, "isAutogeneratedRow", {
enumerable: true,
get: function () {
return _gridRowsUtils.isAutogeneratedRow;
}
});
var _gridRowsMetaSelector = require("./gridRowsMetaSelector");
Object.keys(_gridRowsMetaSelector).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _gridRowsMetaSelector[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _gridRowsMetaSelector[key];
}
});
});
var _gridRowsMetaState = require("./gridRowsMetaState");
Object.keys(_gridRowsMetaState).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _gridRowsMetaState[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _gridRowsMetaState[key];
}
});
});
var _gridRowsSelector = require("./gridRowsSelector");
var _gridRowsUtils = require("./gridRowsUtils");
+4
View File
@@ -0,0 +1,4 @@
export * from "./gridRowsMetaSelector.mjs";
export * from "./gridRowsMetaState.mjs";
export { gridRowCountSelector, gridRowsLoadingSelector, gridTopLevelRowCountSelector, gridRowsLookupSelector, gridRowTreeSelector, gridRowGroupingNameSelector, gridRowTreeDepthsSelector, gridRowMaximumTreeDepthSelector, gridDataRowIdsSelector, gridRowNodeSelector, gridRowSelector } from "./gridRowsSelector.mjs";
export { GRID_ROOT_GROUP_ID, checkGridRowIdIsValid, isAutogeneratedRow } from "./gridRowsUtils.mjs";
@@ -0,0 +1,13 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.mjs";
import type { GridConfiguration } from "../../../models/configuration/gridConfiguration.mjs";
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.mjs";
/**
* @requires useGridColumns (method)
* @requires useGridRows (method)
* @requires useGridFocus (state)
* @requires useGridEditing (method)
* TODO: Impossible priority - useGridEditing also needs to be after useGridParamsApi
* TODO: Impossible priority - useGridFocus also needs to be after useGridParamsApi
*/
export declare function useGridParamsApi(apiRef: RefObject<GridPrivateApiCommunity>, props: DataGridProcessedProps, configuration: GridConfiguration): void;
@@ -0,0 +1,13 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.js";
import type { GridConfiguration } from "../../../models/configuration/gridConfiguration.js";
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.js";
/**
* @requires useGridColumns (method)
* @requires useGridRows (method)
* @requires useGridFocus (state)
* @requires useGridEditing (method)
* TODO: Impossible priority - useGridEditing also needs to be after useGridParamsApi
* TODO: Impossible priority - useGridFocus also needs to be after useGridParamsApi
*/
export declare function useGridParamsApi(apiRef: RefObject<GridPrivateApiCommunity>, props: DataGridProcessedProps, configuration: GridConfiguration): void;
@@ -0,0 +1,125 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridParamsApi = useGridParamsApi;
var React = _interopRequireWildcard(require("react"));
var _domUtils = require("../../../utils/domUtils");
var _useGridApiMethod = require("../../utils/useGridApiMethod");
var _gridFocusStateSelector = require("../focus/gridFocusStateSelector");
var _gridListViewSelectors = require("../listView/gridListViewSelectors");
var _gridRowsSelector = require("./gridRowsSelector");
class MissingRowIdError extends Error {}
/**
* @requires useGridColumns (method)
* @requires useGridRows (method)
* @requires useGridFocus (state)
* @requires useGridEditing (method)
* TODO: Impossible priority - useGridEditing also needs to be after useGridParamsApi
* TODO: Impossible priority - useGridFocus also needs to be after useGridParamsApi
*/
function useGridParamsApi(apiRef, props, configuration) {
const getColumnHeaderParams = React.useCallback(field => ({
field,
colDef: apiRef.current.getColumn(field)
}), [apiRef]);
const getRowParams = React.useCallback(id => {
const row = apiRef.current.getRow(id);
if (!row) {
throw new MissingRowIdError(`MUI X: No row with id #${id} found`);
}
const params = {
id,
columns: apiRef.current.getAllColumns(),
row
};
return params;
}, [apiRef]);
const getCellParamsForRow = React.useCallback((id, field, row, {
cellMode,
colDef,
hasFocus,
rowNode,
tabIndex,
value: forcedValue,
formattedValue: forcedFormattedValue
}) => {
const value = forcedValue !== undefined ? forcedValue : apiRef.current.getRowValue(row, colDef);
const formattedValue = forcedFormattedValue !== undefined ? forcedFormattedValue : apiRef.current.getRowFormattedValue(row, colDef);
const params = {
id,
field,
row,
rowNode,
colDef,
cellMode,
hasFocus,
tabIndex,
value,
formattedValue,
isEditable: false,
api: apiRef.current
};
params.isEditable = colDef && apiRef.current.isCellEditable(params);
return params;
}, [apiRef]);
const getCellParams = React.useCallback((id, field) => {
const row = apiRef.current.getRow(id);
const rowNode = (0, _gridRowsSelector.gridRowNodeSelector)(apiRef, id);
if (!row || !rowNode) {
throw new MissingRowIdError(`MUI X: No row with id #${id} found`);
}
const cellFocus = (0, _gridFocusStateSelector.gridFocusCellSelector)(apiRef);
const cellTabIndex = (0, _gridFocusStateSelector.gridTabIndexCellSelector)(apiRef);
const cellMode = apiRef.current.getCellMode(id, field);
return apiRef.current.getCellParamsForRow(id, field, row, {
// Params keep a non-nullable `colDef`, but it can be `undefined` at runtime for an unknown field.
colDef: props.listView && props.listViewColumn?.field === field ? (0, _gridListViewSelectors.gridListColumnSelector)(apiRef) : apiRef.current.getColumn(field),
rowNode,
hasFocus: cellFocus !== null && cellFocus.field === field && cellFocus.id === id,
tabIndex: cellTabIndex && cellTabIndex.field === field && cellTabIndex.id === id ? 0 : -1,
cellMode
});
}, [apiRef, props.listView, props.listViewColumn?.field]);
const getColumnHeaderElement = React.useCallback(field => {
if (!apiRef.current.rootElementRef.current) {
return null;
}
return (0, _domUtils.getGridColumnHeaderElement)(apiRef.current.rootElementRef.current, field);
}, [apiRef]);
const getRowElement = React.useCallback(id => {
if (!apiRef.current.rootElementRef.current) {
return null;
}
return (0, _domUtils.getGridRowElement)(apiRef.current.rootElementRef.current, id);
}, [apiRef]);
const getCellElement = React.useCallback((id, field) => {
if (!apiRef.current.rootElementRef.current) {
return null;
}
return (0, _domUtils.getGridCellElement)(apiRef.current.rootElementRef.current, {
id,
field
});
}, [apiRef]);
const overridableParamsMethods = configuration.hooks.useGridParamsOverridableMethods(apiRef);
const paramsApi = {
getCellValue: overridableParamsMethods.getCellValue,
getCellParams,
getCellElement,
getRowValue: overridableParamsMethods.getRowValue,
getRowFormattedValue: overridableParamsMethods.getRowFormattedValue,
getRowParams,
getRowElement,
getColumnHeaderParams,
getColumnHeaderElement
};
const paramsPrivateApi = {
getCellParamsForRow
};
(0, _useGridApiMethod.useGridApiMethod)(apiRef, paramsApi, 'public');
(0, _useGridApiMethod.useGridApiMethod)(apiRef, paramsPrivateApi, 'private');
}
@@ -0,0 +1,118 @@
import * as React from 'react';
import { getGridCellElement, getGridColumnHeaderElement, getGridRowElement } from "../../../utils/domUtils.mjs";
import { useGridApiMethod } from "../../utils/useGridApiMethod.mjs";
import { gridFocusCellSelector, gridTabIndexCellSelector } from "../focus/gridFocusStateSelector.mjs";
import { gridListColumnSelector } from "../listView/gridListViewSelectors.mjs";
import { gridRowNodeSelector } from "./gridRowsSelector.mjs";
class MissingRowIdError extends Error {}
/**
* @requires useGridColumns (method)
* @requires useGridRows (method)
* @requires useGridFocus (state)
* @requires useGridEditing (method)
* TODO: Impossible priority - useGridEditing also needs to be after useGridParamsApi
* TODO: Impossible priority - useGridFocus also needs to be after useGridParamsApi
*/
export function useGridParamsApi(apiRef, props, configuration) {
const getColumnHeaderParams = React.useCallback(field => ({
field,
colDef: apiRef.current.getColumn(field)
}), [apiRef]);
const getRowParams = React.useCallback(id => {
const row = apiRef.current.getRow(id);
if (!row) {
throw new MissingRowIdError(`MUI X: No row with id #${id} found`);
}
const params = {
id,
columns: apiRef.current.getAllColumns(),
row
};
return params;
}, [apiRef]);
const getCellParamsForRow = React.useCallback((id, field, row, {
cellMode,
colDef,
hasFocus,
rowNode,
tabIndex,
value: forcedValue,
formattedValue: forcedFormattedValue
}) => {
const value = forcedValue !== undefined ? forcedValue : apiRef.current.getRowValue(row, colDef);
const formattedValue = forcedFormattedValue !== undefined ? forcedFormattedValue : apiRef.current.getRowFormattedValue(row, colDef);
const params = {
id,
field,
row,
rowNode,
colDef,
cellMode,
hasFocus,
tabIndex,
value,
formattedValue,
isEditable: false,
api: apiRef.current
};
params.isEditable = colDef && apiRef.current.isCellEditable(params);
return params;
}, [apiRef]);
const getCellParams = React.useCallback((id, field) => {
const row = apiRef.current.getRow(id);
const rowNode = gridRowNodeSelector(apiRef, id);
if (!row || !rowNode) {
throw new MissingRowIdError(`MUI X: No row with id #${id} found`);
}
const cellFocus = gridFocusCellSelector(apiRef);
const cellTabIndex = gridTabIndexCellSelector(apiRef);
const cellMode = apiRef.current.getCellMode(id, field);
return apiRef.current.getCellParamsForRow(id, field, row, {
// Params keep a non-nullable `colDef`, but it can be `undefined` at runtime for an unknown field.
colDef: props.listView && props.listViewColumn?.field === field ? gridListColumnSelector(apiRef) : apiRef.current.getColumn(field),
rowNode,
hasFocus: cellFocus !== null && cellFocus.field === field && cellFocus.id === id,
tabIndex: cellTabIndex && cellTabIndex.field === field && cellTabIndex.id === id ? 0 : -1,
cellMode
});
}, [apiRef, props.listView, props.listViewColumn?.field]);
const getColumnHeaderElement = React.useCallback(field => {
if (!apiRef.current.rootElementRef.current) {
return null;
}
return getGridColumnHeaderElement(apiRef.current.rootElementRef.current, field);
}, [apiRef]);
const getRowElement = React.useCallback(id => {
if (!apiRef.current.rootElementRef.current) {
return null;
}
return getGridRowElement(apiRef.current.rootElementRef.current, id);
}, [apiRef]);
const getCellElement = React.useCallback((id, field) => {
if (!apiRef.current.rootElementRef.current) {
return null;
}
return getGridCellElement(apiRef.current.rootElementRef.current, {
id,
field
});
}, [apiRef]);
const overridableParamsMethods = configuration.hooks.useGridParamsOverridableMethods(apiRef);
const paramsApi = {
getCellValue: overridableParamsMethods.getCellValue,
getCellParams,
getCellElement,
getRowValue: overridableParamsMethods.getRowValue,
getRowFormattedValue: overridableParamsMethods.getRowFormattedValue,
getRowParams,
getRowElement,
getColumnHeaderParams,
getColumnHeaderElement
};
const paramsPrivateApi = {
getCellParamsForRow
};
useGridApiMethod(apiRef, paramsApi, 'public');
useGridApiMethod(apiRef, paramsPrivateApi, 'private');
}
@@ -0,0 +1,7 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.mjs";
export declare const useGridParamsOverridableMethods: (apiRef: RefObject<GridPrivateApiCommunity>) => {
getCellValue: <V = any>(id: import("@mui/x-data-grid").GridRowId, field: string) => V;
getRowValue: <V = any>(row: import("@mui/x-data-grid").GridRowModel, colDef: import("@mui/x-data-grid").GridColDef) => V;
getRowFormattedValue: <V = any>(row: import("@mui/x-data-grid").GridRowModel, colDef: import("@mui/x-data-grid").GridColDef) => V;
};
@@ -0,0 +1,7 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.js";
export declare const useGridParamsOverridableMethods: (apiRef: RefObject<GridPrivateApiCommunity>) => {
getCellValue: <V = any>(id: import("@mui/x-data-grid").GridRowId, field: string) => V;
getRowValue: <V = any>(row: import("@mui/x-data-grid").GridRowModel, colDef: import("@mui/x-data-grid").GridColDef) => V;
getRowFormattedValue: <V = any>(row: import("@mui/x-data-grid").GridRowModel, colDef: import("@mui/x-data-grid").GridColDef) => V;
};
@@ -0,0 +1,38 @@
"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.useGridParamsOverridableMethods = void 0;
var _formatErrorMessage2 = _interopRequireDefault(require("@mui/x-internals/formatErrorMessage"));
var React = _interopRequireWildcard(require("react"));
var _gridRowsUtils = require("./gridRowsUtils");
const useGridParamsOverridableMethods = apiRef => {
const getCellValue = React.useCallback((id, field) => {
const colDef = apiRef.current.getColumn(field);
const row = apiRef.current.getRow(id);
if (!row) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No row with id #${id} found` : (0, _formatErrorMessage2.default)(87, id));
}
if (!colDef || !colDef.valueGetter) {
return row[field];
}
return colDef.valueGetter(row[colDef.field], row, colDef, apiRef);
}, [apiRef]);
const getRowValue = React.useCallback((row, colDef) => (0, _gridRowsUtils.getRowValue)(row, colDef, apiRef), [apiRef]);
const getRowFormattedValue = React.useCallback((row, colDef) => {
const value = getRowValue(row, colDef);
if (!colDef || !colDef.valueFormatter) {
return value;
}
return colDef.valueFormatter(value, row, colDef, apiRef);
}, [apiRef, getRowValue]);
return {
getCellValue,
getRowValue,
getRowFormattedValue
};
};
exports.useGridParamsOverridableMethods = useGridParamsOverridableMethods;
@@ -0,0 +1,29 @@
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import * as React from 'react';
import { getRowValue as getRowValueFn } from "./gridRowsUtils.mjs";
export const useGridParamsOverridableMethods = apiRef => {
const getCellValue = React.useCallback((id, field) => {
const colDef = apiRef.current.getColumn(field);
const row = apiRef.current.getRow(id);
if (!row) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No row with id #${id} found` : _formatErrorMessage(87, id));
}
if (!colDef || !colDef.valueGetter) {
return row[field];
}
return colDef.valueGetter(row[colDef.field], row, colDef, apiRef);
}, [apiRef]);
const getRowValue = React.useCallback((row, colDef) => getRowValueFn(row, colDef, apiRef), [apiRef]);
const getRowFormattedValue = React.useCallback((row, colDef) => {
const value = getRowValue(row, colDef);
if (!colDef || !colDef.valueFormatter) {
return value;
}
return colDef.valueFormatter(value, row, colDef, apiRef);
}, [apiRef, getRowValue]);
return {
getCellValue,
getRowValue,
getRowFormattedValue
};
};
@@ -0,0 +1,2 @@
import type { GetRowAriaAttributesFn } from "../../../models/configuration/gridRowConfiguration.mjs";
export declare const useGridRowAriaAttributes: () => GetRowAriaAttributesFn;
@@ -0,0 +1,2 @@
import type { GetRowAriaAttributesFn } from "../../../models/configuration/gridRowConfiguration.js";
export declare const useGridRowAriaAttributes: () => GetRowAriaAttributesFn;
@@ -0,0 +1,27 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridRowAriaAttributes = void 0;
var React = _interopRequireWildcard(require("react"));
var _useGridSelector = require("../../utils/useGridSelector");
var _gridColumnGroupsSelector = require("../columnGrouping/gridColumnGroupsSelector");
var _useGridPrivateApiContext = require("../../utils/useGridPrivateApiContext");
const useGridRowAriaAttributes = () => {
const apiRef = (0, _useGridPrivateApiContext.useGridPrivateApiContext)();
const headerGroupingMaxDepth = (0, _useGridSelector.useGridSelector)(apiRef, _gridColumnGroupsSelector.gridColumnGroupsHeaderMaxDepthSelector);
return React.useCallback((rowNode, index) => {
const ariaAttributes = {};
const ariaRowIndex = index + headerGroupingMaxDepth + 2; // 1 for the header row and 1 as it's 1-based
ariaAttributes['aria-rowindex'] = ariaRowIndex;
// XXX: fix this properly
if (rowNode && apiRef.current.isRowSelectable(rowNode.id)) {
ariaAttributes['aria-selected'] = apiRef.current.isRowSelected(rowNode.id);
}
return ariaAttributes;
}, [apiRef, headerGroupingMaxDepth]);
};
exports.useGridRowAriaAttributes = useGridRowAriaAttributes;
@@ -0,0 +1,19 @@
import * as React from 'react';
import { useGridSelector } from "../../utils/useGridSelector.mjs";
import { gridColumnGroupsHeaderMaxDepthSelector } from "../columnGrouping/gridColumnGroupsSelector.mjs";
import { useGridPrivateApiContext } from "../../utils/useGridPrivateApiContext.mjs";
export const useGridRowAriaAttributes = () => {
const apiRef = useGridPrivateApiContext();
const headerGroupingMaxDepth = useGridSelector(apiRef, gridColumnGroupsHeaderMaxDepthSelector);
return React.useCallback((rowNode, index) => {
const ariaAttributes = {};
const ariaRowIndex = index + headerGroupingMaxDepth + 2; // 1 for the header row and 1 as it's 1-based
ariaAttributes['aria-rowindex'] = ariaRowIndex;
// XXX: fix this properly
if (rowNode && apiRef.current.isRowSelectable(rowNode.id)) {
ariaAttributes['aria-selected'] = apiRef.current.isRowSelected(rowNode.id);
}
return ariaAttributes;
}, [apiRef, headerGroupingMaxDepth]);
};
@@ -0,0 +1,17 @@
import type { RefObject } from '@mui/x-internals/types';
import type { RowSpanningState } from '@mui/x-virtualizer/models';
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.mjs";
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.mjs";
import type { GridStateInitializer } from "../../utils/useGridInitializeState.mjs";
export interface GridRowSpanningState extends RowSpanningState {}
export type RowRange = {
firstRowIndex: number;
lastRowIndex: number;
};
/**
* @requires columnsStateInitializer (method) - should be initialized before
* @requires rowsStateInitializer (method) - should be initialized before
* @requires filterStateInitializer (method) - should be initialized before
*/
export declare const rowSpanningStateInitializer: GridStateInitializer;
export declare const useGridRowSpanning: (apiRef: RefObject<GridPrivateApiCommunity>, props: Pick<DataGridProcessedProps, 'rowSpanning' | 'pagination' | 'paginationMode'>) => void;
@@ -0,0 +1,17 @@
import type { RefObject } from '@mui/x-internals/types';
import type { RowSpanningState } from '@mui/x-virtualizer/models';
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.js";
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.js";
import type { GridStateInitializer } from "../../utils/useGridInitializeState.js";
export interface GridRowSpanningState extends RowSpanningState {}
export type RowRange = {
firstRowIndex: number;
lastRowIndex: number;
};
/**
* @requires columnsStateInitializer (method) - should be initialized before
* @requires rowsStateInitializer (method) - should be initialized before
* @requires filterStateInitializer (method) - should be initialized before
*/
export declare const rowSpanningStateInitializer: GridStateInitializer;
export declare const useGridRowSpanning: (apiRef: RefObject<GridPrivateApiCommunity>, props: Pick<DataGridProcessedProps, 'rowSpanning' | 'pagination' | 'paginationMode'>) => void;
@@ -0,0 +1,217 @@
"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.useGridRowSpanning = exports.rowSpanningStateInitializer = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _features = require("@mui/x-virtualizer/features");
var _gridColumnsSelector = require("../columns/gridColumnsSelector");
var _useGridVisibleRows = require("../../utils/useGridVisibleRows");
var _gridVirtualizationSelectors = require("../virtualization/gridVirtualizationSelectors");
var _gridRowSpanningUtils = require("./gridRowSpanningUtils");
var _useGridEvent = require("../../utils/useGridEvent");
var _utils = require("../../../utils/utils");
var _useRunOncePerLoop = require("../../utils/useRunOncePerLoop");
const EMPTY_CACHES = {
spannedCells: {},
hiddenCells: {},
hiddenCellOriginMap: {}
};
const EMPTY_RANGE = {
firstRowIndex: 0,
lastRowIndex: 0
};
const EMPTY_STATE = {
caches: EMPTY_CACHES,
processedRange: EMPTY_RANGE
};
const computeRowSpanningState = (apiRef, colDefs, visibleRows, range, rangeToProcess, resetState) => {
const virtualizer = apiRef.current.virtualizer;
const previousState = resetState ? EMPTY_STATE : _features.Rowspan.selectors.state(virtualizer.store.state);
const spannedCells = (0, _extends2.default)({}, previousState.caches.spannedCells);
const hiddenCells = (0, _extends2.default)({}, previousState.caches.hiddenCells);
const hiddenCellOriginMap = (0, _extends2.default)({}, previousState.caches.hiddenCellOriginMap);
const processedRange = {
firstRowIndex: Math.min(previousState.processedRange.firstRowIndex, rangeToProcess.firstRowIndex),
lastRowIndex: Math.max(previousState.processedRange.lastRowIndex, rangeToProcess.lastRowIndex)
};
colDefs.forEach((colDef, columnIndex) => {
for (let index = rangeToProcess.firstRowIndex; index < rangeToProcess.lastRowIndex; index += 1) {
const row = visibleRows[index];
if (hiddenCells[row.id]?.[columnIndex]) {
continue;
}
const cellValue = (0, _gridRowSpanningUtils.getCellValue)(row.model, colDef, apiRef);
if (cellValue == null) {
continue;
}
let spannedRowId = row.id;
let spannedRowIndex = index;
let rowSpan = 0;
// For first index, also scan in the previous rows to handle the reset state case e.g by sorting
const backwardsHiddenCells = [];
if (index === rangeToProcess.firstRowIndex) {
let prevIndex = index - 1;
let prevRowEntry = visibleRows[prevIndex];
while (prevIndex >= range.firstRowIndex && prevRowEntry && (0, _gridRowSpanningUtils.getCellValue)(prevRowEntry.model, colDef, apiRef) === cellValue) {
const currentRow = visibleRows[prevIndex + 1];
if (hiddenCells[currentRow.id]) {
hiddenCells[currentRow.id][columnIndex] = true;
} else {
hiddenCells[currentRow.id] = {
[columnIndex]: true
};
}
backwardsHiddenCells.push(index);
rowSpan += 1;
spannedRowId = prevRowEntry.id;
spannedRowIndex = prevIndex;
prevIndex -= 1;
prevRowEntry = visibleRows[prevIndex];
}
}
backwardsHiddenCells.forEach(hiddenCellIndex => {
if (hiddenCellOriginMap[hiddenCellIndex]) {
hiddenCellOriginMap[hiddenCellIndex][columnIndex] = spannedRowIndex;
} else {
hiddenCellOriginMap[hiddenCellIndex] = {
[columnIndex]: spannedRowIndex
};
}
});
// Scan the next rows
let relativeIndex = index + 1;
while (relativeIndex <= range.lastRowIndex && visibleRows[relativeIndex] && (0, _gridRowSpanningUtils.getCellValue)(visibleRows[relativeIndex].model, colDef, apiRef) === cellValue) {
const currentRow = visibleRows[relativeIndex];
if (hiddenCells[currentRow.id]) {
hiddenCells[currentRow.id][columnIndex] = true;
} else {
hiddenCells[currentRow.id] = {
[columnIndex]: true
};
}
if (hiddenCellOriginMap[relativeIndex]) {
hiddenCellOriginMap[relativeIndex][columnIndex] = spannedRowIndex;
} else {
hiddenCellOriginMap[relativeIndex] = {
[columnIndex]: spannedRowIndex
};
}
relativeIndex += 1;
rowSpan += 1;
}
if (rowSpan > 0) {
if (spannedCells[spannedRowId]) {
spannedCells[spannedRowId][columnIndex] = rowSpan + 1;
} else {
spannedCells[spannedRowId] = {
[columnIndex]: rowSpan + 1
};
}
}
}
});
return {
caches: {
spannedCells,
hiddenCells,
hiddenCellOriginMap
},
processedRange
};
};
/**
* @requires columnsStateInitializer (method) - should be initialized before
* @requires rowsStateInitializer (method) - should be initialized before
* @requires filterStateInitializer (method) - should be initialized before
*/
const rowSpanningStateInitializer = state => {
return (0, _extends2.default)({}, state, {
rowSpanning: EMPTY_STATE
});
};
exports.rowSpanningStateInitializer = rowSpanningStateInitializer;
const useGridRowSpanning = (apiRef, props) => {
const updateRowSpanningState = React.useCallback((renderContext, resetState = false) => {
const store = apiRef.current.virtualizer.store;
const {
range,
rows: visibleRows
} = (0, _useGridVisibleRows.getVisibleRows)(apiRef);
if (resetState) {
store.set('rowSpanning', EMPTY_STATE);
}
if (range === null || !(0, _gridRowSpanningUtils.isRowContextInitialized)(renderContext)) {
return;
}
const previousState = resetState ? EMPTY_STATE : _features.Rowspan.selectors.state(store.state);
const rangeToProcess = (0, _gridRowSpanningUtils.getUnprocessedRange)({
firstRowIndex: renderContext.firstRowIndex,
lastRowIndex: Math.min(renderContext.lastRowIndex, range.lastRowIndex - range.firstRowIndex + 1)
}, previousState.processedRange);
if (rangeToProcess === null) {
return;
}
const colDefs = (0, _gridColumnsSelector.gridVisibleColumnDefinitionsSelector)(apiRef);
const newState = computeRowSpanningState(apiRef, colDefs, visibleRows, range, rangeToProcess, resetState);
const newSpannedCellsCount = Object.keys(newState.caches.spannedCells).length;
const newHiddenCellsCount = Object.keys(newState.caches.hiddenCells).length;
const previousSpannedCellsCount = Object.keys(previousState.caches.spannedCells).length;
const previousHiddenCellsCount = Object.keys(previousState.caches.hiddenCells).length;
const shouldUpdateState = resetState || newSpannedCellsCount !== previousSpannedCellsCount || newHiddenCellsCount !== previousHiddenCellsCount;
const hasNoSpannedCells = newSpannedCellsCount === 0 && previousSpannedCellsCount === 0;
if (!shouldUpdateState || hasNoSpannedCells) {
return;
}
store.set('rowSpanning', newState);
}, [apiRef]);
// Reset events trigger a full re-computation of the row spanning state:
// - The `rowSpanning` prop is updated (feature flag)
// - The filtering is applied
// - The sorting is applied
// - The `paginationModel` is updated
// - The rows are updated
const {
schedule: deferredUpdateRowSpanningState,
cancel
} = (0, _useRunOncePerLoop.useRunOncePerLoop)(updateRowSpanningState);
const resetRowSpanningState = React.useCallback(() => {
const renderContext = (0, _gridVirtualizationSelectors.gridRenderContextSelector)(apiRef);
if (!(0, _gridRowSpanningUtils.isRowContextInitialized)(renderContext)) {
return;
}
deferredUpdateRowSpanningState(renderContext, true);
}, [apiRef, deferredUpdateRowSpanningState]);
(0, _useGridEvent.useGridEvent)(apiRef, 'renderedRowsIntervalChange', (0, _utils.runIf)(props.rowSpanning, renderContext => {
const didHavePendingReset = cancel();
updateRowSpanningState(renderContext, didHavePendingReset);
}));
(0, _useGridEvent.useGridEvent)(apiRef, 'sortedRowsSet', (0, _utils.runIf)(props.rowSpanning, resetRowSpanningState));
(0, _useGridEvent.useGridEvent)(apiRef, 'paginationModelChange', (0, _utils.runIf)(props.rowSpanning, resetRowSpanningState));
(0, _useGridEvent.useGridEvent)(apiRef, 'filteredRowsSet', (0, _utils.runIf)(props.rowSpanning, resetRowSpanningState));
(0, _useGridEvent.useGridEvent)(apiRef, 'columnsChange', (0, _utils.runIf)(props.rowSpanning, resetRowSpanningState));
(0, _useGridEvent.useGridEvent)(apiRef, 'rowExpansionChange', (0, _utils.runIf)(props.rowSpanning, resetRowSpanningState));
React.useEffect(() => {
const store = apiRef.current.virtualizer?.store;
if (!store) {
return;
}
if (!props.rowSpanning) {
if (store.state.rowSpanning !== EMPTY_STATE) {
store.set('rowSpanning', EMPTY_STATE);
}
} else if (store.state.rowSpanning === EMPTY_STATE) {
updateRowSpanningState((0, _gridVirtualizationSelectors.gridRenderContextSelector)(apiRef));
}
}, [apiRef, props.rowSpanning, updateRowSpanningState]);
};
exports.useGridRowSpanning = useGridRowSpanning;
@@ -0,0 +1,208 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import { Rowspan } from '@mui/x-virtualizer/features';
import { gridVisibleColumnDefinitionsSelector } from "../columns/gridColumnsSelector.mjs";
import { getVisibleRows } from "../../utils/useGridVisibleRows.mjs";
import { gridRenderContextSelector } from "../virtualization/gridVirtualizationSelectors.mjs";
import { getUnprocessedRange, isRowContextInitialized, getCellValue } from "./gridRowSpanningUtils.mjs";
import { useGridEvent } from "../../utils/useGridEvent.mjs";
import { runIf } from "../../../utils/utils.mjs";
import { useRunOncePerLoop } from "../../utils/useRunOncePerLoop.mjs";
const EMPTY_CACHES = {
spannedCells: {},
hiddenCells: {},
hiddenCellOriginMap: {}
};
const EMPTY_RANGE = {
firstRowIndex: 0,
lastRowIndex: 0
};
const EMPTY_STATE = {
caches: EMPTY_CACHES,
processedRange: EMPTY_RANGE
};
const computeRowSpanningState = (apiRef, colDefs, visibleRows, range, rangeToProcess, resetState) => {
const virtualizer = apiRef.current.virtualizer;
const previousState = resetState ? EMPTY_STATE : Rowspan.selectors.state(virtualizer.store.state);
const spannedCells = _extends({}, previousState.caches.spannedCells);
const hiddenCells = _extends({}, previousState.caches.hiddenCells);
const hiddenCellOriginMap = _extends({}, previousState.caches.hiddenCellOriginMap);
const processedRange = {
firstRowIndex: Math.min(previousState.processedRange.firstRowIndex, rangeToProcess.firstRowIndex),
lastRowIndex: Math.max(previousState.processedRange.lastRowIndex, rangeToProcess.lastRowIndex)
};
colDefs.forEach((colDef, columnIndex) => {
for (let index = rangeToProcess.firstRowIndex; index < rangeToProcess.lastRowIndex; index += 1) {
const row = visibleRows[index];
if (hiddenCells[row.id]?.[columnIndex]) {
continue;
}
const cellValue = getCellValue(row.model, colDef, apiRef);
if (cellValue == null) {
continue;
}
let spannedRowId = row.id;
let spannedRowIndex = index;
let rowSpan = 0;
// For first index, also scan in the previous rows to handle the reset state case e.g by sorting
const backwardsHiddenCells = [];
if (index === rangeToProcess.firstRowIndex) {
let prevIndex = index - 1;
let prevRowEntry = visibleRows[prevIndex];
while (prevIndex >= range.firstRowIndex && prevRowEntry && getCellValue(prevRowEntry.model, colDef, apiRef) === cellValue) {
const currentRow = visibleRows[prevIndex + 1];
if (hiddenCells[currentRow.id]) {
hiddenCells[currentRow.id][columnIndex] = true;
} else {
hiddenCells[currentRow.id] = {
[columnIndex]: true
};
}
backwardsHiddenCells.push(index);
rowSpan += 1;
spannedRowId = prevRowEntry.id;
spannedRowIndex = prevIndex;
prevIndex -= 1;
prevRowEntry = visibleRows[prevIndex];
}
}
backwardsHiddenCells.forEach(hiddenCellIndex => {
if (hiddenCellOriginMap[hiddenCellIndex]) {
hiddenCellOriginMap[hiddenCellIndex][columnIndex] = spannedRowIndex;
} else {
hiddenCellOriginMap[hiddenCellIndex] = {
[columnIndex]: spannedRowIndex
};
}
});
// Scan the next rows
let relativeIndex = index + 1;
while (relativeIndex <= range.lastRowIndex && visibleRows[relativeIndex] && getCellValue(visibleRows[relativeIndex].model, colDef, apiRef) === cellValue) {
const currentRow = visibleRows[relativeIndex];
if (hiddenCells[currentRow.id]) {
hiddenCells[currentRow.id][columnIndex] = true;
} else {
hiddenCells[currentRow.id] = {
[columnIndex]: true
};
}
if (hiddenCellOriginMap[relativeIndex]) {
hiddenCellOriginMap[relativeIndex][columnIndex] = spannedRowIndex;
} else {
hiddenCellOriginMap[relativeIndex] = {
[columnIndex]: spannedRowIndex
};
}
relativeIndex += 1;
rowSpan += 1;
}
if (rowSpan > 0) {
if (spannedCells[spannedRowId]) {
spannedCells[spannedRowId][columnIndex] = rowSpan + 1;
} else {
spannedCells[spannedRowId] = {
[columnIndex]: rowSpan + 1
};
}
}
}
});
return {
caches: {
spannedCells,
hiddenCells,
hiddenCellOriginMap
},
processedRange
};
};
/**
* @requires columnsStateInitializer (method) - should be initialized before
* @requires rowsStateInitializer (method) - should be initialized before
* @requires filterStateInitializer (method) - should be initialized before
*/
export const rowSpanningStateInitializer = state => {
return _extends({}, state, {
rowSpanning: EMPTY_STATE
});
};
export const useGridRowSpanning = (apiRef, props) => {
const updateRowSpanningState = React.useCallback((renderContext, resetState = false) => {
const store = apiRef.current.virtualizer.store;
const {
range,
rows: visibleRows
} = getVisibleRows(apiRef);
if (resetState) {
store.set('rowSpanning', EMPTY_STATE);
}
if (range === null || !isRowContextInitialized(renderContext)) {
return;
}
const previousState = resetState ? EMPTY_STATE : Rowspan.selectors.state(store.state);
const rangeToProcess = getUnprocessedRange({
firstRowIndex: renderContext.firstRowIndex,
lastRowIndex: Math.min(renderContext.lastRowIndex, range.lastRowIndex - range.firstRowIndex + 1)
}, previousState.processedRange);
if (rangeToProcess === null) {
return;
}
const colDefs = gridVisibleColumnDefinitionsSelector(apiRef);
const newState = computeRowSpanningState(apiRef, colDefs, visibleRows, range, rangeToProcess, resetState);
const newSpannedCellsCount = Object.keys(newState.caches.spannedCells).length;
const newHiddenCellsCount = Object.keys(newState.caches.hiddenCells).length;
const previousSpannedCellsCount = Object.keys(previousState.caches.spannedCells).length;
const previousHiddenCellsCount = Object.keys(previousState.caches.hiddenCells).length;
const shouldUpdateState = resetState || newSpannedCellsCount !== previousSpannedCellsCount || newHiddenCellsCount !== previousHiddenCellsCount;
const hasNoSpannedCells = newSpannedCellsCount === 0 && previousSpannedCellsCount === 0;
if (!shouldUpdateState || hasNoSpannedCells) {
return;
}
store.set('rowSpanning', newState);
}, [apiRef]);
// Reset events trigger a full re-computation of the row spanning state:
// - The `rowSpanning` prop is updated (feature flag)
// - The filtering is applied
// - The sorting is applied
// - The `paginationModel` is updated
// - The rows are updated
const {
schedule: deferredUpdateRowSpanningState,
cancel
} = useRunOncePerLoop(updateRowSpanningState);
const resetRowSpanningState = React.useCallback(() => {
const renderContext = gridRenderContextSelector(apiRef);
if (!isRowContextInitialized(renderContext)) {
return;
}
deferredUpdateRowSpanningState(renderContext, true);
}, [apiRef, deferredUpdateRowSpanningState]);
useGridEvent(apiRef, 'renderedRowsIntervalChange', runIf(props.rowSpanning, renderContext => {
const didHavePendingReset = cancel();
updateRowSpanningState(renderContext, didHavePendingReset);
}));
useGridEvent(apiRef, 'sortedRowsSet', runIf(props.rowSpanning, resetRowSpanningState));
useGridEvent(apiRef, 'paginationModelChange', runIf(props.rowSpanning, resetRowSpanningState));
useGridEvent(apiRef, 'filteredRowsSet', runIf(props.rowSpanning, resetRowSpanningState));
useGridEvent(apiRef, 'columnsChange', runIf(props.rowSpanning, resetRowSpanningState));
useGridEvent(apiRef, 'rowExpansionChange', runIf(props.rowSpanning, resetRowSpanningState));
React.useEffect(() => {
const store = apiRef.current.virtualizer?.store;
if (!store) {
return;
}
if (!props.rowSpanning) {
if (store.state.rowSpanning !== EMPTY_STATE) {
store.set('rowSpanning', EMPTY_STATE);
}
} else if (store.state.rowSpanning === EMPTY_STATE) {
updateRowSpanningState(gridRenderContextSelector(apiRef));
}
}, [apiRef, props.rowSpanning, updateRowSpanningState]);
};
@@ -0,0 +1,7 @@
import type { RefObject } from '@mui/x-internals/types';
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.mjs";
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.mjs";
import type { GridStateInitializer } from "../../utils/useGridInitializeState.mjs";
import type { GridConfiguration } from "../../../models/configuration/gridConfiguration.mjs";
export declare const rowsStateInitializer: GridStateInitializer<Pick<DataGridProcessedProps, 'dataSource' | 'rows' | 'rowCount' | 'getRowId' | 'loading'>>;
export declare const useGridRows: (apiRef: RefObject<GridPrivateApiCommunity>, props: Pick<DataGridProcessedProps, 'rows' | 'getRowId' | 'rowCount' | 'throttleRowsMs' | 'signature' | 'pagination' | 'paginationMode' | 'loading' | 'dataSource' | 'processRowUpdate' | 'onProcessRowUpdateError'>, configuration: GridConfiguration) => void;
@@ -0,0 +1,7 @@
import type { RefObject } from '@mui/x-internals/types';
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.js";
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.js";
import type { GridStateInitializer } from "../../utils/useGridInitializeState.js";
import type { GridConfiguration } from "../../../models/configuration/gridConfiguration.js";
export declare const rowsStateInitializer: GridStateInitializer<Pick<DataGridProcessedProps, 'dataSource' | 'rows' | 'rowCount' | 'getRowId' | 'loading'>>;
export declare const useGridRows: (apiRef: RefObject<GridPrivateApiCommunity>, props: Pick<DataGridProcessedProps, 'rows' | 'getRowId' | 'rowCount' | 'throttleRowsMs' | 'signature' | 'pagination' | 'paginationMode' | 'loading' | 'dataSource' | 'processRowUpdate' | 'onProcessRowUpdateError'>, configuration: GridConfiguration) => void;
@@ -0,0 +1,494 @@
"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.useGridRows = exports.rowsStateInitializer = void 0;
var _formatErrorMessage2 = _interopRequireDefault(require("@mui/x-internals/formatErrorMessage"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _useLazyRef = _interopRequireDefault(require("@mui/utils/useLazyRef"));
var _isObjectEmpty = require("@mui/x-internals/isObjectEmpty");
var _useGridApiMethod = require("../../utils/useGridApiMethod");
var _useGridLogger = require("../../utils/useGridLogger");
var _gridRowsSelector = require("./gridRowsSelector");
var _gridPropsSelectors = require("../../core/gridPropsSelectors");
var _useTimeout = require("../../utils/useTimeout");
var _signature = require("../../../constants/signature");
var _useGridEvent = require("../../utils/useGridEvent");
var _useGridVisibleRows = require("../../utils/useGridVisibleRows");
var _gridSortingSelector = require("../sorting/gridSortingSelector");
var _gridFilterSelector = require("../filter/gridFilterSelector");
var _gridRowsUtils = require("./gridRowsUtils");
var _pipeProcessing = require("../../core/pipeProcessing");
var _strategyProcessing = require("../../core/strategyProcessing");
var _pivoting = require("../pivoting");
const rowsStateInitializer = (state, props, apiRef) => {
const isDataSourceAvailable = !!props.dataSource;
apiRef.current.caches.rows = (0, _gridRowsUtils.createRowsInternalCache)({
rows: isDataSourceAvailable ? [] : props.rows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
});
return (0, _extends2.default)({}, state, {
rows: (0, _gridRowsUtils.getRowsStateFromCache)({
apiRef,
rowCountProp: props.rowCount,
loadingProp: isDataSourceAvailable ? true : props.loading,
previousTree: null,
previousTreeDepths: null
})
});
};
exports.rowsStateInitializer = rowsStateInitializer;
const useGridRows = (apiRef, props, configuration) => {
if (process.env.NODE_ENV !== 'production') {
try {
// Freeze the `rows` prop so developers have a fast failure if they try to use Array.prototype.push().
Object.freeze(props.rows);
} catch (error) {
// Sometimes, it's impossible to freeze, so we give up on it.
}
}
const logger = (0, _useGridLogger.useGridLogger)(apiRef, 'useGridRows');
const lastUpdateMs = React.useRef(Date.now());
const lastRowCount = React.useRef(props.rowCount);
const timeout = (0, _useTimeout.useTimeout)();
// Get overridable methods from configuration
const {
setRowIndex,
setRowPosition
} = configuration.hooks.useGridRowsOverridableMethods(apiRef, props);
const getRow = React.useCallback(id => {
const model = (0, _gridRowsSelector.gridRowsLookupSelector)(apiRef)[id];
if (model) {
return model;
}
const node = (0, _gridRowsSelector.gridRowNodeSelector)(apiRef, id);
if (node && (0, _gridRowsUtils.isAutogeneratedRowNode)(node)) {
return {
[_gridRowsUtils.GRID_ID_AUTOGENERATED]: id
};
}
return null;
}, [apiRef]);
const getRowId = React.useCallback(row => (0, _gridPropsSelectors.gridRowIdSelector)(apiRef, row), [apiRef]);
const throttledRowsChange = React.useCallback(({
cache,
throttle
}) => {
const run = () => {
lastUpdateMs.current = Date.now();
apiRef.current.setState(state => (0, _extends2.default)({}, state, {
rows: (0, _gridRowsUtils.getRowsStateFromCache)({
apiRef,
rowCountProp: props.rowCount,
loadingProp: props.loading,
previousTree: (0, _gridRowsSelector.gridRowTreeSelector)(apiRef),
previousTreeDepths: (0, _gridRowsSelector.gridRowTreeDepthsSelector)(apiRef),
previousGroupsToFetch: (0, _gridRowsSelector.gridRowGroupsToFetchSelector)(apiRef)
})
}));
apiRef.current.publishEvent('rowsSet');
};
timeout.clear();
apiRef.current.caches.rows = cache;
if (!throttle) {
run();
return;
}
const throttleRemainingTimeMs = props.throttleRowsMs - (Date.now() - lastUpdateMs.current);
if (throttleRemainingTimeMs > 0) {
timeout.start(throttleRemainingTimeMs, run);
return;
}
run();
}, [props.throttleRowsMs, props.rowCount, props.loading, apiRef, timeout]);
/**
* API METHODS
*/
const setRows = React.useCallback(rows => {
logger.debug(`Updating all rows, new length ${rows.length}`);
if (!props.dataSource && (0, _pivoting.gridPivotActiveSelector)(apiRef)) {
apiRef.current.updateNonPivotRows(rows, false);
return;
}
const cache = (0, _gridRowsUtils.createRowsInternalCache)({
rows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
});
const prevCache = apiRef.current.caches.rows;
cache.rowsBeforePartialUpdates = prevCache.rowsBeforePartialUpdates;
throttledRowsChange({
cache,
throttle: true
});
}, [logger, props.getRowId, props.dataSource, props.loading, props.rowCount, throttledRowsChange, apiRef]);
const updateRows = React.useCallback(updates => {
if (props.signature === _signature.GridSignature.DataGrid && updates.length > 1) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: You cannot update several rows at once in \`apiRef.current.updateRows\` on the DataGrid.
You need to upgrade to DataGridPro or DataGridPremium component to unlock this feature.` : (0, _formatErrorMessage2.default)(88));
}
if (!props.dataSource && (0, _pivoting.gridPivotActiveSelector)(apiRef)) {
apiRef.current.updateNonPivotRows(updates);
return;
}
const nonPinnedRowsUpdates = (0, _gridRowsUtils.computeRowsUpdates)(apiRef, updates, props.getRowId);
const cache = (0, _gridRowsUtils.updateCacheWithNewRows)({
updates: nonPinnedRowsUpdates,
getRowId: props.getRowId,
previousCache: apiRef.current.caches.rows
});
throttledRowsChange({
cache,
throttle: true
});
}, [props.signature, props.dataSource, props.getRowId, throttledRowsChange, apiRef]);
const updateNestedRows = React.useCallback((updates, groupKeys) => {
const nonPinnedRowsUpdates = (0, _gridRowsUtils.computeRowsUpdates)(apiRef, updates, props.getRowId);
const cache = (0, _gridRowsUtils.updateCacheWithNewRows)({
updates: nonPinnedRowsUpdates,
getRowId: props.getRowId,
previousCache: apiRef.current.caches.rows,
groupKeys: groupKeys ?? []
});
throttledRowsChange({
cache,
throttle: false
});
}, [props.getRowId, throttledRowsChange, apiRef]);
const setLoading = React.useCallback(loading => {
logger.debug(`Setting loading to ${loading}`);
apiRef.current.setState(state => (0, _extends2.default)({}, state, {
rows: (0, _extends2.default)({}, state.rows, {
loading
})
}));
apiRef.current.caches.rows.loadingPropBeforePartialUpdates = loading;
}, [apiRef, logger]);
const getRowModels = React.useCallback(() => {
const dataRows = (0, _gridRowsSelector.gridDataRowIdsSelector)(apiRef);
const idRowsLookup = (0, _gridRowsSelector.gridRowsLookupSelector)(apiRef);
return new Map(dataRows.map(id => [id, idRowsLookup[id] ?? {}]));
}, [apiRef]);
const getRowsCount = React.useCallback(() => (0, _gridRowsSelector.gridRowCountSelector)(apiRef), [apiRef]);
const getAllRowIds = React.useCallback(() => (0, _gridRowsSelector.gridDataRowIdsSelector)(apiRef), [apiRef]);
const getRowIndexRelativeToVisibleRows = React.useCallback(id => {
const {
rowIdToIndexMap
} = (0, _useGridVisibleRows.getVisibleRows)(apiRef);
return rowIdToIndexMap.get(id);
}, [apiRef]);
const setRowChildrenExpansion = React.useCallback((id, isExpanded) => {
const currentNode = (0, _gridRowsSelector.gridRowNodeSelector)(apiRef, id);
if (!currentNode) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No row with id #${id} found.` : (0, _formatErrorMessage2.default)(89, id));
}
if (currentNode.type !== 'group') {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: Only group nodes can be expanded or collapsed.' : (0, _formatErrorMessage2.default)(90));
}
const newNode = (0, _extends2.default)({}, currentNode, {
childrenExpanded: isExpanded
});
apiRef.current.setState(state => {
return (0, _extends2.default)({}, state, {
rows: (0, _extends2.default)({}, state.rows, {
tree: (0, _extends2.default)({}, state.rows.tree, {
[id]: newNode
})
})
});
});
apiRef.current.publishEvent('rowExpansionChange', newNode);
}, [apiRef]);
const expandAllRows = React.useCallback(() => {
const tree = (0, _extends2.default)({}, (0, _gridRowsSelector.gridRowTreeSelector)(apiRef));
const traverse = nodeId => {
const node = tree[nodeId];
if (node?.type === 'group') {
tree[nodeId] = (0, _extends2.default)({}, node, {
childrenExpanded: true
});
node.children.forEach(traverse);
}
};
traverse(_gridRowsUtils.GRID_ROOT_GROUP_ID);
apiRef.current.setState(state => (0, _extends2.default)({}, state, {
rows: (0, _extends2.default)({}, state.rows, {
tree
})
}));
apiRef.current.publishEvent('rowExpansionChange', tree[_gridRowsUtils.GRID_ROOT_GROUP_ID]);
}, [apiRef]);
const collapseAllRows = React.useCallback(() => {
const tree = (0, _extends2.default)({}, (0, _gridRowsSelector.gridRowTreeSelector)(apiRef));
const traverse = nodeId => {
const node = tree[nodeId];
if (node?.type === 'group') {
tree[nodeId] = (0, _extends2.default)({}, node, {
childrenExpanded: false
});
node.children.forEach(traverse);
}
};
traverse(_gridRowsUtils.GRID_ROOT_GROUP_ID);
apiRef.current.setState(state => (0, _extends2.default)({}, state, {
rows: (0, _extends2.default)({}, state.rows, {
tree
})
}));
apiRef.current.publishEvent('rowExpansionChange', tree[_gridRowsUtils.GRID_ROOT_GROUP_ID]);
}, [apiRef]);
const getRowNode = React.useCallback(id => (0, _gridRowsSelector.gridRowNodeSelector)(apiRef, id) ?? null, [apiRef]);
const getRowGroupChildren = React.useCallback(({
skipAutoGeneratedRows = true,
groupId,
applySorting,
applyFiltering,
directChildrenOnly = false
}) => {
const tree = (0, _gridRowsSelector.gridRowTreeSelector)(apiRef);
let children;
if (applySorting) {
const groupNode = tree[groupId];
if (!groupNode) {
return [];
}
const sortedRowIds = (0, _gridSortingSelector.gridSortedRowIdsSelector)(apiRef);
children = [];
const startIndex = sortedRowIds.findIndex(id => id === groupId) + 1;
for (let index = startIndex; index < sortedRowIds.length && (directChildrenOnly ? tree[sortedRowIds[index]].depth === groupNode.depth + 1 : tree[sortedRowIds[index]].depth > groupNode.depth); index += 1) {
const id = sortedRowIds[index];
if (!skipAutoGeneratedRows || !(0, _gridRowsUtils.isAutogeneratedRowNode)(tree[id])) {
children.push(id);
}
}
} else {
children = (0, _gridRowsUtils.getTreeNodeDescendants)(tree, groupId, skipAutoGeneratedRows, directChildrenOnly);
}
if (applyFiltering) {
const filteredRowsLookup = (0, _gridFilterSelector.gridFilteredRowsLookupSelector)(apiRef);
children = (0, _isObjectEmpty.isObjectEmpty)(filteredRowsLookup) ? children : children.filter(childId => filteredRowsLookup[childId] !== false);
}
return children;
}, [apiRef]);
const replaceRows = React.useCallback((firstRowToRender, newRows) => {
if (props.signature === _signature.GridSignature.DataGrid && newRows.length > 1) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: You cannot replace rows using \`apiRef.current.unstable_replaceRows\` on the DataGrid.
You need to upgrade to DataGridPro or DataGridPremium component to unlock this feature.` : (0, _formatErrorMessage2.default)(91));
}
if (newRows.length === 0) {
return;
}
const treeDepth = (0, _gridRowsSelector.gridRowMaximumTreeDepthSelector)(apiRef);
if (treeDepth > 1) {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: `apiRef.current.unstable_replaceRows` is not compatible with tree data and row grouping' : (0, _formatErrorMessage2.default)(92));
}
const tree = (0, _extends2.default)({}, (0, _gridRowsSelector.gridRowTreeSelector)(apiRef));
const dataRowIdToModelLookup = (0, _extends2.default)({}, (0, _gridRowsSelector.gridRowsLookupSelector)(apiRef));
const rootGroup = tree[_gridRowsUtils.GRID_ROOT_GROUP_ID];
const rootGroupChildren = [...rootGroup.children];
const seenIds = new Set();
for (let i = 0; i < newRows.length; i += 1) {
const rowModel = newRows[i];
const rowId = (0, _gridRowsUtils.getRowIdFromRowModel)(rowModel, props.getRowId, 'A row was provided without id when calling replaceRows().');
const [removedRowId] = rootGroupChildren.splice(firstRowToRender + i, 1, rowId);
if (!seenIds.has(removedRowId)) {
delete dataRowIdToModelLookup[removedRowId];
delete tree[removedRowId];
}
const rowTreeNodeConfig = {
id: rowId,
depth: 0,
parent: _gridRowsUtils.GRID_ROOT_GROUP_ID,
type: 'leaf',
groupingKey: null
};
dataRowIdToModelLookup[rowId] = rowModel;
tree[rowId] = rowTreeNodeConfig;
seenIds.add(rowId);
}
tree[_gridRowsUtils.GRID_ROOT_GROUP_ID] = (0, _extends2.default)({}, rootGroup, {
children: rootGroupChildren
});
// Removes potential remaining skeleton rows from the dataRowIds.
const dataRowIds = rootGroupChildren.filter(childId => tree[childId]?.type === 'leaf');
apiRef.current.caches.rows.dataRowIdToModelLookup = dataRowIdToModelLookup;
apiRef.current.setState(state => (0, _extends2.default)({}, state, {
rows: (0, _extends2.default)({}, state.rows, {
loading: props.loading,
totalRowCount: Math.max(props.rowCount || 0, rootGroupChildren.length),
dataRowIdToModelLookup,
dataRowIds,
tree
})
}));
apiRef.current.publishEvent('rowsSet');
}, [apiRef, props.signature, props.getRowId, props.loading, props.rowCount]);
const rowApi = {
getRow,
setLoading,
getRowId,
getRowModels,
getRowsCount,
getAllRowIds,
setRows,
updateRows,
getRowNode,
getRowIndexRelativeToVisibleRows,
unstable_replaceRows: replaceRows
};
const rowProApi = {
setRowIndex,
setRowPosition,
setRowChildrenExpansion,
getRowGroupChildren,
expandAllRows,
collapseAllRows
};
const rowProPrivateApi = {
updateNestedRows
};
/**
* EVENTS
*/
const groupRows = React.useCallback(() => {
logger.info(`Row grouping pre-processing have changed, regenerating the row tree`);
let cache;
if (apiRef.current.caches.rows.rowsBeforePartialUpdates === props.rows) {
// The `props.rows` did not change since the last row grouping
// We can use the current rows cache which contains the partial updates done recently.
cache = (0, _extends2.default)({}, apiRef.current.caches.rows, {
updates: {
type: 'full',
rows: (0, _gridRowsSelector.gridDataRowIdsSelector)(apiRef)
}
});
} else {
// The `props.rows` has changed since the last row grouping
// We must use the new `props.rows` on the new grouping
// This occurs because this event is triggered before the `useEffect` on the rows when both the grouping pre-processing and the rows changes on the same render
cache = (0, _gridRowsUtils.createRowsInternalCache)({
rows: props.rows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
});
}
throttledRowsChange({
cache,
throttle: false
});
}, [logger, apiRef, props.rows, props.getRowId, props.loading, props.rowCount, throttledRowsChange]);
const previousDataSource = (0, _useLazyRef.default)(() => props.dataSource);
const handleStrategyProcessorChange = React.useCallback(methodName => {
if (props.dataSource && props.dataSource !== previousDataSource.current) {
previousDataSource.current = props.dataSource;
return;
}
if (methodName === 'rowTreeCreation') {
groupRows();
}
}, [groupRows, previousDataSource, props.dataSource]);
const handleStrategyActivityChange = React.useCallback(() => {
// `rowTreeCreation` is the only processor ran when `strategyAvailabilityChange` is fired.
// All the other processors listen to `rowsSet` which will be published by the `groupRows` method below.
if (apiRef.current.getActiveStrategy(_strategyProcessing.GridStrategyGroup.RowTree) !== (0, _gridRowsSelector.gridRowGroupingNameSelector)(apiRef)) {
groupRows();
}
}, [apiRef, groupRows]);
(0, _useGridEvent.useGridEvent)(apiRef, 'activeStrategyProcessorChange', handleStrategyProcessorChange);
(0, _useGridEvent.useGridEvent)(apiRef, 'strategyAvailabilityChange', handleStrategyActivityChange);
/**
* APPLIERS
*/
const applyHydrateRowsProcessor = React.useCallback(() => {
apiRef.current.setState(state => {
const response = apiRef.current.unstable_applyPipeProcessors('hydrateRows', {
tree: (0, _gridRowsSelector.gridRowTreeSelector)(apiRef),
treeDepths: (0, _gridRowsSelector.gridRowTreeDepthsSelector)(apiRef),
dataRowIds: (0, _gridRowsSelector.gridDataRowIdsSelector)(apiRef),
dataRowIdToModelLookup: (0, _gridRowsSelector.gridRowsLookupSelector)(apiRef)
});
return (0, _extends2.default)({}, state, {
rows: (0, _extends2.default)({}, state.rows, response, {
totalTopLevelRowCount: (0, _gridRowsUtils.getTopLevelRowCount)({
tree: response.tree,
rowCountProp: props.rowCount
})
})
});
});
apiRef.current.publishEvent('rowsSet');
}, [apiRef, props.rowCount]);
(0, _pipeProcessing.useGridRegisterPipeApplier)(apiRef, 'hydrateRows', applyHydrateRowsProcessor);
(0, _useGridApiMethod.useGridApiMethod)(apiRef, rowApi, 'public');
(0, _useGridApiMethod.useGridApiMethod)(apiRef, rowProApi, props.signature === _signature.GridSignature.DataGrid ? 'private' : 'public');
(0, _useGridApiMethod.useGridApiMethod)(apiRef, rowProPrivateApi, 'private');
// The effect do not track any value defined synchronously during the 1st render by hooks called after `useGridRows`
// As a consequence, the state generated by the 1st run of this useEffect will always be equal to the initialization one
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}
let isRowCountPropUpdated = false;
if (props.rowCount !== lastRowCount.current) {
isRowCountPropUpdated = true;
lastRowCount.current = props.rowCount;
}
const currentRows = props.dataSource ? (0, _gridRowsSelector.gridDataRowsSelector)(apiRef) : props.rows;
const areNewRowsAlreadyInState = apiRef.current.caches.rows.rowsBeforePartialUpdates === currentRows;
const isNewLoadingAlreadyInState = apiRef.current.caches.rows.loadingPropBeforePartialUpdates === props.loading;
const isNewRowCountAlreadyInState = apiRef.current.caches.rows.rowCountPropBeforePartialUpdates === props.rowCount;
// The new rows have already been applied (most likely in the `'rowGroupsPreProcessingChange'` listener)
if (areNewRowsAlreadyInState) {
// If the loading prop has changed, we need to update its value in the state because it won't be done by `throttledRowsChange`
if (!isNewLoadingAlreadyInState) {
apiRef.current.setState(state => (0, _extends2.default)({}, state, {
rows: (0, _extends2.default)({}, state.rows, {
loading: props.loading
})
}));
apiRef.current.caches.rows.loadingPropBeforePartialUpdates = props.loading;
}
if (!isNewRowCountAlreadyInState) {
apiRef.current.setState(state => (0, _extends2.default)({}, state, {
rows: (0, _extends2.default)({}, state.rows, {
totalRowCount: Math.max(props.rowCount || 0, state.rows.totalRowCount),
totalTopLevelRowCount: Math.max(props.rowCount || 0, state.rows.totalTopLevelRowCount)
})
}));
apiRef.current.caches.rows.rowCountPropBeforePartialUpdates = props.rowCount;
}
if (!isRowCountPropUpdated) {
return;
}
}
logger.debug(`Updating all rows, new length ${currentRows?.length}`);
throttledRowsChange({
cache: (0, _gridRowsUtils.createRowsInternalCache)({
rows: currentRows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
}),
throttle: false
});
}, [props.rows, props.rowCount, props.getRowId, props.loading, props.dataSource, logger, throttledRowsChange, apiRef]);
};
exports.useGridRows = useGridRows;
@@ -0,0 +1,485 @@
'use client';
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import useLazyRef from '@mui/utils/useLazyRef';
import { isObjectEmpty } from '@mui/x-internals/isObjectEmpty';
import { useGridApiMethod } from "../../utils/useGridApiMethod.mjs";
import { useGridLogger } from "../../utils/useGridLogger.mjs";
import { gridRowCountSelector, gridRowsLookupSelector, gridRowTreeSelector, gridRowGroupingNameSelector, gridRowTreeDepthsSelector, gridDataRowIdsSelector, gridRowMaximumTreeDepthSelector, gridRowGroupsToFetchSelector, gridRowNodeSelector, gridDataRowsSelector } from "./gridRowsSelector.mjs";
import { gridRowIdSelector } from "../../core/gridPropsSelectors.mjs";
import { useTimeout } from "../../utils/useTimeout.mjs";
import { GridSignature } from "../../../constants/signature.mjs";
import { useGridEvent } from "../../utils/useGridEvent.mjs";
import { getVisibleRows } from "../../utils/useGridVisibleRows.mjs";
import { gridSortedRowIdsSelector } from "../sorting/gridSortingSelector.mjs";
import { gridFilteredRowsLookupSelector } from "../filter/gridFilterSelector.mjs";
import { getTreeNodeDescendants, createRowsInternalCache, getRowsStateFromCache, isAutogeneratedRowNode, GRID_ROOT_GROUP_ID, GRID_ID_AUTOGENERATED, updateCacheWithNewRows, getTopLevelRowCount, getRowIdFromRowModel, computeRowsUpdates } from "./gridRowsUtils.mjs";
import { useGridRegisterPipeApplier } from "../../core/pipeProcessing/index.mjs";
import { GridStrategyGroup } from "../../core/strategyProcessing/index.mjs";
import { gridPivotActiveSelector } from "../pivoting/index.mjs";
export const rowsStateInitializer = (state, props, apiRef) => {
const isDataSourceAvailable = !!props.dataSource;
apiRef.current.caches.rows = createRowsInternalCache({
rows: isDataSourceAvailable ? [] : props.rows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
});
return _extends({}, state, {
rows: getRowsStateFromCache({
apiRef,
rowCountProp: props.rowCount,
loadingProp: isDataSourceAvailable ? true : props.loading,
previousTree: null,
previousTreeDepths: null
})
});
};
export const useGridRows = (apiRef, props, configuration) => {
if (process.env.NODE_ENV !== 'production') {
try {
// Freeze the `rows` prop so developers have a fast failure if they try to use Array.prototype.push().
Object.freeze(props.rows);
} catch (error) {
// Sometimes, it's impossible to freeze, so we give up on it.
}
}
const logger = useGridLogger(apiRef, 'useGridRows');
const lastUpdateMs = React.useRef(Date.now());
const lastRowCount = React.useRef(props.rowCount);
const timeout = useTimeout();
// Get overridable methods from configuration
const {
setRowIndex,
setRowPosition
} = configuration.hooks.useGridRowsOverridableMethods(apiRef, props);
const getRow = React.useCallback(id => {
const model = gridRowsLookupSelector(apiRef)[id];
if (model) {
return model;
}
const node = gridRowNodeSelector(apiRef, id);
if (node && isAutogeneratedRowNode(node)) {
return {
[GRID_ID_AUTOGENERATED]: id
};
}
return null;
}, [apiRef]);
const getRowId = React.useCallback(row => gridRowIdSelector(apiRef, row), [apiRef]);
const throttledRowsChange = React.useCallback(({
cache,
throttle
}) => {
const run = () => {
lastUpdateMs.current = Date.now();
apiRef.current.setState(state => _extends({}, state, {
rows: getRowsStateFromCache({
apiRef,
rowCountProp: props.rowCount,
loadingProp: props.loading,
previousTree: gridRowTreeSelector(apiRef),
previousTreeDepths: gridRowTreeDepthsSelector(apiRef),
previousGroupsToFetch: gridRowGroupsToFetchSelector(apiRef)
})
}));
apiRef.current.publishEvent('rowsSet');
};
timeout.clear();
apiRef.current.caches.rows = cache;
if (!throttle) {
run();
return;
}
const throttleRemainingTimeMs = props.throttleRowsMs - (Date.now() - lastUpdateMs.current);
if (throttleRemainingTimeMs > 0) {
timeout.start(throttleRemainingTimeMs, run);
return;
}
run();
}, [props.throttleRowsMs, props.rowCount, props.loading, apiRef, timeout]);
/**
* API METHODS
*/
const setRows = React.useCallback(rows => {
logger.debug(`Updating all rows, new length ${rows.length}`);
if (!props.dataSource && gridPivotActiveSelector(apiRef)) {
apiRef.current.updateNonPivotRows(rows, false);
return;
}
const cache = createRowsInternalCache({
rows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
});
const prevCache = apiRef.current.caches.rows;
cache.rowsBeforePartialUpdates = prevCache.rowsBeforePartialUpdates;
throttledRowsChange({
cache,
throttle: true
});
}, [logger, props.getRowId, props.dataSource, props.loading, props.rowCount, throttledRowsChange, apiRef]);
const updateRows = React.useCallback(updates => {
if (props.signature === GridSignature.DataGrid && updates.length > 1) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: You cannot update several rows at once in \`apiRef.current.updateRows\` on the DataGrid.
You need to upgrade to DataGridPro or DataGridPremium component to unlock this feature.` : _formatErrorMessage(88));
}
if (!props.dataSource && gridPivotActiveSelector(apiRef)) {
apiRef.current.updateNonPivotRows(updates);
return;
}
const nonPinnedRowsUpdates = computeRowsUpdates(apiRef, updates, props.getRowId);
const cache = updateCacheWithNewRows({
updates: nonPinnedRowsUpdates,
getRowId: props.getRowId,
previousCache: apiRef.current.caches.rows
});
throttledRowsChange({
cache,
throttle: true
});
}, [props.signature, props.dataSource, props.getRowId, throttledRowsChange, apiRef]);
const updateNestedRows = React.useCallback((updates, groupKeys) => {
const nonPinnedRowsUpdates = computeRowsUpdates(apiRef, updates, props.getRowId);
const cache = updateCacheWithNewRows({
updates: nonPinnedRowsUpdates,
getRowId: props.getRowId,
previousCache: apiRef.current.caches.rows,
groupKeys: groupKeys ?? []
});
throttledRowsChange({
cache,
throttle: false
});
}, [props.getRowId, throttledRowsChange, apiRef]);
const setLoading = React.useCallback(loading => {
logger.debug(`Setting loading to ${loading}`);
apiRef.current.setState(state => _extends({}, state, {
rows: _extends({}, state.rows, {
loading
})
}));
apiRef.current.caches.rows.loadingPropBeforePartialUpdates = loading;
}, [apiRef, logger]);
const getRowModels = React.useCallback(() => {
const dataRows = gridDataRowIdsSelector(apiRef);
const idRowsLookup = gridRowsLookupSelector(apiRef);
return new Map(dataRows.map(id => [id, idRowsLookup[id] ?? {}]));
}, [apiRef]);
const getRowsCount = React.useCallback(() => gridRowCountSelector(apiRef), [apiRef]);
const getAllRowIds = React.useCallback(() => gridDataRowIdsSelector(apiRef), [apiRef]);
const getRowIndexRelativeToVisibleRows = React.useCallback(id => {
const {
rowIdToIndexMap
} = getVisibleRows(apiRef);
return rowIdToIndexMap.get(id);
}, [apiRef]);
const setRowChildrenExpansion = React.useCallback((id, isExpanded) => {
const currentNode = gridRowNodeSelector(apiRef, id);
if (!currentNode) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No row with id #${id} found.` : _formatErrorMessage(89, id));
}
if (currentNode.type !== 'group') {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: Only group nodes can be expanded or collapsed.' : _formatErrorMessage(90));
}
const newNode = _extends({}, currentNode, {
childrenExpanded: isExpanded
});
apiRef.current.setState(state => {
return _extends({}, state, {
rows: _extends({}, state.rows, {
tree: _extends({}, state.rows.tree, {
[id]: newNode
})
})
});
});
apiRef.current.publishEvent('rowExpansionChange', newNode);
}, [apiRef]);
const expandAllRows = React.useCallback(() => {
const tree = _extends({}, gridRowTreeSelector(apiRef));
const traverse = nodeId => {
const node = tree[nodeId];
if (node?.type === 'group') {
tree[nodeId] = _extends({}, node, {
childrenExpanded: true
});
node.children.forEach(traverse);
}
};
traverse(GRID_ROOT_GROUP_ID);
apiRef.current.setState(state => _extends({}, state, {
rows: _extends({}, state.rows, {
tree
})
}));
apiRef.current.publishEvent('rowExpansionChange', tree[GRID_ROOT_GROUP_ID]);
}, [apiRef]);
const collapseAllRows = React.useCallback(() => {
const tree = _extends({}, gridRowTreeSelector(apiRef));
const traverse = nodeId => {
const node = tree[nodeId];
if (node?.type === 'group') {
tree[nodeId] = _extends({}, node, {
childrenExpanded: false
});
node.children.forEach(traverse);
}
};
traverse(GRID_ROOT_GROUP_ID);
apiRef.current.setState(state => _extends({}, state, {
rows: _extends({}, state.rows, {
tree
})
}));
apiRef.current.publishEvent('rowExpansionChange', tree[GRID_ROOT_GROUP_ID]);
}, [apiRef]);
const getRowNode = React.useCallback(id => gridRowNodeSelector(apiRef, id) ?? null, [apiRef]);
const getRowGroupChildren = React.useCallback(({
skipAutoGeneratedRows = true,
groupId,
applySorting,
applyFiltering,
directChildrenOnly = false
}) => {
const tree = gridRowTreeSelector(apiRef);
let children;
if (applySorting) {
const groupNode = tree[groupId];
if (!groupNode) {
return [];
}
const sortedRowIds = gridSortedRowIdsSelector(apiRef);
children = [];
const startIndex = sortedRowIds.findIndex(id => id === groupId) + 1;
for (let index = startIndex; index < sortedRowIds.length && (directChildrenOnly ? tree[sortedRowIds[index]].depth === groupNode.depth + 1 : tree[sortedRowIds[index]].depth > groupNode.depth); index += 1) {
const id = sortedRowIds[index];
if (!skipAutoGeneratedRows || !isAutogeneratedRowNode(tree[id])) {
children.push(id);
}
}
} else {
children = getTreeNodeDescendants(tree, groupId, skipAutoGeneratedRows, directChildrenOnly);
}
if (applyFiltering) {
const filteredRowsLookup = gridFilteredRowsLookupSelector(apiRef);
children = isObjectEmpty(filteredRowsLookup) ? children : children.filter(childId => filteredRowsLookup[childId] !== false);
}
return children;
}, [apiRef]);
const replaceRows = React.useCallback((firstRowToRender, newRows) => {
if (props.signature === GridSignature.DataGrid && newRows.length > 1) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: You cannot replace rows using \`apiRef.current.unstable_replaceRows\` on the DataGrid.
You need to upgrade to DataGridPro or DataGridPremium component to unlock this feature.` : _formatErrorMessage(91));
}
if (newRows.length === 0) {
return;
}
const treeDepth = gridRowMaximumTreeDepthSelector(apiRef);
if (treeDepth > 1) {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: `apiRef.current.unstable_replaceRows` is not compatible with tree data and row grouping' : _formatErrorMessage(92));
}
const tree = _extends({}, gridRowTreeSelector(apiRef));
const dataRowIdToModelLookup = _extends({}, gridRowsLookupSelector(apiRef));
const rootGroup = tree[GRID_ROOT_GROUP_ID];
const rootGroupChildren = [...rootGroup.children];
const seenIds = new Set();
for (let i = 0; i < newRows.length; i += 1) {
const rowModel = newRows[i];
const rowId = getRowIdFromRowModel(rowModel, props.getRowId, 'A row was provided without id when calling replaceRows().');
const [removedRowId] = rootGroupChildren.splice(firstRowToRender + i, 1, rowId);
if (!seenIds.has(removedRowId)) {
delete dataRowIdToModelLookup[removedRowId];
delete tree[removedRowId];
}
const rowTreeNodeConfig = {
id: rowId,
depth: 0,
parent: GRID_ROOT_GROUP_ID,
type: 'leaf',
groupingKey: null
};
dataRowIdToModelLookup[rowId] = rowModel;
tree[rowId] = rowTreeNodeConfig;
seenIds.add(rowId);
}
tree[GRID_ROOT_GROUP_ID] = _extends({}, rootGroup, {
children: rootGroupChildren
});
// Removes potential remaining skeleton rows from the dataRowIds.
const dataRowIds = rootGroupChildren.filter(childId => tree[childId]?.type === 'leaf');
apiRef.current.caches.rows.dataRowIdToModelLookup = dataRowIdToModelLookup;
apiRef.current.setState(state => _extends({}, state, {
rows: _extends({}, state.rows, {
loading: props.loading,
totalRowCount: Math.max(props.rowCount || 0, rootGroupChildren.length),
dataRowIdToModelLookup,
dataRowIds,
tree
})
}));
apiRef.current.publishEvent('rowsSet');
}, [apiRef, props.signature, props.getRowId, props.loading, props.rowCount]);
const rowApi = {
getRow,
setLoading,
getRowId,
getRowModels,
getRowsCount,
getAllRowIds,
setRows,
updateRows,
getRowNode,
getRowIndexRelativeToVisibleRows,
unstable_replaceRows: replaceRows
};
const rowProApi = {
setRowIndex,
setRowPosition,
setRowChildrenExpansion,
getRowGroupChildren,
expandAllRows,
collapseAllRows
};
const rowProPrivateApi = {
updateNestedRows
};
/**
* EVENTS
*/
const groupRows = React.useCallback(() => {
logger.info(`Row grouping pre-processing have changed, regenerating the row tree`);
let cache;
if (apiRef.current.caches.rows.rowsBeforePartialUpdates === props.rows) {
// The `props.rows` did not change since the last row grouping
// We can use the current rows cache which contains the partial updates done recently.
cache = _extends({}, apiRef.current.caches.rows, {
updates: {
type: 'full',
rows: gridDataRowIdsSelector(apiRef)
}
});
} else {
// The `props.rows` has changed since the last row grouping
// We must use the new `props.rows` on the new grouping
// This occurs because this event is triggered before the `useEffect` on the rows when both the grouping pre-processing and the rows changes on the same render
cache = createRowsInternalCache({
rows: props.rows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
});
}
throttledRowsChange({
cache,
throttle: false
});
}, [logger, apiRef, props.rows, props.getRowId, props.loading, props.rowCount, throttledRowsChange]);
const previousDataSource = useLazyRef(() => props.dataSource);
const handleStrategyProcessorChange = React.useCallback(methodName => {
if (props.dataSource && props.dataSource !== previousDataSource.current) {
previousDataSource.current = props.dataSource;
return;
}
if (methodName === 'rowTreeCreation') {
groupRows();
}
}, [groupRows, previousDataSource, props.dataSource]);
const handleStrategyActivityChange = React.useCallback(() => {
// `rowTreeCreation` is the only processor ran when `strategyAvailabilityChange` is fired.
// All the other processors listen to `rowsSet` which will be published by the `groupRows` method below.
if (apiRef.current.getActiveStrategy(GridStrategyGroup.RowTree) !== gridRowGroupingNameSelector(apiRef)) {
groupRows();
}
}, [apiRef, groupRows]);
useGridEvent(apiRef, 'activeStrategyProcessorChange', handleStrategyProcessorChange);
useGridEvent(apiRef, 'strategyAvailabilityChange', handleStrategyActivityChange);
/**
* APPLIERS
*/
const applyHydrateRowsProcessor = React.useCallback(() => {
apiRef.current.setState(state => {
const response = apiRef.current.unstable_applyPipeProcessors('hydrateRows', {
tree: gridRowTreeSelector(apiRef),
treeDepths: gridRowTreeDepthsSelector(apiRef),
dataRowIds: gridDataRowIdsSelector(apiRef),
dataRowIdToModelLookup: gridRowsLookupSelector(apiRef)
});
return _extends({}, state, {
rows: _extends({}, state.rows, response, {
totalTopLevelRowCount: getTopLevelRowCount({
tree: response.tree,
rowCountProp: props.rowCount
})
})
});
});
apiRef.current.publishEvent('rowsSet');
}, [apiRef, props.rowCount]);
useGridRegisterPipeApplier(apiRef, 'hydrateRows', applyHydrateRowsProcessor);
useGridApiMethod(apiRef, rowApi, 'public');
useGridApiMethod(apiRef, rowProApi, props.signature === GridSignature.DataGrid ? 'private' : 'public');
useGridApiMethod(apiRef, rowProPrivateApi, 'private');
// The effect do not track any value defined synchronously during the 1st render by hooks called after `useGridRows`
// As a consequence, the state generated by the 1st run of this useEffect will always be equal to the initialization one
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}
let isRowCountPropUpdated = false;
if (props.rowCount !== lastRowCount.current) {
isRowCountPropUpdated = true;
lastRowCount.current = props.rowCount;
}
const currentRows = props.dataSource ? gridDataRowsSelector(apiRef) : props.rows;
const areNewRowsAlreadyInState = apiRef.current.caches.rows.rowsBeforePartialUpdates === currentRows;
const isNewLoadingAlreadyInState = apiRef.current.caches.rows.loadingPropBeforePartialUpdates === props.loading;
const isNewRowCountAlreadyInState = apiRef.current.caches.rows.rowCountPropBeforePartialUpdates === props.rowCount;
// The new rows have already been applied (most likely in the `'rowGroupsPreProcessingChange'` listener)
if (areNewRowsAlreadyInState) {
// If the loading prop has changed, we need to update its value in the state because it won't be done by `throttledRowsChange`
if (!isNewLoadingAlreadyInState) {
apiRef.current.setState(state => _extends({}, state, {
rows: _extends({}, state.rows, {
loading: props.loading
})
}));
apiRef.current.caches.rows.loadingPropBeforePartialUpdates = props.loading;
}
if (!isNewRowCountAlreadyInState) {
apiRef.current.setState(state => _extends({}, state, {
rows: _extends({}, state.rows, {
totalRowCount: Math.max(props.rowCount || 0, state.rows.totalRowCount),
totalTopLevelRowCount: Math.max(props.rowCount || 0, state.rows.totalTopLevelRowCount)
})
}));
apiRef.current.caches.rows.rowCountPropBeforePartialUpdates = props.rowCount;
}
if (!isRowCountPropUpdated) {
return;
}
}
logger.debug(`Updating all rows, new length ${currentRows?.length}`);
throttledRowsChange({
cache: createRowsInternalCache({
rows: currentRows,
getRowId: props.getRowId,
loading: props.loading,
rowCount: props.rowCount
}),
throttle: false
});
}, [props.rows, props.rowCount, props.getRowId, props.loading, props.dataSource, logger, throttledRowsChange, apiRef]);
};
@@ -0,0 +1,10 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.mjs";
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.mjs";
import type { GridStateInitializer } from "../../utils/useGridInitializeState.mjs";
export declare const rowsMetaStateInitializer: GridStateInitializer;
/**
* @requires useGridPageSize (method)
* @requires useGridPage (method)
*/
export declare const useGridRowsMeta: (apiRef: RefObject<GridPrivateApiCommunity>, _props: Pick<DataGridProcessedProps, 'getRowHeight' | 'getEstimatedRowHeight' | 'getRowSpacing' | 'pagination' | 'paginationMode' | 'rowHeight'>) => void;
@@ -0,0 +1,10 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.js";
import type { DataGridProcessedProps } from "../../../models/props/DataGridProps.js";
import type { GridStateInitializer } from "../../utils/useGridInitializeState.js";
export declare const rowsMetaStateInitializer: GridStateInitializer;
/**
* @requires useGridPageSize (method)
* @requires useGridPage (method)
*/
export declare const useGridRowsMeta: (apiRef: RefObject<GridPrivateApiCommunity>, _props: Pick<DataGridProcessedProps, 'getRowHeight' | 'getEstimatedRowHeight' | 'getRowSpacing' | 'pagination' | 'paginationMode' | 'rowHeight'>) => void;
@@ -0,0 +1,69 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridRowsMeta = exports.rowsMetaStateInitializer = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _useGridApiMethod = require("../../utils/useGridApiMethod");
var _gridPaginationSelector = require("../pagination/gridPaginationSelector");
var _pipeProcessing = require("../../core/pipeProcessing");
var _gridRowsSelector = require("./gridRowsSelector");
var _gridDimensionsSelectors = require("../dimensions/gridDimensionsSelectors");
const rowsMetaStateInitializer = (state, props, apiRef) => {
// FIXME: This should be handled in the virtualizer eventually, but there are interdependencies
// between state initializers that need to be untangled carefully.
const baseRowHeight = (0, _gridDimensionsSelectors.gridRowHeightSelector)(apiRef);
const dataRowCount = (0, _gridRowsSelector.gridRowCountSelector)(apiRef);
const pagination = (0, _gridPaginationSelector.gridPaginationSelector)(apiRef);
const rowCount = Math.min(pagination.enabled ? pagination.paginationModel.pageSize : dataRowCount, dataRowCount);
return (0, _extends2.default)({}, state, {
rowsMeta: {
currentPageTotalHeight: rowCount * baseRowHeight,
positions: Array.from({
length: rowCount
}, (_, i) => i * baseRowHeight),
pinnedTopRowsTotalHeight: 0,
pinnedBottomRowsTotalHeight: 0
}
});
};
/**
* @requires useGridPageSize (method)
* @requires useGridPage (method)
*/
exports.rowsMetaStateInitializer = rowsMetaStateInitializer;
const useGridRowsMeta = (apiRef, _props) => {
const virtualizer = apiRef.current.virtualizer;
const {
getRowHeight,
setLastMeasuredRowIndex,
storeRowHeightMeasurement,
resetRowHeights,
hydrateRowsMeta,
observeRowHeight,
rowHasAutoHeight,
getRowHeightEntry,
getLastMeasuredRowIndex
} = virtualizer.api.rowsMeta;
(0, _pipeProcessing.useGridRegisterPipeApplier)(apiRef, 'rowHeight', hydrateRowsMeta);
const rowsMetaApi = {
unstable_getRowHeight: getRowHeight,
unstable_setLastMeasuredRowIndex: setLastMeasuredRowIndex,
unstable_storeRowHeightMeasurement: storeRowHeightMeasurement,
resetRowHeights
};
const rowsMetaPrivateApi = {
hydrateRowsMeta,
observeRowHeight,
rowHasAutoHeight,
getRowHeightEntry,
getLastMeasuredRowIndex
};
(0, _useGridApiMethod.useGridApiMethod)(apiRef, rowsMetaApi, 'public');
(0, _useGridApiMethod.useGridApiMethod)(apiRef, rowsMetaPrivateApi, 'private');
};
exports.useGridRowsMeta = useGridRowsMeta;
@@ -0,0 +1,60 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import { useGridApiMethod } from "../../utils/useGridApiMethod.mjs";
import { gridPaginationSelector } from "../pagination/gridPaginationSelector.mjs";
import { useGridRegisterPipeApplier } from "../../core/pipeProcessing/index.mjs";
import { gridRowCountSelector } from "./gridRowsSelector.mjs";
import { gridRowHeightSelector } from "../dimensions/gridDimensionsSelectors.mjs";
export const rowsMetaStateInitializer = (state, props, apiRef) => {
// FIXME: This should be handled in the virtualizer eventually, but there are interdependencies
// between state initializers that need to be untangled carefully.
const baseRowHeight = gridRowHeightSelector(apiRef);
const dataRowCount = gridRowCountSelector(apiRef);
const pagination = gridPaginationSelector(apiRef);
const rowCount = Math.min(pagination.enabled ? pagination.paginationModel.pageSize : dataRowCount, dataRowCount);
return _extends({}, state, {
rowsMeta: {
currentPageTotalHeight: rowCount * baseRowHeight,
positions: Array.from({
length: rowCount
}, (_, i) => i * baseRowHeight),
pinnedTopRowsTotalHeight: 0,
pinnedBottomRowsTotalHeight: 0
}
});
};
/**
* @requires useGridPageSize (method)
* @requires useGridPage (method)
*/
export const useGridRowsMeta = (apiRef, _props) => {
const virtualizer = apiRef.current.virtualizer;
const {
getRowHeight,
setLastMeasuredRowIndex,
storeRowHeightMeasurement,
resetRowHeights,
hydrateRowsMeta,
observeRowHeight,
rowHasAutoHeight,
getRowHeightEntry,
getLastMeasuredRowIndex
} = virtualizer.api.rowsMeta;
useGridRegisterPipeApplier(apiRef, 'rowHeight', hydrateRowsMeta);
const rowsMetaApi = {
unstable_getRowHeight: getRowHeight,
unstable_setLastMeasuredRowIndex: setLastMeasuredRowIndex,
unstable_storeRowHeightMeasurement: storeRowHeightMeasurement,
resetRowHeights
};
const rowsMetaPrivateApi = {
hydrateRowsMeta,
observeRowHeight,
rowHasAutoHeight,
getRowHeightEntry,
getLastMeasuredRowIndex
};
useGridApiMethod(apiRef, rowsMetaApi, 'public');
useGridApiMethod(apiRef, rowsMetaPrivateApi, 'private');
};
@@ -0,0 +1,7 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridRowId } from "../../../models/gridRows.mjs";
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.mjs";
export declare const useGridRowsOverridableMethods: (apiRef: RefObject<GridPrivateApiCommunity>) => {
setRowIndex: (rowId: GridRowId, targetIndex: number) => void;
setRowPosition: (sourceRowId: GridRowId, targetRowId: GridRowId, position: import("../../../internals/index.mjs").RowReorderDropPosition) => void | Promise<void>;
};
@@ -0,0 +1,7 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridRowId } from "../../../models/gridRows.js";
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.js";
export declare const useGridRowsOverridableMethods: (apiRef: RefObject<GridPrivateApiCommunity>) => {
setRowIndex: (rowId: GridRowId, targetIndex: number) => void;
setRowPosition: (sourceRowId: GridRowId, targetRowId: GridRowId, position: import("../../../internals/index.js").RowReorderDropPosition) => void | Promise<void>;
};
@@ -0,0 +1,125 @@
"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.useGridRowsOverridableMethods = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _formatErrorMessage2 = _interopRequireDefault(require("@mui/x-internals/formatErrorMessage"));
var React = _interopRequireWildcard(require("react"));
var _gridRowsSelector = require("./gridRowsSelector");
var _gridFilterSelector = require("../filter/gridFilterSelector");
var _gridRowsUtils = require("./gridRowsUtils");
const useGridRowsOverridableMethods = apiRef => {
const setRowPosition = React.useCallback((sourceRowId, targetRowId, position) => {
const sourceNode = (0, _gridRowsSelector.gridRowNodeSelector)(apiRef, sourceRowId);
const targetNode = (0, _gridRowsSelector.gridRowNodeSelector)(apiRef, targetRowId);
if (!sourceNode) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No row with id #${sourceRowId} found.` : (0, _formatErrorMessage2.default)(89, sourceRowId));
}
if (!targetNode) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No row with id #${targetRowId} found.` : (0, _formatErrorMessage2.default)(89, targetRowId));
}
if (sourceNode.type !== 'leaf') {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: The row reordering does not support reordering of footer or grouping rows.` : (0, _formatErrorMessage2.default)(93));
}
if (position === 'inside') {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: The 'inside' position is only supported for tree data. Use 'above' or 'below' for flat data.` : (0, _formatErrorMessage2.default)(94));
}
// Resolve positions in the filtered view to detect visible-order no-ops.
const sortedFilteredRowIndexLookup = (0, _gridFilterSelector.gridExpandedSortedRowIndexLookupSelector)(apiRef);
const targetFilteredIndex = sortedFilteredRowIndexLookup[targetRowId];
const sourceFilteredIndex = sortedFilteredRowIndexLookup[sourceRowId];
if (targetFilteredIndex === undefined) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: Target row with id #${targetRowId} not found in current view.` : (0, _formatErrorMessage2.default)(95, targetRowId));
}
if (sourceFilteredIndex === undefined) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: Source row with id #${sourceRowId} not found in current view.` : (0, _formatErrorMessage2.default)(96, sourceRowId));
}
// No-op when the requested drop would not change the visible order.
// Mutating the backing tree here would silently reshuffle filtered-out
// rows around the source without any visible feedback.
if (sourceFilteredIndex === targetFilteredIndex || position === 'above' && sourceFilteredIndex === targetFilteredIndex - 1 || position === 'below' && sourceFilteredIndex === targetFilteredIndex + 1) {
return;
}
apiRef.current.setState(state => {
const group = (0, _gridRowsSelector.gridRowTreeSelector)(apiRef)[_gridRowsUtils.GRID_ROOT_GROUP_ID];
const allRows = group.children;
// Single pass: skip source and inline-insert it adjacent to the target
// anchor id so filtered-out rows between source and target keep their
// position next to the anchor.
const updatedRows = [];
let sourceFound = false;
let targetFound = false;
for (let i = 0; i < allRows.length; i += 1) {
const id = allRows[i];
if (id === sourceRowId) {
sourceFound = true;
continue;
}
if (id === targetRowId) {
targetFound = true;
if (position === 'above') {
updatedRows.push(sourceRowId, id);
} else {
updatedRows.push(id, sourceRowId);
}
continue;
}
updatedRows.push(id);
}
if (!sourceFound || !targetFound) {
return state;
}
return (0, _extends2.default)({}, state, {
rows: (0, _extends2.default)({}, state.rows, {
tree: (0, _extends2.default)({}, state.rows.tree, {
[_gridRowsUtils.GRID_ROOT_GROUP_ID]: (0, _extends2.default)({}, group, {
children: updatedRows
})
})
})
});
});
apiRef.current.publishEvent('rowsSet');
}, [apiRef]);
const setRowIndex = React.useCallback((rowId, targetIndex) => {
const node = (0, _gridRowsSelector.gridRowNodeSelector)(apiRef, rowId);
if (!node) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X Data Grid: No row with id "${rowId}" found. ` + 'The row to reorder does not exist in the grid. ' + 'Verify the row id is correct and the row exists.' : (0, _formatErrorMessage2.default)(97, rowId));
}
if (node.type !== 'leaf') {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X Data Grid: Row reordering does not support reordering of footer or grouping rows. ' + 'Only leaf (data) rows can be reordered. ' + 'Ensure you are only reordering data rows.' : (0, _formatErrorMessage2.default)(98));
}
apiRef.current.setState(state => {
const group = (0, _gridRowsSelector.gridRowTreeSelector)(apiRef)[_gridRowsUtils.GRID_ROOT_GROUP_ID];
const allRows = group.children;
const oldIndex = allRows.findIndex(row => row === rowId);
if (oldIndex === -1 || oldIndex === targetIndex) {
return state;
}
const updatedRows = [...allRows];
updatedRows.splice(targetIndex, 0, updatedRows.splice(oldIndex, 1)[0]);
return (0, _extends2.default)({}, state, {
rows: (0, _extends2.default)({}, state.rows, {
tree: (0, _extends2.default)({}, state.rows.tree, {
[_gridRowsUtils.GRID_ROOT_GROUP_ID]: (0, _extends2.default)({}, group, {
children: updatedRows
})
})
})
});
});
apiRef.current.publishEvent('rowsSet');
}, [apiRef]);
return {
setRowIndex,
setRowPosition
};
};
exports.useGridRowsOverridableMethods = useGridRowsOverridableMethods;
@@ -0,0 +1,116 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import * as React from 'react';
import { gridRowTreeSelector, gridRowNodeSelector } from "./gridRowsSelector.mjs";
import { gridExpandedSortedRowIndexLookupSelector } from "../filter/gridFilterSelector.mjs";
import { GRID_ROOT_GROUP_ID } from "./gridRowsUtils.mjs";
export const useGridRowsOverridableMethods = apiRef => {
const setRowPosition = React.useCallback((sourceRowId, targetRowId, position) => {
const sourceNode = gridRowNodeSelector(apiRef, sourceRowId);
const targetNode = gridRowNodeSelector(apiRef, targetRowId);
if (!sourceNode) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No row with id #${sourceRowId} found.` : _formatErrorMessage(89, sourceRowId));
}
if (!targetNode) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: No row with id #${targetRowId} found.` : _formatErrorMessage(89, targetRowId));
}
if (sourceNode.type !== 'leaf') {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: The row reordering does not support reordering of footer or grouping rows.` : _formatErrorMessage(93));
}
if (position === 'inside') {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: The 'inside' position is only supported for tree data. Use 'above' or 'below' for flat data.` : _formatErrorMessage(94));
}
// Resolve positions in the filtered view to detect visible-order no-ops.
const sortedFilteredRowIndexLookup = gridExpandedSortedRowIndexLookupSelector(apiRef);
const targetFilteredIndex = sortedFilteredRowIndexLookup[targetRowId];
const sourceFilteredIndex = sortedFilteredRowIndexLookup[sourceRowId];
if (targetFilteredIndex === undefined) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: Target row with id #${targetRowId} not found in current view.` : _formatErrorMessage(95, targetRowId));
}
if (sourceFilteredIndex === undefined) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X: Source row with id #${sourceRowId} not found in current view.` : _formatErrorMessage(96, sourceRowId));
}
// No-op when the requested drop would not change the visible order.
// Mutating the backing tree here would silently reshuffle filtered-out
// rows around the source without any visible feedback.
if (sourceFilteredIndex === targetFilteredIndex || position === 'above' && sourceFilteredIndex === targetFilteredIndex - 1 || position === 'below' && sourceFilteredIndex === targetFilteredIndex + 1) {
return;
}
apiRef.current.setState(state => {
const group = gridRowTreeSelector(apiRef)[GRID_ROOT_GROUP_ID];
const allRows = group.children;
// Single pass: skip source and inline-insert it adjacent to the target
// anchor id so filtered-out rows between source and target keep their
// position next to the anchor.
const updatedRows = [];
let sourceFound = false;
let targetFound = false;
for (let i = 0; i < allRows.length; i += 1) {
const id = allRows[i];
if (id === sourceRowId) {
sourceFound = true;
continue;
}
if (id === targetRowId) {
targetFound = true;
if (position === 'above') {
updatedRows.push(sourceRowId, id);
} else {
updatedRows.push(id, sourceRowId);
}
continue;
}
updatedRows.push(id);
}
if (!sourceFound || !targetFound) {
return state;
}
return _extends({}, state, {
rows: _extends({}, state.rows, {
tree: _extends({}, state.rows.tree, {
[GRID_ROOT_GROUP_ID]: _extends({}, group, {
children: updatedRows
})
})
})
});
});
apiRef.current.publishEvent('rowsSet');
}, [apiRef]);
const setRowIndex = React.useCallback((rowId, targetIndex) => {
const node = gridRowNodeSelector(apiRef, rowId);
if (!node) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI X Data Grid: No row with id "${rowId}" found. ` + 'The row to reorder does not exist in the grid. ' + 'Verify the row id is correct and the row exists.' : _formatErrorMessage(97, rowId));
}
if (node.type !== 'leaf') {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X Data Grid: Row reordering does not support reordering of footer or grouping rows. ' + 'Only leaf (data) rows can be reordered. ' + 'Ensure you are only reordering data rows.' : _formatErrorMessage(98));
}
apiRef.current.setState(state => {
const group = gridRowTreeSelector(apiRef)[GRID_ROOT_GROUP_ID];
const allRows = group.children;
const oldIndex = allRows.findIndex(row => row === rowId);
if (oldIndex === -1 || oldIndex === targetIndex) {
return state;
}
const updatedRows = [...allRows];
updatedRows.splice(targetIndex, 0, updatedRows.splice(oldIndex, 1)[0]);
return _extends({}, state, {
rows: _extends({}, state.rows, {
tree: _extends({}, state.rows.tree, {
[GRID_ROOT_GROUP_ID]: _extends({}, group, {
children: updatedRows
})
})
})
});
});
apiRef.current.publishEvent('rowsSet');
}, [apiRef]);
return {
setRowIndex,
setRowPosition
};
};
@@ -0,0 +1,3 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.mjs";
export declare const useGridRowsPreProcessors: (apiRef: RefObject<GridPrivateApiCommunity>) => void;
@@ -0,0 +1,3 @@
import type { RefObject } from '@mui/x-internals/types';
import type { GridPrivateApiCommunity } from "../../../models/api/gridApiCommunity.js";
export declare const useGridRowsPreProcessors: (apiRef: RefObject<GridPrivateApiCommunity>) => void;
@@ -0,0 +1,89 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useGridRowsPreProcessors = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _strategyProcessing = require("../../core/strategyProcessing");
var _gridRowsUtils = require("./gridRowsUtils");
const createFlatRowTree = rows => {
const tree = {
[_gridRowsUtils.GRID_ROOT_GROUP_ID]: (0, _extends2.default)({}, (0, _gridRowsUtils.buildRootGroup)(), {
children: rows
})
};
for (let i = 0; i < rows.length; i += 1) {
const rowId = rows[i];
tree[rowId] = {
id: rowId,
depth: 0,
parent: _gridRowsUtils.GRID_ROOT_GROUP_ID,
type: 'leaf',
groupingKey: null
};
}
return {
groupingName: _strategyProcessing.GRID_DEFAULT_STRATEGY,
tree,
treeDepths: {
0: rows.length
},
dataRowIds: rows
};
};
const updateFlatRowTree = ({
previousTree,
actions
}) => {
const tree = (0, _extends2.default)({}, previousTree);
const idsToRemoveFromRootGroup = {};
for (let i = 0; i < actions.remove.length; i += 1) {
const idToDelete = actions.remove[i];
idsToRemoveFromRootGroup[idToDelete] = true;
delete tree[idToDelete];
}
for (let i = 0; i < actions.insert.length; i += 1) {
const idToInsert = actions.insert[i];
tree[idToInsert] = {
id: idToInsert,
depth: 0,
parent: _gridRowsUtils.GRID_ROOT_GROUP_ID,
type: 'leaf',
groupingKey: null
};
}
// TODO rows v6: Support row unpinning
const rootGroup = tree[_gridRowsUtils.GRID_ROOT_GROUP_ID];
let rootGroupChildren = [...rootGroup.children, ...actions.insert];
if (Object.values(idsToRemoveFromRootGroup).length) {
rootGroupChildren = rootGroupChildren.filter(id => !idsToRemoveFromRootGroup[id]);
}
tree[_gridRowsUtils.GRID_ROOT_GROUP_ID] = (0, _extends2.default)({}, rootGroup, {
children: rootGroupChildren
});
return {
groupingName: _strategyProcessing.GRID_DEFAULT_STRATEGY,
tree,
treeDepths: {
0: rootGroupChildren.length
},
dataRowIds: rootGroupChildren
};
};
const flatRowTreeCreationMethod = params => {
if (params.updates.type === 'full') {
return createFlatRowTree(params.updates.rows);
}
return updateFlatRowTree({
previousTree: params.previousTree,
actions: params.updates.actions
});
};
const useGridRowsPreProcessors = apiRef => {
(0, _strategyProcessing.useGridRegisterStrategyProcessor)(apiRef, _strategyProcessing.GRID_DEFAULT_STRATEGY, 'rowTreeCreation', flatRowTreeCreationMethod);
};
exports.useGridRowsPreProcessors = useGridRowsPreProcessors;
@@ -0,0 +1,81 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import { GRID_DEFAULT_STRATEGY, useGridRegisterStrategyProcessor } from "../../core/strategyProcessing/index.mjs";
import { buildRootGroup, GRID_ROOT_GROUP_ID } from "./gridRowsUtils.mjs";
const createFlatRowTree = rows => {
const tree = {
[GRID_ROOT_GROUP_ID]: _extends({}, buildRootGroup(), {
children: rows
})
};
for (let i = 0; i < rows.length; i += 1) {
const rowId = rows[i];
tree[rowId] = {
id: rowId,
depth: 0,
parent: GRID_ROOT_GROUP_ID,
type: 'leaf',
groupingKey: null
};
}
return {
groupingName: GRID_DEFAULT_STRATEGY,
tree,
treeDepths: {
0: rows.length
},
dataRowIds: rows
};
};
const updateFlatRowTree = ({
previousTree,
actions
}) => {
const tree = _extends({}, previousTree);
const idsToRemoveFromRootGroup = {};
for (let i = 0; i < actions.remove.length; i += 1) {
const idToDelete = actions.remove[i];
idsToRemoveFromRootGroup[idToDelete] = true;
delete tree[idToDelete];
}
for (let i = 0; i < actions.insert.length; i += 1) {
const idToInsert = actions.insert[i];
tree[idToInsert] = {
id: idToInsert,
depth: 0,
parent: GRID_ROOT_GROUP_ID,
type: 'leaf',
groupingKey: null
};
}
// TODO rows v6: Support row unpinning
const rootGroup = tree[GRID_ROOT_GROUP_ID];
let rootGroupChildren = [...rootGroup.children, ...actions.insert];
if (Object.values(idsToRemoveFromRootGroup).length) {
rootGroupChildren = rootGroupChildren.filter(id => !idsToRemoveFromRootGroup[id]);
}
tree[GRID_ROOT_GROUP_ID] = _extends({}, rootGroup, {
children: rootGroupChildren
});
return {
groupingName: GRID_DEFAULT_STRATEGY,
tree,
treeDepths: {
0: rootGroupChildren.length
},
dataRowIds: rootGroupChildren
};
};
const flatRowTreeCreationMethod = params => {
if (params.updates.type === 'full') {
return createFlatRowTree(params.updates.rows);
}
return updateFlatRowTree({
previousTree: params.previousTree,
actions: params.updates.actions
});
};
export const useGridRowsPreProcessors = apiRef => {
useGridRegisterStrategyProcessor(apiRef, GRID_DEFAULT_STRATEGY, 'rowTreeCreation', flatRowTreeCreationMethod);
};