Skip to content

Commit

Permalink
[DataGrid] Focus next row when the focused row is deleted (#15061)
Browse files Browse the repository at this point in the history
  • Loading branch information
cherniavskii authored Oct 23, 2024
1 parent 5f3fc0e commit a01b899
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions packages/x-data-grid/src/hooks/features/focus/useGridFocus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { gridVisibleColumnDefinitionsSelector } from '../columns/gridColumnsSele
import { getVisibleRows } from '../../utils/useGridVisibleRows';
import { clamp } from '../../../utils/utils';
import { GridCellCoordinates } from '../../../models/gridCell';
import { GridRowEntry } from '../../../models/gridRows';
import type { GridRowEntry, GridRowId } from '../../../models/gridRows';
import { gridPinnedRowsSelector } from '../rows/gridRowsSelector';

export const focusStateInitializer: GridStateInitializer = (state) => ({
Expand Down Expand Up @@ -423,19 +423,36 @@ export const useGridFocus = (
const handleRowSet = React.useCallback<GridEventListener<'rowsSet'>>(() => {
const cell = gridFocusCellSelector(apiRef);

// If the focused cell is in a row which does not exist anymore, then remove the focus
// If the focused cell is in a row which does not exist anymore,
// focus previous row or remove the focus
if (cell && !apiRef.current.getRow(cell.id)) {
const lastFocusedRowId = gridFocusCellSelector(apiRef)?.id;

let nextRowId: GridRowId | null = null;
if (typeof lastFocusedRowId !== 'undefined') {
const lastFocusedRowIndex =
apiRef.current.getRowIndexRelativeToVisibleRows(lastFocusedRowId);
const currentPage = getVisibleRows(apiRef, {
pagination: props.pagination,
paginationMode: props.paginationMode,
});

const nextRow =
currentPage.rows[clamp(lastFocusedRowIndex, 0, currentPage.rows.length - 1)];
nextRowId = nextRow.id ?? null;
}

apiRef.current.setState((state) => ({
...state,
focus: {
cell: null,
cell: nextRowId === null ? null : { id: nextRowId, field: cell.field },
columnHeader: null,
columnHeaderFilter: null,
columnGroupHeader: null,
},
}));
}
}, [apiRef]);
}, [apiRef, props.pagination, props.paginationMode]);

const handlePaginationModelChange = useEventcallback(() => {
const currentFocusedCell = gridFocusCellSelector(apiRef);
Expand Down

0 comments on commit a01b899

Please sign in to comment.