From a331b246d98551cdbf94a6b01a48fc687f51b3d5 Mon Sep 17 00:00:00 2001 From: matttdawson <89495499+matttdawson@users.noreply.github.com> Date: Tue, 2 Jul 2024 16:39:07 +1200 Subject: [PATCH] fix: custom filter loses focus after filter (#468) * fix filter loses focus after filter --- src/contexts/GridContextProvider.tsx | 19 ++++++++++++++++++- src/stories/grid/GridReadOnly.stories.tsx | 9 ++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/contexts/GridContextProvider.tsx b/src/contexts/GridContextProvider.tsx index cd9aeddb..a4114824 100644 --- a/src/contexts/GridContextProvider.tsx +++ b/src/contexts/GridContextProvider.tsx @@ -639,7 +639,24 @@ export const GridContextProvider = (props: PropsWithC const onFilterChanged = useMemo( () => debounce(() => { - gridApi && gridApi.onFilterChanged(); + // This is terrible, but there's no other way for me to check whether a filter has changed the grid + const getDisplayedRowsHash = () => { + const arr: any[] = []; + gridApi?.forEachNodeAfterFilter((rowNode) => { + arr.push(rowNode.id); + }); + return arr.join("|"); + }; + + if (gridApi) { + const hasFocusedCell = gridApi.getFocusedCell(); + const preHash = hasFocusedCell && getDisplayedRowsHash(); + gridApi.onFilterChanged(); + const postHash = hasFocusedCell && getDisplayedRowsHash(); + // Ag-grid has a bug where if a focused cell comes into view after a filter the filter loses focus + // So the focus is cleared to prevent this + preHash !== postHash && gridApi.clearFocusedCell(); + } }, 200), [gridApi], ); diff --git a/src/stories/grid/GridReadOnly.stories.tsx b/src/stories/grid/GridReadOnly.stories.tsx index 8bf14d51..f7aecc16 100644 --- a/src/stories/grid/GridReadOnly.stories.tsx +++ b/src/stories/grid/GridReadOnly.stories.tsx @@ -255,7 +255,14 @@ const GridReadOnlyTemplate: StoryFn = (props: GridProps) => { ); }; -const GridFilterLessThan = (props: { field: keyof ITestRow; text: string }): ReactElement => { +type KeysOfType = { + [K in keyof TObject]: TObject[K] extends TValue ? K : never; +}[keyof TObject]; + +const GridFilterLessThan = (props: { + field: KeysOfType; + text: string; +}): ReactElement => { const [value, setValue] = useState(); const filter = useCallback(