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] Fix filters on rendering new rows #642

Merged
merged 8 commits into from
Nov 27, 2020
Merged
Show file tree
Hide file tree
Changes from 7 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
14 changes: 2 additions & 12 deletions packages/grid/_modules_/grid/GridComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export const GridComponent = React.forwardRef<HTMLDivElement, GridComponentProps
useSorting(apiRef, props.rows);
useColumnMenu(apiRef);
usePreferencesPanel(apiRef);
useFilter(apiRef);
useFilter(apiRef, props.rows);
dtassone marked this conversation as resolved.
Show resolved Hide resolved
useContainerProps(windowRef, apiRef);
const renderCtx = useVirtualRows(columnsHeaderRef, windowRef, renderingZoneRef, apiRef);

Expand Down Expand Up @@ -202,17 +202,7 @@ export const GridComponent = React.forwardRef<HTMLDivElement, GridComponentProps
!!gridState.options.pagination &&
gridState.pagination.pageSize != null &&
!gridState.options.hideFooterPagination &&
(customComponents.paginationComponent || (
<Pagination
setPage={apiRef.current.setPage}
currentPage={gridState.pagination.page}
pageCount={gridState.pagination.pageCount}
pageSize={gridState.pagination.pageSize}
rowCount={gridState.pagination.rowCount}
setPageSize={apiRef.current.setPageSize}
rowsPerPageOptions={gridState.options.rowsPerPageOptions}
/>
))
(customComponents.paginationComponent || <Pagination />)
}
/>
)}
Expand Down
49 changes: 22 additions & 27 deletions packages/grid/_modules_/grid/components/pagination.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import { useContext } from 'react';
import * as React from 'react';
import TablePagination from '@material-ui/core/TablePagination';
import { makeStyles, Theme } from '@material-ui/core/styles';

export interface PaginationComponentProps {
pageCount: number;
setPage: (pageCount: number) => void;
setPageSize: (pageSize: number) => void;
currentPage: number;
rowCount: number;
pageSize: number;
rowsPerPageOptions?: number[];
}
import { useGridSelector } from '../hooks/features/core/useGridSelector';
import { paginationSelector } from '../hooks/features/pagination/paginationSelector';
import { optionsSelector } from '../hooks/utils/useOptionsProp';
import { ApiContext } from './api-context';

// Used to hide the drop down select from the TablePaginagion
const useStyles = makeStyles((theme: Theme) => ({
Expand All @@ -31,42 +26,42 @@ const useStyles = makeStyles((theme: Theme) => ({
},
}));

export const Pagination: React.FC<PaginationComponentProps> = ({
setPage,
setPageSize,
pageSize,
rowCount,
currentPage,
rowsPerPageOptions,
}) => {
export function Pagination() {
const classes = useStyles();
const apiRef = useContext(ApiContext);
const paginationState = useGridSelector(apiRef, paginationSelector);
const options = useGridSelector(apiRef, optionsSelector);

const onPageSizeChange = React.useCallback(
(event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
const newPageSize = Number(event.target.value);
setPageSize(newPageSize);
apiRef!.current!.setPageSize(newPageSize);
},
[setPageSize],
[apiRef],
);

const onPageChange = React.useCallback(
(event: any, page: number) => {
setPage(page + 1);
apiRef!.current!.setPage(page + 1);
},
[setPage],
[apiRef],
);

return (
<TablePagination
classes={classes}
component="div"
count={rowCount}
page={currentPage - 1}
count={paginationState.rowCount}
page={paginationState.page - 1}
onChangePage={onPageChange}
rowsPerPageOptions={
rowsPerPageOptions && rowsPerPageOptions.indexOf(pageSize) > -1 ? rowsPerPageOptions : []
options.rowsPerPageOptions &&
options.rowsPerPageOptions.indexOf(paginationState.pageSize) > -1
? options.rowsPerPageOptions
: []
}
rowsPerPage={pageSize}
rowsPerPage={paginationState.pageSize}
onChangeRowsPerPage={onPageSizeChange}
/>
);
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ export const FilterInputValue: React.FC<TypeFilterInputValueProps> = ({
};
}, []);

React.useEffect(() => {
setFilterValueState(item.value || '');
}, [item.value]);

const inputProps = applying ? { endAdornment: <LoadIcon /> } : undefined;

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createSelector } from 'reselect';
import { FilterItem } from '../../../models/filterItem';
import { RowModel } from '../../../models/rows';
import { GridState } from '../core/gridState';
import { rowCountSelector } from '../rows/rowsSelector';
import { sortedRowsSelector } from '../sorting/sortingSelector';
import { FilterModelState } from './FilterModelState';
import { VisibleRowsState } from './visibleRowsState';
Expand All @@ -17,9 +18,18 @@ export const visibleSortedRowsSelector = createSelector<
return [...sortedRows].filter((row) => visibleRowsState.visibleRowsLookup[row.id] !== false);
});

export const visibleRowCountSelector = createSelector<GridState, RowModel[], number>(
export const visibleRowCountSelector = createSelector<
GridState,
RowModel[],
RowModel[],
number,
number
>(
visibleSortedRowsSelector,
(rows) => rows.length,
sortedRowsSelector,
rowCountSelector,
(visibleRows, sortedRows, totalRowsCount) =>
totalRowsCount - (sortedRows.length - visibleRows.length),
);

export const filterStateSelector: (state: GridState) => FilterModelState = (state) => state.filter;
Expand Down
72 changes: 47 additions & 25 deletions packages/grid/_modules_/grid/hooks/features/filter/useFilter.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import * as React from 'react';
import { ROWS_UPDATED } from '../../../constants/eventsConstants';
import { ApiRef } from '../../../models/api/apiRef';
import { FilterApi } from '../../../models/api/filterApi';
import { FilterItem, LinkOperator } from '../../../models/filterItem';
import { RowId, RowsProp } from '../../../models/rows';
import { buildCellParams } from '../../../utils/paramsUtils';
import { isEqual } from '../../../utils/utils';
import { useApiEventHandler } from '../../root/useApiEventHandler';
import { useApiMethod } from '../../root/useApiMethod';
import { useLogger } from '../../utils/useLogger';
import { optionsSelector } from '../../utils/useOptionsProp';
import { PreferencePanelsValue } from '../preferencesPanel/preferencesPanelValue';
import { filterableColumnsSelector } from '../columns/columnsSelector';
import { useGridSelector } from '../core/useGridSelector';
import { useGridState } from '../core/useGridState';
import { PreferencePanelsValue } from '../preferencesPanel/preferencesPanelValue';
import { sortedRowsSelector } from '../sorting/sortingSelector';
import { getInitialVisibleRowsState } from './visibleRowsState';

export const useFilter = (apiRef: ApiRef): void => {
export const useFilter = (apiRef: ApiRef, rowsProp: RowsProp): void => {
const logger = useLogger('useFilter');
const [gridState, setGridState, forceUpdate] = useGridState(apiRef);

const rows = useGridSelector(apiRef, sortedRowsSelector);
const filterableColumns = useGridSelector(apiRef, filterableColumnsSelector);
const { disableMultipleColumnsFiltering } = useGridSelector(apiRef, optionsSelector);

Expand All @@ -29,7 +31,7 @@ export const useFilter = (apiRef: ApiRef): void => {
}, [setGridState]);

const applyFilter = React.useCallback(
(filterItem: FilterItem, linkOperator: LinkOperator) => {
(filterItem: FilterItem, linkOperator: LinkOperator = LinkOperator.And) => {
if (!filterItem.columnField || !filterItem.operatorValue || !filterItem.value) {
return;
}
Expand All @@ -50,6 +52,10 @@ export const useFilter = (apiRef: ApiRef): void => {

setGridState((state) => {
const visibleRowsLookup = { ...state.visibleRows.visibleRowsLookup };
const visibleRows: RowId[] = [];
// We run the selector on the state here to avoid rendering the rows and then filtering again.
// This way we have latest rows on the first rendering
const rows = sortedRowsSelector(state);

rows.forEach((row, rowIndex) => {
const params = buildCellParams({
Expand All @@ -61,22 +67,26 @@ export const useFilter = (apiRef: ApiRef): void => {
});

const isShown = applyFilterOnRow(params);
visibleRowsLookup[row.id] =
// eslint-disable-next-line no-nested-ternary
visibleRowsLookup[row.id] == null
? isShown
: linkOperator === LinkOperator.And
? visibleRowsLookup[row.id] && isShown
: visibleRowsLookup[row.id] || isShown;
if (visibleRowsLookup[row.id] == null) {
visibleRowsLookup[row.id] = isShown;
} else {
visibleRowsLookup[row.id] =
linkOperator === LinkOperator.And
? visibleRowsLookup[row.id] && isShown
: visibleRowsLookup[row.id] || isShown;
}
if (isShown) {
visibleRows.push(row.id);
}
});
return {
...state,
visibleRows: { visibleRowsLookup, visibleRows: Object.keys(visibleRowsLookup) },
visibleRows: { visibleRowsLookup, visibleRows },
};
});
forceUpdate();
},
[apiRef, forceUpdate, logger, rows, setGridState],
[apiRef, forceUpdate, logger, setGridState],
);

const applyFilters = React.useCallback(() => {
Expand Down Expand Up @@ -177,15 +187,27 @@ export const useFilter = (apiRef: ApiRef): void => {
[applyFilters, setGridState],
);

useApiMethod(
apiRef,
{
applyFilterLinkOperator,
applyFilters,
upsertFilter,
deleteFilter,
showFilterPanel,
},
'FilterApi',
);
const onRowsUpdated = React.useCallback(() => {
if (gridState.filter.items.length > 0) {
apiRef.current.applyFilters();
}
}, [gridState.filter.items.length, apiRef]);

useApiEventHandler(apiRef, ROWS_UPDATED, onRowsUpdated);
const filterApi: FilterApi = {
applyFilterLinkOperator,
applyFilters,
applyFilter,
upsertFilter,
deleteFilter,
showFilterPanel,
};
useApiMethod(apiRef, filterApi, 'FilterApi');

React.useEffect(() => {
if (apiRef.current) {
// When the rows prop change, we reapply the filters.
apiRef.current.applyFilters();
}
}, [apiRef, rowsProp]);
};
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,24 @@ export const setPageSizeStateUpdate = (
return state;
}

const newState: PaginationState = { ...state, pageSize };
const newState: PaginationState = {
...state,
pageSize,
pageCount: getPageCount(pageSize, state.rowCount),
};
return newState;
};

export const setRowCountStateUpdate = (state, payload): PaginationState => {
const { totalRowCount } = payload;
if (state.rowCount !== totalRowCount) {
const newPageCount = getPageCount(state.pageSize, totalRowCount);
return { ...state, pageCount: newPageCount, rowCount: totalRowCount };
return {
...state,
pageCount: newPageCount,
rowCount: totalRowCount,
page: state.page > newPageCount ? newPageCount : state.page,
};
}
return state;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import * as React from 'react';
import { PAGE_CHANGED, PAGESIZE_CHANGED, RESIZE } from '../../../constants/eventsConstants';
import { containerSizesSelector } from '../../../components/viewport';
import { PAGE_CHANGED, PAGESIZE_CHANGED } from '../../../constants/eventsConstants';
import { ApiRef } from '../../../models/api/apiRef';
import { PaginationApi } from '../../../models/api/paginationApi';
import { PaginationProps } from '../../../models/paginationProps';
import { PageChangeParams } from '../../../models/params/pageChangeParams';
import { useApiEventHandler } from '../../root/useApiEventHandler';
import { useApiMethod } from '../../root/useApiMethod';
import { useLogger } from '../../utils/useLogger';
import { optionsSelector } from '../../utils/useOptionsProp';
import { visibleColumnsLengthSelector } from '../columns/columnsSelector';
import { useGridReducer } from '../core/useGridReducer';
import { useGridSelector } from '../core/useGridSelector';
import { rowCountSelector } from '../rows/rowsSelector';
import { visibleRowCountSelector } from '../filter/filterSelector';
import {
INITIAL_PAGINATION_STATE,
PaginationActions,
Expand All @@ -25,7 +24,7 @@ import {

const PAGINATION_STATE_ID = 'pagination';

export const usePagination = (apiRef: ApiRef): PaginationProps => {
export const usePagination = (apiRef: ApiRef): void => {
const logger = useLogger('usePagination');

const { gridState, dispatch } = useGridReducer<PaginationState, PaginationActions>(
Expand All @@ -35,8 +34,8 @@ export const usePagination = (apiRef: ApiRef): PaginationProps => {
{ ...INITIAL_PAGINATION_STATE },
);
const options = useGridSelector(apiRef, optionsSelector);
const totalRowCount = useGridSelector(apiRef, rowCountSelector);
const visibleColumnsLength = useGridSelector(apiRef, visibleColumnsLengthSelector);
const visibleRowCount = useGridSelector(apiRef, visibleRowCountSelector);
const containerSizes = useGridSelector(apiRef, containerSizesSelector);

const setPage = React.useCallback(
(page: number) => {
Expand Down Expand Up @@ -76,25 +75,9 @@ export const usePagination = (apiRef: ApiRef): PaginationProps => {
[apiRef],
);

const resetAutopageSize = React.useCallback(() => {
if (options.autoPageSize) {
const containerProps = apiRef?.current?.getContainerPropsState();
const autoPagesize = containerProps?.viewportPageSize;
if (autoPagesize) {
logger.debug(`Setting autoPagesize to ${autoPagesize}`);
setPageSize(autoPagesize);
}
}
}, [options.autoPageSize, apiRef, logger, setPageSize]);

useApiEventHandler(apiRef, RESIZE, resetAutopageSize);
useApiEventHandler(apiRef, PAGE_CHANGED, options.onPageChange);
useApiEventHandler(apiRef, PAGESIZE_CHANGED, options.onPageSizeChange);

React.useEffect(() => {
dispatch(setRowCountActionCreator({ totalRowCount }));
}, [apiRef, dispatch, totalRowCount]);

React.useEffect(() => {
dispatch(setPaginationModeActionCreator({ paginationMode: options.paginationMode! }));
}, [apiRef, dispatch, options.paginationMode]);
Expand All @@ -110,10 +93,14 @@ export const usePagination = (apiRef: ApiRef): PaginationProps => {
}, [options.autoPageSize, options.pageSize, logger, setPageSize]);

React.useEffect(() => {
if (options.autoPageSize && visibleColumnsLength > 0) {
resetAutopageSize();
if (options.autoPageSize && containerSizes && containerSizes?.viewportPageSize > 0) {
setPageSize(containerSizes?.viewportPageSize);
}
}, [options.autoPageSize, resetAutopageSize, visibleColumnsLength]);
}, [containerSizes, options.autoPageSize, setPageSize]);

React.useEffect(() => {
dispatch(setRowCountActionCreator({ totalRowCount: visibleRowCount }));
}, [apiRef, dispatch, visibleRowCount]);

React.useEffect(() => {
if (apiRef.current?.isInitialised) {
Expand All @@ -129,10 +116,4 @@ export const usePagination = (apiRef: ApiRef): PaginationProps => {
};

useApiMethod(apiRef, paginationApi, 'paginationApi');

return {
...gridState.pagination,
setPage,
setPageSize,
};
};
Loading