From 34657c14e2bf4bc4d2df7b6a70588b2aac789318 Mon Sep 17 00:00:00 2001 From: Andrew Cherniavskii Date: Wed, 23 Oct 2024 10:52:16 +0200 Subject: [PATCH] [DataGrid] Focus next row when the focused row is deleted (#15061) --- .../src/hooks/features/focus/useGridFocus.ts | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/packages/x-data-grid/src/hooks/features/focus/useGridFocus.ts b/packages/x-data-grid/src/hooks/features/focus/useGridFocus.ts index 2c8e83b00875..f45197e90ea4 100644 --- a/packages/x-data-grid/src/hooks/features/focus/useGridFocus.ts +++ b/packages/x-data-grid/src/hooks/features/focus/useGridFocus.ts @@ -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) => ({ @@ -423,19 +423,36 @@ export const useGridFocus = ( const handleRowSet = React.useCallback>(() => { 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);