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

[core] Remove rowsCache from state #4480

Merged
merged 3 commits into from
May 5, 2022
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export function useGridApiInitialization<Api extends GridApiCommon>(
if (!apiRef.current) {
apiRef.current = {
unstable_eventManager: new EventManager(),
unstable_caches: {},
state: {} as Api['state'],
instanceId: globalId,
} as Api;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export interface GridRowTreeCreationValue {

export type GridRowInternalCacheValue = Omit<GridRowTreeCreationParams, 'previousTree'>;

export interface GridRowsInternalCacheState {
export interface GridRowsInternalCache {
value: GridRowInternalCacheValue;
/**
* The rows as they were the last time all the rows have been updated at once
Expand All @@ -36,12 +36,6 @@ export interface GridRowsInternalCacheState {
rowsBeforePartialUpdates: GridRowsProp;
}

export interface GridRowsInternalCache {
state: GridRowsInternalCacheState;
timeout: NodeJS.Timeout | null;
lastUpdateMs: number;
}

export interface GridRowsState extends GridRowTreeCreationValue {
/**
* Matches the value of the `loading` prop.
Expand Down
118 changes: 57 additions & 61 deletions packages/grid/x-data-grid/src/hooks/features/rows/useGridRows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,11 @@ import { GridStateInitializer } from '../../utils/useGridInitializeState';
import { useGridVisibleRows } from '../../utils/useGridVisibleRows';
import { gridSortedRowIdsSelector } from '../sorting/gridSortingSelector';
import { gridFilteredRowsLookupSelector } from '../filter/gridFilterSelector';
import {
GridRowsInternalCacheState,
GridRowInternalCacheValue,
GridRowsInternalCache,
GridRowsState,
} from './gridRowsState';
import { GridRowInternalCacheValue, GridRowsInternalCache, GridRowsState } from './gridRowsState';
import { checkGridRowIdIsValid, getTreeNodeDescendants } from './gridRowsUtils';

interface ConvertGridRowsPropToStateParams {
prevState: GridRowsInternalCacheState;
interface ConvertRowsPropToStateParams {
prevCache: GridRowsInternalCache;
getRowId: DataGridProcessedProps['getRowId'];
rows?: GridRowsProp;
}
Expand All @@ -49,11 +44,11 @@ function getGridRowId(
return id;
}

const convertGridRowsPropToState = ({
prevState,
const convertRowsPropToState = ({
prevCache: prevState,
rows,
getRowId,
}: ConvertGridRowsPropToStateParams): GridRowsInternalCacheState => {
}: ConvertRowsPropToStateParams): GridRowsInternalCache => {
let value: GridRowInternalCacheValue;
if (rows) {
value = {
Expand Down Expand Up @@ -85,7 +80,7 @@ const getRowsStateFromCache = (
rowCountProp: number | undefined,
loadingProp: boolean | undefined,
): GridRowsState => {
const { value } = rowsCache.state;
const { value } = rowsCache;
const rowCount = rowCountProp ?? 0;

const groupingResponse = apiRef.current.unstable_applyStrategyProcessor('rowTreeCreation', {
Expand All @@ -109,27 +104,28 @@ const getRowsStateFromCache = (
export const rowsStateInitializer: GridStateInitializer<
Pick<DataGridProcessedProps, 'rows' | 'rowCount' | 'getRowId' | 'loading'>
> = (state, props, apiRef) => {
const rowsCache = {
state: convertGridRowsPropToState({
rows: props.rows,
getRowId: props.getRowId,
prevState: {
value: {
idRowsLookup: {},
idToIdLookup: {},
ids: [],
},
rowsBeforePartialUpdates: [],
apiRef.current.unstable_caches.rows = convertRowsPropToState({
rows: props.rows,
getRowId: props.getRowId,
prevCache: {
value: {
idRowsLookup: {},
idToIdLookup: {},
ids: [],
},
}),
timeout: null,
lastUpdateMs: Date.now(),
};
rowsBeforePartialUpdates: [],
},
});

return {
...state,
rows: getRowsStateFromCache(rowsCache, null, apiRef, props.rowCount, props.loading),
rowsCache, // TODO remove from state
rows: getRowsStateFromCache(
apiRef.current.unstable_caches.rows,
null,
apiRef,
props.rowCount,
props.loading,
),
};
};

Expand All @@ -153,9 +149,11 @@ export const useGridRows = (
}

const logger = useGridLogger(apiRef, 'useGridRows');
const rowsCache = React.useRef(apiRef.current.state.rowsCache); // To avoid listing rowsCache as useEffect dep
const currentPage = useGridVisibleRows(apiRef, props);

const lastUpdateMs = React.useRef(Date.now());
const timeout = React.useRef<NodeJS.Timeout | null>(null);

const getRow = React.useCallback<GridRowApi['getRow']>(
(id) => (gridRowsLookupSelector(apiRef)[id] as any) ?? null,
[apiRef],
Expand All @@ -171,14 +169,14 @@ export const useGridRows = (
);

const throttledRowsChange = React.useCallback(
(newState: GridRowsInternalCacheState, throttle: boolean) => {
(newCache: GridRowsInternalCache, throttle: boolean) => {
const run = () => {
rowsCache.current.timeout = null;
rowsCache.current.lastUpdateMs = Date.now();
timeout.current = null;
lastUpdateMs.current = Date.now();
apiRef.current.setState((state) => ({
...state,
rows: getRowsStateFromCache(
rowsCache.current,
apiRef.current.unstable_caches.rows!,
gridRowTreeSelector(apiRef),
apiRef,
props.rowCount,
Expand All @@ -189,22 +187,21 @@ export const useGridRows = (
apiRef.current.forceUpdate();
};

if (rowsCache.current.timeout) {
clearTimeout(rowsCache.current.timeout);
if (timeout.current) {
clearTimeout(timeout.current);
timeout.current = null;
}

rowsCache.current.state = newState;
rowsCache.current.timeout = null;
apiRef.current.unstable_caches.rows = newCache;

if (!throttle) {
run();
return;
}

const throttleRemainingTimeMs =
props.throttleRowsMs - (Date.now() - rowsCache.current.lastUpdateMs);
const throttleRemainingTimeMs = props.throttleRowsMs - (Date.now() - lastUpdateMs.current);
if (throttleRemainingTimeMs > 0) {
rowsCache.current.timeout = setTimeout(run, throttleRemainingTimeMs);
timeout.current = setTimeout(run, throttleRemainingTimeMs);
return;
}

Expand All @@ -220,15 +217,15 @@ export const useGridRows = (
(rows) => {
logger.debug(`Updating all rows, new length ${rows.length}`);
throttledRowsChange(
convertGridRowsPropToState({
convertRowsPropToState({
rows,
prevState: rowsCache.current.state,
prevCache: apiRef.current.unstable_caches.rows!,
getRowId: props.getRowId,
}),
true,
);
},
[logger, props.getRowId, throttledRowsChange],
[apiRef, logger, props.getRowId, throttledRowsChange],
);

const updateRows = React.useCallback<GridRowApi['updateRows']>(
Expand Down Expand Up @@ -263,9 +260,9 @@ export const useGridRows = (
const deletedRowIds: GridRowId[] = [];

const newStateValue: GridRowInternalCacheValue = {
idRowsLookup: { ...rowsCache.current.state.value.idRowsLookup },
idToIdLookup: { ...rowsCache.current.state.value.idToIdLookup },
ids: [...rowsCache.current.state.value.ids],
idRowsLookup: { ...apiRef.current.unstable_caches.rows!.value.idRowsLookup },
idToIdLookup: { ...apiRef.current.unstable_caches.rows!.value.idToIdLookup },
ids: [...apiRef.current.unstable_caches.rows!.value.ids],
};

uniqUpdates.forEach((partialRow, id) => {
Expand All @@ -292,14 +289,14 @@ export const useGridRows = (
newStateValue.ids = newStateValue.ids.filter((id) => !deletedRowIds.includes(id));
}

const state: GridRowsInternalCacheState = {
...rowsCache.current.state,
const state: GridRowsInternalCache = {
...apiRef.current.unstable_caches.rows!,
value: newStateValue,
};

throttledRowsChange(state, true);
},
[apiRef, props.getRowId, throttledRowsChange, props.signature],
[props.signature, props.getRowId, throttledRowsChange, apiRef],
);

const getRowModels = React.useCallback<GridRowApi['getRowModels']>(() => {
Expand Down Expand Up @@ -434,7 +431,7 @@ export const useGridRows = (
logger.info(`Row grouping pre-processing have changed, regenerating the row tree`);

let rows: GridRowsProp | undefined;
if (rowsCache.current.state.rowsBeforePartialUpdates === props.rows) {
if (apiRef.current.unstable_caches.rows!.rowsBeforePartialUpdates === props.rows) {
// The `props.rows` has not changed since the last row grouping
// We can keep the potential updates stored in `inputRowsAfterUpdates` on the new grouping
rows = undefined;
Expand All @@ -445,14 +442,14 @@ export const useGridRows = (
rows = props.rows;
}
throttledRowsChange(
convertGridRowsPropToState({
convertRowsPropToState({
rows,
getRowId: props.getRowId,
prevState: rowsCache.current.state,
prevCache: apiRef.current.unstable_caches.rows!,
}),
false,
);
}, [logger, throttledRowsChange, props.getRowId, props.rows]);
}, [logger, apiRef, props.rows, props.getRowId, throttledRowsChange]);

const handleStrategyProcessorChange = React.useCallback<
GridEventListener<'activeStrategyProcessorChange'>
Expand Down Expand Up @@ -487,9 +484,8 @@ export const useGridRows = (
*/
React.useEffect(() => {
return () => {
if (rowsCache.current.timeout !== null) {
// eslint-disable-next-line react-hooks/exhaustive-deps
clearTimeout(rowsCache.current.timeout);
if (timeout.current !== null) {
clearTimeout(timeout.current);
}
};
}, []);
Expand All @@ -504,18 +500,18 @@ export const useGridRows = (
}

// The new rows have already been applied (most likely in the `'rowGroupsPreProcessingChange'` listener)
if (rowsCache.current.state.rowsBeforePartialUpdates === props.rows) {
if (apiRef.current.unstable_caches.rows!.rowsBeforePartialUpdates === props.rows) {
return;
}

logger.debug(`Updating all rows, new length ${props.rows.length}`);
throttledRowsChange(
convertGridRowsPropToState({
convertRowsPropToState({
rows: props.rows,
getRowId: props.getRowId,
prevState: rowsCache.current.state,
prevCache: apiRef.current.unstable_caches.rows!,
}),
false,
);
}, [props.rows, props.rowCount, props.getRowId, logger, throttledRowsChange]);
}, [props.rows, props.rowCount, props.getRowId, logger, throttledRowsChange, apiRef]);
};
11 changes: 11 additions & 0 deletions packages/grid/x-data-grid/src/models/api/gridCoreApi.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import * as React from 'react';
import { GridEventPublisher, GridEventListener, GridEventsStr } from '../events';
import { EventManager, EventListenerOptions } from '../../utils/EventManager';
import { GridRowsInternalCache } from '../../hooks/features/rows/gridRowsState';

// TODO: Export and make it augmentable
interface Caches {
rows?: GridRowsInternalCache;
}

/**
* The core API interface that is available in the grid `apiRef`.
Expand Down Expand Up @@ -46,6 +52,11 @@ export interface GridCoreApi {
* @ignore - do not document
*/
unstable_eventManager: EventManager;
/**
* The caches used by hooks and state initializers.
* @ignore - do not document.
*/
unstable_caches: Caches;
/**
* Registers a handler for an event.
* @param {string} event The name of the event.
Expand Down
2 changes: 0 additions & 2 deletions packages/grid/x-data-grid/src/models/gridStateCommunity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import type {
GridTabIndexState,
} from '../hooks';
import type { GridRowsMetaState } from '../hooks/features/rows/gridRowsMetaState';
import type { GridRowsInternalCache } from '../hooks/features/rows/gridRowsState';
import type { GridEditRowsModel } from './gridEditRowModel';
import type { GridSelectionModel } from './gridSelectionModel';

Expand All @@ -25,7 +24,6 @@ import type { GridSelectionModel } from './gridSelectionModel';
*/
export interface GridStateCommunity {
rows: GridRowsState;
rowsCache: GridRowsInternalCache;
rowsMeta: GridRowsMetaState;
editRows: GridEditRowsModel;
pagination: GridPaginationState;
Expand Down