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

[SecuritySolution] Close field editor when page context is lost #124378

Merged
merged 4 commits into from
Feb 3, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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 @@ -33,6 +33,11 @@ jest.mock('../../../timelines/containers', () => ({

jest.mock('../../components/url_state/normalize_time_range.ts');

const mockUseCreateFieldButton = jest.fn().mockReturnValue(<></>);
jest.mock('../../../timelines/components/create_field_button', () => ({
useCreateFieldButton: (...params: unknown[]) => mockUseCreateFieldButton(...params),
}));

const mockUseResizeObserver: jest.Mock = useResizeObserver as jest.Mock;
jest.mock('use-resize-observer/polyfilled');
mockUseResizeObserver.mockImplementation(() => ({}));
Expand Down Expand Up @@ -87,4 +92,21 @@ describe('StatefulEventsViewer', () => {
expect(wrapper.find(`InspectButtonContainer`).exists()).toBe(true);
});
});

test('it closes field editor when unmounted', async () => {
const mockCloseEditor = jest.fn();
mockUseCreateFieldButton.mockImplementation((_, __, fieldEditorActionsRef) => {
fieldEditorActionsRef.current = { closeEditor: mockCloseEditor };
return <></>;
});

const wrapper = mount(
<TestProviders>
<StatefulEventsViewer {...testProps} />
</TestProviders>
);
wrapper.unmount();

expect(mockCloseEditor).toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import React, { useCallback, useMemo, useEffect } from 'react';
import React, { useRef, useCallback, useMemo, useEffect } from 'react';
import { connect, ConnectedProps, useDispatch } from 'react-redux';
import deepEqual from 'fast-deep-equal';
import styled from 'styled-components';
Expand All @@ -29,7 +29,10 @@ import { CellValueElementProps } from '../../../timelines/components/timeline/ce
import { FIELDS_WITHOUT_CELL_ACTIONS } from '../../lib/cell_actions/constants';
import { useKibana } from '../../lib/kibana';
import { GraphOverlay } from '../../../timelines/components/graph_overlay';
import { useCreateFieldButton } from '../../../timelines/components/create_field_button';
import {
CreateFieldEditorActions,
useCreateFieldButton,
} from '../../../timelines/components/create_field_button';

const EMPTY_CONTROL_COLUMNS: ControlColumnProps[] = [];

Expand Down Expand Up @@ -121,6 +124,8 @@ const StatefulEventsViewerComponent: React.FC<Props> = ({
const tGridEventRenderedViewEnabled = useIsExperimentalFeatureEnabled(
'tGridEventRenderedViewEnabled'
);
const editorActionsRef = useRef<CreateFieldEditorActions>(null);

useEffect(() => {
if (createTimeline != null) {
createTimeline({
Expand All @@ -137,6 +142,10 @@ const StatefulEventsViewerComponent: React.FC<Props> = ({
}
return () => {
deleteEventQuery({ id, inputId: 'global' });
if (editorActionsRef.current) {
// eslint-disable-next-line react-hooks/exhaustive-deps
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you need this here? i thought just above the dependency array

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, It is needed here too, this error pops if not diabled:

The ref value 'fieldEditorActionsRef.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'fieldEditorActionsRef.current' to a variable inside the effect, and use that variable in the cleanup function

editorActionsRef.current.closeEditor();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Expand Down Expand Up @@ -167,7 +176,7 @@ const StatefulEventsViewerComponent: React.FC<Props> = ({
}, [id, timelineQuery, globalQuery]);
const bulkActions = useMemo(() => ({ onAlertStatusActionSuccess }), [onAlertStatusActionSuccess]);

const createFieldComponent = useCreateFieldButton(scopeId, id);
const createFieldComponent = useCreateFieldButton(scopeId, id, editorActionsRef);

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
*/

import { render, fireEvent, act, screen } from '@testing-library/react';
import React from 'react';
import { CreateFieldButton } from './index';
import React, { MutableRefObject } from 'react';
import { CreateFieldButton, CreateFieldEditorActions } from './index';
import {
indexPatternFieldEditorPluginMock,
Start,
Expand Down Expand Up @@ -108,4 +108,29 @@ describe('CreateFieldButton', () => {
fireEvent.click(screen.getByRole('button'));
expect(onClickParam).toHaveBeenCalled();
});

it("stores 'closeEditor' in the actions ref when editor is open", async () => {
const closeEditorDummyFn = () => {};
useKibanaMock().services.data.dataViews.get = () => Promise.resolve({} as DataView);
useKibanaMock().services.dataViewFieldEditor.openEditor = () => closeEditorDummyFn;

const editorActionsRef: MutableRefObject<CreateFieldEditorActions> = React.createRef();
await act(async () => {
render(
<CreateFieldButton
selectedDataViewId={'dataViewId'}
onClick={() => undefined}
timelineId={TimelineId.detectionsPage}
editorActionsRef={editorActionsRef}
/>,
{
wrapper: TestProviders,
}
);
await runAllPromises();
});

fireEvent.click(screen.getByRole('button'));
expect(editorActionsRef?.current?.closeEditor).toBe(closeEditorDummyFn);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, { MutableRefObject, useCallback, useEffect, useMemo, useState } from 'react';
import { EuiButton } from '@elastic/eui';
import styled from 'styled-components';

Expand All @@ -23,17 +23,21 @@ import { useDeepEqualSelector } from '../../../common/hooks/use_selector';
import { DEFAULT_COLUMN_MIN_WIDTH } from '../timeline/body/constants';
import { defaultColumnHeaderType } from '../timeline/body/column_headers/default_headers';

export type CreateFieldEditorActions = { closeEditor: () => void } | null;
type CreateFieldEditorActionsRef = MutableRefObject<CreateFieldEditorActions>;

interface CreateFieldButtonProps {
selectedDataViewId: string;
onClick: () => void;
timelineId: TimelineId;
editorActionsRef?: CreateFieldEditorActionsRef;
}
const StyledButton = styled(EuiButton)`
margin-left: ${({ theme }) => theme.eui.paddingSizes.m};
`;

export const CreateFieldButton = React.memo<CreateFieldButtonProps>(
({ selectedDataViewId, onClick: onClickParam, timelineId }) => {
({ selectedDataViewId, onClick: onClickParam, timelineId, editorActionsRef }) => {
const [dataView, setDataView] = useState<DataView | null>(null);
const dispatch = useDispatch();

Expand All @@ -52,7 +56,7 @@ export const CreateFieldButton = React.memo<CreateFieldButtonProps>(

const onClick = useCallback(() => {
if (dataView) {
dataViewFieldEditor?.openEditor({
const closeEditor = dataViewFieldEditor?.openEditor({
ctx: { dataView },
onSave: async (field: DataViewField) => {
// Fetch the updated list of fields
Expand All @@ -72,6 +76,9 @@ export const CreateFieldButton = React.memo<CreateFieldButtonProps>(
);
},
});
if (editorActionsRef) {
editorActionsRef.current = { closeEditor };
}
}
onClickParam();
}, [
Expand All @@ -82,6 +89,7 @@ export const CreateFieldButton = React.memo<CreateFieldButtonProps>(
selectedDataViewId,
dispatch,
timelineId,
editorActionsRef,
]);

if (
Expand Down Expand Up @@ -116,7 +124,8 @@ CreateFieldButton.displayName = 'CreateFieldButton';
*/
export const useCreateFieldButton = (
sourcererScope: SourcererScopeName,
timelineId: TimelineId
timelineId: TimelineId,
editorActionsRef?: CreateFieldEditorActionsRef
) => {
const scopeIdSelector = useMemo(() => sourcererSelectors.scopeIdSelector(), []);
const { missingPatterns, selectedDataViewId } = useDeepEqualSelector((state) =>
Expand All @@ -133,9 +142,10 @@ export const useCreateFieldButton = (
selectedDataViewId={selectedDataViewId}
onClick={onClick}
timelineId={timelineId}
editorActionsRef={editorActionsRef}
/>
);

return CreateFieldButtonComponent;
}, [missingPatterns.length, selectedDataViewId, timelineId]);
}, [missingPatterns.length, selectedDataViewId, timelineId, editorActionsRef]);
};

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading