Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DataGrid] Focus next row when the focused row is deleted #15067

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading