@mui/x-data-grid-premium 8.10.2 → 8.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +214 -13
  2. package/DataGridPremium/DataGridPremium.js +6 -4
  3. package/DataGridPremium/useDataGridPremiumComponent.d.ts +2 -1
  4. package/DataGridPremium/useDataGridPremiumComponent.js +2 -2
  5. package/esm/DataGridPremium/DataGridPremium.js +6 -4
  6. package/esm/DataGridPremium/useDataGridPremiumComponent.d.ts +2 -1
  7. package/esm/DataGridPremium/useDataGridPremiumComponent.js +2 -2
  8. package/esm/hooks/features/aggregation/wrapColumnWithAggregation.d.ts +1 -0
  9. package/esm/hooks/features/clipboard/useGridClipboardImport.js +1 -1
  10. package/esm/hooks/features/export/serializer/setupExcelExportWebWorker.js +1 -2
  11. package/esm/hooks/features/rowGrouping/createGroupingColDef.d.ts +2 -1
  12. package/esm/hooks/features/rowGrouping/createGroupingColDef.js +31 -7
  13. package/esm/hooks/features/rowGrouping/gridRowGroupingInterfaces.d.ts +1 -0
  14. package/esm/hooks/features/rowGrouping/gridRowGroupingUtils.js +5 -1
  15. package/esm/hooks/features/rowGrouping/useGridRowGrouping.d.ts +1 -1
  16. package/esm/hooks/features/rowGrouping/useGridRowGrouping.js +48 -2
  17. package/esm/hooks/features/rowReorder/operations.d.ts +40 -0
  18. package/esm/hooks/features/rowReorder/operations.js +535 -0
  19. package/esm/hooks/features/rowReorder/reorderExecutor.d.ts +15 -0
  20. package/esm/hooks/features/rowReorder/reorderExecutor.js +25 -0
  21. package/esm/hooks/features/rowReorder/reorderValidator.d.ts +16 -0
  22. package/esm/hooks/features/rowReorder/reorderValidator.js +116 -0
  23. package/esm/hooks/features/rowReorder/types.d.ts +42 -0
  24. package/esm/hooks/features/rowReorder/types.js +1 -0
  25. package/esm/hooks/features/rowReorder/utils.d.ts +127 -0
  26. package/esm/hooks/features/rowReorder/utils.js +343 -0
  27. package/esm/hooks/features/rows/useGridRowsOverridableMethods.d.ts +7 -0
  28. package/esm/hooks/features/rows/useGridRowsOverridableMethods.js +52 -0
  29. package/esm/index.js +1 -1
  30. package/esm/models/gridGroupingValueSetter.d.ts +14 -0
  31. package/esm/models/gridGroupingValueSetter.js +1 -0
  32. package/esm/models/index.d.ts +1 -0
  33. package/esm/models/index.js +1 -0
  34. package/esm/typeOverloads/modules.d.ts +7 -1
  35. package/hooks/features/aggregation/wrapColumnWithAggregation.d.ts +1 -0
  36. package/hooks/features/clipboard/useGridClipboardImport.js +1 -1
  37. package/hooks/features/export/serializer/setupExcelExportWebWorker.js +1 -2
  38. package/hooks/features/rowGrouping/createGroupingColDef.d.ts +2 -1
  39. package/hooks/features/rowGrouping/createGroupingColDef.js +31 -7
  40. package/hooks/features/rowGrouping/gridRowGroupingInterfaces.d.ts +1 -0
  41. package/hooks/features/rowGrouping/gridRowGroupingUtils.js +5 -1
  42. package/hooks/features/rowGrouping/useGridRowGrouping.d.ts +1 -1
  43. package/hooks/features/rowGrouping/useGridRowGrouping.js +46 -0
  44. package/hooks/features/rowReorder/operations.d.ts +40 -0
  45. package/hooks/features/rowReorder/operations.js +546 -0
  46. package/hooks/features/rowReorder/reorderExecutor.d.ts +15 -0
  47. package/hooks/features/rowReorder/reorderExecutor.js +31 -0
  48. package/hooks/features/rowReorder/reorderValidator.d.ts +16 -0
  49. package/hooks/features/rowReorder/reorderValidator.js +122 -0
  50. package/hooks/features/rowReorder/types.d.ts +42 -0
  51. package/hooks/features/rowReorder/types.js +5 -0
  52. package/hooks/features/rowReorder/utils.d.ts +127 -0
  53. package/hooks/features/rowReorder/utils.js +360 -0
  54. package/hooks/features/rows/useGridRowsOverridableMethods.d.ts +7 -0
  55. package/hooks/features/rows/useGridRowsOverridableMethods.js +60 -0
  56. package/index.js +1 -1
  57. package/models/gridGroupingValueSetter.d.ts +14 -0
  58. package/models/gridGroupingValueSetter.js +5 -0
  59. package/models/index.d.ts +1 -0
  60. package/models/index.js +11 -0
  61. package/package.json +14 -14
  62. package/typeOverloads/modules.d.ts +7 -1
@@ -0,0 +1,16 @@
1
+ import { ReorderValidationContext } from "./types.js";
2
+ interface ValidationRule {
3
+ name: string;
4
+ applies: (ctx: ReorderValidationContext) => boolean;
5
+ isInvalid: (ctx: ReorderValidationContext) => boolean;
6
+ message?: string;
7
+ }
8
+ declare class RowReorderValidator {
9
+ private rules;
10
+ constructor(rules?: ValidationRule[]);
11
+ addRule(rule: ValidationRule): void;
12
+ removeRule(ruleName: string): void;
13
+ validate(context: ReorderValidationContext): boolean;
14
+ }
15
+ export declare const rowGroupingReorderValidator: RowReorderValidator;
16
+ export {};
@@ -0,0 +1,116 @@
1
+ import { conditions } from "./utils.js";
2
+ const validationRules = [
3
+ // ===== Basic invalid cases =====
4
+ {
5
+ name: 'same-position',
6
+ applies: ctx => ctx.sourceRowIndex === ctx.targetRowIndex,
7
+ isInvalid: () => true,
8
+ message: 'Source and target are the same'
9
+ }, {
10
+ name: 'adjacent-position',
11
+ applies: ctx => conditions.isAdjacentPosition(ctx),
12
+ isInvalid: () => true,
13
+ message: 'Source and target are adjacent'
14
+ }, {
15
+ name: 'group-to-leaf',
16
+ applies: conditions.isGroupToLeaf,
17
+ isInvalid: () => true,
18
+ message: 'Cannot drop group on leaf'
19
+ },
20
+ // ===== Group to Group Rules =====
21
+ {
22
+ name: 'group-to-group-above-leaf-belongs-to-source',
23
+ applies: ctx => conditions.isGroupToGroup(ctx) && conditions.isDropAbove(ctx) && conditions.prevIsLeaf(ctx),
24
+ isInvalid: conditions.prevBelongsToSource,
25
+ message: 'Previous leaf belongs to source group or its descendants'
26
+ }, {
27
+ name: 'group-to-group-above-invalid-depth',
28
+ applies: ctx => conditions.isGroupToGroup(ctx) && conditions.isDropAbove(ctx) && !conditions.sameDepth(ctx) && !(ctx.targetNode.depth < ctx.sourceNode.depth && (conditions.prevIsLeaf(ctx) || conditions.prevIsGroup(ctx) && conditions.prevDepthEqualsSource(ctx))),
29
+ isInvalid: () => true,
30
+ message: 'Invalid depth configuration for group above group'
31
+ }, {
32
+ name: 'group-to-group-above-different-parent-depth',
33
+ applies: ctx => conditions.isGroupToGroup(ctx) && conditions.isDropAbove(ctx) && conditions.prevIsGroup(ctx) && conditions.prevDepthEqualsSource(ctx) && conditions.targetGroupExpanded(ctx),
34
+ isInvalid: ctx => ctx.prevNode.depth !== ctx.sourceNode.depth,
35
+ message: 'Cannot reorder groups with different depths'
36
+ }, {
37
+ name: 'group-to-group-below-invalid-config',
38
+ applies: ctx => conditions.isGroupToGroup(ctx) && conditions.isDropBelow(ctx),
39
+ isInvalid: ctx => {
40
+ // Valid case 1: Same depth and target not expanded
41
+ if (conditions.sameDepth(ctx) && conditions.targetGroupCollapsed(ctx)) {
42
+ return false;
43
+ }
44
+ // Valid case 2: Target is parent level, expanded, with compatible first child
45
+ if (conditions.targetDepthIsSourceMinusOne(ctx) && conditions.targetGroupExpanded(ctx) && conditions.targetFirstChildIsGroupWithSourceDepth(ctx)) {
46
+ return false;
47
+ }
48
+ return true;
49
+ },
50
+ message: 'Invalid group below group configuration'
51
+ },
52
+ // ===== Leaf to Leaf Rules =====
53
+ {
54
+ name: 'leaf-to-leaf-different-depth',
55
+ applies: ctx => conditions.isLeafToLeaf(ctx) && !conditions.sameDepth(ctx),
56
+ isInvalid: () => true,
57
+ message: 'Leaves at different depths cannot be reordered'
58
+ }, {
59
+ name: 'leaf-to-leaf-invalid-below',
60
+ applies: ctx => conditions.isLeafToLeaf(ctx) && conditions.sameDepth(ctx) && !conditions.sameParent(ctx) && conditions.isDropBelow(ctx),
61
+ isInvalid: ctx => !(conditions.nextIsGroup(ctx) && ctx.sourceNode.depth > ctx.nextNode.depth) && !conditions.nextIsLeaf(ctx),
62
+ message: 'Invalid leaf below leaf configuration'
63
+ },
64
+ // ===== Leaf to Group Rules =====
65
+ {
66
+ name: 'leaf-to-group-above-no-prev-leaf',
67
+ applies: ctx => conditions.isLeafToGroup(ctx) && conditions.isDropAbove(ctx),
68
+ isInvalid: ctx => !conditions.hasPrevNode(ctx) || !conditions.prevIsLeaf(ctx),
69
+ message: 'No valid previous leaf for leaf above group'
70
+ }, {
71
+ name: 'leaf-to-group-above-depth-mismatch',
72
+ applies: ctx => conditions.isLeafToGroup(ctx) && conditions.isDropAbove(ctx) && conditions.prevIsLeaf(ctx) && !(ctx.sourceNode.depth > ctx.targetNode.depth && ctx.targetNode.depth === 0),
73
+ isInvalid: ctx => ctx.prevNode.depth !== ctx.sourceNode.depth,
74
+ message: 'Previous node depth mismatch for leaf above group'
75
+ }, {
76
+ name: 'leaf-to-group-below-collapsed',
77
+ applies: ctx => conditions.isLeafToGroup(ctx) && conditions.isDropBelow(ctx),
78
+ isInvalid: conditions.targetGroupCollapsed,
79
+ message: 'Cannot drop below collapsed group'
80
+ }, {
81
+ name: 'leaf-to-group-below-invalid-depth',
82
+ applies: ctx => conditions.isLeafToGroup(ctx) && conditions.isDropBelow(ctx) && conditions.targetGroupExpanded(ctx),
83
+ isInvalid: ctx => {
84
+ // Valid case 1: Target is parent level
85
+ if (ctx.sourceNode.depth > ctx.targetNode.depth && ctx.targetNode.depth === ctx.sourceNode.depth - 1) {
86
+ return false;
87
+ }
88
+ // Valid case 2: First child has same depth as source
89
+ if (conditions.targetFirstChildDepthEqualsSource(ctx)) {
90
+ return false;
91
+ }
92
+ return true;
93
+ },
94
+ message: 'Invalid depth configuration for leaf below group'
95
+ }];
96
+ class RowReorderValidator {
97
+ constructor(rules = validationRules) {
98
+ this.rules = rules;
99
+ }
100
+ addRule(rule) {
101
+ this.rules.push(rule);
102
+ }
103
+ removeRule(ruleName) {
104
+ this.rules = this.rules.filter(r => r.name !== ruleName);
105
+ }
106
+ validate(context) {
107
+ // Check all validation rules
108
+ for (const rule of this.rules) {
109
+ if (rule.applies(context) && rule.isInvalid(context)) {
110
+ return false;
111
+ }
112
+ }
113
+ return true;
114
+ }
115
+ }
116
+ export const rowGroupingReorderValidator = new RowReorderValidator(validationRules);
@@ -0,0 +1,42 @@
1
+ import { GridRowId, GridTreeNode } from '@mui/x-data-grid-pro';
2
+ import type { GridRowTreeConfig } from '@mui/x-data-grid-pro';
3
+ import { RefObject } from '@mui/x-internals/types';
4
+ import { GridPrivateApiPremium } from "../../../models/gridApiPremium.js";
5
+ import { DataGridPremiumProcessedProps } from "../../../models/dataGridPremiumProps.js";
6
+ export type DropPosition = 'above' | 'below';
7
+ export type DragDirection = 'up' | 'down';
8
+ export interface ReorderValidationContext {
9
+ sourceNode: GridTreeNode;
10
+ targetNode: GridTreeNode;
11
+ prevNode: GridTreeNode | null;
12
+ nextNode: GridTreeNode | null;
13
+ rowTree: Record<GridRowId, GridTreeNode>;
14
+ dropPosition: DropPosition;
15
+ dragDirection: DragDirection;
16
+ targetRowIndex: number;
17
+ sourceRowIndex: number;
18
+ expandedSortedRowIndexLookup: Record<GridRowId, number>;
19
+ }
20
+ export interface ReorderExecutionContext {
21
+ sourceRowId: GridRowId;
22
+ placeholderIndex: number;
23
+ sortedFilteredRowIds: GridRowId[];
24
+ sortedFilteredRowIndexLookup: Record<GridRowId, number>;
25
+ rowTree: GridRowTreeConfig;
26
+ apiRef: RefObject<GridPrivateApiPremium>;
27
+ processRowUpdate?: DataGridPremiumProcessedProps['processRowUpdate'];
28
+ onProcessRowUpdateError?: DataGridPremiumProcessedProps['onProcessRowUpdateError'];
29
+ }
30
+ export interface ReorderOperation {
31
+ sourceNode: GridTreeNode;
32
+ targetNode: GridTreeNode;
33
+ actualTargetIndex: number;
34
+ isLastChild: boolean;
35
+ operationType: ReorderOperationType;
36
+ }
37
+ export interface ReorderScenario {
38
+ name: string;
39
+ detectOperation: (ctx: ReorderExecutionContext) => ReorderOperation | null;
40
+ execute: (operation: ReorderOperation, ctx: ReorderExecutionContext) => Promise<void> | void;
41
+ }
42
+ export type ReorderOperationType = 'same-parent-swap' | 'cross-parent-leaf' | 'cross-parent-group';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,127 @@
1
+ import type { RefObject } from '@mui/x-internals/types';
2
+ import { type GridRowId, type GridTreeNode, type GridGroupNode, type GridRowTreeConfig, type GridKeyValue, type GridValidRowModel } from '@mui/x-data-grid-pro';
3
+ import type { RowTreeBuilderGroupingCriterion } from '@mui/x-data-grid-pro/internals';
4
+ import type { ReorderValidationContext as Ctx, ReorderOperationType } from "./types.js";
5
+ import type { GridPrivateApiPremium } from "../../../models/gridApiPremium.js";
6
+ import { DataGridPremiumProcessedProps } from "../../../models/dataGridPremiumProps.js";
7
+ /**
8
+ * Reusable validation conditions for row reordering validation
9
+ */
10
+ export declare const conditions: {
11
+ isGroupToGroup: (ctx: Ctx) => boolean;
12
+ isLeafToLeaf: (ctx: Ctx) => boolean;
13
+ isLeafToGroup: (ctx: Ctx) => boolean;
14
+ isGroupToLeaf: (ctx: Ctx) => boolean;
15
+ isDropAbove: (ctx: Ctx) => boolean;
16
+ isDropBelow: (ctx: Ctx) => boolean;
17
+ sameDepth: (ctx: Ctx) => boolean;
18
+ sourceDepthGreater: (ctx: Ctx) => boolean;
19
+ targetDepthIsSourceMinusOne: (ctx: Ctx) => boolean;
20
+ sameParent: (ctx: Ctx) => boolean;
21
+ targetGroupExpanded: (ctx: Ctx) => boolean;
22
+ targetGroupCollapsed: (ctx: Ctx) => boolean;
23
+ hasPrevNode: (ctx: Ctx) => boolean;
24
+ hasNextNode: (ctx: Ctx) => boolean;
25
+ prevIsLeaf: (ctx: Ctx) => boolean;
26
+ prevIsGroup: (ctx: Ctx) => boolean;
27
+ nextIsLeaf: (ctx: Ctx) => boolean;
28
+ nextIsGroup: (ctx: Ctx) => boolean;
29
+ prevDepthEquals: (ctx: Ctx, depth: number) => boolean;
30
+ prevDepthEqualsSource: (ctx: Ctx) => boolean;
31
+ prevBelongsToSource: (ctx: Ctx) => boolean;
32
+ isAdjacentPosition: (ctx: Ctx) => boolean;
33
+ targetFirstChildIsGroupWithSourceDepth: (ctx: Ctx) => boolean;
34
+ targetFirstChildDepthEqualsSource: (ctx: Ctx) => boolean;
35
+ };
36
+ export declare function determineOperationType(sourceNode: GridTreeNode, targetNode: GridTreeNode): ReorderOperationType;
37
+ export declare function calculateTargetIndex(sourceNode: GridTreeNode, targetNode: GridTreeNode, isLastChild: boolean, rowTree: Record<GridRowId, GridTreeNode>): number;
38
+ export declare const getNodePathInTree: ({
39
+ id,
40
+ tree
41
+ }: {
42
+ id: GridRowId;
43
+ tree: GridRowTreeConfig;
44
+ }) => RowTreeBuilderGroupingCriterion[];
45
+ export declare const collectAllLeafDescendants: (groupNode: GridGroupNode, tree: GridRowTreeConfig) => GridRowId[];
46
+ /**
47
+ * Adjusts the target node based on specific reorder scenarios and constraints.
48
+ *
49
+ * This function applies scenario-specific logic to find the actual target node
50
+ * for operations, handling cases like:
51
+ * - Moving to collapsed groups
52
+ * - Depth-based adjustments
53
+ * - End-of-list positioning
54
+ *
55
+ * @param sourceNode The node being moved
56
+ * @param targetNode The initial target node
57
+ * @param targetIndex The index of the target node in the visible rows
58
+ * @param placeholderIndex The index where the placeholder appears
59
+ * @param sortedFilteredRowIds Array of visible row IDs in display order
60
+ * @param apiRef Reference to the grid API
61
+ * @returns Object containing the adjusted target node and last child flag
62
+ */
63
+ export declare function adjustTargetNode(sourceNode: GridTreeNode, targetNode: GridTreeNode, targetIndex: number, placeholderIndex: number, sortedFilteredRowIds: GridRowId[], apiRef: RefObject<GridPrivateApiPremium>): {
64
+ adjustedTargetNode: GridTreeNode;
65
+ isLastChild: boolean;
66
+ };
67
+ /**
68
+ * Finds an existing group node with the same groupingKey and groupingField under a parent.
69
+ *
70
+ * @param parentNode - The parent group node to search in
71
+ * @param groupingKey - The grouping key to match
72
+ * @param groupingField - The grouping field to match
73
+ * @param tree - The row tree configuration
74
+ * @returns The existing group node if found, null otherwise
75
+ */
76
+ export declare function findExistingGroupWithSameKey(parentNode: GridGroupNode, groupingKey: GridKeyValue, groupingField: string, tree: GridRowTreeConfig): GridGroupNode | null;
77
+ /**
78
+ * Removes empty ancestor groups from the tree after a row move operation.
79
+ * Walks up the tree from the given group, removing any empty groups encountered.
80
+ *
81
+ * @param groupId - The ID of the group to start checking from
82
+ * @param tree - The row tree configuration
83
+ * @param removedGroups - Set to track which groups have been removed
84
+ * @returns The number of root-level groups that were removed
85
+ */
86
+ export declare function removeEmptyAncestors(groupId: GridRowId, tree: GridRowTreeConfig, removedGroups: Set<GridRowId>): number;
87
+ export declare function handleProcessRowUpdateError(error: any, onProcessRowUpdateError?: DataGridPremiumProcessedProps['onProcessRowUpdateError']): void;
88
+ /**
89
+ * Handles batch row updates with partial failure tracking.
90
+ *
91
+ * This class is designed for operations that need to update multiple rows
92
+ * atomically (like moving entire groups), while gracefully handling cases
93
+ * where some updates succeed and others fail.
94
+ *
95
+ * @example
96
+ * ```tsx
97
+ * const updater = new BatchRowUpdater(processRowUpdate, onError);
98
+ *
99
+ * // Queue multiple updates
100
+ * updater.queueUpdate('row1', originalRow1, newRow1);
101
+ * updater.queueUpdate('row2', originalRow2, newRow2);
102
+ *
103
+ * // Execute all updates
104
+ * const { successful, failed, updates } = await updater.executeAll();
105
+ *
106
+ * // Handle results
107
+ * if (successful.length > 0) {
108
+ * apiRef.current.updateRows(updates);
109
+ * }
110
+ * ```
111
+ */
112
+ export declare class BatchRowUpdater {
113
+ private processRowUpdate;
114
+ private onProcessRowUpdateError;
115
+ private rowsToUpdate;
116
+ private originalRows;
117
+ private successfulRowIds;
118
+ private failedRowIds;
119
+ private pendingRowUpdates;
120
+ constructor(processRowUpdate: DataGridPremiumProcessedProps['processRowUpdate'] | undefined, onProcessRowUpdateError: DataGridPremiumProcessedProps['onProcessRowUpdateError'] | undefined);
121
+ queueUpdate(rowId: GridRowId, originalRow: GridValidRowModel, updatedRow: GridValidRowModel): void;
122
+ executeAll(): Promise<{
123
+ successful: GridRowId[];
124
+ failed: GridRowId[];
125
+ updates: GridValidRowModel[];
126
+ }>;
127
+ }
@@ -0,0 +1,343 @@
1
+ import { GRID_ROOT_GROUP_ID, gridRowNodeSelector } from '@mui/x-data-grid-pro';
2
+ import { warnOnce } from '@mui/x-internals/warning';
3
+ // TODO: Share these conditions with the executor by making the contexts similar
4
+ /**
5
+ * Reusable validation conditions for row reordering validation
6
+ */
7
+ export const conditions = {
8
+ // Node type checks
9
+ isGroupToGroup: ctx => ctx.sourceNode.type === 'group' && ctx.targetNode.type === 'group',
10
+ isLeafToLeaf: ctx => ctx.sourceNode.type === 'leaf' && ctx.targetNode.type === 'leaf',
11
+ isLeafToGroup: ctx => ctx.sourceNode.type === 'leaf' && ctx.targetNode.type === 'group',
12
+ isGroupToLeaf: ctx => ctx.sourceNode.type === 'group' && ctx.targetNode.type === 'leaf',
13
+ // Drop position checks
14
+ isDropAbove: ctx => ctx.dropPosition === 'above',
15
+ isDropBelow: ctx => ctx.dropPosition === 'below',
16
+ // Depth checks
17
+ sameDepth: ctx => ctx.sourceNode.depth === ctx.targetNode.depth,
18
+ sourceDepthGreater: ctx => ctx.sourceNode.depth > ctx.targetNode.depth,
19
+ targetDepthIsSourceMinusOne: ctx => ctx.targetNode.depth === ctx.sourceNode.depth - 1,
20
+ // Parent checks
21
+ sameParent: ctx => ctx.sourceNode.parent === ctx.targetNode.parent,
22
+ // Node state checks
23
+ targetGroupExpanded: ctx => (ctx.targetNode.type === 'group' && ctx.targetNode.childrenExpanded) ?? false,
24
+ targetGroupCollapsed: ctx => ctx.targetNode.type === 'group' && !ctx.targetNode.childrenExpanded,
25
+ // Previous/Next node checks
26
+ hasPrevNode: ctx => ctx.prevNode !== null,
27
+ hasNextNode: ctx => ctx.nextNode !== null,
28
+ prevIsLeaf: ctx => ctx.prevNode?.type === 'leaf',
29
+ prevIsGroup: ctx => ctx.prevNode?.type === 'group',
30
+ nextIsLeaf: ctx => ctx.nextNode?.type === 'leaf',
31
+ nextIsGroup: ctx => ctx.nextNode?.type === 'group',
32
+ prevDepthEquals: (ctx, depth) => ctx.prevNode?.depth === depth,
33
+ prevDepthEqualsSource: ctx => ctx.prevNode?.depth === ctx.sourceNode.depth,
34
+ // Complex checks
35
+ prevBelongsToSource: ctx => {
36
+ if (!ctx.prevNode) {
37
+ return false;
38
+ }
39
+ // Check if prevNode.parent OR any of its ancestors === sourceNode.id
40
+ let currentId = ctx.prevNode.parent;
41
+ while (currentId) {
42
+ if (currentId === ctx.sourceNode.id) {
43
+ return true;
44
+ }
45
+ const node = ctx.rowTree[currentId];
46
+ if (!node) {
47
+ break;
48
+ }
49
+ currentId = node.parent;
50
+ }
51
+ return false;
52
+ },
53
+ // Position checks
54
+ isAdjacentPosition: ctx => {
55
+ const {
56
+ sourceRowIndex,
57
+ targetRowIndex,
58
+ dropPosition
59
+ } = ctx;
60
+ return dropPosition === 'above' && targetRowIndex === sourceRowIndex + 1 || dropPosition === 'below' && targetRowIndex === sourceRowIndex - 1;
61
+ },
62
+ // First child check
63
+ targetFirstChildIsGroupWithSourceDepth: ctx => {
64
+ if (ctx.targetNode.type !== 'group') {
65
+ return false;
66
+ }
67
+ const targetGroup = ctx.targetNode;
68
+ const firstChild = targetGroup.children?.[0] ? ctx.rowTree[targetGroup.children[0]] : null;
69
+ return firstChild?.type === 'group' && firstChild.depth === ctx.sourceNode.depth;
70
+ },
71
+ targetFirstChildDepthEqualsSource: ctx => {
72
+ if (ctx.targetNode.type !== 'group') {
73
+ return false;
74
+ }
75
+ const targetGroup = ctx.targetNode;
76
+ const firstChild = targetGroup.children?.[0] ? ctx.rowTree[targetGroup.children[0]] : null;
77
+ return firstChild ? firstChild.depth === ctx.sourceNode.depth : false;
78
+ }
79
+ };
80
+ export function determineOperationType(sourceNode, targetNode) {
81
+ if (sourceNode.parent === targetNode.parent) {
82
+ return 'same-parent-swap';
83
+ }
84
+ if (sourceNode.type === 'leaf') {
85
+ return 'cross-parent-leaf';
86
+ }
87
+ return 'cross-parent-group';
88
+ }
89
+ export function calculateTargetIndex(sourceNode, targetNode, isLastChild, rowTree) {
90
+ if (sourceNode.parent === targetNode.parent && !isLastChild) {
91
+ // Same parent: find target's position in parent's children
92
+ const parent = rowTree[sourceNode.parent];
93
+ return parent.children.findIndex(id => id === targetNode.id);
94
+ }
95
+ if (isLastChild) {
96
+ // Append at the end
97
+ const targetParent = rowTree[targetNode.parent];
98
+ return targetParent.children.length;
99
+ }
100
+
101
+ // Find position in target parent
102
+ const targetParent = rowTree[targetNode.parent];
103
+ const targetIndex = targetParent.children.findIndex(id => id === targetNode.id);
104
+ return targetIndex >= 0 ? targetIndex : 0;
105
+ }
106
+
107
+ // Get the path from a node to the root in the tree
108
+ export const getNodePathInTree = ({
109
+ id,
110
+ tree
111
+ }) => {
112
+ const path = [];
113
+ let node = tree[id];
114
+ while (node.id !== GRID_ROOT_GROUP_ID) {
115
+ path.push({
116
+ field: node.type === 'leaf' ? null : node.groupingField,
117
+ key: node.groupingKey
118
+ });
119
+ node = tree[node.parent];
120
+ }
121
+ path.reverse();
122
+ return path;
123
+ };
124
+
125
+ // Recursively collect all leaf node IDs from a group
126
+ export const collectAllLeafDescendants = (groupNode, tree) => {
127
+ const leafIds = [];
128
+ const collectFromNode = nodeId => {
129
+ const node = tree[nodeId];
130
+ if (node.type === 'leaf') {
131
+ leafIds.push(nodeId);
132
+ } else if (node.type === 'group') {
133
+ node.children.forEach(collectFromNode);
134
+ }
135
+ };
136
+ groupNode.children.forEach(collectFromNode);
137
+ return leafIds;
138
+ };
139
+
140
+ /**
141
+ * Adjusts the target node based on specific reorder scenarios and constraints.
142
+ *
143
+ * This function applies scenario-specific logic to find the actual target node
144
+ * for operations, handling cases like:
145
+ * - Moving to collapsed groups
146
+ * - Depth-based adjustments
147
+ * - End-of-list positioning
148
+ *
149
+ * @param sourceNode The node being moved
150
+ * @param targetNode The initial target node
151
+ * @param targetIndex The index of the target node in the visible rows
152
+ * @param placeholderIndex The index where the placeholder appears
153
+ * @param sortedFilteredRowIds Array of visible row IDs in display order
154
+ * @param apiRef Reference to the grid API
155
+ * @returns Object containing the adjusted target node and last child flag
156
+ */
157
+ export function adjustTargetNode(sourceNode, targetNode, targetIndex, placeholderIndex, sortedFilteredRowIds, apiRef) {
158
+ let adjustedTargetNode = targetNode;
159
+ let isLastChild = false;
160
+
161
+ // Handle end-of-list case
162
+ if (placeholderIndex >= sortedFilteredRowIds.length && sortedFilteredRowIds.length > 0) {
163
+ isLastChild = true;
164
+ }
165
+
166
+ // Case A and B adjustment: Move to last child of parent where target should be the node above
167
+ if (targetNode.type === 'group' && sourceNode.parent !== targetNode.parent && sourceNode.depth > targetNode.depth) {
168
+ // Find the first node with the same depth as source before target and quit early if a
169
+ // node with depth < source.depth is found
170
+ let i = targetIndex - 1;
171
+ while (i >= 0) {
172
+ const node = apiRef.current.getRowNode(sortedFilteredRowIds[i]);
173
+ if (node && node.depth < sourceNode.depth) {
174
+ break;
175
+ }
176
+ if (node && node.depth === sourceNode.depth) {
177
+ adjustedTargetNode = node;
178
+ break;
179
+ }
180
+ i -= 1;
181
+ }
182
+ }
183
+
184
+ // Case D adjustment: Leaf to group where we need previous leaf
185
+ if (sourceNode.type === 'leaf' && targetNode.type === 'group' && targetNode.depth < sourceNode.depth) {
186
+ isLastChild = true;
187
+ const prevIndex = placeholderIndex - 1;
188
+ if (prevIndex >= 0) {
189
+ const prevRowId = sortedFilteredRowIds[prevIndex];
190
+ const leafTargetNode = gridRowNodeSelector(apiRef, prevRowId);
191
+ if (leafTargetNode && leafTargetNode.type === 'leaf') {
192
+ adjustedTargetNode = leafTargetNode;
193
+ }
194
+ }
195
+ }
196
+ return {
197
+ adjustedTargetNode,
198
+ isLastChild
199
+ };
200
+ }
201
+
202
+ /**
203
+ * Finds an existing group node with the same groupingKey and groupingField under a parent.
204
+ *
205
+ * @param parentNode - The parent group node to search in
206
+ * @param groupingKey - The grouping key to match
207
+ * @param groupingField - The grouping field to match
208
+ * @param tree - The row tree configuration
209
+ * @returns The existing group node if found, null otherwise
210
+ */
211
+ export function findExistingGroupWithSameKey(parentNode, groupingKey, groupingField, tree) {
212
+ for (const childId of parentNode.children) {
213
+ const childNode = tree[childId];
214
+ if (childNode && childNode.type === 'group' && childNode.groupingKey === groupingKey && childNode.groupingField === groupingField) {
215
+ return childNode;
216
+ }
217
+ }
218
+ return null;
219
+ }
220
+
221
+ /**
222
+ * Removes empty ancestor groups from the tree after a row move operation.
223
+ * Walks up the tree from the given group, removing any empty groups encountered.
224
+ *
225
+ * @param groupId - The ID of the group to start checking from
226
+ * @param tree - The row tree configuration
227
+ * @param removedGroups - Set to track which groups have been removed
228
+ * @returns The number of root-level groups that were removed
229
+ */
230
+ export function removeEmptyAncestors(groupId, tree, removedGroups) {
231
+ let rootLevelRemovals = 0;
232
+ let currentGroupId = groupId;
233
+ while (currentGroupId && currentGroupId !== GRID_ROOT_GROUP_ID) {
234
+ const group = tree[currentGroupId];
235
+ if (!group) {
236
+ break;
237
+ }
238
+ const remainingChildren = group.children.filter(childId => !removedGroups.has(childId));
239
+ if (remainingChildren.length > 0) {
240
+ break;
241
+ }
242
+ if (group.depth === 0) {
243
+ rootLevelRemovals += 1;
244
+ }
245
+ removedGroups.add(currentGroupId);
246
+ currentGroupId = group.parent;
247
+ }
248
+ return rootLevelRemovals;
249
+ }
250
+ export function handleProcessRowUpdateError(error, onProcessRowUpdateError) {
251
+ if (onProcessRowUpdateError) {
252
+ onProcessRowUpdateError(error);
253
+ } else if (process.env.NODE_ENV !== 'production') {
254
+ warnOnce(['MUI X: A call to `processRowUpdate()` threw an error which was not handled because `onProcessRowUpdateError()` is missing.', 'To handle the error pass a callback to the `onProcessRowUpdateError()` prop, for example `<DataGrid onProcessRowUpdateError={(error) => ...} />`.', 'For more detail, see https://mui.com/x/react-data-grid/editing/persistence/.'], 'error');
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Handles batch row updates with partial failure tracking.
260
+ *
261
+ * This class is designed for operations that need to update multiple rows
262
+ * atomically (like moving entire groups), while gracefully handling cases
263
+ * where some updates succeed and others fail.
264
+ *
265
+ * @example
266
+ * ```tsx
267
+ * const updater = new BatchRowUpdater(processRowUpdate, onError);
268
+ *
269
+ * // Queue multiple updates
270
+ * updater.queueUpdate('row1', originalRow1, newRow1);
271
+ * updater.queueUpdate('row2', originalRow2, newRow2);
272
+ *
273
+ * // Execute all updates
274
+ * const { successful, failed, updates } = await updater.executeAll();
275
+ *
276
+ * // Handle results
277
+ * if (successful.length > 0) {
278
+ * apiRef.current.updateRows(updates);
279
+ * }
280
+ * ```
281
+ */
282
+ export class BatchRowUpdater {
283
+ rowsToUpdate = (() => new Map())();
284
+ originalRows = (() => new Map())();
285
+ successfulRowIds = (() => new Set())();
286
+ failedRowIds = (() => new Set())();
287
+ pendingRowUpdates = [];
288
+ constructor(processRowUpdate, onProcessRowUpdateError) {
289
+ this.processRowUpdate = processRowUpdate;
290
+ this.onProcessRowUpdateError = onProcessRowUpdateError;
291
+ }
292
+ queueUpdate(rowId, originalRow, updatedRow) {
293
+ this.originalRows.set(rowId, originalRow);
294
+ this.rowsToUpdate.set(rowId, updatedRow);
295
+ }
296
+ async executeAll() {
297
+ const rowIds = Array.from(this.rowsToUpdate.keys());
298
+ if (rowIds.length === 0) {
299
+ return {
300
+ successful: [],
301
+ failed: [],
302
+ updates: []
303
+ };
304
+ }
305
+
306
+ // Handle each row update, tracking success/failure
307
+ const handleRowUpdate = async rowId => {
308
+ const newRow = this.rowsToUpdate.get(rowId);
309
+ const oldRow = this.originalRows.get(rowId);
310
+ try {
311
+ if (typeof this.processRowUpdate === 'function') {
312
+ const params = {
313
+ rowId,
314
+ previousRow: oldRow,
315
+ updatedRow: newRow
316
+ };
317
+ const finalRow = await this.processRowUpdate(newRow, oldRow, params);
318
+ this.pendingRowUpdates.push(finalRow || newRow);
319
+ this.successfulRowIds.add(rowId);
320
+ } else {
321
+ this.pendingRowUpdates.push(newRow);
322
+ this.successfulRowIds.add(rowId);
323
+ }
324
+ } catch (error) {
325
+ this.failedRowIds.add(rowId);
326
+ handleProcessRowUpdateError(error, this.onProcessRowUpdateError);
327
+ }
328
+ };
329
+
330
+ // Use Promise.all with wrapped promises to avoid Promise.allSettled (browser support)
331
+ const promises = rowIds.map(rowId => {
332
+ return new Promise(resolve => {
333
+ handleRowUpdate(rowId).then(resolve).catch(resolve);
334
+ });
335
+ });
336
+ await Promise.all(promises);
337
+ return {
338
+ successful: Array.from(this.successfulRowIds),
339
+ failed: Array.from(this.failedRowIds),
340
+ updates: this.pendingRowUpdates
341
+ };
342
+ }
343
+ }
@@ -0,0 +1,7 @@
1
+ import { GridRowId } from '@mui/x-data-grid-pro';
2
+ import type { RefObject } from '@mui/x-internals/types';
3
+ import type { GridPrivateApiPremium } from "../../../models/gridApiPremium.js";
4
+ import type { DataGridPremiumProcessedProps } from "../../../models/dataGridPremiumProps.js";
5
+ export declare const useGridRowsOverridableMethods: (apiRef: RefObject<GridPrivateApiPremium>, props: Pick<DataGridPremiumProcessedProps, "processRowUpdate" | "onProcessRowUpdateError">) => {
6
+ setRowIndex: (sourceRowId: GridRowId, targetOriginalIndex: number) => Promise<void>;
7
+ };