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

[EuiDataGrid] track re-renders from hooks #4347

Closed
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
91 changes: 62 additions & 29 deletions src/components/datagrid/data_grid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import React, {
useEffect,
Fragment,
ReactChild,
useMemo,
useRef,
Dispatch,
SetStateAction,
Expand Down Expand Up @@ -79,6 +78,7 @@ import {
import { useDataGridColumnSorting } from './column_sorting';
import { EuiMutationObserver } from '../observer/mutation_observer';
import { DataGridContext } from './data_grid_context';
import { useDebugMemo } from './debug_hooks';

// Used to short-circuit some async browser behaviour that is difficult to account for in tests
const IS_JEST_ENVIRONMENT = global.hasOwnProperty('_isJest');
Expand Down Expand Up @@ -156,6 +156,10 @@ type CommonGridProps = CommonProps &
* Defines a minimum width for the grid to show all controls in its header.
*/
minSizeForControls?: number;
/**
* Allow to track and logging execution of hooks.
*/
debugMode?: boolean | string[];
};

// Force either aria-label or aria-labelledby to be defined
Expand Down Expand Up @@ -302,7 +306,6 @@ function useDefaultColumnWidth(
const computeDefaultWidth = useCallback((): number | null => {
if (IS_JEST_ENVIRONMENT) return 100;
if (gridWidth === 0) return null; // we can't tell what size to compute yet

const controlColumnWidths = [
...leadingControlColumns,
...trailingControlColumns,
Expand Down Expand Up @@ -405,7 +408,8 @@ function useOnResize(

function useInMemoryValues(
inMemory: EuiDataGridInMemory | undefined,
rowCount: number
rowCount: number,
debugMode: boolean | string[]
): [
EuiDataGridInMemoryValues,
(rowIndex: number, columnId: string, value: string) => void
Expand All @@ -423,9 +427,12 @@ function useInMemoryValues(
const [inMemoryValuesVersion, setInMemoryValuesVersion] = useState(0);

// eslint-disable-next-line react-hooks/exhaustive-deps
const inMemoryValues = useMemo(() => ({ ..._inMemoryValues.current }), [
inMemoryValuesVersion,
]);
const inMemoryValues = useDebugMemo(
() => ({ ..._inMemoryValues.current }),
[inMemoryValuesVersion],
'inMemoryValues',
debugMode
);

const onCellRender = useCallback((rowIndex, columnId, value) => {
const nextInMemoryValues = _inMemoryValues.current;
Expand Down Expand Up @@ -538,7 +545,6 @@ function createKeyDownHandler(
function useAfterRender(fn: Function): Function {
const [isSubscribed, setIsSubscribed] = useState(false);
const [needsExecution, setNeedsExecution] = useState(false);

// first useEffect waits for the parent & children to render & flush to dom
useEffect(() => {
if (isSubscribed) {
Expand All @@ -563,7 +569,8 @@ function useAfterRender(fn: Function): Function {

type FocusProps = Pick<HTMLAttributes<HTMLDivElement>, 'tabIndex' | 'onFocus'>;
const useFocus = (
headerIsInteractive: boolean
headerIsInteractive: boolean,
debugMode: boolean | string[]
): [
FocusProps,
EuiDataGridFocusedCell | undefined,
Expand All @@ -573,9 +580,14 @@ const useFocus = (
EuiDataGridFocusedCell | undefined
>(undefined);

const hasHadFocus = useMemo(() => focusedCell != null, [focusedCell]);
const hasHadFocus = useDebugMemo(
() => focusedCell != null,
[focusedCell],
'hasHadFocus',
debugMode
);

const focusProps = useMemo<FocusProps>(
const focusProps = useDebugMemo(
() =>
hasHadFocus
? {
Expand All @@ -594,7 +606,9 @@ const useFocus = (
}
},
},
[hasHadFocus, setFocusedCell, headerIsInteractive]
[hasHadFocus, setFocusedCell, headerIsInteractive],
'focusProps',
debugMode
);

return [focusProps, focusedCell, setFocusedCell];
Expand Down Expand Up @@ -635,10 +649,15 @@ export const EuiDataGrid: FunctionComponent<EuiDataGridProps> = (props) => {
const [interactiveCellId] = useState(htmlIdGenerator()());
const [headerIsInteractive, setHeaderIsInteractive] = useState(false);

const setContainerRef = useCallback((ref) => _setContainerRef(ref), []);
const setContainerRef = useCallback((ref) => {
return _setContainerRef(ref);
}, []);

const { debugMode = false } = props;

const [wrappingDivFocusProps, focusedCell, setFocusedCell] = useFocus(
headerIsInteractive
headerIsInteractive,
debugMode
);

const handleHeaderChange = useCallback<(headerRow: HTMLElement) => void>(
Expand Down Expand Up @@ -729,23 +748,34 @@ export const EuiDataGrid: FunctionComponent<EuiDataGridProps> = (props) => {
// apply style props on top of defaults
const gridStyleWithDefaults = { ...startingStyles, ...gridStyle };

const [inMemoryValues, onCellRender] = useInMemoryValues(inMemory, rowCount);
const [inMemoryValues, onCellRender] = useInMemoryValues(
inMemory,
rowCount,
debugMode
);

const definedColumnSchemas = useMemo(() => {
return columns.reduce<{ [key: string]: string }>(
(definedColumnSchemas, { id, schema }) => {
if (schema != null) {
definedColumnSchemas[id] = schema;
}
return definedColumnSchemas;
},
{}
);
}, [columns]);
const definedColumnSchemas = useDebugMemo(
() => {
return columns.reduce<{ [key: string]: string }>(
(definedColumnSchemas, { id, schema }) => {
if (schema != null) {
definedColumnSchemas[id] = schema;
}
return definedColumnSchemas;
},
{}
);
},
[columns],
'definedColumnSchemas',
debugMode
);

const allSchemaDetectors = useMemo(
const allSchemaDetectors = useDebugMemo(
() => [...providedSchemaDetectors, ...(schemaDetectors || [])],
[schemaDetectors]
[schemaDetectors],
'allSchemaDetectors',
debugMode
);
const detectedSchema = useDetectSchema(
inMemory,
Expand Down Expand Up @@ -919,7 +949,7 @@ export const EuiDataGrid: FunctionComponent<EuiDataGridProps> = (props) => {
}
});

const datagridContext = useMemo(
const datagridContext = useDebugMemo(
() => ({
onFocusUpdate: (cell: EuiDataGridFocusedCell, updateFocus: Function) => {
const key = `${cell[0]}-${cell[1]}`;
Expand All @@ -929,8 +959,11 @@ export const EuiDataGrid: FunctionComponent<EuiDataGridProps> = (props) => {
cellsUpdateFocus.current.delete(key);
};
},
debugMode,
}),
[]
[],
'datagridContext',
debugMode
);

const gridIds = htmlIdGenerator();
Expand Down
1 change: 1 addition & 0 deletions src/components/datagrid/data_grid_context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ import { EuiDataGridFocusedCell } from './data_grid_types';

export const DataGridContext = React.createContext({
onFocusUpdate: (_cell: EuiDataGridFocusedCell, _updateFocus: Function) => {},
debugMode: false,
});
108 changes: 108 additions & 0 deletions src/components/datagrid/debug_hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { isArray, isBoolean } from 'lodash';
import { useEffect, useRef, useMemo } from 'react';

function compareDependencies(oldDeps: any[], newDeps: any[]) {
oldDeps.forEach((oldDep, index) => {
const newDep = newDeps[index];
if (newDep !== oldDep) {
console.log(`The dependency changed in position ${index}`);
console.log('Old value: ', oldDep);
console.log('New value: ', newDep);
}
});
}

function enhanceHookFn(hookFn: Function, name: string) {
return (params?: any) => {
window.performance.mark(`execute hook for ${name}`);
const obj = window.performance.getEntriesByName(`execute hook for ${name}`);
console.log(`hook was called for ${name}`, obj[obj.length - 1]);
return hookFn(params);
};
}

function checkDebugMode(debugMode: boolean | string[], name: string) {
return (
(isBoolean(debugMode) && debugMode) ||
(isArray(debugMode) && debugMode.includes(name))
);
}

function useDebugHooks(
hook: Function,
hookFn: Function,
dependencies: any[],
name: string,
isShouldReturn = false,
debugMode: boolean | string[] = false
) {
const oldDepsRef = useRef(dependencies);
return hook((params?: any) => {
const oldDeps = oldDepsRef.current;

if (checkDebugMode(debugMode, name) && dependencies.length !== 0) {
console.log(
`hook for ${name} was executed cause some dependency was changed`
);
compareDependencies(oldDeps, dependencies);
}
// Save the current dependencies
oldDepsRef.current = dependencies;
if (isShouldReturn) {
return hookFn(params);
} else {
hookFn(params);
}
}, dependencies);
}

export function useDebugEffect(
hookFn: Function,
dependencies: any[],
name: string,
debugMode: boolean | string[]
) {
return useDebugHooks(
useEffect,
debugMode ? enhanceHookFn(hookFn, name) : hookFn,
dependencies,
name,
false,
debugMode
);
}

export function useDebugMemo(
hookFn: Function,
dependencies: any[],
name: string,
debugMode: boolean | string[]
) {
return useDebugHooks(
useMemo,
debugMode ? enhanceHookFn(hookFn, name) : hookFn,
dependencies,
name,
true,
debugMode
);
}